From 6b6c4b18a0acb67dbad93240978a0607e92d4e27 Mon Sep 17 00:00:00 2001 From: Mihai Serban Date: Fri, 15 Oct 2021 11:12:33 +0300 Subject: [PATCH 01/12] add renaming on manager --- LICENSE | 18 +- README.md | 38 +- docs/api/README.md | 10 +- docs/api/addbackupinfo.md | 2 +- docs/api/analyzecaslog.md | 2 +- docs/api/backupdb.md | 2 +- docs/api/backupvolinfo.md | 2 +- docs/api/broker_setparam.md | 2 +- docs/api/copydb.md | 6 +- docs/api/createdb.md | 14 +- docs/api/dbspaceinfo.md | 12 +- docs/api/getaddbrokerinfo.md | 2 +- docs/api/getallsysparam.md | 4 +- docs/api/getcaslogtopresult.md | 4 +- docs/api/getcmsenv.md | 2 +- docs/api/getdbmtuserinfo.md | 2 +- docs/api/getdbprocstat.md | 2 +- docs/api/gethaapplyinfo.md | 2 +- docs/api/getloginfo.md | 22 +- docs/api/gettransactioninfo.md | 2 +- docs/api/ha_reload.md | 2 +- docs/api/ha_start.md | 2 +- docs/api/ha_status.md | 2 +- docs/api/ha_stop.md | 2 +- docs/api/heartbeatlist.md | 2 +- docs/api/killtransaction.md | 2 +- docs/api/loaddb.md | 4 +- docs/api/monitorprocess.md | 4 +- docs/api/renamedb.md | 2 +- docs/api/restoredb.md | 4 +- docs/api/setbackupinfo.md | 2 +- docs/api/setsysparam.md | 16 +- docs/api/startinfo.md | 10 +- docs/api/unloaddb.md | 2 +- docs/api/userinfo.md | 2 +- docs/api/viewlogviewlog2.md | 8 +- server/build_cms_env.sh | 36 +- server/build_internal.bat | 44 +- server/build_server.bat | 4 +- server/cmserver/Makefile.am | 8 +- server/cmserver/conf/cm.conf | 18 +- server/configure.ac | 76 +- server/external/README | 6 +- server/hudsonbuild.cmd | 14 +- server/set_hudson_env.sh | 18 +- server/src/cm_auto_task.cpp | 12 +- server/src/cm_autojob.cpp | 98 +-- server/src/cm_cci_interface.cpp | 46 +- server/src/cm_cci_interface.h | 8 +- server/src/cm_cmd_exec.cpp | 142 +-- server/src/cm_cmd_exec.h | 66 +- server/src/cm_cmd_task.cpp | 2 +- server/src/cm_config.cpp | 94 +- server/src/cm_config.h | 108 +-- server/src/cm_http_server.cpp | 4 +- server/src/cm_httpd.cpp | 88 +- server/src/cm_job_task.cpp | 826 +++++++++--------- server/src/cm_job_task.h | 4 +- server/src/cm_log.h | 10 +- server/src/cm_server_autoupdate.cpp | 42 +- server/src/cm_server_autoupdate.h | 4 +- server/src/cm_server_extend_interface.cpp | 32 +- server/src/cm_server_extend_interface.h | 2 +- server/src/cm_server_interface.cpp | 96 +- server/src/cm_server_interface.h | 4 +- server/src/cm_server_stat.c | 2 +- server/src/cm_server_stat.h | 2 +- server/src/cm_server_util.cpp | 32 +- server/src/cm_server_util.h | 4 +- server/src/cm_user.cpp | 42 +- server/test/cm_mon_data/dump_data.py | 2 +- server/test/hudsonbuild.sh | 32 +- server/test/task_list.txt | 2 +- server/test/task_test_case/addbackupinfo | 2 +- .../test/task_test_case/addvoldb_nullpurpose | 2 +- server/test/task_test_case/addvoldb_nullsize | 2 +- server/test/task_test_case/analyzecaslog | 2 +- .../task_test_case/analyzecaslog_option_no | 2 +- server/test/task_test_case/applylogdb | 2 +- server/test/task_test_case/backupdb | 2 +- server/test/task_test_case/backupdb_nullname | 2 +- server/test/task_test_case/backupdb_rep | 2 +- server/test/task_test_case/backupvolinfo | 2 +- server/test/task_test_case/broker_setparam | 2 +- server/test/task_test_case/checkdir | 2 +- server/test/task_test_case/checkfile | 2 +- server/test/task_test_case/class | 2 +- server/test/task_test_case/classinfo | 2 +- server/test/task_test_case/copydb | 6 +- server/test/task_test_case/copydb_advance | 8 +- server/test/task_test_case/copydb_nulldest | 6 +- .../test/task_test_case/copydb_nulldestpath | 4 +- .../test/task_test_case/copydb_nullexvolpath | 4 +- server/test/task_test_case/copydb_nulllogpath | 4 +- server/test/task_test_case/copydb_nullop | 6 +- server/test/task_test_case/copydb_nullsrc | 6 +- server/test/task_test_case/copylogdb | 2 +- server/test/task_test_case/createdb | 6 +- server/test/task_test_case/createdb_accesslog | 2 +- .../test/task_test_case/createdb_errlogpath | 2 +- .../test/task_test_case/createdb_errlogpath1 | 2 +- .../test/task_test_case/createdb_errvolpath | 4 +- .../createdb_fail_with_dup_name | 4 +- .../test/task_test_case/createdb_for_copydb | 4 +- server/test/task_test_case/createuser | 2 +- server/test/task_test_case/dbmtuserlogin | 2 +- server/test/task_test_case/deleteuser | 2 +- server/test/task_test_case/getcaslogtopresult | 2 +- server/test/task_test_case/gettriggerinfo | 2 +- server/test/task_test_case/loaddb | 4 +- server/test/task_test_case/optimizedb | 2 +- .../task_test_case/removecasrunnertmpfile | 2 +- server/test/task_test_case/removefiles | 2 +- server/test/task_test_case/removelog | 2 +- server/test/task_test_case/renamedb | 2 +- server/test/task_test_case/renamedb_adoff | 2 +- .../test/task_test_case/renamedb_nullrename | 2 +- server/test/task_test_case/resetlog | 2 +- server/test/task_test_case/restoredb | 4 +- server/test/task_test_case/setbackupinfo | 2 +- server/test/task_test_case/setsysparam | 16 +- ...ram_cubridconf => setsysparam_arniadbconf} | 16 +- server/test/task_test_case/unloaddb | 2 +- server/test/task_test_case/unloaddb_advance | 2 +- server/test/task_test_case/unloaddb_nullname | 2 +- .../test/task_test_case/unloaddb_nulltarget | 2 +- server/test/task_test_case/updateattribute | 2 +- server/test/task_test_case/userinfo | 2 +- server/test/task_test_case/viewlog | 2 +- server/test/task_test_case_json/addvoldb.txt | 4 +- .../task_test_case_json/analyzecaslog.txt | 4 +- .../analyzecaslog_option_no.txt | 4 +- .../test/task_test_case_json/applylogdb.txt | 2 +- server/test/task_test_case_json/backupdb.txt | 4 +- .../task_test_case_json/backupvolinfo.txt | 2 +- .../task_test_case_json/broker_setparam.txt | 4 +- server/test/task_test_case_json/checkdir.txt | 2 +- server/test/task_test_case_json/checkfile.txt | 2 +- server/test/task_test_case_json/copydb.txt | 8 +- .../task_test_case_json/copydb_advance.txt | 10 +- .../test/task_test_case_json/copyfolder.txt | 4 +- server/test/task_test_case_json/copylogdb.txt | 4 +- server/test/task_test_case_json/createdb.txt | 8 +- .../createdb_fail_with_dup_name.txt | 6 +- .../createdb_for_copydb.txt | 6 +- .../test/task_test_case_json/deletefolder.txt | 2 +- .../task_test_case_json/getallsysparam.txt | 2 +- .../getcaslogtopresult.txt | 4 +- .../task_test_case_json/getenvvarbyname.txt | 2 +- .../getfiletotallinenum.txt | 2 +- .../getfolderswithkeyword.txt | 4 +- server/test/task_test_case_json/loaddb.txt | 6 +- .../removecasrunnertmpfile.txt | 2 +- server/test/task_test_case_json/removelog.txt | 4 +- server/test/task_test_case_json/renamedb.txt | 4 +- server/test/task_test_case_json/resetlog.txt | 2 +- server/test/task_test_case_json/restoredb.txt | 4 +- .../task_test_case_json/setbackupinfo.txt | 4 +- .../test/task_test_case_json/setsysparam.txt | 16 +- ...idconf.txt => setsysparam_arniadbconf.txt} | 16 +- server/test/task_test_case_json/unloaddb.txt | 4 +- server/test/task_test_case_json/viewlog.txt | 4 +- ...cubrid_broker.conf => arniadb_broker.conf} | 2 +- server/test/task_test_config/cm_conf/cm.conf | 10 +- .../test/task_test_config/ha_conf/README.txt | 2 +- .../ha_conf/{cubrid.conf => arniadb.conf} | 14 +- server/test/task_test_config/orign/README.txt | 2 +- .../tmp_file_for_test/analyzelog_1.res | 8 +- server/test/test_tasks.php | 56 +- server/test/test_tasks.py | 22 +- .../arn_manager.vcproj} | 20 +- .../{cub_manager => arn_manager}/resource.h | 0 .../{cub_manager => arn_manager}/version.rc | 8 +- server/win/cm_admin/cm_admin.vcproj | 16 +- server/win/cm_admin/version.rc | 6 +- server/win/cmserver.sln | 2 +- server/win/install/install.vcproj | 2 +- 177 files changed, 1377 insertions(+), 1377 deletions(-) rename server/test/task_test_case/{setsysparam_cubridconf => setsysparam_arniadbconf} (87%) rename server/test/task_test_case_json/{setsysparam_cubridconf.txt => setsysparam_arniadbconf.txt} (82%) rename server/test/task_test_config/cm_conf/{cubrid_broker.conf => arniadb_broker.conf} (96%) rename server/test/task_test_config/ha_conf/{cubrid.conf => arniadb.conf} (88%) rename server/win/{cub_manager/cub_manager.vcproj => arn_manager/arn_manager.vcproj} (87%) rename server/win/{cub_manager => arn_manager}/resource.h (100%) rename server/win/{cub_manager => arn_manager}/version.rc (90%) diff --git a/LICENSE b/LICENSE index 46d4ce3..1b3f16c 100644 --- a/LICENSE +++ b/LICENSE @@ -1,13 +1,13 @@ Copyright (C) 2008-2015 Search Solution Corporation. All rights reserved. -CUBRID is registered trademark of Search Solution Corporation. +ARNIADB is registered trademark of Search Solution Corporation. -This Software is released under GNU GPL v2, GPL v3 according to CUBRID Manager components. -For brevity, CUBRID Manager Server is under GPL v2 and it uses MIT, BSD licensed libraries. -CUBRID Web Manager is under GPL v3 and it uses MIT, BSD and GPL v3 licensed libraries. -For details, please refer to the CUBRID License Page(http://www.cubrid.org/license). +This Software is released under GNU GPL v2, GPL v3 according to ARNIADB Manager components. +For brevity, ARNIADB Manager Server is under GPL v2 and it uses MIT, BSD licensed libraries. +ARNIADB Web Manager is under GPL v3 and it uses MIT, BSD and GPL v3 licensed libraries. +For details, please refer to the ARNIADB License Page(http://www.arniadb.org/license). -* CUBRID Manager Server under GPL v2 or later(http://opensource.org/licenses/GPL-2.0) +* ARNIADB Manager Server under GPL v2 or later(http://opensource.org/licenses/GPL-2.0) -------------------------------------------------------------------------------- The GNU General Public License (GPL) Version 2, June 1991 @@ -133,7 +133,7 @@ Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovis This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. -------------------------------------------------------------------------------- -* Library license for CUBRID Manager Server +* Library license for ARNIADB Manager Server ** The JsonCpp library under MIT License(http://opensource.org/licenses/mit-license.php) -------------------------------------------------------------------------------- @@ -398,7 +398,7 @@ The arc4module is available under the following, sometimes called the -------------------------------------------------------------------------------- -* CUBRID Web Manager under GPL v3(http://opensource.org/licenses/GPL-3.0) +* ARNIADB Web Manager under GPL v3(http://opensource.org/licenses/GPL-3.0) -------------------------------------------------------------------------------- GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 @@ -641,7 +641,7 @@ You should also get your employer (if you work as a programmer) or school, if an The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . -------------------------------------------------------------------------------- -* Library license for CUBRID Web Manager +* Library license for ARNIADB Web Manager ** Code Mirror library under MIT License(http://opensource.org/licenses/mit-license.php) -------------------------------------------------------------------------------- diff --git a/README.md b/README.md index f5a0cd9..b871473 100644 --- a/README.md +++ b/README.md @@ -1,30 +1,30 @@ -# CUBRID Manager Server System +# ARNIADB Manager Server System -CUBRID Manager Server(CMS) is a part of CUBRID Tools. +ARNIADB Manager Server(CMS) is a part of ARNIADB Tools. -CMS provides both HTTP or Socket interfaces for CUBRID Manager -to managing CUBRID system, and also provides monitoring information about CUBRID system. +CMS provides both HTTP or Socket interfaces for ARNIADB Manager +to managing ARNIADB system, and also provides monitoring information about ARNIADB system. ## MAJOR REFERENCES -- CUBRID Official Site: http://www.cubrid.org and http://www.cubrid.com +- ARNIADB Official Site: http://www.arniadb.org and http://www.arniadb.com ## DOWNLOADS and FILE REPOSITORIES -CMS is distributed within CUBRID distribution which can be found here: +CMS is distributed within ARNIADB distribution which can be found here: -- http://www.cubrid.org/downloads -- http://ftp.cubrid.org +- http://www.arniadb.org/downloads +- http://ftp.arniadb.org ## HOW TO BUILD/INSTALL CMS ### build and install on Linux -Unzip the package of CUBRID and you can find the source code of CMS here: cubrid-{version}/cubridmanager/server. +Unzip the package of ARNIADB and you can find the source code of CMS here: arniadb-{version}/arniadbmanager/server. 1. Move to the directory where the source is stored. ``` - cd $HOME/cubridmanager/server + cd $HOME/arniadbmanager/server ``` 2. Execute autogen.sh. @@ -36,12 +36,12 @@ Unzip the package of CUBRID and you can find the source code of CMS here: cubrid 3. Execute the configure script. ``` - ./configure --prefix=$CUBRID + ./configure --prefix=$ARNIADB ``` - - `--prefix=$CUBRID` : It specifies a directory to be installed. + - `--prefix=$ARNIADB` : It specifies a directory to be installed. - `--enable-debug` : Used to enable debug mode. - - `--enable-64bit` : Used to build in a 64-bit environment since supporting 64-bit from CUBRID 2008 R2.0 or higher. + - `--enable-64bit` : Used to build in a 64-bit environment since supporting 64-bit from ARNIADB 2008 R2.0 or higher. 4. Build by using make. @@ -62,18 +62,18 @@ If you want to build CMS on windows, VS2008 must be installed. 1. Open a commander "cmd.exe" and Move to the directory where the source is stored. ``` - cd %CUBRID-SRC%/cubridmanager/server + cd %ARNIADB-SRC%/arniadbmanager/server ``` 2. Execute the build batche file ``` - cmd /c build.bat --prefix=%CUBRID% --with-cubrid-dir=%CUBRID% + cmd /c build.bat --prefix=%ARNIADB% --with-arniadb-dir=%ARNIADB% ``` - - `--prefix=%CUBRID%` : It specifies a directory to be installed. - - `--enable-64bit` : Used to build in a 64-bit environment since supporting 64-bit from CUBRID 2008 R2.0 or higher. - - `--with-cubrid-dir=%CUBRID%` : Option specifies the directory CUBRID is installed. + - `--prefix=%ARNIADB%` : It specifies a directory to be installed. + - `--enable-64bit` : Used to build in a 64-bit environment since supporting 64-bit from ARNIADB 2008 R2.0 or higher. + - `--with-arniadb-dir=%ARNIADB%` : Option specifies the directory ARNIADB is installed. ## PROGRAMMING APIs @@ -85,7 +85,7 @@ If you want to build CMS on windows, VS2008 must be installed. If You encounter any difficulties with getting started, or just have some questions, or find bugs, or have some suggestions, we kindly ask you to -post your thoughts on our subreddit at https://www.reddit.com/r/CUBRID/. +post your thoughts on our subreddit at https://www.reddit.com/r/ARNIADB/. Sincerely, Your CMS Development Team. diff --git a/docs/api/README.md b/docs/api/README.md index da9a9e1..692eefb 100644 --- a/docs/api/README.md +++ b/docs/api/README.md @@ -1,12 +1,12 @@ -# CUBRID Manager Server API Manual +# ARNIADB Manager Server API Manual ## Overview -The CUBRID Manager Server (CMS) HTTP Interface is an interface that exists between the CUBRID manager server and the application client, through which a web-based application client can access the CUBRID manager server. The CUBRID manager server delivers the request received from an application client to the CUBRID, and transfers the execution result to the client. +The ARNIADB Manager Server (CMS) HTTP Interface is an interface that exists between the ARNIADB manager server and the application client, through which a web-based application client can access the ARNIADB manager server. The ARNIADB manager server delivers the request received from an application client to the ARNIADB, and transfers the execution result to the client. ## System Architecture -CMS is a manager tools for CUBRID including database configure, monitor, SQL query. As the component of the CUBRID Database Management System, CMS provides a web-based tool that allows users to remotely manage the database and the Broker. +CMS is a manager tools for ARNIADB including database configure, monitor, SQL query. As the component of the ARNIADB Database Management System, CMS provides a web-based tool that allows users to remotely manage the database and the Broker. ![CMS Architecture](images/architecture.png?raw=true "CMS Architecture") CMS Architecture @@ -56,13 +56,13 @@ There are seven permissions. These permissions can indicate which authorities ar | BRK | Broker Authority - Can only modify brokers (include shard broker | | MON | Monitoring - R/W Configuration | | JOB | Automation Authority - Can only use automations | -| VAR | Show Variable Authority - Can only read cubrid.conf, cubrid_broker.conf, ... etc. | +| VAR | Show Variable Authority - Can only read arniadb.conf, arniadb_broker.conf, ... etc. | | ADMIN | Indicate the authority of admin | | ALL_AUTHORITY | This value is equal to "DBC | DBO | BRK | MON | JOB | VAR" | ## CMS Interfaces -CMs Interfaces are conposed by Json and is used for communication between CMS and Cubrid Manager. +CMs Interfaces are conposed by Json and is used for communication between CMS and Arniadb Manager. ### Broker diff --git a/docs/api/addbackupinfo.md b/docs/api/addbackupinfo.md index e7dfbf0..aebc8e3 100644 --- a/docs/api/addbackupinfo.md +++ b/docs/api/addbackupinfo.md @@ -17,7 +17,7 @@ Add a backup schedule. "token": "cdfb4c5717170c5e51196b3bf16112949ea2e1dcf05030c13351f8d4306356bf7926f07dd201b6aa", "dbname": "demodb", "backupid": "qw", - "path": "$CUBRID_DATABASES/alatestdb/backup", + "path": "$ARNIADB_DATABASES/alatestdb/backup", "period_type": "Special", "period_date": "$AUTO_DATE", "time": "$AUTO_TIME", diff --git a/docs/api/analyzecaslog.md b/docs/api/analyzecaslog.md index 71d94ed..fe74261 100644 --- a/docs/api/analyzecaslog.md +++ b/docs/api/analyzecaslog.md @@ -17,7 +17,7 @@ The analyzecaslog interface will fetch top list to parse broker sql log(s) with "token": "cdfb4c5717170c5e9c6856b4d1c61ee8132bcc7d82bd609066ed9ece2554c47f7926f07dd201b6aa", "logfilelist": [ { - "logfile": "$CUBRID/log/broker/sql_log/query_editor_1.sql.log" + "logfile": "$ARNIADB/log/broker/sql_log/query_editor_1.sql.log" } ], "option_t": "yes" diff --git a/docs/api/backupdb.md b/docs/api/backupdb.md index af364eb..b011a13 100644 --- a/docs/api/backupdb.md +++ b/docs/api/backupdb.md @@ -18,7 +18,7 @@ The backupdb interface will create databases backup file. "dbname": "alatestdb", "level": "0", "volname": "alatestdb_backup_lv0", - "backupdir": "$CUBRID_DATABASES/alatestdb/backup", + "backupdir": "$ARNIADB_DATABASES/alatestdb/backup", "removelog": "n", "check": "y", "mt": "0", diff --git a/docs/api/backupvolinfo.md b/docs/api/backupvolinfo.md index cfe8470..e20be6a 100644 --- a/docs/api/backupvolinfo.md +++ b/docs/api/backupvolinfo.md @@ -17,6 +17,6 @@ The backupvolinfo interface will get databases backup volume information. "token": "cdfb4c5717170c5e9c6856b4d1c61ee8132bcc7d82bd609066ed9ece2554c47f7926f07dd201b6aa", "dbname": "alatestdb", "level": "0", - "pathname": "$CUBRID_DATABASES/alatestdb/backup/alatestdb_backup_lv0" + "pathname": "$ARNIADB_DATABASES/alatestdb/backup/alatestdb_backup_lv0" } ``` diff --git a/docs/api/broker_setparam.md b/docs/api/broker_setparam.md index c1761d5..4c3fed1 100644 --- a/docs/api/broker_setparam.md +++ b/docs/api/broker_setparam.md @@ -35,7 +35,7 @@ Update broker.conf file. "#", "[broker]", "MASTER_SHM_ID=30001", - "ADMIN_LOG_FILE=log/broker/cubrid_broker.log", + "ADMIN_LOG_FILE=log/broker/arniadb_broker.log", "", "", "[%broker1]", diff --git a/docs/api/copydb.md b/docs/api/copydb.md index 6ff345b..806a361 100644 --- a/docs/api/copydb.md +++ b/docs/api/copydb.md @@ -24,9 +24,9 @@ Copy database. "token":"cdfb4c5717170c5edfc2912f2940ab35013dd1336cf7d77e4cfaae281cffa1417926f07dd201b6aa", "srcdbname":"alatestdb", "destdbname":"destinationdb", - "destdbpath":"$CUBRID_DATABASES/destinationdb", - "exvolpath":"$CUBRID_DATABASES/destinationdb", - "logpath":"$CUBRID_DATABASES/destinationdb", + "destdbpath":"$ARNIADB_DATABASES/destinationdb", + "exvolpath":"$ARNIADB_DATABASES/destinationdb", + "logpath":"$ARNIADB_DATABASES/destinationdb", "overwrite":"y", "move":"n", "advanced":"off" diff --git a/docs/api/createdb.md b/docs/api/createdb.md index 5012b97..05e588a 100644 --- a/docs/api/createdb.md +++ b/docs/api/createdb.md @@ -15,7 +15,7 @@ Create database. | genvolpath | data volume path | | logvolpath | log volume path | | exvol | extend volume information | -| charset | language and charset, ex. en_US.iso88591, ko_KR.utf8. please refer to $CUBRID/conf/cubrid_locales.all.txt | +| charset | language and charset, ex. en_US.iso88591, ko_KR.utf8. please refer to $ARNIADB/conf/arniadb_locales.all.txt | ## Request Sample @@ -28,9 +28,9 @@ Create database. "pagesize":"4096", "logsize":"10240", "logpagesize":"4096", - "genvolpath":"$CUBRID_DATABASES/alatestdb", - "logvolpath":"$CUBRID_DATABASES/alatestdb", - "exvol":{"alatestdb_data_x001":"data;100;$CUBRID_DATABASES/alatestdb"}, + "genvolpath":"$ARNIADB_DATABASES/alatestdb", + "logvolpath":"$ARNIADB_DATABASES/alatestdb", + "exvol":{"alatestdb_data_x001":"data;100;$ARNIADB_DATABASES/alatestdb"}, "charset":"en_US.utf8", "overwrite_config_file":"YES" } @@ -84,9 +84,9 @@ Create database. "pagesize":"4096", "logsize":"10240", "logpagesize":"4096", - "genvolpath":"$CUBRID_DATABASES/alatestdb", - "logvolpath":"$CUBRID_DATABASES/alatestdb", - "exvol":{"alatestdb_data_x001":"data;100;$CUBRID_DATABASES/alatestdb"}, + "genvolpath":"$ARNIADB_DATABASES/alatestdb", + "logvolpath":"$ARNIADB_DATABASES/alatestdb", + "exvol":{"alatestdb_data_x001":"data;100;$ARNIADB_DATABASES/alatestdb"}, "overwrite_config_file":"YES" } ``` diff --git a/docs/api/dbspaceinfo.md b/docs/api/dbspaceinfo.md index 598ab32..1155815 100644 --- a/docs/api/dbspaceinfo.md +++ b/docs/api/dbspaceinfo.md @@ -52,7 +52,7 @@ Get specified database space information. { "date" : "20130131", "freepage" : "1192", - "location" : "/home/huangqiyu/cubrid_8.4.3/databases/testdb", + "location" : "/home/huangqiyu/arniadb_8.4.3/databases/testdb", "spacename" : "testdb", "totalpage" : "1280", "type" : "GENERIC" @@ -60,7 +60,7 @@ Get specified database space information. { "date" : "20130131", "freepage" : "0", - "location" : "/home/huangqiyu/cubrid_8.4.3/databases/testdb", + "location" : "/home/huangqiyu/arniadb_8.4.3/databases/testdb", "spacename" : "testdb_v1", "totalpage" : "1000", "type" : "DATA" @@ -68,7 +68,7 @@ Get specified database space information. { "date" : "20130131", "freepage" : "1746", - "location" : "/home/huangqiyu/cubrid_8.4.3/databases/testdb", + "location" : "/home/huangqiyu/arniadb_8.4.3/databases/testdb", "spacename" : "testdb_x002", "totalpage" : "1920", "type" : "DATA" @@ -76,7 +76,7 @@ Get specified database space information. { "date" : "20130131", "freepage" : "385", - "location" : "/home/huangqiyu/cubrid_8.4.3/databases/testdb", + "location" : "/home/huangqiyu/arniadb_8.4.3/databases/testdb", "spacename" : "testdb_t32766", "totalpage" : "434", "type" : "TEMP" @@ -84,7 +84,7 @@ Get specified database space information. { "date" : "20130201", "freepage" : " ", - "location" : "/home/huangqiyu/cubrid_8.4.3/databases/testdb", + "location" : "/home/huangqiyu/arniadb_8.4.3/databases/testdb", "spacename" : "testdb_lgat", "totalpage" : "32768", "type" : "Active_log" @@ -92,7 +92,7 @@ Get specified database space information. { "date" : "20130131", "freepage" : " ", - "location" : "/home/huangqiyu/cubrid_8.4.3/databases/testdb", + "location" : "/home/huangqiyu/arniadb_8.4.3/databases/testdb", "spacename" : "testdb_lgar_t", "totalpage" : "32768", "type" : "Archive_log" diff --git a/docs/api/getaddbrokerinfo.md b/docs/api/getaddbrokerinfo.md index 3c58ad6..b9e8124 100644 --- a/docs/api/getaddbrokerinfo.md +++ b/docs/api/getaddbrokerinfo.md @@ -1,6 +1,6 @@ # getaddbrokerinfo -Get borker configurations from a cubrid_broker.conf file. +Get borker configurations from a arniadb_broker.conf file. ## Request Json Syntax diff --git a/docs/api/getallsysparam.md b/docs/api/getallsysparam.md index c4789bb..6468629 100644 --- a/docs/api/getallsysparam.md +++ b/docs/api/getallsysparam.md @@ -8,7 +8,7 @@ Get configuration files. | --- | --- | | task | task name | | token | token string encrypted. | -| confname | cubridconf, cmconf, haconf, databases | +| confname | arniadbconf, cmconf, haconf, databases | ## Request Sample @@ -16,6 +16,6 @@ Get configuration files. { "task": "getallsysparam", "token": "cdfb4c5717170c5e237a227a2ceeccc6ae9e10c16754fb85371c0d74fa0d9d577926f07dd201b6aa", - "confname": "cubridconf" + "confname": "arniadbconf" } ``` diff --git a/docs/api/getcaslogtopresult.md b/docs/api/getcaslogtopresult.md index 57eb60c..a65cb42 100644 --- a/docs/api/getcaslogtopresult.md +++ b/docs/api/getcaslogtopresult.md @@ -1,6 +1,6 @@ # getcaslogtopresult -Get databases' information in cubrid. +Get databases' information in arniadb. ## Request Json Syntax @@ -18,7 +18,7 @@ Get databases' information in cubrid. { "task": "getcaslogtopresult", "token": "cdfb4c5717170c5e9c6856b4d1c61ee8132bcc7d82bd609066ed9ece2554c47f7926f07dd201b6aa", - "filename": "$CUBRID/tmp/analyzelog_1.res", + "filename": "$ARNIADB/tmp/analyzelog_1.res", "qindex": "[Q14]" } ``` diff --git a/docs/api/getcmsenv.md b/docs/api/getcmsenv.md index 07c2689..103c84f 100644 --- a/docs/api/getcmsenv.md +++ b/docs/api/getcmsenv.md @@ -1,6 +1,6 @@ # getcmsenv -Get databases' information in cubrid. +Get databases' information in arniadb. ## Request Json Syntax diff --git a/docs/api/getdbmtuserinfo.md b/docs/api/getdbmtuserinfo.md index cf4cba9..12c4151 100644 --- a/docs/api/getdbmtuserinfo.md +++ b/docs/api/getdbmtuserinfo.md @@ -1,6 +1,6 @@ # getdbmtuserinfo -The getdbmtuserinfo interface will fetch cubrid manager information. +The getdbmtuserinfo interface will fetch arniadb manager information. ## Request Json Syntax diff --git a/docs/api/getdbprocstat.md b/docs/api/getdbprocstat.md index c41e578..bb2ae42 100644 --- a/docs/api/getdbprocstat.md +++ b/docs/api/getdbprocstat.md @@ -1,6 +1,6 @@ # getdbprocstat -Get databases' information in cubrid. +Get databases' information in arniadb. ## Request Json Syntax diff --git a/docs/api/gethaapplyinfo.md b/docs/api/gethaapplyinfo.md index 3a3e44f..19e6f5a 100644 --- a/docs/api/gethaapplyinfo.md +++ b/docs/api/gethaapplyinfo.md @@ -19,7 +19,7 @@ Get copylog and apply log operations information "task": "gethaapplyinfo", "token": "8ec1ab8a91333c789ca635659ff41d6887cec4cd14324d3baee6412d6bbc1277e3e8c307e2088d187926f07dd201b6aa7926f07dd201b6aa7926f07dd201b6aa", "dbname": "ha_testdb", - "copylogpath": "/home/huangqiyu/cubrid_8.4.3/databases/ha_testdb_DEV_92/", + "copylogpath": "/home/huangqiyu/arniadb_8.4.3/databases/ha_testdb_DEV_92/", "remotehostname": "DEV_92" } ``` diff --git a/docs/api/getloginfo.md b/docs/api/getloginfo.md index 7582ffd..2df532c 100644 --- a/docs/api/getloginfo.md +++ b/docs/api/getloginfo.md @@ -45,67 +45,67 @@ Get database log file information. { "@owner" : "huangqiyu", "lastupdate" : "2013.01.07", - "path" : "/home/huangqiyu/cubrid_8.4.3/log/server/testdb_20130107_1419.err", + "path" : "/home/huangqiyu/arniadb_8.4.3/log/server/testdb_20130107_1419.err", "size" : "0" }, { "@owner" : "huangqiyu", "lastupdate" : "2013.01.31", - "path" : "/home/huangqiyu/cubrid_8.4.3/log/server/testdb_20130131_1823.err", + "path" : "/home/huangqiyu/arniadb_8.4.3/log/server/testdb_20130131_1823.err", "size" : "0" }, { "@owner" : "huangqiyu", "lastupdate" : "2013.01.07", - "path" : "/home/huangqiyu/cubrid_8.4.3/log/server/testdb_20130107_1453.err", + "path" : "/home/huangqiyu/arniadb_8.4.3/log/server/testdb_20130107_1453.err", "size" : "0" }, { "@owner" : "huangqiyu", "lastupdate" : "2013.01.15", - "path" : "/home/huangqiyu/cubrid_8.4.3/log/server/testdb_20130115_1028.err", + "path" : "/home/huangqiyu/arniadb_8.4.3/log/server/testdb_20130115_1028.err", "size" : "0" }, { "@owner" : "huangqiyu", "lastupdate" : "2013.01.10", - "path" : "/home/huangqiyu/cubrid_8.4.3/log/server/testdb_20130110_1528.err", + "path" : "/home/huangqiyu/arniadb_8.4.3/log/server/testdb_20130110_1528.err", "size" : "0" }, { "@owner" : "huangqiyu", "lastupdate" : "2013.01.05", - "path" : "/home/huangqiyu/cubrid_8.4.3/log/server/testdb_20130105_1628.err", + "path" : "/home/huangqiyu/arniadb_8.4.3/log/server/testdb_20130105_1628.err", "size" : "0" }, { "@owner" : "huangqiyu", "lastupdate" : "2013.01.05", - "path" : "/home/huangqiyu/cubrid_8.4.3/log/server/testdb_20130105_1140.err", + "path" : "/home/huangqiyu/arniadb_8.4.3/log/server/testdb_20130105_1140.err", "size" : "9629" }, { "@owner" : "huangqiyu", "lastupdate" : "2013.01.10", - "path" : "/home/huangqiyu/cubrid_8.4.3/log/server/testdb_20130110_1526.err", + "path" : "/home/huangqiyu/arniadb_8.4.3/log/server/testdb_20130110_1526.err", "size" : "0" }, { "@owner" : "huangqiyu", "lastupdate" : "2013.01.05", - "path" : "/home/huangqiyu/cubrid_8.4.3/log/server/testdb_20130105_1525.err", + "path" : "/home/huangqiyu/arniadb_8.4.3/log/server/testdb_20130105_1525.err", "size" : "0" }, { "@owner" : "huangqiyu", "lastupdate" : "2013.01.07", - "path" : "/home/huangqiyu/cubrid_8.4.3/log/server/testdb_20130107_1350.err", + "path" : "/home/huangqiyu/arniadb_8.4.3/log/server/testdb_20130107_1350.err", "size" : "0" }, { "@owner" : "huangqiyu", "lastupdate" : "2013.01.11", - "path" : "/home/huangqiyu/cubrid_8.4.3/log/server/testdb_20130111_1453.err", + "path" : "/home/huangqiyu/arniadb_8.4.3/log/server/testdb_20130111_1453.err", "size" : "0" } } diff --git a/docs/api/gettransactioninfo.md b/docs/api/gettransactioninfo.md index 7b3f94d..b36f60c 100644 --- a/docs/api/gettransactioninfo.md +++ b/docs/api/gettransactioninfo.md @@ -58,7 +58,7 @@ The gettransactioninfo interface fetches databases transactions information. "SQL_ID" : "82353eb5cc51f", "SQL_Text" : "select dept.department_id, dept.employee_name where dept.employee_id = 100", "pid" : "6632", - "program" : "query_editor_cub_cas_1", + "program" : "query_editor_arn_cas_1", "query_time" : "0.40", "tran_time" : "0.40", "tranindex" : "1(ACTIVE)" diff --git a/docs/api/ha_reload.md b/docs/api/ha_reload.md index 0617440..34fc894 100644 --- a/docs/api/ha_reload.md +++ b/docs/api/ha_reload.md @@ -1,6 +1,6 @@ # ha_reload -Runs `cubrid heartbeat reload` command. +Runs `arniadb heartbeat reload` command. ## Request Json Syntax diff --git a/docs/api/ha_start.md b/docs/api/ha_start.md index 27599b3..dfc8a1c 100644 --- a/docs/api/ha_start.md +++ b/docs/api/ha_start.md @@ -1,6 +1,6 @@ # ha_start -Runs `cubrid heartbeat start` command. +Runs `arniadb heartbeat start` command. ## Request Json Syntax diff --git a/docs/api/ha_status.md b/docs/api/ha_status.md index 0d0b087..397b3f4 100644 --- a/docs/api/ha_status.md +++ b/docs/api/ha_status.md @@ -1,6 +1,6 @@ # ha_status -Runs `cubrid heartbeat status` command. +Runs `arniadb heartbeat status` command. ## Request Json Syntax diff --git a/docs/api/ha_stop.md b/docs/api/ha_stop.md index de8b500..5e86264 100644 --- a/docs/api/ha_stop.md +++ b/docs/api/ha_stop.md @@ -1,6 +1,6 @@ # ha_stop -Runs `cubrid heartbeat stop` command. +Runs `arniadb heartbeat stop` command. ## Request Json Syntax diff --git a/docs/api/heartbeatlist.md b/docs/api/heartbeatlist.md index aff1183..7488262 100644 --- a/docs/api/heartbeatlist.md +++ b/docs/api/heartbeatlist.md @@ -1,6 +1,6 @@ # heartbeatlist -Runs `cubrid heartbeat list` command. +Runs `arniadb heartbeat list` command. ## Request Json Syntax diff --git a/docs/api/killtransaction.md b/docs/api/killtransaction.md index c083aac..2f8d971 100644 --- a/docs/api/killtransaction.md +++ b/docs/api/killtransaction.md @@ -68,7 +68,7 @@ other letters should cause an error.  "@user" : "DBA", "host" : "huangqiyu-VirtualBox", "pid" : "6632", - "program" : "query_editor_cub_cas_1", + "program" : "query_editor_arn_cas_1", "tranindex" : "1(ACTIVE)" } } diff --git a/docs/api/loaddb.md b/docs/api/loaddb.md index 2cf5c2a..f78a513 100644 --- a/docs/api/loaddb.md +++ b/docs/api/loaddb.md @@ -35,8 +35,8 @@ The loaddb interface will load database from files. "estimated": "none", "oiduse": "yes", "nolog": "no", - "schema": "$CUBRID_DATABASES/demodb/demodb_schema", - "object": "$CUBRID_DATABASES/demodb/demodb_objects", + "schema": "$ARNIADB_DATABASES/demodb/demodb_schema", + "object": "$ARNIADB_DATABASES/demodb/demodb_objects", "index": "none", "errorcontrolfile": "none", "ignoreclassfile": "none", diff --git a/docs/api/monitorprocess.md b/docs/api/monitorprocess.md index 94a3964..21c3ed0 100644 --- a/docs/api/monitorprocess.md +++ b/docs/api/monitorprocess.md @@ -25,13 +25,13 @@ Monitor CMS process status. | task | task name | | status | execution result, success or failed. | | note | if failed, a brief description will be given here | -| cub_master | the value should be "exist" or "don't exist" in order to indicate whether this process exists. | +| arn_master | the value should be "exist" or "don't exist" in order to indicate whether this process exists. | ## Response Sample ``` { - "cub_master": "don't exist", + "arn_master": "don't exist", "note": "none", "status": "success", "task": "monitorprocess" diff --git a/docs/api/renamedb.md b/docs/api/renamedb.md index dd745b1..30ae294 100644 --- a/docs/api/renamedb.md +++ b/docs/api/renamedb.md @@ -24,7 +24,7 @@ Rename database. "rename":"anotherdb", "exvolpath":"none", "advanced":"on", - "volume":{"$CUBRID_DATABASES/destinationdb/destinationdb":"$CUBRID_DATABASES/anotherdb/anotherdb"}, + "volume":{"$ARNIADB_DATABASES/destinationdb/destinationdb":"$ARNIADB_DATABASES/anotherdb/anotherdb"}, "forcedel":"y" } ``` diff --git a/docs/api/restoredb.md b/docs/api/restoredb.md index 9a0cef9..1fd8609 100644 --- a/docs/api/restoredb.md +++ b/docs/api/restoredb.md @@ -25,7 +25,7 @@ The restoredb interface will restore database from backup. "date": "none", "level": "0", "partial": "y", - "pathname": "$CUBRID_DATABASES/alatestdb/backup/alatestdb_backup_lv0", - "recoverypath": "$CUBRID_DATABASES/alatestdb" + "pathname": "$ARNIADB_DATABASES/alatestdb/backup/alatestdb_backup_lv0", + "recoverypath": "$ARNIADB_DATABASES/alatestdb" } ``` diff --git a/docs/api/setbackupinfo.md b/docs/api/setbackupinfo.md index 78ed877..d91a520 100644 --- a/docs/api/setbackupinfo.md +++ b/docs/api/setbackupinfo.md @@ -29,7 +29,7 @@ Add an auto-backup plan "token": "cdfb4c5717170c5e9c6856b4d1c61ee8132bcc7d82bd609066ed9ece2554c47f7926f07dd201b6aa", "dbname": "alatestdb", "backupid": "qw", - "path": "$CUBRID_DATABASES/alatestdb/backup", + "path": "$ARNIADB_DATABASES/alatestdb/backup", "period_type": "Special", "period_date": "$AUTO_DATE", "time": "$AUTO_TIME", diff --git a/docs/api/setsysparam.md b/docs/api/setsysparam.md index 0cfeb38..b173a05 100644 --- a/docs/api/setsysparam.md +++ b/docs/api/setsysparam.md @@ -17,7 +17,7 @@ Update configuration files. { "task": "setsysparam", "token": "cdfb4c5717170c5e9c6856b4d1c61ee8132bcc7d82bd609066ed9ece2554c47f7926f07dd201b6aa", - "confname": "cubridconf", + "confname": "arniadbconf", "confdata": [ "#", "# Copyright (C) 2009 Search Solution Corporation. All rights reserved by Search Solution.", @@ -38,19 +38,19 @@ Update configuration files. "#", "# $Id$", "#", - "# cubrid.conf", + "# arniadb.conf", "#", - "# For complete information on parameters, see the CUBRID", + "# For complete information on parameters, see the ARNIADB", "# Database Administration Guide chapter on System Parameters", "", - "# Service section - a section for 'cubrid service' command", + "# Service section - a section for 'arniadb service' command", "[service]", "", - "# The list of processes to be started automatically by 'cubrid service start' command", + "# The list of processes to be started automatically by 'arniadb service start' command", "# Any combinations are available with server, broker and manager.", "service=server,broker,manager", "", - "# The list of database servers in all by 'cubrid service start' command.", + "# The list of database servers in all by 'arniadb service start' command.", "# This property is effective only when the above 'service' property contains 'server' keyword.", "server=demodb", "", @@ -73,8 +73,8 @@ Update configuration files. "# This value also means the total # of concurrent transactions.", "max_clients=100", "", - "# TCP port id for the CUBRID programs (used by all clients).", - "cubrid_port_id=1523" + "# TCP port id for the ARNIADB programs (used by all clients).", + "arniadb_port_id=1523" ] } ``` diff --git a/docs/api/startinfo.md b/docs/api/startinfo.md index df3c61f..d460cf8 100644 --- a/docs/api/startinfo.md +++ b/docs/api/startinfo.md @@ -1,6 +1,6 @@ # startinfo -Get databases' information in cubrid. +Get databases' information in arniadb. ## Request Json Syntax @@ -30,7 +30,7 @@ Get databases' information in cubrid. | task | task name | | status | execution result, success or failed. | | note | if failed, a brief description will be given here | -| dblist | the whole databases in the cubrid, including its name and path.  | +| dblist | the whole databases in the arniadb, including its name and path.  | | activelist | get the databaes' name in active status. | @@ -51,15 +51,15 @@ Get databases' information in cubrid. { "dbs" : [ { - "dbdir" : "/home/huangqiyu/cubrid_8.4.3/databases/testdb3", + "dbdir" : "/home/huangqiyu/arniadb_8.4.3/databases/testdb3", "dbname" : "testdb3" }, { - "dbdir" : "/home/huangqiyu/cubrid_8.4.3/databases/testdb2", + "dbdir" : "/home/huangqiyu/arniadb_8.4.3/databases/testdb2", "dbname" : "testdb2" }, { - "dbdir" : "/home/huangqiyu/cubrid_8.4.3/databases/testdb", + "dbdir" : "/home/huangqiyu/arniadb_8.4.3/databases/testdb", "dbname" : "testdb" } } diff --git a/docs/api/unloaddb.md b/docs/api/unloaddb.md index de38bfc..719f911 100644 --- a/docs/api/unloaddb.md +++ b/docs/api/unloaddb.md @@ -30,7 +30,7 @@ The unloaddb interface will unload database server. "task": "unloaddb", "token": "cdfb4c5717170c5e34919b640249979f8375a218acf865b0b8100f0f25c069587926f07dd201b6aa", "dbname": "demodb", - "targetdir": "$CUBRID_DATABASES/demodb", + "targetdir": "$ARNIADB_DATABASES/demodb", "usehash": "no", "hashdir": "none", "target": "both", diff --git a/docs/api/userinfo.md b/docs/api/userinfo.md index 3f19817..cd1ad90 100644 --- a/docs/api/userinfo.md +++ b/docs/api/userinfo.md @@ -1,6 +1,6 @@ # userinfo -Get Databases' user information in cubrid. +Get Databases' user information in arniadb. ## Request Json Syntax diff --git a/docs/api/viewlogviewlog2.md b/docs/api/viewlogviewlog2.md index 00e4b79..8abc681 100644 --- a/docs/api/viewlogviewlog2.md +++ b/docs/api/viewlogviewlog2.md @@ -19,7 +19,7 @@ Viwe specified log file. "task":"viewlog", "token":"cdfb4c5717170c5e9c6856b4d1c61ee8132bcc7d82bd609066ed9ece2554c47f7926f07dd201b6aa", "dbname":"demodb", - "path":"$CUBRID/log/manager/cub_js.access.log", + "path":"$ARNIADB/log/manager/arn_js.access.log", "start":"1", "end":"1000" } @@ -58,7 +58,7 @@ Viwe specified log file. "Number of pages was not given on line 1.", "", "Time: 01/07/13 14:44:06.484 - ERROR *** file ../../src/transaction/boot_sr.c, line 2827 ERROR CODE = -123 Tran = -1, EID = 3", - "Unable to create \"allvols\" for database \"/home/huangqiyu/cubrid_8.4.3/databases/testdb/testdb\".", + "Unable to create \"allvols\" for database \"/home/huangqiyu/arniadb_8.4.3/databases/testdb/testdb\".", "", "*** The previous error message is the last one. ***", "", @@ -67,14 +67,14 @@ Viwe specified log file. "Number of pages was not given on line 1.", "", "Time: 01/07/13 14:45:25.822 - ERROR *** file ../../src/transaction/boot_sr.c, line 2827 ERROR CODE = -123 Tran = -1, EID = 2", - "Unable to create \"allvols\" for database \"/home/huangqiyu/cubrid_8.4.3/databases/testdb/testdb\".", + "Unable to create \"allvols\" for database \"/home/huangqiyu/arniadb_8.4.3/databases/testdb/testdb\".", "", "*** The previous error message is the last one. ***", "" } ], "note" : "none", - "path" : "/home/huangqiyu/cubrid_8.4.3/log/testdb_createdb.err", + "path" : "/home/huangqiyu/arniadb_8.4.3/log/testdb_createdb.err", "start" : "1", "status" : "success", "task" : "viewlog", diff --git a/server/build_cms_env.sh b/server/build_cms_env.sh index a4d0b83..4196b42 100644 --- a/server/build_cms_env.sh +++ b/server/build_cms_env.sh @@ -29,42 +29,42 @@ cp src/lib_json/libjson.a /usr/local/lib cd .. -#build cubrid -wget ftp://ftp.cubrid.org/CUBRID_Engine/8.4.1/Linux/CUBRID-8.4.1.2032.src.tar.gz -tar xzvf CUBRID-8.4.1.2032.src.tar.gz +#build arniadb +wget ftp://ftp.arniadb.org/ARNIADB_Engine/8.4.1/Linux/ARNIADB-8.4.1.2032.src.tar.gz +tar xzvf ARNIADB-8.4.1.2032.src.tar.gz -cd cubrid-8.4.1.2032 +cd arniadb-8.4.1.2032 ./configure --enable-64bit --enable-debug make make install -#configure cubrid env +#configure arniadb env -cat >> .cubrid.sh << EOF +cat >> .arniadb.sh << EOF #!/bin/bash -CUBRID=/root/cubrid -CUBRID_DATABASES=/root/cubrid/databases -CUBRID_LANG=en_US +ARNIADB=/root/arniadb +ARNIADB_DATABASES=/root/arniadb/databases +ARNIADB_LANG=en_US ld_lib_path=`printenv LD_LIBRARY_PATH` if [ "$ld_lib_path" = "" ] then -LD_LIBRARY_PATH=$CUBRID/lib +LD_LIBRARY_PATH=$ARNIADB/lib else -LD_LIBRARY_PATH=$CUBRID/lib:$LD_LIBRARY_PATH +LD_LIBRARY_PATH=$ARNIADB/lib:$LD_LIBRARY_PATH fi SHLIB_PATH=$LD_LIBRARY_PATH LIBPATH=$LD_LIBRARY_PATH -PATH=$CUBRID/bin:$CUBRID/cubridmanager:$PATH -export CUBRID -export CUBRID_DATABASES -export CUBRID_LANG +PATH=$ARNIADB/bin:$ARNIADB/arniadbmanager:$PATH +export ARNIADB +export ARNIADB_DATABASES +export ARNIADB_LANG export LD_LIBRARY_PATH export SHLIB_PATH export LIBPATH export PATH EOF -chmod +x .cubrid.sh -./.cubrid.sh +chmod +x .arniadb.sh +./.arniadb.sh -mkdir $CUBRID_DATABASES +mkdir $ARNIADB_DATABASES diff --git a/server/build_internal.bat b/server/build_internal.bat index edd41c7..ce0a31e 100644 --- a/server/build_internal.bat +++ b/server/build_internal.bat @@ -2,7 +2,7 @@ if "%1" == "" goto PRINT_USAGE -set cubrid_dir=%CUBRID% +set arniadb_dir=%ARNIADB% set platform=Win32 set mode=release @@ -12,30 +12,30 @@ if "%1" == "" goto LOOP_END if "%1" == "--help" goto PRINT_USAGE if "%1" == "--prefix" set prefix=%2& shift & shift & goto LOOP_BEGIN -if "%1" == "--with-cubrid-dir" set cubrid_dir=%2& shift & shift & goto LOOP_BEGIN -if "%1" == "--with-cubrid-libdir" set cubrid_libdir=%2& shift & shift & goto LOOP_BEGIN -if "%1" == "--with-cubrid-includedir" set cubrid_includedir=%2& shift & shift & goto LOOP_BEGIN +if "%1" == "--with-arniadb-dir" set arniadb_dir=%2& shift & shift & goto LOOP_BEGIN +if "%1" == "--with-arniadb-libdir" set arniadb_libdir=%2& shift & shift & goto LOOP_BEGIN +if "%1" == "--with-arniadb-includedir" set arniadb_includedir=%2& shift & shift & goto LOOP_BEGIN if "%1" == "--enable-64bit" set platform=x64& shift & goto LOOP_BEGIN if "%1" == "--enable-debug" set mode=debug& shift & goto LOOP_BEGIN shift :LOOP_END -if "%cubrid_libdir%" == "" ( - set cubrid_libdir=%cubrid_dir%\lib +if "%arniadb_libdir%" == "" ( + set arniadb_libdir=%arniadb_dir%\lib ) -if "%cubrid_includedir%" == "" ( - set cubrid_includedir=%cubrid_dir%\include +if "%arniadb_includedir%" == "" ( + set arniadb_includedir=%arniadb_dir%\include ) -if "%cubrid_libdir%" == "\lib" ( - echo "Please specify --with-cubrid-libdir option" +if "%arniadb_libdir%" == "\lib" ( + echo "Please specify --with-arniadb-libdir option" exit /B 1 ) -if "%cubrid_includedir%" == "\include" ( - echo "Please specify --with-cubrid-includedir option" +if "%arniadb_includedir%" == "\include" ( + echo "Please specify --with-arniadb-includedir option" exit /B 1 ) @@ -44,8 +44,8 @@ if "%prefix%" == "" ( exit /B 1 ) -echo CUBRID include path is %cubrid_libdir% -echo CUBRID lib path is %cubrid_includedir% +echo ARNIADB include path is %arniadb_libdir% +echo ARNIADB lib path is %arniadb_includedir% echo OUTPUT path is %prefix% echo Platform type is "%platform%" @@ -76,19 +76,19 @@ exit /b :PRINT_USAGE @echo Usage: build [OPTION] -@echo Build whole CUBRID Manager project +@echo Build whole ARNIADB Manager project @echo. @echo --prefix=DIR build result output directory (required) -@echo --with-cubrid-dir=DIR directory have two sub directory (optional) -@echo 'include', 'lib'. default to %%CUBRID%% -@echo --with-cubrid-libdir=DIR directory have cubrid lib files (optional) -@echo default to with_cubrid_dir\lib -@echo --with-cubrid-includedir=DIR directory have cubrid include files (optional) -@echo default to with_cubrid_dir\include +@echo --with-arniadb-dir=DIR directory have two sub directory (optional) +@echo 'include', 'lib'. default to %%ARNIADB%% +@echo --with-arniadb-libdir=DIR directory have arniadb lib files (optional) +@echo default to with_arniadb_dir\lib +@echo --with-arniadb-includedir=DIR directory have arniadb include files (optional) +@echo default to with_arniadb_dir\include @echo --enable-64bit build 64bit applications @echo --enable-debug build debug version applications @echo. @echo --help display this help and exit @echo. @echo Examples: -@echo build --prefix=c:\out\x64 --with-cubrid-dir=%%CUBRID%% +@echo build --prefix=c:\out\x64 --with-arniadb-dir=%%ARNIADB%% diff --git a/server/build_server.bat b/server/build_server.bat index a6dd7fd..ea806a2 100644 --- a/server/build_server.bat +++ b/server/build_server.bat @@ -7,8 +7,8 @@ call "%VS90COMNTOOLS%vsvars32.bat" echo Start build cm_server ... cd win -set cubrid_libdir=%cubrid_libdir% -set cubrid_includedir=%cubrid_includedir% +set arniadb_libdir=%arniadb_libdir% +set arniadb_includedir=%arniadb_includedir% cmd /c devenv cmserver.sln /project install /rebuild "%mode%|%platform%" set exitcode=%errorlevel% diff --git a/server/cmserver/Makefile.am b/server/cmserver/Makefile.am index de364e5..28f5f95 100644 --- a/server/cmserver/Makefile.am +++ b/server/cmserver/Makefile.am @@ -27,7 +27,7 @@ INCLUDES = @SRC_INC@ DEFS += @SYS_DEFS@ @VERSION_DEFS@ @COMMON_DEFS@ LIBS += @SYS_LIBS@ -bin_PROGRAMS = cm_admin cub_manager +bin_PROGRAMS = cm_admin arn_manager cm_admin_SOURCES = \ $(DBMT_DIR)/cm_text_encryption.c \ @@ -41,7 +41,7 @@ cm_admin_SOURCES = \ cm_admin_CFLAGS = -D_FILE_OFFSET_BITS=64 cm_admin_LDFLAGS = @CMDEP_LIB@ -D_FILE_OFFSET_BITS=64 -cub_manager_SOURCES = \ +arn_manager_SOURCES = \ $(DBMT_DIR)/cm_server_util.cpp \ $(DBMT_DIR)/cm_autojob.cpp \ $(DBMT_DIR)/cm_text_encryption.c \ @@ -58,5 +58,5 @@ cub_manager_SOURCES = \ $(DBMT_DIR)/cm_server_interface.cpp \ $(DBMT_DIR)/cm_cci_interface.cpp \ $(DBMT_DIR)/cm_server_autoupdate.cpp -cub_manager_CPPFLAGS = $(AM_CFLAGS) -DFSERVER_SLAVE -DJSON_SUPPORT -DEVENT__HAVE_OPENSSL -D_FILE_OFFSET_BITS=64 @EXTERNAL_INC@ -cub_manager_LDFLAGS = -lcubridcs @CMSTAT_LIB@ @CMDEP_LIB@ @EXTERNAL_LIB@ -lrt -lcascci +arn_manager_CPPFLAGS = $(AM_CFLAGS) -DFSERVER_SLAVE -DJSON_SUPPORT -DEVENT__HAVE_OPENSSL -D_FILE_OFFSET_BITS=64 @EXTERNAL_INC@ +arn_manager_LDFLAGS = -larniadbcs @CMSTAT_LIB@ @CMDEP_LIB@ @EXTERNAL_LIB@ -lrt -lcascci diff --git a/server/cmserver/conf/cm.conf b/server/cmserver/conf/cm.conf index d8a7ea5..9db30d1 100644 --- a/server/cmserver/conf/cm.conf +++ b/server/cmserver/conf/cm.conf @@ -1,19 +1,19 @@ # cm.conf -# -- CUBRID database management tool server configuration file +# -- ARNIADB database management tool server configuration file # # # When server starts, it looks for the environment variable -# 'CUBRID_MANAGER' and use it to locate this file. It is assumed that -# 'CUBRID_MANAGER' is the root directory of all CUBRID Manager related files. +# 'ARNIADB_MANAGER' and use it to locate this file. It is assumed that +# 'ARNIADB_MANAGER' is the root directory of all ARNIADB Manager related files. # -# Manager server section - a section for 'cubrid service' command -# Common section - properties for CUBRID Manager Server +# Manager server section - a section for 'arniadb service' command +# Common section - properties for ARNIADB Manager Server # This section will be applied before starting manager server. [cm] # # Port number designation -# A port for the connection between CUBRID Manager server and Client. -# CUBRID Manager server uses the value cm_port. +# A port for the connection between ARNIADB Manager server and Client. +# ARNIADB Manager server uses the value cm_port. # The default value is 8001. # cm_port=8001 @@ -24,7 +24,7 @@ cm_port=8001 cm_process_monitor_interval=5 # -# Allowing Multiple connection with one CUBRID Manager user. +# Allowing Multiple connection with one ARNIADB Manager user. # allow_user_multi_connection=YES @@ -54,7 +54,7 @@ auto_job_timeout=43200 # # support monitoring statistic (YES/NO), default NO -# If you want to use the advanced monitoring feature on CUBRID Manager, +# If you want to use the advanced monitoring feature on ARNIADB Manager, # you should set this value to YES. # support_mon_statistic=NO diff --git a/server/configure.ac b/server/configure.ac index d10e60b..3ab88d2 100644 --- a/server/configure.ac +++ b/server/configure.ac @@ -2,9 +2,9 @@ # Process this file with autoconf to produce a configure script. AC_PREREQ(2.59) -AC_INIT([CUBRID 2008], RELEASE, , cubrid) +AC_INIT([ARNIADB 2008], RELEASE, , arniadb) -AC_PREFIX_DEFAULT("${CUBRID}") +AC_PREFIX_DEFAULT("${ARNIADB}") AC_CONFIG_SRCDIR([src/cm_autojob.cpp]) AC_CONFIG_AUX_DIR(config) @@ -41,7 +41,7 @@ AM_CONDITIONAL([BUILD_64], [test "$bit_model" = "yes"]) if test x"$prefix" = x"NONE" then - prefix="${CUBRID}" + prefix="${ARNIADB}" fi #System type @@ -210,46 +210,46 @@ then CXXFLAGS="$CXXFLAGS -g -pg" fi -AC_ARG_WITH([cubrid-dir], - AS_HELP_STRING([--with-cubrid-dir=PATH], - [directory for cubrid @<:@default=$CUBRID@:>@]), - [CUBRID_DIR=$withval], - [CUBRID_DIR="${CUBRID}"]) - -AC_MSG_CHECKING([cubrid lib directory]) -AC_ARG_WITH([cubrid-libdir], - AS_HELP_STRING([--with-cubrid-libdir=PATH], - [directory for cubrid lib files @<:@default=with-cubrid-dir/lib@:>@]), - [CUBRID_LIBDIR=$withval], - [CUBRID_LIBDIR="$CUBRID_DIR/lib"]) -AC_MSG_RESULT($CUBRID_LIBDIR) - -AC_MSG_CHECKING([cubrid include directory]) -AC_ARG_WITH([cubrid-includedir], - AS_HELP_STRING([--with-cubrid-includedir=PATH], - [directory for cubrid include files @<:@default=with-cubrid-dir/include@:>@]), - [CUBRID_INCLUDEDIR=$withval], - [CUBRID_INCLUDEDIR="$CUBRID_DIR/include"]) -AC_MSG_RESULT($CUBRID_INCLUDEDIR) - - -if test x"$CUBRID_LIBDIR" = x"/lib" +AC_ARG_WITH([arniadb-dir], + AS_HELP_STRING([--with-arniadb-dir=PATH], + [directory for arniadb @<:@default=$ARNIADB@:>@]), + [ARNIADB_DIR=$withval], + [ARNIADB_DIR="${ARNIADB}"]) + +AC_MSG_CHECKING([arniadb lib directory]) +AC_ARG_WITH([arniadb-libdir], + AS_HELP_STRING([--with-arniadb-libdir=PATH], + [directory for arniadb lib files @<:@default=with-arniadb-dir/lib@:>@]), + [ARNIADB_LIBDIR=$withval], + [ARNIADB_LIBDIR="$ARNIADB_DIR/lib"]) +AC_MSG_RESULT($ARNIADB_LIBDIR) + +AC_MSG_CHECKING([arniadb include directory]) +AC_ARG_WITH([arniadb-includedir], + AS_HELP_STRING([--with-arniadb-includedir=PATH], + [directory for arniadb include files @<:@default=with-arniadb-dir/include@:>@]), + [ARNIADB_INCLUDEDIR=$withval], + [ARNIADB_INCLUDEDIR="$ARNIADB_DIR/include"]) +AC_MSG_RESULT($ARNIADB_INCLUDEDIR) + + +if test x"$ARNIADB_LIBDIR" = x"/lib" then - AC_MSG_ERROR([--with-cubrid-libdir option not set properly, must not be empty!]) -elif test x"$CUBRID_INCLUDEDIR" = x"/include" + AC_MSG_ERROR([--with-arniadb-libdir option not set properly, must not be empty!]) +elif test x"$ARNIADB_INCLUDEDIR" = x"/include" then - AC_MSG_ERROR([--with-cubrid-includedir option not set properly, must not be empty!]) + AC_MSG_ERROR([--with-arniadb-includedir option not set properly, must not be empty!]) else - if test ! -d $CUBRID_LIBDIR; then - AC_MSG_ERROR([--with-cubrid-libdir option not set properly, direcoty "$CUBRID_LIBDIR" is not exist.]) + if test ! -d $ARNIADB_LIBDIR; then + AC_MSG_ERROR([--with-arniadb-libdir option not set properly, direcoty "$ARNIADB_LIBDIR" is not exist.]) fi - if test ! -d $CUBRID_INCLUDEDIR; then - AC_MSG_ERROR([--with-cubrid-includedir option not set properly, direcoty "$CUBRID_INCLUDEDIR" is not exist.]) + if test ! -d $ARNIADB_INCLUDEDIR; then + AC_MSG_ERROR([--with-arniadb-includedir option not set properly, direcoty "$ARNIADB_INCLUDEDIR" is not exist.]) fi - CUBCS_LIB="-lcubridcs" - CMDEP_LIB="-L$CUBRID_LIBDIR -lcmdep $CUBCS_LIB" - CMSTAT_LIB="-L$CUBRID_LIBDIR -lcmstat $CMSTAT_LIB" - SRC_INC="-I$CUBRID_INCLUDEDIR" + ARNCS_LIB="-larniadbcs" + CMDEP_LIB="-L$ARNIADB_LIBDIR -lcmdep $ARNCS_LIB" + CMSTAT_LIB="-L$ARNIADB_LIBDIR -lcmstat $CMSTAT_LIB" + SRC_INC="-I$ARNIADB_INCLUDEDIR" fi if test -e "$srcdir/build_external.sh"; then diff --git a/server/external/README b/server/external/README index 2a6fd65..a3ddbcb 100644 --- a/server/external/README +++ b/server/external/README @@ -1,6 +1,6 @@ -CUBRID Manager Server System +ARNIADB Manager Server System ============================= -CUBRID Manager Server(CMS) use some 3rd software, like openssl, libevent and json. +ARNIADB Manager Server(CMS) use some 3rd software, like openssl, libevent and json. The following is steps to compile them by yourself. ============== @@ -74,4 +74,4 @@ nmake OPENSSL_DIR=F:\openssl /f Makefile.nmake Sincerely, -Your CMS Development Team. \ No newline at end of file +Your CMS Development Team. diff --git a/server/hudsonbuild.cmd b/server/hudsonbuild.cmd index 6955962..2a931bd 100644 --- a/server/hudsonbuild.cmd +++ b/server/hudsonbuild.cmd @@ -25,18 +25,18 @@ fi ######### run test ############# case x$1 in xtest) -cp $CUBRID/conf/cubrid.conf $CRT_PATH/test/task_test_config/orign/ -#cp $CRT_PATH/test/task_test_config/ha_conf/cubrid.conf $CUBRID/conf/ -cp -f $CRT_PATH/test/task_test_config/cm_conf/*.conf $CUBRID/conf/ +cp $ARNIADB/conf/arniadb.conf $CRT_PATH/test/task_test_config/orign/ +#cp $CRT_PATH/test/task_test_config/ha_conf/arniadb.conf $ARNIADB/conf/ +cp -f $CRT_PATH/test/task_test_config/cm_conf/*.conf $ARNIADB/conf/ -cubrid service restart -cubrid server start demodb +arniadb service restart +arniadb server start demodb cd test/ ./hudsonbuild.sh -cubrid service stop +arniadb service stop -#cp $CRT_PATH/test/task_test_config/orign/cubrid.conf $CUBRID/conf/ +#cp $CRT_PATH/test/task_test_config/orign/arniadb.conf $ARNIADB/conf/ echo "test done!" ;; diff --git a/server/set_hudson_env.sh b/server/set_hudson_env.sh index 0a77022..cc7e865 100644 --- a/server/set_hudson_env.sh +++ b/server/set_hudson_env.sh @@ -1,19 +1,19 @@ -CUBRID=/home/hudson/workspace/jobs/CUBRID-CM-Common-8.4.1/deploy -CUBRID_DATABASES=$CUBRID/databases -CUBRID_LANG=en_US +ARNIADB=/home/hudson/workspace/jobs/ARNIADB-CM-Common-8.4.1/deploy +ARNIADB_DATABASES=$ARNIADB/databases +ARNIADB_LANG=en_US ld_lib_path=`printenv LD_LIBRARY_PATH` if [ "$ld_lib_path" = "" ] then -LD_LIBRARY_PATH=$CUBRID/lib +LD_LIBRARY_PATH=$ARNIADB/lib else -LD_LIBRARY_PATH=$CUBRID/lib:$LD_LIBRARY_PATH +LD_LIBRARY_PATH=$ARNIADB/lib:$LD_LIBRARY_PATH fi SHLIB_PATH=$LD_LIBRARY_PATH LIBPATH=$LD_LIBRARY_PATH -PATH=$CUBRID/bin:$CUBRID/cubridmanager:$PATH -export CUBRID -export CUBRID_DATABASES -export CUBRID_LANG +PATH=$ARNIADB/bin:$ARNIADB/arniadbmanager:$PATH +export ARNIADB +export ARNIADB_DATABASES +export ARNIADB_LANG export LD_LIBRARY_PATH export SHLIB_PATH export LIBPATH diff --git a/server/src/cm_auto_task.cpp b/server/src/cm_auto_task.cpp index 43e2a76..3b679c7 100644 --- a/server/src/cm_auto_task.cpp +++ b/server/src/cm_auto_task.cpp @@ -181,20 +181,20 @@ ts_get_server_version (nvplist *req, nvplist *res) char tmpfile[PATH_MAX]; char strbuf[1024]; FILE *infile; - char cmd_name[CUBRID_CMD_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; const char *argv[5]; nv_update_val (res, "task", "getversion"); snprintf (tmpfile, PATH_MAX - 1, "%s/DBMT_task_015", sco.dbmt_tmp_dir); cmd_name[0] = '\0'; - snprintf (cmd_name, sizeof (cmd_name) - 1, "%s/%s%s", sco.szCubrid, - CUBRID_DIR_BIN, UTIL_CUBRID_REL_NAME); + snprintf (cmd_name, sizeof (cmd_name) - 1, "%s/%s%s", sco.szArniadb, + ARNIADB_DIR_BIN, UTIL_ARNIADB_REL_NAME); argv[0] = cmd_name; argv[1] = NULL; - run_child (argv, 1, NULL, tmpfile, NULL, NULL); /* cubrid_rel */ + run_child (argv, 1, NULL, tmpfile, NULL, NULL); /* arniadb_rel */ if ((infile = fopen (tmpfile, "r")) != NULL) { @@ -203,12 +203,12 @@ ts_get_server_version (nvplist *req, nvplist *res) uRemoveCRLF (strbuf); fclose (infile); unlink (tmpfile); - nv_add_nvp (res, "CUBRIDVER", strbuf); + nv_add_nvp (res, "ARNIADBVER", strbuf); nv_update_val (res, "status", "success"); } else { - nv_add_nvp (res, "CUBRIDVER", "none"); + nv_add_nvp (res, "ARNIADBVER", "none"); nv_update_val (res, "status", "failure"); nv_update_val (res, "note", "version information not available"); return 0; diff --git a/server/src/cm_autojob.cpp b/server/src/cm_autojob.cpp index f129c54..b855884 100644 --- a/server/src/cm_autojob.cpp +++ b/server/src/cm_autojob.cpp @@ -260,7 +260,7 @@ aj_add_volume (char *dbname, const char *type, int increase, time_t mytime; int retval; char log_file_name[512]; - char cmd_name[CUBRID_CMD_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; char inc_str[128]; const char *argv[16]; int argc = 0; @@ -294,7 +294,7 @@ aj_add_volume (char *dbname, const char *type, int increase, nt_style_path (dbloca, dbloca); #endif - cubrid_cmd_name (cmd_name); + arniadb_cmd_name (cmd_name); argv[argc++] = cmd_name; argv[argc++] = UTIL_OPTION_ADDVOLDB; argv[argc++] = "--" ADDVOL_FILE_PATH_L; @@ -324,7 +324,7 @@ aj_add_volume (char *dbname, const char *type, int increase, mytime = 0; - all_volumes = cmd_spacedb (dbname, CUBRID_MODE_CS); + all_volumes = cmd_spacedb (dbname, ARNIADB_MODE_CS); if (all_volumes == NULL) { return; @@ -399,10 +399,10 @@ aj_autohistory_handler (void *ajp, time_t prev_check_time, time_t cur_time) { time_to_str (mytime, "%04d%02d%02d.%02d%02d%02d", timestr, TIME_STR_FMT_DATE_TIME); -#if !defined (DO_NOT_USE_CUBRIDENV) - sprintf (strbuf, "%s/logs/_dbmt_history.%s", sco.szCubrid, timestr); +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (strbuf, "%s/logs/_dbmt_history.%s", sco.szArniadb, timestr); #else - sprintf (strbuf, "%s/_dbmt_history.%s", CUBRID_LOGDIR, timestr); + sprintf (strbuf, "%s/_dbmt_history.%s", ARNIADB_LOGDIR, timestr); #endif hsp->hfile = fopen (strbuf, "w"); } @@ -511,11 +511,11 @@ aj_autoaddvoldb_handler (void *hd, time_t prev_check_time, time_t cur_time) { append_host_to_dbname (dbname_at_hostname, curr->dbname, sizeof (dbname_at_hostname)); - spacedb_res = cmd_spacedb (dbname_at_hostname, CUBRID_MODE_CS); + spacedb_res = cmd_spacedb (dbname_at_hostname, ARNIADB_MODE_CS); } else { - spacedb_res = cmd_spacedb (curr->dbname, CUBRID_MODE_CS); + spacedb_res = cmd_spacedb (curr->dbname, ARNIADB_MODE_CS); } if (spacedb_res == NULL) @@ -1218,28 +1218,28 @@ aj_execquery (autoexecquery_node *c) int retval; int argc = 0; const char *argv[11]; - char cmd_name[CUBRID_CMD_NAME_LEN + 1]; + char cmd_name[ARNIADB_CMD_NAME_LEN + 1]; int ha_mode; T_DB_SERVICE_MODE db_mode; char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; char dbpasswd[PASSWD_LENGTH + 1]; int error_code; char error_buffer[1024]; - char cubrid_err_file[PATH_MAX]; + char arniadb_err_file[PATH_MAX]; char input_filename[256]; FILE *input_file; - cubrid_err_file[0] = '\0'; + arniadb_err_file[0] = '\0'; _aj_autoexecquery_error_log (c, 0, PRINT_CMD_START); memset (error_buffer, '\0', sizeof (error_buffer)); cmd_name[0] = '\0'; -#if !defined (DO_NOT_USE_CUBRIDENV) - sprintf (cmd_name, "%s/%s%s", sco.szCubrid, CUBRID_DIR_BIN, UTIL_CSQL_NAME); +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ASQL_NAME); #else - sprintf (cmd_name, "%s/%s", CUBRID_BINDIR, UTIL_CSQL_NAME); + sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_ASQL_NAME); #endif argv[argc++] = cmd_name; @@ -1263,26 +1263,26 @@ aj_execquery (autoexecquery_node *c) _aj_autoexecquery_error_log (c, ERR_GENERAL_ERROR, error_buffer); return; case DB_SERVICE_MODE_CS: - argv[argc++] = "--" CSQL_CS_MODE_L; + argv[argc++] = "--" ASQL_CS_MODE_L; break; case DB_SERVICE_MODE_NONE: - argv[argc++] = "--" CSQL_SA_MODE_L; + argv[argc++] = "--" ASQL_SA_MODE_L; break; } sprintf (input_filename, "%s/dbmt_auto_execquery_%d", sco.dbmt_tmp_dir, (int) getpid ()); - argv[argc++] = "--" CSQL_INPUT_FILE_L; + argv[argc++] = "--" ASQL_INPUT_FILE_L; argv[argc++] = input_filename; - argv[argc++] = "--" CSQL_USER_L; + argv[argc++] = "--" ASQL_USER_L; argv[argc++] = c->db_uid; uDecrypt (PASSWD_LENGTH, c->db_passwd, dbpasswd); - argv[argc++] = "--" CSQL_PASSWORD_L; + argv[argc++] = "--" ASQL_PASSWORD_L; argv[argc++] = dbpasswd; - argv[argc++] = "--" CSQL_NO_AUTO_COMMIT_L; + argv[argc++] = "--" ASQL_NO_AUTO_COMMIT_L; for (; argc < 11; argc++) { @@ -1303,41 +1303,41 @@ aj_execquery (autoexecquery_node *c) return; } - snprintf (cubrid_err_file, PATH_MAX, "%s/%s.%u.err.tmp", + snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", sco.dbmt_tmp_dir, "aj_execquery", getpid ()); - retval = run_child (argv, 1, NULL, NULL, cubrid_err_file, NULL); /* csql auto-execute */ + retval = run_child (argv, 1, NULL, NULL, arniadb_err_file, NULL); /* asql auto-execute */ unlink (input_filename); if (retval != 0) { sprintf (error_buffer, "Failed to execute Query with"); _aj_autoexecquery_error_log (c, ERR_SYSTEM_CALL, error_buffer); - if (access (cubrid_err_file, F_OK) == 0) + if (access (arniadb_err_file, F_OK) == 0) { - unlink (cubrid_err_file); + unlink (arniadb_err_file); } return; } else { - if (read_error_file2 (cubrid_err_file, error_buffer, DBMT_ERROR_MSG_SIZE, &error_code) < 0) + if (read_error_file2 (arniadb_err_file, error_buffer, DBMT_ERROR_MSG_SIZE, &error_code) < 0) { if (error_code == 0) { error_code = ERR_GENERAL_ERROR; } _aj_autoexecquery_error_log (c, error_code, error_buffer); - if (access (cubrid_err_file, F_OK) == 0) + if (access (arniadb_err_file, F_OK) == 0) { - unlink (cubrid_err_file); + unlink (arniadb_err_file); } return; } else { _aj_autoexecquery_error_log (c, 0, "success"); - if (access (cubrid_err_file, F_OK) == 0) + if (access (arniadb_err_file, F_OK) == 0) { - unlink (cubrid_err_file); + unlink (arniadb_err_file); } } } @@ -1354,10 +1354,10 @@ _aj_autoexecquery_error_log (autoexecquery_node *node, int error_code, char strbuf[128]; tt = time (&tt); -#if !defined (DO_NOT_USE_CUBRIDENV) - sprintf (logfile, "%s/log/manager/auto_execquery.log", sco.szCubrid); +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (logfile, "%s/log/manager/auto_execquery.log", sco.szArniadb); #else - sprintf (logfile, "%s/manager/auto_execquery.log", CUBRID_LOGDIR); + sprintf (logfile, "%s/manager/auto_execquery.log", ARNIADB_LOGDIR); #endif outfile = fopen (logfile, "a"); @@ -1471,10 +1471,10 @@ _aj_autobackupdb_error_log (autobackupdb_node *n, char *errmsg) char strbuf[128]; tt = time (&tt); -#if !defined (DO_NOT_USE_CUBRIDENV) - sprintf (logfile, "%s/log/manager/auto_backupdb.log", sco.szCubrid); +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (logfile, "%s/log/manager/auto_backupdb.log", sco.szArniadb); #else - sprintf (logfile, "%s/manager/auto_backupdb.log", CUBRID_LOGDIR); + sprintf (logfile, "%s/manager/auto_backupdb.log", ARNIADB_LOGDIR); #endif outfile = fopen (logfile, "a"); @@ -1502,9 +1502,9 @@ aj_backupdb (autobackupdb_node *n) char backup_vol_name[128]; const char *opt_mode; char db_start_flag = 0; - char cubrid_err_file[PATH_MAX]; + char arniadb_err_file[PATH_MAX]; int retval; - char cmd_name[CUBRID_CMD_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; char level_str[32]; char strtime[32]; char thread_num_str[16]; @@ -1513,7 +1513,7 @@ aj_backupdb (autobackupdb_node *n) FILE *inputfile; T_DB_SERVICE_MODE db_mode; - cubrid_err_file[0] = '\0'; + arniadb_err_file[0] = '\0'; sprintf (buf, "backupdb(%s): auto job start", n->dbname); _aj_autobackupdb_error_log (n, buf); @@ -1578,9 +1578,9 @@ aj_backupdb (autobackupdb_node *n) db_start_flag = 1; } - opt_mode = (n->onoff == 0) ? "--" CSQL_SA_MODE_L : "--" CSQL_CS_MODE_L; + opt_mode = (n->onoff == 0) ? "--" ASQL_SA_MODE_L : "--" ASQL_CS_MODE_L; - cubrid_cmd_name (cmd_name); + arniadb_cmd_name (cmd_name); sprintf (thread_num_str, "%d", n->mt); sprintf (level_str, "%d", n->level); argc = 0; @@ -1624,7 +1624,7 @@ aj_backupdb (autobackupdb_node *n) } argv[argc++] = NULL; - snprintf (cubrid_err_file, PATH_MAX, "%s/%s.%u.err.tmp", + snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", sco.dbmt_tmp_dir, "aj_backupdb", getpid ()); sprintf (inputfilepath, "%s/DBMT_task_%d.%d", sco.dbmt_tmp_dir, TS_BACKUPDB, @@ -1642,21 +1642,21 @@ aj_backupdb (autobackupdb_node *n) return; } - retval = run_child (argv, 1, inputfilepath, NULL, cubrid_err_file, NULL); /* backupdb */ + retval = run_child (argv, 1, inputfilepath, NULL, arniadb_err_file, NULL); /* backupdb */ unlink (inputfilepath); - if (read_error_file (cubrid_err_file, buf, sizeof (buf)) < 0) + if (read_error_file (arniadb_err_file, buf, sizeof (buf)) < 0) { _aj_autobackupdb_error_log (n, buf); - if (access (cubrid_err_file, F_OK) == 0) + if (access (arniadb_err_file, F_OK) == 0) { - unlink (cubrid_err_file); + unlink (arniadb_err_file); } return; } - if (access (cubrid_err_file, F_OK) == 0) + if (access (arniadb_err_file, F_OK) == 0) { - unlink (cubrid_err_file); + unlink (arniadb_err_file); } if (retval < 0) { @@ -1667,12 +1667,12 @@ aj_backupdb (autobackupdb_node *n) } sprintf (buf, "backupdb(%s): success", n->dbname); - _aj_autobackupdb_error_log (n, buf); /* log success info to notify cubrid manager user */ + _aj_autobackupdb_error_log (n, buf); /* log success info to notify arniadb manager user */ /* update statistics */ if (n->onoff == 0 && n->updatestatus) { - cubrid_cmd_name (cmd_name); + arniadb_cmd_name (cmd_name); argv[0] = cmd_name; argv[1] = UTIL_OPTION_OPTIMIZEDB; argv[2] = n->dbname; diff --git a/server/src/cm_cci_interface.cpp b/server/src/cm_cci_interface.cpp index 3a404a5..16bc275 100644 --- a/server/src/cm_cci_interface.cpp +++ b/server/src/cm_cci_interface.cpp @@ -48,9 +48,9 @@ using namespace std; static T_HTTP_TASK_INFO http_task_info[] = { - {"exportdb", 0, http_cubrid_exportdb}, - {"importdb", 0, http_cubrid_importdb}, - {"sql", 0, http_cubrid_sql}, + {"exportdb", 0, http_arniadb_exportdb}, + {"importdb", 0, http_arniadb_importdb}, + {"sql", 0, http_arniadb_sql}, {NULL, 0, NULL} }; @@ -94,7 +94,7 @@ _get_col_info (int req, T_CCI_SQLX_CMD &cmd_type, Json::Value &response) Json::Value attribute, col; res_col_info = cci_get_result_info (req, &cmd_type, &col_count); - if (cmd_type == CUBRID_STMT_SELECT && !res_col_info) + if (cmd_type == ARNIADB_STMT_SELECT && !res_col_info) { return -1; } @@ -192,7 +192,7 @@ _execute_async_stmt (int con_id, const char *stmt, int fetch_size, } response["exec_retval"] = res; - if (dump_plan && cmd_type == CUBRID_STMT_SELECT) + if (dump_plan && cmd_type == ARNIADB_STMT_SELECT) { if (cci_get_query_plan (req, &plan) >= 0) { @@ -1213,7 +1213,7 @@ _get_export_path (string &export_path, string &export_filename, } int -http_cubrid_exportdb (Json::Value &request, Json::Value &response) +http_arniadb_exportdb (Json::Value &request, Json::Value &response) { int con_handle, port, export_size, export_type, export_flag, res; unsigned int i; @@ -1294,8 +1294,8 @@ _import_class_sql (Json::Value &request, Json::Value &response) string import_filename; string import_path; string error_continue_option = "y"; - T_CSQL_RESULT *csql_result; - T_CUBRID_MODE mode; + T_ASQL_RESULT *asql_result; + T_ARNIADB_MODE mode; JSON_FIND_V (request, "dbname", build_common_header (response, ERR_PARAM_MISSING, "dbname")); @@ -1317,23 +1317,23 @@ _import_class_sql (Json::Value &request, Json::Value &response) import_path = string (sco.dbmt_tmp_dir) + "/" + import_filename; mode = (uDatabaseMode ((char *) db_name.c_str (), NULL) == - DB_SERVICE_MODE_NONE ? CUBRID_MODE_SA : CUBRID_MODE_CS); - csql_result = - cmd_csql ((char *) db_name.c_str (), (char *) db_user.c_str (), + DB_SERVICE_MODE_NONE ? ARNIADB_MODE_SA : ARNIADB_MODE_CS); + asql_result = + cmd_asql ((char *) db_name.c_str (), (char *) db_user.c_str (), (char *) dbpasswd.c_str (), mode, (char *) import_path.c_str (), NULL, (char *) error_continue_option.c_str ()); - if (csql_result == NULL) + if (asql_result == NULL) { return build_common_header (response, ERR_WITH_MSG, - "Error occur when execurating csql."); + "Error occur when execurating asql."); } - else if (strlen (csql_result->err_msg) != 0) + else if (strlen (asql_result->err_msg) != 0) { - build_common_header (response, ERR_WITH_MSG, csql_result->err_msg); - free (csql_result); + build_common_header (response, ERR_WITH_MSG, asql_result->err_msg); + free (asql_result); return ERR_WITH_MSG; } - free (csql_result); + free (asql_result); return build_common_header (response, ERR_NO_ERROR, "none"); } @@ -1518,7 +1518,7 @@ _import_class_csv (Json::Value &request, Json::Value &response) } int -http_cubrid_importdb (Json::Value &request, Json::Value &response) +http_arniadb_importdb (Json::Value &request, Json::Value &response) { int import_type, result = ERR_NO_ERROR; string ip, db_name, db_user, dbpasswd; @@ -1540,7 +1540,7 @@ http_cubrid_importdb (Json::Value &request, Json::Value &response) } int -http_cubrid_sql (Json::Value &request, Json::Value &response) +http_arniadb_sql (Json::Value &request, Json::Value &response) { int con_handle, port, fetch_size, fetch_offset, dump_plan, time_out; unsigned int i; @@ -1612,7 +1612,7 @@ http_cubrid_sql (Json::Value &request, Json::Value &response) } int -cub_cci_request_handler (Json::Value &request, Json::Value &response) +arn_cci_request_handler (Json::Value &request, Json::Value &response) { int res; int elapsed_msec = 0; @@ -1624,7 +1624,7 @@ cub_cci_request_handler (Json::Value &request, Json::Value &response) build_common_header (response, ERR_PARAM_MISSING, "task")); task_name = request["task"].asString (); - /* record the start time of running cub_manager task. */ + /* record the start time of running arn_manager task. */ gettimeofday (&task_begin, NULL); get_cci_task_info (task_name.c_str (), &task_func); @@ -1644,10 +1644,10 @@ cub_cci_request_handler (Json::Value &request, Json::Value &response) res = build_common_header (response, ERR_UNDEFINED_TASK, task_name.c_str ()); } - /* record the end time of running cub_manager task. */ + /* record the end time of running arn_manager task. */ gettimeofday (&task_end, NULL); - /* caculate the running time of cub_manager task. */ + /* caculate the running time of arn_manager task. */ _ut_timeval_diff (&task_begin, &task_end, &elapsed_msec); response["__EXEC_TIME"] = elapsed_msec; diff --git a/server/src/cm_cci_interface.h b/server/src/cm_cci_interface.h index 9f80fc4..5bb3a6d 100644 --- a/server/src/cm_cci_interface.h +++ b/server/src/cm_cci_interface.h @@ -44,10 +44,10 @@ typedef union tagUNI_CCI_A_TYPE if (Json::Value::null == root[key]) \ return err; -int http_cubrid_exportdb (Json::Value &request, Json::Value &response); -int http_cubrid_importdb (Json::Value &request, Json::Value &response); -int http_cubrid_sql (Json::Value &request, Json::Value &response); +int http_arniadb_exportdb (Json::Value &request, Json::Value &response); +int http_arniadb_importdb (Json::Value &request, Json::Value &response); +int http_arniadb_sql (Json::Value &request, Json::Value &response); int get_cci_task_info (const char *task, T_HTTP_TASK_FUNC *task_func); -int cub_cci_request_handler (Json::Value &request, Json::Value &response); +int arn_cci_request_handler (Json::Value &request, Json::Value &response); #endif diff --git a/server/src/cm_cmd_exec.cpp b/server/src/cm_cmd_exec.cpp index 67d06bb..8d344ce 100644 --- a/server/src/cm_cmd_exec.cpp +++ b/server/src/cm_cmd_exec.cpp @@ -47,10 +47,10 @@ #endif #define new_servstat_result() (T_SERVER_STATUS_RESULT*) new_cmd_result() -#define new_csql_result() (T_CSQL_RESULT*) new_cmd_result() +#define new_asql_result() (T_ASQL_RESULT*) new_cmd_result() static T_CMD_RESULT *new_cmd_result (void); -static const char *get_cubrid_mode_opt (T_CUBRID_MODE mode); +static const char *get_arniadb_mode_opt (T_ARNIADB_MODE mode); static void read_server_status_output (T_SERVER_STATUS_RESULT *res, char *out_file); static void read_spacedb_output (GeneralSpacedbResult *res, char *out_file); @@ -62,56 +62,56 @@ static int read_start_server_output (char *stdout_log_file, static int _size_to_byte_by_unit (double orgin_num, char unit); char * -cubrid_cmd_name (char *buf) +arniadb_cmd_name (char *buf) { buf[0] = '\0'; -#if !defined (DO_NOT_USE_CUBRIDENV) - sprintf (buf, "%s/%s%s", sco.szCubrid, CUBRID_DIR_BIN, UTIL_CUBRID); +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (buf, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ARNIADB); #else - sprintf (buf, "%s/%s", CUBRID_BINDIR, UTIL_CUBRID); + sprintf (buf, "%s/%s", ARNIADB_BINDIR, UTIL_ARNIADB); #endif return buf; } -T_CSQL_RESULT * -cmd_csql (char *dbname, char *uid, char *passwd, T_CUBRID_MODE mode, +T_ASQL_RESULT * +cmd_asql (char *dbname, char *uid, char *passwd, T_ARNIADB_MODE mode, char *infile, char *command, char *error_continue) { - char cubrid_err_file[PATH_MAX]; + char arniadb_err_file[PATH_MAX]; char out_file[512]; - T_CSQL_RESULT *res; - char cmd_name[CUBRID_CMD_NAME_LEN]; + T_ASQL_RESULT *res; + char cmd_name[ARNIADB_CMD_NAME_LEN]; const char *argv[15]; int argc = 0; cmd_name[0] = '\0'; - cubrid_err_file[0] = '\0'; -#if !defined (DO_NOT_USE_CUBRIDENV) - sprintf (cmd_name, "%s/%s%s", sco.szCubrid, CUBRID_DIR_BIN, UTIL_CSQL_NAME); + arniadb_err_file[0] = '\0'; +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ASQL_NAME); #else - sprintf (cmd_name, "%s/%s", CUBRID_BINDIR, UTIL_CSQL_NAME); + sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_ASQL_NAME); #endif argv[argc++] = cmd_name; - argv[argc++] = get_cubrid_mode_opt (mode); + argv[argc++] = get_arniadb_mode_opt (mode); if (uid) { - argv[argc++] = "--" CSQL_USER_L; + argv[argc++] = "--" ASQL_USER_L; argv[argc++] = uid; if (passwd) { - argv[argc++] = "--" CSQL_PASSWORD_L; + argv[argc++] = "--" ASQL_PASSWORD_L; argv[argc++] = passwd; } } if (infile) { - argv[argc++] = "--" CSQL_INPUT_FILE_L; + argv[argc++] = "--" ASQL_INPUT_FILE_L; argv[argc++] = infile; } else if (command) { - argv[argc++] = "--" CSQL_COMMAND_L; + argv[argc++] = "--" ASQL_COMMAND_L; argv[argc++] = command; } else @@ -121,25 +121,25 @@ cmd_csql (char *dbname, char *uid, char *passwd, T_CUBRID_MODE mode, if (uStringEqualIgnoreCase (error_continue, "y")) { - argv[argc++] = "--" CSQL_ERROR_CONTINUE_L; + argv[argc++] = "--" ASQL_ERROR_CONTINUE_L; } argv[argc++] = dbname; argv[argc++] = NULL; -#if !defined (DO_NOT_USE_CUBRIDENV) - sprintf (out_file, "%s/tmp/DBMT_util_003.%d", sco.szCubrid, +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (out_file, "%s/tmp/DBMT_util_003.%d", sco.szArniadb, (int) getpid ()); #else - sprintf (out_file, "%s/DBMT_util_003.%d", CUBRID_TMPDIR, (int) getpid ()); + sprintf (out_file, "%s/DBMT_util_003.%d", ARNIADB_TMPDIR, (int) getpid ()); #endif - snprintf (cubrid_err_file, PATH_MAX, "%s/%s.%u.err.tmp", - sco.dbmt_tmp_dir, "cmd_csql", getpid ()); + snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", + sco.dbmt_tmp_dir, "cmd_asql", getpid ()); SET_TRANSACTION_NO_WAIT_MODE_ENV (); - run_child (argv, 1, NULL, NULL, out_file, NULL); /* csql */ + run_child (argv, 1, NULL, NULL, out_file, NULL); /* asql */ - res = new_csql_result (); + res = new_asql_result (); if (res == NULL) { return NULL; @@ -151,15 +151,15 @@ cmd_csql (char *dbname, char *uid, char *passwd, T_CUBRID_MODE mode, return res; } -void find_and_parse_cub_admin_version (int &major_version, int &minor_version) +void find_and_parse_arn_admin_version (int &major_version, int &minor_version) { const char *argv[3]; char tmpfile[PATH_MAX], strbuf[BUFFER_MAX_LEN]; FILE *infile; - char cmd_name[CUBRID_CMD_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; - cubrid_cmd_name (cmd_name); - snprintf (tmpfile, PATH_MAX - 1, "%s/cub_admin_version", sco.dbmt_tmp_dir); + arniadb_cmd_name (cmd_name); + snprintf (tmpfile, PATH_MAX - 1, "%s/arn_admin_version", sco.dbmt_tmp_dir); argv[0] = cmd_name; argv[1] = "--version"; argv[2] = NULL; @@ -191,27 +191,27 @@ void find_and_parse_cub_admin_version (int &major_version, int &minor_version) } GeneralSpacedbResult * -cmd_spacedb (const char *dbname, T_CUBRID_MODE mode) +cmd_spacedb (const char *dbname, T_ARNIADB_MODE mode) { GeneralSpacedbResult *res = NULL; int minor_version, major_version; char out_file[PATH_MAX]; - char cubrid_err_file[PATH_MAX]; - char cmd_name[CUBRID_CMD_NAME_LEN]; + char arniadb_err_file[PATH_MAX]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; char err_message[ERR_MSG_SIZE]; const char *argv[10]; int argc = 0; - cubrid_err_file[0] = '\0'; + arniadb_err_file[0] = '\0'; - if (IS_INVALID_CUBRID_VERS_MAJOR (cubrid_version_major)) + if (IS_INVALID_ARNIADB_VERS_MAJOR (arniadb_version_major)) { - LOG_ERROR ("Invalid CUBRID Engine Version: %d.%d", cubrid_version_major, cubrid_version_minor); - find_and_parse_cub_admin_version (major_version, minor_version); - cubrid_version_major = major_version; - cubrid_version_minor = minor_version; + LOG_ERROR ("Invalid ARNIADB Engine Version: %d.%d", arniadb_version_major, arniadb_version_minor); + find_and_parse_arn_admin_version (major_version, minor_version); + arniadb_version_major = major_version; + arniadb_version_minor = minor_version; } - if (cubrid_version_major < 10 || (cubrid_version_minor == 10 && cubrid_version_minor == 0)) + if (arniadb_version_major < 10 || (arniadb_version_minor == 10 && arniadb_version_minor == 0)) { res = new SpaceDbResultOldFormat(); } @@ -222,10 +222,10 @@ cmd_spacedb (const char *dbname, T_CUBRID_MODE mode) sprintf (out_file, "%s/DBMT_util_002.%d", sco.dbmt_tmp_dir, (int) getpid ()); - cubrid_cmd_name (cmd_name); + arniadb_cmd_name (cmd_name); argv[argc++] = cmd_name; argv[argc++] = UTIL_OPTION_SPACEDB; - argv[argc++] = get_cubrid_mode_opt (mode); + argv[argc++] = get_arniadb_mode_opt (mode); argv[argc++] = "--" SPACE_SIZE_UNIT_L; argv[argc++] = "PAGE"; argv[argc++] = "--" SPACE_OUTPUT_FILE_L; @@ -234,15 +234,15 @@ cmd_spacedb (const char *dbname, T_CUBRID_MODE mode) argv[argc++] = "-p"; argv[argc++] = NULL; - snprintf (cubrid_err_file, PATH_MAX, "%s/%s.%u.err.tmp", + snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", sco.dbmt_tmp_dir, "cmd_spacedb", getpid ()); - run_child (argv, 1, NULL, NULL, cubrid_err_file, NULL); /* spacedb */ - read_error_file (cubrid_err_file, err_message, ERR_MSG_SIZE); + run_child (argv, 1, NULL, NULL, arniadb_err_file, NULL); /* spacedb */ + read_error_file (arniadb_err_file, err_message, ERR_MSG_SIZE); res->set_err_msg (err_message); read_spacedb_output (res, out_file); - if (access (cubrid_err_file, F_OK) == 0) + if (access (arniadb_err_file, F_OK) == 0) { - unlink (cubrid_err_file); + unlink (arniadb_err_file); } unlink (out_file); return res; @@ -256,7 +256,7 @@ cmd_start_server (char *dbname, char *err_buf, int err_buf_size) char stderr_log_file[512]; int pid; int ret_val; - char cmd_name[CUBRID_CMD_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; const char *argv[5]; #ifdef HPUX @@ -270,18 +270,18 @@ cmd_start_server (char *dbname, char *err_buf, int err_buf_size) (int) getpid ()); - /* unset CUBRID_ERROR_LOG environment variable, using default value */ + /* unset ARNIADB_ERROR_LOG environment variable, using default value */ #if defined(WINDOWS) - _putenv ("CUBRID_ERROR_LOG="); + _putenv ("ARNIADB_ERROR_LOG="); #else - unsetenv ("CUBRID_ERROR_LOG"); + unsetenv ("ARNIADB_ERROR_LOG"); #endif cmd_name[0] = '\0'; -#if !defined (DO_NOT_USE_CUBRIDENV) - sprintf (cmd_name, "%s/%s%s", sco.szCubrid, CUBRID_DIR_BIN, UTIL_CUBRID); +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ARNIADB); #else - sprintf (cmd_name, "%s/%s", CUBRID_BINDIR, UTIL_CUBRID); + sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_ARNIADB); #endif argv[0] = cmd_name; @@ -329,7 +329,7 @@ cmd_stop_server (char *dbname, char *err_buf, int err_buf_size) { char strbuf[1024]; int t, timeout = 30, interval = 3; /* sec */ - char cmd_name[CUBRID_CMD_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; const char *argv[5]; if (err_buf) @@ -338,10 +338,10 @@ cmd_stop_server (char *dbname, char *err_buf, int err_buf_size) } cmd_name[0] = '\0'; -#if !defined (DO_NOT_USE_CUBRIDENV) - sprintf (cmd_name, "%s/%s%s", sco.szCubrid, CUBRID_DIR_BIN, UTIL_CUBRID); +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ARNIADB); #else - sprintf (cmd_name, "%s/%s", CUBRID_BINDIR, UTIL_CUBRID); + sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_ARNIADB); #endif argv[0] = cmd_name; @@ -381,26 +381,26 @@ void cmd_start_master (void) { int pid; - char cmd_name[CUBRID_CMD_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; const char *argv[2]; cmd_name[0] = '\0'; -#if !defined (DO_NOT_USE_CUBRIDENV) - sprintf (cmd_name, "%s/%s%s", sco.szCubrid, - CUBRID_DIR_BIN, UTIL_MASTER_NAME); +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (cmd_name, "%s/%s%s", sco.szArniadb, + ARNIADB_DIR_BIN, UTIL_MASTER_NAME); #else - sprintf (cmd_name, "%s/%s", CUBRID_BINDIR, UTIL_MASTER_NAME); + sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_MASTER_NAME); #endif argv[0] = cmd_name; argv[1] = NULL; - pid = run_child (argv, 0, NULL, NULL, NULL, NULL); /* cub_master */ + pid = run_child (argv, 0, NULL, NULL, NULL, NULL); /* arn_master */ SLEEP_MILISEC (0, 500); } int -read_csql_error_file (char *err_file, char *err_buf, int err_buf_size) +read_asql_error_file (char *err_file, char *err_buf, int err_buf_size) { FILE *fp; char buf[1024]; @@ -671,14 +671,14 @@ new_cmd_result (void) } static const char * -get_cubrid_mode_opt (T_CUBRID_MODE mode) +get_arniadb_mode_opt (T_ARNIADB_MODE mode) { - if (mode == CUBRID_MODE_SA) + if (mode == ARNIADB_MODE_SA) { - return ("--" CSQL_SA_MODE_L); + return ("--" ASQL_SA_MODE_L); } - return ("--" CSQL_CS_MODE_L); + return ("--" ASQL_CS_MODE_L); } static bool is_valid_database_description (char *str) diff --git a/server/src/cm_cmd_exec.h b/server/src/cm_cmd_exec.h index c89ef12..54ed878 100644 --- a/server/src/cm_cmd_exec.h +++ b/server/src/cm_cmd_exec.h @@ -36,7 +36,7 @@ #endif #define cmd_servstat_result_free(RESULT) cmd_result_free(RESULT) -#define cmd_csql_result_free(RESULT) cmd_result_free(RESULT) +#define cmd_asql_result_free(RESULT) cmd_result_free(RESULT) #define ERR_MSG_SIZE 1024 #define COLUMN_VALUE_MAX_SIZE 32 @@ -44,36 +44,36 @@ #define FILES_DESCRIPTION_NUM_LINES 4 #define BUFFER_MAX_LEN 128 -#if !defined (DO_NOT_USE_CUBRIDENV) -#define CUBRID_ERROR_LOG_DIR "log/server" -#define CUBRID_BROKER_LOG_DIR "log/broker" +#if !defined (DO_NOT_USE_ARNIADBENV) +#define ARNIADB_ERROR_LOG_DIR "log/server" +#define ARNIADB_BROKER_LOG_DIR "log/broker" #else -#define CUBRID_ERROR_LOG_DIR CUBRID_LOGDIR "/server" -#define CUBRID_BROKER_LOG_DIR CUBRID_LOGDIR"/broker" +#define ARNIADB_ERROR_LOG_DIR ARNIADB_LOGDIR "/server" +#define ARNIADB_BROKER_LOG_DIR ARNIADB_LOGDIR"/broker" #endif -#define CUBRID_DATABASE_TXT "databases.txt" -#define CUBRID_CUBRID_CONF "cubrid.conf" -#define CUBRID_DBMT_CONF "cm.conf" -#define CUBRID_BROKER_CONF "cubrid_broker.conf" -#define CUBRID_HA_CONF "cubrid_ha.conf" -#define CUBRID_UNLOAD_EXT_INDEX "_indexes" -#define CUBRID_UNLOAD_EXT_TRIGGER "_trigger" -#define CUBRID_UNLOAD_EXT_OBJ "_objects" -#define CUBRID_UNLOAD_EXT_SCHEMA "_schema" -#define CUBRID_SERVER_LOCK_EXT "_lgat__lock" -#define CUBRID_ACT_LOG_EXT "_lgat" -#define CUBRID_ARC_LOG_EXT "_lgar" -#define CUBRID_BACKUP_INFO_EXT "_bkvinf" -#define CUBRID_ARC_LOG_EXT_LEN strlen(CUBRID_ARC_LOG_EXT) +#define ARNIADB_DATABASE_TXT "databases.txt" +#define ARNIADB_ARNIADB_CONF "arniadb.conf" +#define ARNIADB_DBMT_CONF "cm.conf" +#define ARNIADB_BROKER_CONF "arniadb_broker.conf" +#define ARNIADB_HA_CONF "arniadb_ha.conf" +#define ARNIADB_UNLOAD_EXT_INDEX "_indexes" +#define ARNIADB_UNLOAD_EXT_TRIGGER "_trigger" +#define ARNIADB_UNLOAD_EXT_OBJ "_objects" +#define ARNIADB_UNLOAD_EXT_SCHEMA "_schema" +#define ARNIADB_SERVER_LOCK_EXT "_lgat__lock" +#define ARNIADB_ACT_LOG_EXT "_lgat" +#define ARNIADB_ARC_LOG_EXT "_lgar" +#define ARNIADB_BACKUP_INFO_EXT "_bkvinf" +#define ARNIADB_ARC_LOG_EXT_LEN strlen(ARNIADB_ARC_LOG_EXT) -#define CUBRID_CMD_NAME_LEN 128 +#define ARNIADB_CMD_NAME_LEN 128 -#if !defined (DO_NOT_USE_CUBRIDENV) +#if !defined (DO_NOT_USE_ARNIADBENV) #if defined(WINDOWS) -#define CUBRID_DIR_BIN "bin\\" +#define ARNIADB_DIR_BIN "bin\\" #else -#define CUBRID_DIR_BIN "bin/" +#define ARNIADB_DIR_BIN "bin/" #endif #endif @@ -82,9 +82,9 @@ typedef enum { - CUBRID_MODE_CS = 0, - CUBRID_MODE_SA = 1 -} T_CUBRID_MODE; + ARNIADB_MODE_CS = 0, + ARNIADB_MODE_SA = 1 +} T_ARNIADB_MODE; struct SpaceDbVolumeInfoOldFormat { @@ -263,17 +263,17 @@ class SpaceDbResultOldFormat : public GeneralSpacedbResult std::vector temporary_volumes; }; -typedef T_CMD_RESULT T_CSQL_RESULT; +typedef T_CMD_RESULT T_ASQL_RESULT; -GeneralSpacedbResult *cmd_spacedb (const char *dbname, T_CUBRID_MODE mode); -T_CSQL_RESULT *cmd_csql (char *dbname, char *uid, char *passwd, - T_CUBRID_MODE mode, char *infile, char *command, char *error_continue); +GeneralSpacedbResult *cmd_spacedb (const char *dbname, T_ARNIADB_MODE mode); +T_ASQL_RESULT *cmd_asql (char *dbname, char *uid, char *passwd, + T_ARNIADB_MODE mode, char *infile, char *command, char *error_continue); int cmd_start_server (char *dbname, char *err_buf, int err_buf_size); int cmd_stop_server (char *dbname, char *err_buf, int err_buf_size); void cmd_start_master (void); -char *cubrid_cmd_name (char *buf); +char *arniadb_cmd_name (char *buf); int read_error_file (const char *err_file, char *err_buf, int err_buf_size); int read_error_file2 (char *err_file, char *err_buf, int err_buf_size, int *err_code); -int read_csql_error_file (char *err_file, char *err_buf, int err_buf_size); +int read_asql_error_file (char *err_file, char *err_buf, int err_buf_size); #endif /* _CM_COMMAND_EXECUTE_H_ */ diff --git a/server/src/cm_cmd_task.cpp b/server/src/cm_cmd_task.cpp index 8879204..1508a81 100644 --- a/server/src/cm_cmd_task.cpp +++ b/server/src/cm_cmd_task.cpp @@ -159,7 +159,7 @@ cmd_listdb (int argc, const char *in_argv[]) FILE *fp = NULL; snprintf (db_txt_path, sizeof (db_txt_path) - 1, "%s/%s", - sco.szCubrid_databases, CUBRID_DATABASE_TXT); + sco.szArniadb_databases, ARNIADB_DATABASE_TXT); if ((fp = fopen (db_txt_path, "r")) == NULL) { diff --git a/server/src/cm_config.cpp b/server/src/cm_config.cpp index be92d37..565d870 100644 --- a/server/src/cm_config.cpp +++ b/server/src/cm_config.cpp @@ -108,7 +108,7 @@ static T_DBMT_FILE_INFO dbmt_file[NUM_DBMT_FILE] = { {FID_DBMT_CONF, DBMT_CONF_DIR, "cm.conf"}, {FID_DBMT_PASS, DBMT_CONF_DIR, "cm.pass"}, - {FID_DBMT_CUBRID_PASS, DBMT_CONF_DIR, "cmdb.pass"}, + {FID_DBMT_ARNIADB_PASS, DBMT_CONF_DIR, "cmdb.pass"}, {FID_CONN_LIST, DBMT_LOG_DIR, "conlist"}, {FID_AUTO_ADDVOLDB_CONF, DBMT_CONF_DIR, "autoaddvoldb.conf"}, {FID_AUTO_ADDVOLDB_LOG, DBMT_LOG_DIR, "autoaddvoldb.log"}, @@ -124,9 +124,9 @@ static T_DBMT_FILE_INFO dbmt_file[NUM_DBMT_FILE] = {FID_DIAG_STATUS_TEMPLATE, DBMT_CONF_DIR, "diagstatustemplate.conf"}, {FID_DIAG_ACTIVITY_TEMPLATE, DBMT_CONF_DIR, "diagactivitytemplate.conf"}, {FID_DIAG_SERVER_PID, DBMT_LOG_DIR, "diag.pid"}, - {FID_CMSERVER_PID, DBMT_PID_DIR, DBMT_CUB_CMS_PID}, - {FID_CMS_LOG, DBMT_LOG_DIR, "cub_manager.log"}, - {FID_CMS_ERROR_LOG, DBMT_LOG_DIR, "cub_manager.err"}, + {FID_CMSERVER_PID, DBMT_PID_DIR, DBMT_ARN_CMS_PID}, + {FID_CMS_LOG, DBMT_LOG_DIR, "arn_manager.log"}, + {FID_CMS_ERROR_LOG, DBMT_LOG_DIR, "arn_manager.err"}, {FID_AUTO_JOBS_CONF, DBMT_CONF_DIR, "autojobs.conf"}, {FID_SHARD_CONF, DBMT_CONF_DIR, "shard.conf"}, }; @@ -148,62 +148,62 @@ uReadEnvVariables (char *progname) char tmpstrbuf[DBMT_ERROR_MSG_SIZE]; tmpstrbuf[0] = '\0'; -#if !defined (DO_NOT_USE_CUBRIDENV) - sco.szCubrid = getenv ("CUBRID"); - sco.szCubrid_databases = getenv ("CUBRID_DATABASES"); +#if !defined (DO_NOT_USE_ARNIADBENV) + sco.szArniadb = getenv ("ARNIADB"); + sco.szArniadb_databases = getenv ("ARNIADB_DATABASES"); #else - sco.szCubrid = CUBRID_PREFIXDIR; - sco.szCubrid_databases = CUBRID_VARDIR; + sco.szArniadb = ARNIADB_PREFIXDIR; + sco.szArniadb_databases = ARNIADB_VARDIR; #endif sco.szProgname = strdup (progname); /* not an env variable */ - if (sco.szCubrid == NULL) + if (sco.szArniadb == NULL) { -#if !defined (DO_NOT_USE_CUBRIDENV) +#if !defined (DO_NOT_USE_ARNIADBENV) snprintf (tmpstrbuf, DBMT_ERROR_MSG_SIZE, - "CUBRID Manager Server : Environment variable CUBRID not set. - %s\n", + "ARNIADB Manager Server : Environment variable ARNIADB not set. - %s\n", sco.szProgname); #else snprintf (tmpstrbuf, DBMT_ERROR_MSG_SIZE, - "CUBRID Manager Server : CUBRID prefix directory was not set. - %s\n", + "ARNIADB Manager Server : ARNIADB prefix directory was not set. - %s\n", sco.szProgname); #endif - ut_record_cubrid_utility_log_stderr (tmpstrbuf); + ut_record_arniadb_utility_log_stderr (tmpstrbuf); return -1; } - if (sco.szCubrid_databases == NULL) + if (sco.szArniadb_databases == NULL) { -#if !defined (DO_NOT_USE_CUBRIDENV) +#if !defined (DO_NOT_USE_ARNIADBENV) snprintf (tmpstrbuf, DBMT_ERROR_MSG_SIZE, - "CUBRID Manager Server : Environment variable CUBRID_DATABASES not set. - %s\n", + "ARNIADB Manager Server : Environment variable ARNIADB_DATABASES not set. - %s\n", sco.szProgname); #else snprintf (tmpstrbuf, DBMT_ERROR_MSG_SIZE, - "CUBRID Manager Server : CUBRID databases directory was not set. - %s\n", + "ARNIADB Manager Server : ARNIADB databases directory was not set. - %s\n", sco.szProgname); #endif - ut_record_cubrid_utility_log_stderr (tmpstrbuf); + ut_record_arniadb_utility_log_stderr (tmpstrbuf); return -1; } -#if !defined (DO_NOT_USE_CUBRIDENV) +#if !defined (DO_NOT_USE_ARNIADBENV) sco.dbmt_tmp_dir = - (char *) malloc (strlen (sco.szCubrid) + strlen (DBMT_TMP_DIR) + 2); + (char *) malloc (strlen (sco.szArniadb) + strlen (DBMT_TMP_DIR) + 2); #else - sco.dbmt_tmp_dir = (char *) malloc (strlen (CUBRID_TMPDIR) + 1); + sco.dbmt_tmp_dir = (char *) malloc (strlen (ARNIADB_TMPDIR) + 1); #endif if (sco.dbmt_tmp_dir == NULL) { perror ("malloc"); return -1; } -#if !defined (DO_NOT_USE_CUBRIDENV) +#if !defined (DO_NOT_USE_ARNIADBENV) #ifdef WINDOWS - sprintf (sco.dbmt_tmp_dir, "%s\\%s", sco.szCubrid, DBMT_TMP_DIR); + sprintf (sco.dbmt_tmp_dir, "%s\\%s", sco.szArniadb, DBMT_TMP_DIR); #else - sprintf (sco.dbmt_tmp_dir, "%s/%s", sco.szCubrid, DBMT_TMP_DIR); + sprintf (sco.dbmt_tmp_dir, "%s/%s", sco.szArniadb, DBMT_TMP_DIR); #endif #else - sprintf (sco.dbmt_tmp_dir, "%s", CUBRID_TMPDIR); + sprintf (sco.dbmt_tmp_dir, "%s", ARNIADB_TMPDIR); #endif return 1; @@ -242,7 +242,7 @@ uReadSystemConfig (void) strcpy (sco.szAutoUpdateURL, ""); strcpy (sco.szCMSVersion, ""); strncpy (sco.szTokenActiveTime, "7200", PATH_MAX); - snprintf (sco.szCWMPath, PATH_MAX, "%s%s", sco.szCubrid, + snprintf (sco.szCWMPath, PATH_MAX, "%s%s", sco.szArniadb, DEFAULT_CWM_PATH_SHORT); conf_get_dbmt_file (FID_CMS_LOG, access_log_buf); @@ -395,8 +395,8 @@ uReadSystemConfig (void) { snprintf (sco.szAutoUpdateURL, PATH_MAX, "%s", ent_val); } - else if (strcasecmp (ent_name, "cubrid_server_ver") == 0 || - strcasecmp (ent_name, "CubridServerVer") == 0) + else if (strcasecmp (ent_name, "arniadb_server_ver") == 0 || + strcasecmp (ent_name, "ArniadbServerVer") == 0) { snprintf (sco.szCMSVersion, PATH_MAX, "%s", ent_val); } @@ -451,8 +451,8 @@ uCheckSystemConfig (char *progname) mkdir (sco.dbmt_tmp_dir, 0755); } - /* CUBRID databases.txt file check */ - sprintf (filepath, "%s/%s", sco.szCubrid_databases, CUBRID_DATABASE_TXT); + /* ARNIADB databases.txt file check */ + sprintf (filepath, "%s/%s", sco.szArniadb_databases, ARNIADB_DATABASE_TXT); if (access (filepath, F_OK) < 0) { FILE *fp; @@ -472,26 +472,26 @@ uCheckSystemConfig (char *progname) { return -1; } - if (check_file (conf_get_dbmt_file (FID_DBMT_CUBRID_PASS, filepath), progname) < 0) + if (check_file (conf_get_dbmt_file (FID_DBMT_ARNIADB_PASS, filepath), progname) < 0) { return -1; } - /* cubrid manager only support https connections, + /* arniadb manager only support https connections, * Thus private key and certificate must be checked before process starting. */ - snprintf (sco.szSSLKey, PATH_MAX, "%s/conf/%s", sco.szCubrid, DEFAULT_SSL_PRIVATEKEY); + snprintf (sco.szSSLKey, PATH_MAX, "%s/conf/%s", sco.szArniadb, DEFAULT_SSL_PRIVATEKEY); if (check_file (sco.szSSLKey, progname) < 0) { return -1; } - snprintf (sco.szSSLCertificate, PATH_MAX, "%s/conf/%s", sco.szCubrid, DEFAULT_SSL_CERTIFICATE); + snprintf (sco.szSSLCertificate, PATH_MAX, "%s/conf/%s", sco.szArniadb, DEFAULT_SSL_CERTIFICATE); if (check_file (sco.szSSLCertificate, progname) < 0) { return -1; } -#if !defined (DO_NOT_USE_CUBRIDENV) - sprintf (filepath, "%s/%s", sco.szCubrid, DBMT_LOG_DIR); +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (filepath, "%s/%s", sco.szArniadb, DBMT_LOG_DIR); #else sprintf (filepath, "%s", DBMT_LOG_DIR); #endif @@ -499,8 +499,8 @@ uCheckSystemConfig (char *progname) { return -1; } -#if !defined (DO_NOT_USE_CUBRIDENV) - sprintf (filepath, "%s/%s", sco.szCubrid, DBMT_CONF_DIR); +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (filepath, "%s/%s", sco.szArniadb, DBMT_CONF_DIR); #else sprintf (filepath, "%s", DBMT_CONF_DIR); #endif @@ -508,8 +508,8 @@ uCheckSystemConfig (char *progname) { return -1; } -#if !defined (DO_NOT_USE_CUBRIDENV) - sprintf (filepath, "%s/%s", sco.szCubrid, DBMT_TMP_DIR); +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (filepath, "%s/%s", sco.szArniadb, DBMT_TMP_DIR); #else sprintf (filepath, "%s", DBMT_TMP_DIR); #endif @@ -531,8 +531,8 @@ conf_get_dbmt_file (T_DBMT_FILE_ID dbmt_fid, char *buf) { if (dbmt_fid == dbmt_file[i].fid) { -#if !defined (DO_NOT_USE_CUBRIDENV) - sprintf (buf, "%s/%s/%s", sco.szCubrid, dbmt_file[i].dir_name, +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (buf, "%s/%s/%s", sco.szArniadb, dbmt_file[i].dir_name, dbmt_file[i].file_name); #else sprintf (buf, "%s/%s", dbmt_file[i].dir_name, dbmt_file[i].file_name); @@ -783,8 +783,8 @@ check_file (char *fname, char *pname) if (access (fname, F_OK | R_OK | W_OK) < 0) { snprintf (tmpstrbuf, DBMT_ERROR_MSG_SIZE, - "CUBRID Manager Server : %s - %s. - %s\n", fname, strerror (errno), pname); - ut_record_cubrid_utility_log_stderr (tmpstrbuf); + "ARNIADB Manager Server : %s - %s. - %s\n", fname, strerror (errno), pname); + ut_record_arniadb_utility_log_stderr (tmpstrbuf); return -1; } return 1; @@ -801,8 +801,8 @@ check_path (char *dirname, char *pname) if (access (dirname, F_OK | W_OK | R_OK | X_OK) < 0) { snprintf (tmpstrbuf, DBMT_ERROR_MSG_SIZE, - "CUBRID Manager Server : %s - %s. - %s\n", dirname, strerror (errno), pname); - ut_record_cubrid_utility_log_stderr (tmpstrbuf); + "ARNIADB Manager Server : %s - %s. - %s\n", dirname, strerror (errno), pname); + ut_record_arniadb_utility_log_stderr (tmpstrbuf); return -1; } return 1; diff --git a/server/src/cm_config.h b/server/src/cm_config.h index a4a43e5..a71a83b 100644 --- a/server/src/cm_config.h +++ b/server/src/cm_config.h @@ -44,23 +44,23 @@ #define AUTOBACKUP_PERIOD_TYPE_NUM 5 #define AUTOBACKUP_PERIOD_WEEK_NUM 7 -#define CMS_NAME "cub_manager" +#define CMS_NAME "arn_manager" -#if !defined (DO_NOT_USE_CUBRIDENV) +#if !defined (DO_NOT_USE_ARNIADBENV) #define DBMT_CONF_DIR "conf" #define DBMT_LOG_DIR "log/manager" #define DBMT_PID_DIR "var/manager" #define DBMT_MON_DATA_DIR "var/manager/mon_data" #define DBMT_TMP_DIR "tmp" #else -#define DBMT_CONF_DIR CUBRID_CONFDIR -#define DBMT_LOG_DIR CUBRID_VARDIR "/manager" -#define DBMT_PID_DIR CUBRID_VARDIR "/manager" -#define DBMT_MON_DATA_DIR CUBRID_VARDIR "/manager/mon_data" -#define DBMT_TMP_DIR CUBRID_TMPDIR +#define DBMT_CONF_DIR ARNIADB_CONFDIR +#define DBMT_LOG_DIR ARNIADB_VARDIR "/manager" +#define DBMT_PID_DIR ARNIADB_VARDIR "/manager" +#define DBMT_MON_DATA_DIR ARNIADB_VARDIR "/manager/mon_data" +#define DBMT_TMP_DIR ARNIADB_TMPDIR #endif -#define DBMT_CUB_CMS_PID "cub_manager.pid" +#define DBMT_ARN_CMS_PID "arn_manager.pid" /* utility option list, from executables/utility.h */ #define UTIL_OPTION_CREATEDB "createdb" @@ -120,34 +120,34 @@ /* sqlx option list */ -#define CSQL_SA_MODE_S 'S' -#define CSQL_SA_MODE_L "SA-mode" -#define CSQL_CS_MODE_S 'C' -#define CSQL_CS_MODE_L "CS-mode" -#define CSQL_USER_S 'u' -#define CSQL_USER_L "user" -#define CSQL_PASSWORD_S 'p' -#define CSQL_PASSWORD_L "password" -#define CSQL_ERROR_CONTINUE_S 'e' -#define CSQL_ERROR_CONTINUE_L "error-continue" -#define CSQL_INPUT_FILE_S 'i' -#define CSQL_INPUT_FILE_L "input-file" -#define CSQL_OUTPUT_FILE_S 'o' -#define CSQL_OUTPUT_FILE_L "output-file" -#define CSQL_SINGLE_LINE_S 's' -#define CSQL_SINGLE_LINE_L "single-line" -#define CSQL_COMMAND_S 'c' -#define CSQL_COMMAND_L "command" -#define CSQL_LINE_OUTPUT_S 'l' -#define CSQL_LINE_OUTPUT_L "line-output" -#define CSQL_READ_ONLY_S 'r' -#define CSQL_READ_ONLY_L "read-only" -#define CSQL_NO_AUTO_COMMIT_S 12010 -#define CSQL_NO_AUTO_COMMIT_L "no-auto-commit" -#define CSQL_NO_PAGER_S 12011 -#define CSQL_NO_PAGER_L "no-pager" -#define CSQL_SYSADM_S 12012 -#define CSQL_SYSADM_L "sysadm" +#define ASQL_SA_MODE_S 'S' +#define ASQL_SA_MODE_L "SA-mode" +#define ASQL_CS_MODE_S 'C' +#define ASQL_CS_MODE_L "CS-mode" +#define ASQL_USER_S 'u' +#define ASQL_USER_L "user" +#define ASQL_PASSWORD_S 'p' +#define ASQL_PASSWORD_L "password" +#define ASQL_ERROR_CONTINUE_S 'e' +#define ASQL_ERROR_CONTINUE_L "error-continue" +#define ASQL_INPUT_FILE_S 'i' +#define ASQL_INPUT_FILE_L "input-file" +#define ASQL_OUTPUT_FILE_S 'o' +#define ASQL_OUTPUT_FILE_L "output-file" +#define ASQL_SINGLE_LINE_S 's' +#define ASQL_SINGLE_LINE_L "single-line" +#define ASQL_COMMAND_S 'c' +#define ASQL_COMMAND_L "command" +#define ASQL_LINE_OUTPUT_S 'l' +#define ASQL_LINE_OUTPUT_L "line-output" +#define ASQL_READ_ONLY_S 'r' +#define ASQL_READ_ONLY_L "read-only" +#define ASQL_NO_AUTO_COMMIT_S 12010 +#define ASQL_NO_AUTO_COMMIT_L "no-auto-commit" +#define ASQL_NO_PAGER_S 12011 +#define ASQL_NO_PAGER_L "no-pager" +#define ASQL_SYSADM_S 12012 +#define ASQL_SYSADM_L "sysadm" /* addvoldb option list */ #define ADDVOL_VOLUME_NAME_S 'n' @@ -276,8 +276,8 @@ #define CREATE_MORE_VOLUME_FILE_L "more-volume-file" #define CREATE_USER_DEFINITION_FILE_S 10108 #define CREATE_USER_DEFINITION_FILE_L "user-definition-file" -#define CREATE_CSQL_INITIALIZATION_FILE_S 10109 -#define CREATE_CSQL_INITIALIZATION_FILE_L "csql-initialization-file" +#define CREATE_ASQL_INITIALIZATION_FILE_S 10109 +#define CREATE_ASQL_INITIALIZATION_FILE_L "asql-initialization-file" #define CREATE_OUTPUT_FILE_S 'o' #define CREATE_OUTPUT_FILE_L "output-file" #define CREATE_VERBOSE_S 'v' @@ -403,19 +403,19 @@ #else #define UTIL_SCRIPT_EXT ".sh" #endif -#define UTIL_MASTER_NAME "cub_master" UTIL_EXE_EXT -#define UTIL_COMMDB_NAME "cub_commdb" UTIL_EXE_EXT -#define UTIL_CUBRID_NAME "cub_server" UTIL_EXE_EXT -#define UTIL_BROKER_NAME "cubrid_broker" UTIL_EXE_EXT +#define UTIL_MASTER_NAME "arn_master" UTIL_EXE_EXT +#define UTIL_COMMDB_NAME "arn_commdb" UTIL_EXE_EXT +#define UTIL_ARNIADB_NAME "arn_server" UTIL_EXE_EXT +#define UTIL_BROKER_NAME "arniadb_broker" UTIL_EXE_EXT #define UTIL_MONITOR_NAME "broker_monitor" UTIL_EXE_EXT #define UTIL_REPL_SERVER_NAME "repl_server" UTIL_EXE_EXT #define UTIL_REPL_AGENT_NAME "repl_agent" UTIL_EXE_EXT -#define UTIL_ADMIN_NAME "cub_admin" UTIL_EXE_EXT +#define UTIL_ADMIN_NAME "arn_admin" UTIL_EXE_EXT #define UTIL_SQLX_NAME "sqlx" UTIL_EXE_EXT -#define UTIL_CSQL_NAME "csql" UTIL_EXE_EXT -#define UTIL_CUBRID_REL_NAME "cubrid_rel" UTIL_EXE_EXT +#define UTIL_ASQL_NAME "asql" UTIL_EXE_EXT +#define UTIL_ARNIADB_REL_NAME "arniadb_rel" UTIL_EXE_EXT #define UTIL_OLD_COMMDB_NAME "commdb" UTIL_EXE_EXT -#define UTIL_CUBRID "cubrid" UTIL_EXE_EXT +#define UTIL_ARNIADB "arniadb" UTIL_EXE_EXT #define UTIL_CM_SERVER CMS_NAME UTIL_EXE_EXT #define UTIL_BROKER_CHANGER "broker_changer" UTIL_EXE_EXT @@ -531,7 +531,7 @@ typedef enum { FID_DBMT_CONF, FID_DBMT_PASS, - FID_DBMT_CUBRID_PASS, + FID_DBMT_ARNIADB_PASS, FID_CONN_LIST, FID_AUTO_ADDVOLDB_CONF, FID_AUTO_ADDVOLDB_LOG, @@ -569,10 +569,10 @@ typedef struct char *szProgname; /* - * CUBRID environment variables + * ARNIADB environment variables */ - char *szCubrid; /* CUBRID */ - char *szCubrid_databases; /* CUBRID_DATABASES */ + char *szArniadb; /* ARNIADB */ + char *szArniadb_databases; /* ARNIADB_DATABASES */ char *dbmt_tmp_dir; @@ -613,10 +613,10 @@ extern const char *autounicas_conf_entry[AUTOUNICAS_CONF_ENTRY_NUM]; extern const char *autobackup_period_type[AUTOBACKUP_PERIOD_TYPE_NUM]; extern const char *autobackup_period_week[AUTOBACKUP_PERIOD_WEEK_NUM]; -extern int cubrid_version_major; -extern int cubrid_version_minor; -void find_and_parse_cub_admin_version (int &major_version, int &minor_version); -#define IS_INVALID_CUBRID_VERS_MAJOR(major) (major <= 0) +extern int arniadb_version_major; +extern int arniadb_version_minor; +void find_and_parse_arn_admin_version (int &major_version, int &minor_version); +#define IS_INVALID_ARNIADB_VERS_MAJOR(major) (major <= 0) extern int auto_conf_delete (T_DBMT_FILE_ID fid, char *dbname); extern int auto_conf_rename (T_DBMT_FILE_ID fid, char *src_dbname, diff --git a/server/src/cm_http_server.cpp b/server/src/cm_http_server.cpp index 92e15ac..71f795b 100644 --- a/server/src/cm_http_server.cpp +++ b/server/src/cm_http_server.cpp @@ -615,7 +615,7 @@ static void http_error_404 (struct evhttp_request *req, int fd) "

404 Not Found

" \ "

Request: %s not found

"\ "
"\ - "
Cubrid Manager Server
"\ + "
Arniadb Manager Server
"\ "\n" struct evbuffer *buf = evbuffer_new (); @@ -652,7 +652,7 @@ static void web_error_404 (struct evhttp_request *req) "

404 Not Found

" \ "

Web Manager was not started, please configure it rightly

"\ "
"\ - "
Cubrid Manager Server
"\ + "
Arniadb Manager Server
"\ "\n" struct evbuffer *buf = evbuffer_new (); diff --git a/server/src/cm_httpd.cpp b/server/src/cm_httpd.cpp index b1e16b9..f07cd9d 100644 --- a/server/src/cm_httpd.cpp +++ b/server/src/cm_httpd.cpp @@ -116,8 +116,8 @@ struct worker_context #endif }; -int cubrid_version_major = -1; -int cubrid_version_minor = -1; +int arniadb_version_major = -1; +int arniadb_version_minor = -1; int bind_socket (int port) @@ -193,7 +193,7 @@ dispatch_thread (void *arg) } void -cub_add_private_param (struct evhttp_request *req, Json::Value &root) +arn_add_private_param (struct evhttp_request *req, Json::Value &root) { root["_CLIENTIP"] = req->remote_host; root["_CLIENTPORT"] = req->remote_port; @@ -202,7 +202,7 @@ cub_add_private_param (struct evhttp_request *req, Json::Value &root) } void -cub_generic_request_handler (struct evhttp_request *req, void *arg) +arn_generic_request_handler (struct evhttp_request *req, void *arg) { struct evbuffer *input; struct evkeyvalq *headers; @@ -263,15 +263,15 @@ cub_generic_request_handler (struct evhttp_request *req, void *arg) return; } - cub_add_private_param (req, root); + arn_add_private_param (req, root); if (!strcmp ((char *) arg, "cci")) { - cub_cci_request_handler (root, response); + arn_cci_request_handler (root, response); } else if (!strcmp ((char *) arg, "cm_api")) { - cub_cm_request_handler (root, response); + arn_cm_request_handler (root, response); } //outustr = utf8_encode(writer.write(response).c_str()); @@ -301,18 +301,18 @@ cub_generic_request_handler (struct evhttp_request *req, void *arg) return; } -static int cub_loop_flag = 1; +static int arn_loop_flag = 1; void -cub_ctrl_request_handler (struct evhttp_request *req, void *arg) +arn_ctrl_request_handler (struct evhttp_request *req, void *arg) { evhttp_send_reply (req, HTTP_OK, "", NULL); - cub_loop_flag = 0; + arn_loop_flag = 0; return; } void -cub_post_request_handler (struct evhttp_request *req, void *arg) +arn_post_request_handler (struct evhttp_request *req, void *arg) { string post_msg = "{ \"success\" : true }"; string req_uri (req->uri); @@ -396,10 +396,10 @@ cub_post_request_handler (struct evhttp_request *req, void *arg) } void -cub_timeout_cb (evutil_socket_t fd, short event, void *arg) +arn_timeout_cb (evutil_socket_t fd, short event, void *arg) { struct worker_context *work_ctx = (struct worker_context *) arg; - if (!cub_loop_flag) + if (!arn_loop_flag) { event_base_loopexit (work_ctx->base, NULL); } @@ -415,13 +415,13 @@ start_monitor_stat_cb (evutil_socket_t fd, short event, void *arg) struct timeval stat_tv = { STAT_MONITOR_INTERVAL, 0 }; struct worker_context *work_ctx = (struct worker_context *) arg; - if (!cub_loop_flag) + if (!arn_loop_flag) { event_base_loopexit (work_ctx->base, NULL); return; } - // [CUBRIDSUS-11917]sleep the thread for a while when the CUBRID is starting + // [CUBRIDSUS-11917]sleep the thread for a while when the ARNIADB is starting if (work_ctx->first) { SLEEP_SEC (MIN_INTERVAL - 1); @@ -441,7 +441,7 @@ start_monitor_auto_jobs_cb (evutil_socket_t fd, short event, void *arg) { struct timeval auto_task_tv = { sco.iMonitorInterval, 0 }; struct worker_context *work_ctx = (struct worker_context *) arg; - if (!cub_loop_flag) + if (!arn_loop_flag) { event_base_loopexit (work_ctx->base, NULL); return; @@ -495,9 +495,9 @@ start_service () if (nfd < 0) { snprintf (tmpstrbuf, DBMT_ERROR_MSG_SIZE, - "CUBRID Manager Server : The port %d is still used by other process.\n", + "ARNIADB Manager Server : The port %d is still used by other process.\n", sco.iCMS_port); - ut_record_cubrid_utility_log_stderr (tmpstrbuf); + ut_record_arniadb_utility_log_stderr (tmpstrbuf); return -1; } @@ -522,7 +522,7 @@ start_service () if (i > 1) /* DEFAULT_THRD_NUM - 1 for request handler */ { - start_ctx[i]->timer = event_new (start_ctx[i]->base, -1, EV_PERSIST, cub_timeout_cb, (void *) start_ctx[i]); + start_ctx[i]->timer = event_new (start_ctx[i]->base, -1, EV_PERSIST, arn_timeout_cb, (void *) start_ctx[i]); if (start_ctx[i]->timer == NULL) { continue; @@ -544,10 +544,10 @@ start_service () /* This is the magic that lets evhttp use SSL. */ evhttp_set_bevcb (start_ctx[i]->httpd, create_sslconn_cb, ctx); evhttp_set_cb (start_ctx[i]->httpd, "/cci", - cub_generic_request_handler, (void *) "cci"); - evhttp_set_cb (start_ctx[i]->httpd, "/cm_api", cub_generic_request_handler, (void *) "cm_api"); - evhttp_set_cb (start_ctx[i]->httpd, "/ctrl", cub_ctrl_request_handler, NULL); - evhttp_set_cb (start_ctx[i]->httpd, "/upload", cub_post_request_handler, NULL); + arn_generic_request_handler, (void *) "cci"); + evhttp_set_cb (start_ctx[i]->httpd, "/cm_api", arn_generic_request_handler, (void *) "cm_api"); + evhttp_set_cb (start_ctx[i]->httpd, "/ctrl", arn_ctrl_request_handler, NULL); + evhttp_set_cb (start_ctx[i]->httpd, "/upload", arn_post_request_handler, NULL); /* Start web server*/ evhttp_set_gencb (start_ctx[i]->httpd, load_webfiles_cb, (void *) sco.szCWMPath); } @@ -558,7 +558,7 @@ start_service () (void *) start_ctx[i]); if (start_ctx[i]->timer == NULL) { - ut_record_cubrid_utility_log_stderr ("CUBRID Manager Server : Failed to start monitor of auto job.\n"); + ut_record_arniadb_utility_log_stderr ("ARNIADB Manager Server : Failed to start monitor of auto job.\n"); return -1; } start_ctx[i]->httpd = NULL; @@ -570,8 +570,8 @@ start_service () (void *) start_ctx[i]); if (start_ctx[i]->timer == NULL) { - ut_record_cubrid_utility_log_stderr ( - "CUBRID Manager Server : Failed to start monitoring state job.\n"); + ut_record_arniadb_utility_log_stderr ( + "ARNIADB Manager Server : Failed to start monitoring state job.\n"); return -1; /* Start monitor status job failed */ } start_ctx[i]->httpd = NULL; @@ -632,20 +632,20 @@ stop_service () { FILE *pidfile = NULL; int pidnum = -1; - char cub_manager_pid_file[PATH_MAX]; + char arn_manager_pid_file[PATH_MAX]; char connect_list_file[PATH_MAX]; - cub_manager_pid_file[0] = '\0'; + arn_manager_pid_file[0] = '\0'; connect_list_file[0] = '\0'; - conf_get_dbmt_file (FID_CMSERVER_PID, cub_manager_pid_file); - if (access (cub_manager_pid_file, F_OK) < 0) + conf_get_dbmt_file (FID_CMSERVER_PID, arn_manager_pid_file); + if (access (arn_manager_pid_file, F_OK) < 0) { - ut_record_cubrid_utility_log_stderr ("CUBRID Manager Server : The server is not running.\n"); + ut_record_arniadb_utility_log_stderr ("ARNIADB Manager Server : The server is not running.\n"); } else { - pidfile = fopen (cub_manager_pid_file, "rt"); + pidfile = fopen (arn_manager_pid_file, "rt"); if (pidfile != NULL) { fscanf (pidfile, "%d", &pidnum); @@ -654,11 +654,11 @@ stop_service () if ((pidfile == NULL) || ((kill (pidnum, SIGTERM)) < 0)) { - ut_record_cubrid_utility_log_stderr ("CUBRID Manager Server : Failed to stop the server.\n"); + ut_record_arniadb_utility_log_stderr ("ARNIADB Manager Server : Failed to stop the server.\n"); } else { - unlink (conf_get_dbmt_file (FID_CMSERVER_PID, cub_manager_pid_file)); + unlink (conf_get_dbmt_file (FID_CMSERVER_PID, arn_manager_pid_file)); unlink (conf_get_dbmt_file (FID_CONN_LIST, connect_list_file)); } } @@ -854,7 +854,7 @@ main (int argc, char **argv) tmpstrbuf[0] = '\0'; - cub_cm_init_env (); + arn_cm_init_env (); if (argc >= 2) { if (strcmp (argv[1], "stop") == 0) @@ -864,7 +864,7 @@ main (int argc, char **argv) } else if (strcmp (argv[1], "--version") == 0) { - fprintf (stdout, "CUBRID Manager Server ver : %s\n", + fprintf (stdout, "ARNIADB Manager Server ver : %s\n", makestring (BUILD_NUMBER)); exit (0); } @@ -879,8 +879,8 @@ main (int argc, char **argv) } else if (strcmp (argv[1], PRINT_CMD_START) != 0) { - snprintf (tmpstrbuf, DBMT_ERROR_MSG_SIZE, "CUBRID Manager Server : Invalid command - %s\n", argv[1]); - ut_record_cubrid_utility_log_stderr (tmpstrbuf); + snprintf (tmpstrbuf, DBMT_ERROR_MSG_SIZE, "ARNIADB Manager Server : Invalid command - %s\n", argv[1]); + ut_record_arniadb_utility_log_stderr (tmpstrbuf); print_usage (argv[0]); exit (1); } @@ -889,8 +889,8 @@ main (int argc, char **argv) if ((pidnum = get_processid ()) > 0) { snprintf (tmpstrbuf, DBMT_ERROR_MSG_SIZE, - "CUBRID Manager Server : The [pid=%d] process has been running.\n", pidnum); - ut_record_cubrid_utility_log_stderr (tmpstrbuf); + "ARNIADB Manager Server : The [pid=%d] process has been running.\n", pidnum); + ut_record_arniadb_utility_log_stderr (tmpstrbuf); return 0; } @@ -905,15 +905,15 @@ main (int argc, char **argv) if (ut_write_pid (conf_get_dbmt_file (FID_CMSERVER_PID, dbmt_file)) < 0) { snprintf (tmpstrbuf, DBMT_ERROR_MSG_SIZE, - "CUBRID Manager Server : Fail to store the pid file in (%s).\n", dbmt_file); - ut_record_cubrid_utility_log_stderr (tmpstrbuf); + "ARNIADB Manager Server : Fail to store the pid file in (%s).\n", dbmt_file); + ut_record_arniadb_utility_log_stderr (tmpstrbuf); exit (1); } start_auto_thread (); - find_and_parse_cub_admin_version (cubrid_version_major, cubrid_version_minor); - LOG_INFO ("started '%s' with Engine Version: %d.%d", argv[0], cubrid_version_major, cubrid_version_minor); + find_and_parse_arn_admin_version (arniadb_version_major, arniadb_version_minor); + LOG_INFO ("started '%s' with Engine Version: %d.%d", argv[0], arniadb_version_major, arniadb_version_minor); start_service (); diff --git a/server/src/cm_job_task.cpp b/server/src/cm_job_task.cpp index cd70f34..858356f 100644 --- a/server/src/cm_job_task.cpp +++ b/server/src/cm_job_task.cpp @@ -92,7 +92,7 @@ using namespace std; #define DBMT_ERR_MSG_SET(ERR_BUF, MSG) \ strncpy(ERR_BUF, MSG, DBMT_ERROR_MSG_SIZE - 1) -#define CUBRID_ERR_MSG_SET(ERR_BUF) \ +#define ARNIADB_ERR_MSG_SET(ERR_BUF) \ DBMT_ERR_MSG_SET(ERR_BUF, db_error_string(1)) #define MAX_BROKER_NAMELENGTH 128 @@ -281,7 +281,7 @@ static char *get_ip_from_hostname (char *hostname, char *ipaddr, int ip_len); static int parse_standby_server_stat (T_STANDBY_SERVER_STAT *stat, FILE *outfile, char *_dbmt_error); static int analyze_heartbeat_cmd_outfile (FILE *infile, char *_dbmt_error); -static char *cub_admin_cmd_name (char *cmd_name, int buf_len); +static char *arn_admin_cmd_name (char *cmd_name, int buf_len); static int cmd_get_db_mode (T_DB_MODE_INFO *dbmode, char *dbname, char *dbmt_error); static int fill_dbmode_into_dbinfo_list (T_HA_SERVER_INFO_ALL **all_info, @@ -299,7 +299,7 @@ static int cmd_heartbeat_act (char *_dbmt_error); static int cmd_heartbeat_deact (char *_dbmt_error); static int cmd_changemode (char *dbname, char *modify, char *force, char *server_mode_out, int mode_len, char *_dbmt_error); -static int run_csql_statement (const char *sql_stat, char *dbname, +static int run_asql_statement (const char *sql_stat, char *dbname, char *dbuser, char *dbpasswd, char *outfilepath, char *_dbmt_error); static void set_copylogdb_mode (T_HA_LOG_PROC_INFO *copylogdb); @@ -363,9 +363,9 @@ _verify_user_passwd (char *dbname, char *dbuser, char *dbpasswd, } /* - * using csql to verify the user's password. + * using asql to verify the user's password. */ - retval = run_csql_statement (sql_stat, dbname, dbuser, dbpasswd, NULL, _dbmt_error); /* csql */ + retval = run_asql_statement (sql_stat, dbname, dbuser, dbpasswd, NULL, _dbmt_error); /* asql */ return retval; } @@ -441,7 +441,7 @@ ts_add_nvp_time (nvplist *ref, const char *name, time_t t, const char *fmt, } } -/* if cubrid.conf's error_log is null, construct it by default value if existing */ +/* if arniadb.conf's error_log is null, construct it by default value if existing */ static char * _ts_get_error_log_param (char *dbname) { @@ -454,10 +454,10 @@ _ts_get_error_log_param (char *dbname) return NULL; } -#if !defined (DO_NOT_USE_CUBRIDENV) - snprintf (buf, PATH_MAX - 1, "%s/conf/%s", sco.szCubrid, CUBRID_CUBRID_CONF); +#if !defined (DO_NOT_USE_ARNIADBENV) + snprintf (buf, PATH_MAX - 1, "%s/conf/%s", sco.szArniadb, ARNIADB_ARNIADB_CONF); #else - snprintf (buf, PATH_MAX - 1, "%s/%s", CUBRID_CONFDIR, CUBRID_CUBRID_CONF); + snprintf (buf, PATH_MAX - 1, "%s/%s", ARNIADB_CONFDIR, ARNIADB_ARNIADB_CONF); #endif if ((infile = fopen (buf, "r")) == NULL) @@ -667,29 +667,29 @@ ts_get_diagdata (nvplist *cli_request, nvplist *cli_response, #else nv_add_nvp (cli_response, "db_mon", "start"); #endif - nv_add_nvp_int64 (cli_response, "mon_cub_query_open_page", + nv_add_nvp_int64 (cli_response, "mon_arn_query_open_page", server_result.query_open_page); - nv_add_nvp_int64 (cli_response, "mon_cub_query_opened_page", + nv_add_nvp_int64 (cli_response, "mon_arn_query_opened_page", server_result.query_opened_page); - nv_add_nvp_int64 (cli_response, "mon_cub_query_slow_query", + nv_add_nvp_int64 (cli_response, "mon_arn_query_slow_query", server_result.query_slow_query); - nv_add_nvp_int64 (cli_response, "mon_cub_query_full_scan", + nv_add_nvp_int64 (cli_response, "mon_arn_query_full_scan", server_result.query_full_scan); - nv_add_nvp_int64 (cli_response, "mon_cub_lock_deadlock", + nv_add_nvp_int64 (cli_response, "mon_arn_lock_deadlock", server_result.lock_deadlock); - nv_add_nvp_int64 (cli_response, "mon_cub_lock_request", + nv_add_nvp_int64 (cli_response, "mon_arn_lock_request", server_result.lock_request); - nv_add_nvp_int64 (cli_response, "mon_cub_conn_cli_request", + nv_add_nvp_int64 (cli_response, "mon_arn_conn_cli_request", server_result.conn_cli_request); - nv_add_nvp_int64 (cli_response, "mon_cub_conn_aborted_clients", + nv_add_nvp_int64 (cli_response, "mon_arn_conn_aborted_clients", server_result.conn_aborted_clients); - nv_add_nvp_int64 (cli_response, "mon_cub_conn_conn_req", + nv_add_nvp_int64 (cli_response, "mon_arn_conn_conn_req", server_result.conn_conn_req); - nv_add_nvp_int64 (cli_response, "mon_cub_conn_conn_reject", + nv_add_nvp_int64 (cli_response, "mon_arn_conn_conn_reject", server_result.conn_conn_reject); - nv_add_nvp_int64 (cli_response, "mon_cub_buffer_page_write", + nv_add_nvp_int64 (cli_response, "mon_arn_buffer_page_write", server_result.buffer_page_write); - nv_add_nvp_int64 (cli_response, "mon_cub_buffer_page_read", + nv_add_nvp_int64 (cli_response, "mon_arn_buffer_page_read", server_result.buffer_page_read); #ifdef JSON_SUPPORT nv_add_nvp (cli_response, "close", "db_mon"); @@ -1101,7 +1101,7 @@ ts2_get_logfile_info (nvplist *in, nvplist *out, char *_dbmt_error) strcpy (_dbmt_error, "broker"); return ERR_PARAM_MISSING; } - chdir (sco.szCubrid); + chdir (sco.szArniadb); if (cm_get_broker_conf (&uc_conf, NULL, &error) < 0) { strcpy (_dbmt_error, error.err_msg); @@ -1309,7 +1309,7 @@ ts2_get_add_broker_info (nvplist *in, nvplist *out, char *_dbmt_error) FILE *infile; char broker_conf_path[PATH_MAX], strbuf[1024]; - cm_get_broker_file (UC_FID_CUBRID_BROKER_CONF, broker_conf_path); + cm_get_broker_file (UC_FID_ARNIADB_BROKER_CONF, broker_conf_path); if (access (broker_conf_path, F_OK) < 0) { @@ -1485,7 +1485,7 @@ ts2_set_broker_conf (nvplist *in, nvplist *out, char *_dbmt_error) char *conf, *confdata; int nv_len, i; - cm_get_broker_file (UC_FID_CUBRID_BROKER_CONF, broker_conf_path); + cm_get_broker_file (UC_FID_ARNIADB_BROKER_CONF, broker_conf_path); if ((outfile = fopen (broker_conf_path, "w")) == NULL) { @@ -1679,29 +1679,29 @@ _get_confpath_by_name (const char *conf_name, char *conf_path, int buflen) { int retval = 0; - if (uStringEqual (conf_name, "cubridconf")) + if (uStringEqual (conf_name, "arniadbconf")) { - snprintf (conf_path, buflen - 1, "%s/conf/%s", sco.szCubrid, - CUBRID_CUBRID_CONF); + snprintf (conf_path, buflen - 1, "%s/conf/%s", sco.szArniadb, + ARNIADB_ARNIADB_CONF); } else if (uStringEqual (conf_name, "cmconf")) { - snprintf (conf_path, buflen - 1, "%s/conf/%s", sco.szCubrid, - CUBRID_DBMT_CONF); + snprintf (conf_path, buflen - 1, "%s/conf/%s", sco.szArniadb, + ARNIADB_DBMT_CONF); } else if (uStringEqual (conf_name, "haconf")) { - snprintf (conf_path, buflen - 1, "%s/conf/%s", sco.szCubrid, - CUBRID_HA_CONF); + snprintf (conf_path, buflen - 1, "%s/conf/%s", sco.szArniadb, + ARNIADB_HA_CONF); } else if (uStringEqual (conf_name, "databases")) { - snprintf (conf_path, buflen - 1, "%s/%s", sco.szCubrid_databases, - CUBRID_DATABASE_TXT); + snprintf (conf_path, buflen - 1, "%s/%s", sco.szArniadb_databases, + ARNIADB_DATABASE_TXT); } else { - snprintf (conf_path, buflen - 1, "%s/conf/%s", sco.szCubrid, conf_name); + snprintf (conf_path, buflen - 1, "%s/conf/%s", sco.szArniadb, conf_name); } return retval; @@ -1918,7 +1918,7 @@ tsDeleteDBMTUser (nvplist *req, nvplist *res, char *_dbmt_error) } if (usr_index < 0) { - strcpy (_dbmt_error, conf_get_dbmt_file2 (FID_DBMT_CUBRID_PASS, file)); + strcpy (_dbmt_error, conf_get_dbmt_file2 (FID_DBMT_ARNIADB_PASS, file)); dbmt_user_free (&dbmt_user); return ERR_FILE_INTEGRITY; } @@ -2104,7 +2104,7 @@ tsUpdateDBMTUser (nvplist *req, nvplist *res, char *_dbmt_error) } if (usr_index < 0) { - strcpy (_dbmt_error, conf_get_dbmt_file2 (FID_DBMT_CUBRID_PASS, file)); + strcpy (_dbmt_error, conf_get_dbmt_file2 (FID_DBMT_ARNIADB_PASS, file)); dbmt_user_free (&dbmt_user); if (usr_dbinfo != NULL) { @@ -2300,7 +2300,7 @@ tsChangeDBMTUserPasswd (nvplist *req, nvplist *res, char *_dbmt_error) } if (usr_index < 0) { - strcpy (_dbmt_error, conf_get_dbmt_file2 (FID_DBMT_CUBRID_PASS, file)); + strcpy (_dbmt_error, conf_get_dbmt_file2 (FID_DBMT_ARNIADB_PASS, file)); dbmt_user_free (&dbmt_user); return ERR_FILE_INTEGRITY; } @@ -2375,7 +2375,7 @@ tsCreateDB (nvplist *req, nvplist *res, char *_dbmt_error) char *ip, *port; T_DBMT_USER dbmt_user; T_DBMT_CON_DBINFO con_dbinfo; - char cmd_name[CUBRID_CMD_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; const char *argv[20]; int argc = 0; int gen_dir_created, log_dir_created, ext_dir_created; @@ -2509,12 +2509,12 @@ tsCreateDB (nvplist *req, nvplist *res, char *_dbmt_error) FILE *outfile = NULL; char dstrbuf[PATH_MAX]; -#if !defined (DO_NOT_USE_CUBRIDENV) - snprintf (dstrbuf, PATH_MAX - 1, "%s/conf/%s", sco.szCubrid, - CUBRID_CUBRID_CONF); +#if !defined (DO_NOT_USE_ARNIADBENV) + snprintf (dstrbuf, PATH_MAX - 1, "%s/conf/%s", sco.szArniadb, + ARNIADB_ARNIADB_CONF); #else - snprintf (dstrbuf, PATH_MAX - 1, "%s/%s", CUBRID_CONFDIR, - CUBRID_CUBRID_CONF); + snprintf (dstrbuf, PATH_MAX - 1, "%s/%s", ARNIADB_CONFDIR, + ARNIADB_ARNIADB_CONF); #endif infile = fopen (dstrbuf, "r"); if (infile == NULL) @@ -2523,7 +2523,7 @@ tsCreateDB (nvplist *req, nvplist *res, char *_dbmt_error) return ERR_FILE_OPEN_FAIL; } - snprintf (dstrbuf, PATH_MAX - 1, "%s/%s", targetdir, CUBRID_CUBRID_CONF); + snprintf (dstrbuf, PATH_MAX - 1, "%s/%s", targetdir, ARNIADB_ARNIADB_CONF); outfile = fopen (dstrbuf, "w"); if (outfile == NULL) { @@ -2580,7 +2580,7 @@ tsCreateDB (nvplist *req, nvplist *res, char *_dbmt_error) memset (newfilename, '\0', sizeof (newfilename)); snprintf (oldfilename, PATH_MAX - 1, "%s/%s", targetdir, - CUBRID_CUBRID_CONF); + ARNIADB_ARNIADB_CONF); infile = fopen (oldfilename, "r"); if (infile == NULL) { @@ -2588,7 +2588,7 @@ tsCreateDB (nvplist *req, nvplist *res, char *_dbmt_error) return ERR_FILE_OPEN_FAIL; } - snprintf (newfilename, PATH_MAX - 1, "%s/tempcubrid.conf", targetdir); + snprintf (newfilename, PATH_MAX - 1, "%s/temparniadb.conf", targetdir); outfile = fopen (newfilename, "w"); if (outfile == NULL) { @@ -2661,7 +2661,7 @@ tsCreateDB (nvplist *req, nvplist *res, char *_dbmt_error) } /* construct command */ - cubrid_cmd_name (cmd_name); + arniadb_cmd_name (cmd_name); #if defined(WINDOWS) nt_style_path (targetdir, targetdir); #endif @@ -2834,7 +2834,7 @@ tsCreateDB (nvplist *req, nvplist *res, char *_dbmt_error) memset (newfilename, '\0', sizeof (newfilename)); snprintf (oldfilename, PATH_MAX - 1, "%s/%s", targetdir, - CUBRID_CUBRID_CONF); + ARNIADB_ARNIADB_CONF); infile = fopen (oldfilename, "r"); if (infile == NULL) { @@ -2842,7 +2842,7 @@ tsCreateDB (nvplist *req, nvplist *res, char *_dbmt_error) return ERR_FILE_OPEN_FAIL; } - snprintf (newfilename, PATH_MAX - 1, "%s/tempcubrid.conf", targetdir); + snprintf (newfilename, PATH_MAX - 1, "%s/temparniadb.conf", targetdir); outfile = fopen (newfilename, "w"); if (outfile == NULL) { @@ -2875,7 +2875,7 @@ tsCreateDB (nvplist *req, nvplist *res, char *_dbmt_error) { char strbuf[PATH_MAX]; - snprintf (strbuf, PATH_MAX - 1, "%s/%s", targetdir, CUBRID_CUBRID_CONF); + snprintf (strbuf, PATH_MAX - 1, "%s/%s", targetdir, ARNIADB_ARNIADB_CONF); unlink (strbuf); } @@ -2892,8 +2892,8 @@ tsDeleteDB (nvplist *req, nvplist *res, char *_dbmt_error) T_DBMT_USER dbmt_user; int retval = ERR_NO_ERROR; char *dbname = NULL, *delbackup; - char cubrid_err_file[PATH_MAX]; - char cmd_name[CUBRID_CMD_NAME_LEN]; + char arniadb_err_file[PATH_MAX]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; const char *argv[6]; int argc = 0; @@ -2901,7 +2901,7 @@ tsDeleteDB (nvplist *req, nvplist *res, char *_dbmt_error) char dbvolpath[PATH_MAX]; char dblogpath[PATH_MAX]; - cubrid_err_file[0] = '\0'; + arniadb_err_file[0] = '\0'; if ((dbname = nv_get_val (req, "_DBNAME")) == NULL) { @@ -2917,7 +2917,7 @@ tsDeleteDB (nvplist *req, nvplist *res, char *_dbmt_error) delbackup = nv_get_val (req, "delbackup"); - cubrid_cmd_name (cmd_name); + arniadb_cmd_name (cmd_name); argv[argc++] = cmd_name; argv[argc++] = UTIL_OPTION_DELETEDB; if (uStringEqual (delbackup, "y")) @@ -2927,26 +2927,26 @@ tsDeleteDB (nvplist *req, nvplist *res, char *_dbmt_error) argv[argc++] = dbname; argv[argc++] = NULL; - snprintf (cubrid_err_file, PATH_MAX, "%s/%s.%u.err.tmp", + snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", sco.dbmt_tmp_dir, "deletedb", getpid ()); /*get dbvolpath and dblogpath. */ - get_dbvoldir (dbvolpath, sizeof (dbvolpath), dbname, cubrid_err_file); - get_dblogdir (dblogpath, sizeof (dblogpath), dbname, cubrid_err_file); + get_dbvoldir (dbvolpath, sizeof (dbvolpath), dbname, arniadb_err_file); + get_dblogdir (dblogpath, sizeof (dblogpath), dbname, arniadb_err_file); - retval = run_child (argv, 1, NULL, NULL, cubrid_err_file, NULL); /* deletedb */ + retval = run_child (argv, 1, NULL, NULL, arniadb_err_file, NULL); /* deletedb */ - if (read_error_file (cubrid_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) + if (read_error_file (arniadb_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) { - if (access (cubrid_err_file, F_OK) == 0) + if (access (arniadb_err_file, F_OK) == 0) { - unlink (cubrid_err_file); + unlink (arniadb_err_file); } return ERR_WITH_MSG; } - if (access (cubrid_err_file, F_OK) == 0) + if (access (arniadb_err_file, F_OK) == 0) { - unlink (cubrid_err_file); + unlink (arniadb_err_file); } if (retval < 0) { @@ -2994,7 +2994,7 @@ tsRenameDB (nvplist *req, nvplist *res, char *_dbmt_error) T_DB_SERVICE_MODE db_mode; T_DBMT_USER dbmt_user; - char cmd_name[CUBRID_CMD_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; char tmpfile[PATH_MAX]; cmd_name[0] = '\0'; @@ -3039,7 +3039,7 @@ tsRenameDB (nvplist *req, nvplist *res, char *_dbmt_error) return ERR_DB_ACTIVE; } - cubrid_cmd_name (cmd_name); + arniadb_cmd_name (cmd_name); argv[argc++] = cmd_name; argv[argc++] = UTIL_OPTION_RENAMEDB; @@ -3243,7 +3243,7 @@ tsDbspaceInfo (nvplist *req, nvplist *res, char *_dbmt_error) const char *err_message; char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; int ha_mode = 0; - T_CUBRID_MODE cubrid_mode; + T_ARNIADB_MODE arniadb_mode; GeneralSpacedbResult *cmd_res; T_DB_SERVICE_MODE db_mode; @@ -3265,17 +3265,17 @@ tsDbspaceInfo (nvplist *req, nvplist *res, char *_dbmt_error) nv_add_nvp (res, "pagesize", "-1"); nv_add_nvp (res, "logpagesize", "-1"); - cubrid_mode = - (db_mode == DB_SERVICE_MODE_NONE) ? CUBRID_MODE_SA : CUBRID_MODE_CS; + arniadb_mode = + (db_mode == DB_SERVICE_MODE_NONE) ? ARNIADB_MODE_SA : ARNIADB_MODE_CS; if (ha_mode != 0) { append_host_to_dbname (dbname_at_hostname, dbname, sizeof (dbname_at_hostname)); - cmd_res = cmd_spacedb (dbname_at_hostname, cubrid_mode); + cmd_res = cmd_spacedb (dbname_at_hostname, arniadb_mode); } else { - cmd_res = cmd_spacedb (dbname, cubrid_mode); + cmd_res = cmd_spacedb (dbname, arniadb_mode); } err_message = cmd_res->get_err_msg(); @@ -3375,7 +3375,7 @@ tsRunAddvoldb (nvplist *req, nvplist *res, char *_dbmt_error) T_DB_SERVICE_MODE db_mode; char err_file[PATH_MAX]; int ret; - char cmd_name[CUBRID_CMD_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; const char *argv[15]; int argc = 0; int free_space_mb; @@ -3450,7 +3450,7 @@ tsRunAddvoldb (nvplist *req, nvplist *res, char *_dbmt_error) snprintf (dbvolsize_t, sizeof (dbvolsize_t) - 1, "%lldB", (long long) (atof (dbvolsize) * BYTES_IN_M)); - cubrid_cmd_name (cmd_name); + arniadb_cmd_name (cmd_name); argv[argc++] = cmd_name; argv[argc++] = UTIL_OPTION_ADDVOLDB; @@ -3529,12 +3529,12 @@ ts_copydb (nvplist *req, nvplist *res, char *_dbmt_error) int move_flag = 0; int overwrite_flag = 0; int adv_flag = 0; - char tmpfile[PATH_MAX], cmd_name[CUBRID_CMD_NAME_LEN], + char tmpfile[PATH_MAX], cmd_name[ARNIADB_CMD_NAME_LEN], lob_base_path[PATH_MAX]; char src_conf_file[PATH_MAX], dest_conf_file[PATH_MAX], conf_dir[PATH_MAX]; int i = -1; int retval = -1; - char cubrid_err_file[PATH_MAX]; + char arniadb_err_file[PATH_MAX]; T_DBMT_USER dbmt_user; T_DB_SERVICE_MODE db_mode; const char *argv[15]; @@ -3547,7 +3547,7 @@ ts_copydb (nvplist *req, nvplist *res, char *_dbmt_error) src_conf_file[0] = '\0'; dest_conf_file[0] = '\0'; conf_dir[0] = '\0'; - cubrid_err_file[0] = '\0'; + arniadb_err_file[0] = '\0'; if ((srcdbname = nv_get_val (req, "srcdbname")) == NULL) { @@ -3593,7 +3593,7 @@ ts_copydb (nvplist *req, nvplist *res, char *_dbmt_error) } /* create command */ - cubrid_cmd_name (cmd_name); + arniadb_cmd_name (cmd_name); argv[argc++] = cmd_name; argv[argc++] = UTIL_OPTION_COPYDB; argv[argc++] = "--" COPY_LOG_PATH_L; @@ -3703,25 +3703,25 @@ ts_copydb (nvplist *req, nvplist *res, char *_dbmt_error) return ERR_DIR_CREATE_FAIL; } - snprintf (cubrid_err_file, PATH_MAX, "%s/%s.%u.err.tmp", + snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", sco.dbmt_tmp_dir, "copydb", getpid ()); - retval = run_child (argv, 1, NULL, NULL, cubrid_err_file, NULL); /* copydb */ + retval = run_child (argv, 1, NULL, NULL, arniadb_err_file, NULL); /* copydb */ if (adv_flag) { unlink (tmpfile); } - if (read_error_file (cubrid_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) + if (read_error_file (arniadb_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) { - if (access (cubrid_err_file, F_OK) == 0) + if (access (arniadb_err_file, F_OK) == 0) { - unlink (cubrid_err_file); + unlink (arniadb_err_file); } return ERR_WITH_MSG; } - if (access (cubrid_err_file, F_OK) == 0) + if (access (arniadb_err_file, F_OK) == 0) { - unlink (cubrid_err_file); + unlink (arniadb_err_file); } if (retval < 0) { @@ -3735,14 +3735,14 @@ ts_copydb (nvplist *req, nvplist *res, char *_dbmt_error) strcpy (_dbmt_error, srcdbname); return ERR_DBDIRNAME_NULL; } - snprintf (src_conf_file, sizeof (src_conf_file) - 1, "%s/%s", conf_dir, CUBRID_CUBRID_CONF); + snprintf (src_conf_file, sizeof (src_conf_file) - 1, "%s/%s", conf_dir, ARNIADB_ARNIADB_CONF); if (uRetrieveDBDirectory (destdbname, conf_dir) != ERR_NO_ERROR) { strcpy (_dbmt_error, destdbname); return ERR_DBDIRNAME_NULL; } - snprintf (dest_conf_file, sizeof (dest_conf_file) - 1, "%s/%s", conf_dir, CUBRID_CUBRID_CONF); + snprintf (dest_conf_file, sizeof (dest_conf_file) - 1, "%s/%s", conf_dir, ARNIADB_ARNIADB_CONF); /* Doesn't copy if src and desc is same */ if (strcmp (src_conf_file, dest_conf_file) != 0) @@ -3753,10 +3753,10 @@ ts_copydb (nvplist *req, nvplist *res, char *_dbmt_error) /* if move, delete exist database */ if (move_flag) { - char cmd_name[CUBRID_CMD_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; const char *argv[5]; - cubrid_cmd_name (cmd_name); + arniadb_cmd_name (cmd_name); argv[0] = cmd_name; argv[1] = UTIL_OPTION_DELETEDB; argv[2] = srcdbname; @@ -3812,15 +3812,15 @@ ts_plandump (nvplist *req, nvplist *res, char *_dbmt_error) char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; int ha_mode = 0; T_DB_SERVICE_MODE db_mode; - char cmd_name[CUBRID_CMD_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; char *plandrop = NULL; const char *argv[10]; int argc = 0; - char cubrid_err_file[PATH_MAX]; + char arniadb_err_file[PATH_MAX]; char tmpfilepath[PATH_MAX]; int retval = ERR_NO_ERROR; - cubrid_err_file[0] = '\0'; + arniadb_err_file[0] = '\0'; if ((dbname = nv_get_val (req, "dbname")) == NULL) { @@ -3840,7 +3840,7 @@ ts_plandump (nvplist *req, nvplist *res, char *_dbmt_error) return ERR_STANDALONE_MODE; } - cubrid_cmd_name (cmd_name); + arniadb_cmd_name (cmd_name); argv[argc++] = cmd_name; argv[argc++] = UTIL_OPTION_PLANDUMP; if (uStringEqual (plandrop, "y")) @@ -3861,7 +3861,7 @@ ts_plandump (nvplist *req, nvplist *res, char *_dbmt_error) argv[argc++] = NULL; - snprintf (cubrid_err_file, PATH_MAX, "%s/%s.%u.err.tmp", + snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", sco.dbmt_tmp_dir, "plandump", getpid ()); /* @@ -3871,14 +3871,14 @@ ts_plandump (nvplist *req, nvplist *res, char *_dbmt_error) snprintf (tmpfilepath, PATH_MAX - 1, "%s/DBMT_task_%d.%d", sco.dbmt_tmp_dir, TS_PLANDUMP, (int) getpid ()); - if (run_child (argv, 1, NULL, tmpfilepath, cubrid_err_file, NULL) < 0) /* plandump */ + if (run_child (argv, 1, NULL, tmpfilepath, arniadb_err_file, NULL) < 0) /* plandump */ { strcpy (_dbmt_error, argv[0]); retval = ERR_SYSTEM_CALL; goto rm_tmpfile; } - if (read_error_file (cubrid_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) + if (read_error_file (arniadb_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) { retval = ERR_WITH_MSG; goto rm_tmpfile; @@ -3894,9 +3894,9 @@ ts_plandump (nvplist *req, nvplist *res, char *_dbmt_error) rm_tmpfile: unlink (tmpfilepath); - if (access (cubrid_err_file, F_OK) == 0) + if (access (arniadb_err_file, F_OK) == 0) { - unlink (cubrid_err_file); + unlink (arniadb_err_file); } return retval; } @@ -3909,15 +3909,15 @@ ts_paramdump (nvplist *req, nvplist *res, char *_dbmt_error) int ha_mode = 0; char *bothclientserver = NULL; T_DB_SERVICE_MODE db_mode; - char cmd_name[CUBRID_CMD_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; const char *argv[10]; int argc = 0; - char cubrid_err_file[PATH_MAX]; + char arniadb_err_file[PATH_MAX]; FILE *infile = NULL; char tmpfilepath[PATH_MAX]; int retval = ERR_NO_ERROR; - cubrid_err_file[0] = '\0'; + arniadb_err_file[0] = '\0'; if ((dbname = nv_get_val (req, "dbname")) == NULL) { @@ -3939,7 +3939,7 @@ ts_paramdump (nvplist *req, nvplist *res, char *_dbmt_error) return ERR_STANDALONE_MODE; } - cubrid_cmd_name (cmd_name); + arniadb_cmd_name (cmd_name); argv[argc++] = cmd_name; argv[argc++] = UTIL_OPTION_PARAMDUMP; if (db_mode == DB_SERVICE_MODE_NONE) @@ -3968,7 +3968,7 @@ ts_paramdump (nvplist *req, nvplist *res, char *_dbmt_error) argv[argc++] = NULL; - snprintf (cubrid_err_file, PATH_MAX, "%s/%s.%u.err.tmp", sco.dbmt_tmp_dir, "paramdump", getpid ()); + snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", sco.dbmt_tmp_dir, "paramdump", getpid ()); /* * create a new tmp file to record the content @@ -3976,14 +3976,14 @@ ts_paramdump (nvplist *req, nvplist *res, char *_dbmt_error) */ snprintf (tmpfilepath, PATH_MAX - 1, "%s/DBMT_task_%d.%d", sco.dbmt_tmp_dir, TS_PARAMDUMP, (int) getpid ()); - if (run_child (argv, 1, NULL, tmpfilepath, cubrid_err_file, NULL) < 0) /* paramdump */ + if (run_child (argv, 1, NULL, tmpfilepath, arniadb_err_file, NULL) < 0) /* paramdump */ { strcpy (_dbmt_error, argv[0]); retval = ERR_SYSTEM_CALL; goto rm_tmpfile; } - if (read_error_file (cubrid_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) + if (read_error_file (arniadb_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) { retval = ERR_WITH_MSG; goto rm_tmpfile; @@ -4012,9 +4012,9 @@ ts_paramdump (nvplist *req, nvplist *res, char *_dbmt_error) rm_tmpfile: unlink (tmpfilepath); - if (access (cubrid_err_file, F_OK) == 0) + if (access (arniadb_err_file, F_OK) == 0) { - unlink (cubrid_err_file); + unlink (arniadb_err_file); } return retval; } @@ -4029,7 +4029,7 @@ int ts_checkdb (nvplist *req, nvplist *res, char *_dbmt_error) { char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; - char cmd_name[CUBRID_CMD_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; char task_name[TASKNAME_LEN]; const char *argv[7]; T_DB_SERVICE_MODE db_mode; @@ -4068,7 +4068,7 @@ ts_checkdb (nvplist *req, nvplist *res, char *_dbmt_error) return ERR_STANDALONE_MODE; } - cubrid_cmd_name (cmd_name); + arniadb_cmd_name (cmd_name); argv[argc++] = cmd_name; argv[argc++] = UTIL_OPTION_CHECKDB; if (db_mode == DB_SERVICE_MODE_NONE) @@ -4277,7 +4277,7 @@ ts_statdump (nvplist *req, nvplist *res, char *_dbmt_error) int ts_compactdb (nvplist *req, nvplist *res, char *_dbmt_error) { - char cmd_name[CUBRID_CMD_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; char out_file[PATH_MAX]; char err_file[PATH_MAX]; @@ -4322,7 +4322,7 @@ ts_compactdb (nvplist *req, nvplist *res, char *_dbmt_error) return ERR_STANDALONE_MODE; } - cubrid_cmd_name (cmd_name); + arniadb_cmd_name (cmd_name); argv[argc++] = cmd_name; argv[argc++] = UTIL_OPTION_COMPACTDB; if (uStringEqual (verbose, "y")) @@ -4404,15 +4404,15 @@ ts_backupdb (nvplist *req, nvplist *res, char *_dbmt_error) char *mt, *zip, *safe_replication; char backupfilepath[PATH_MAX]; char inputfilepath[PATH_MAX]; - char cmd_name[CUBRID_CMD_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; char sp_option[256]; const char *argv[16]; int argc = 0; FILE *inputfile; T_DB_SERVICE_MODE db_mode; - char cubrid_err_file[PATH_MAX]; + char arniadb_err_file[PATH_MAX]; - cubrid_err_file[0] = '\0'; + arniadb_err_file[0] = '\0'; if ((dbname = nv_get_val (req, "dbname")) == NULL) { @@ -4453,7 +4453,7 @@ ts_backupdb (nvplist *req, nvplist *res, char *_dbmt_error) } } - cubrid_cmd_name (cmd_name); + arniadb_cmd_name (cmd_name); argv[argc++] = cmd_name; argv[argc++] = UTIL_OPTION_BACKUPDB; if (db_mode == DB_SERVICE_MODE_NONE) @@ -4519,35 +4519,35 @@ ts_backupdb (nvplist *req, nvplist *res, char *_dbmt_error) return ERR_FILE_OPEN_FAIL; } - snprintf (cubrid_err_file, PATH_MAX, "%s/%s.%u.err.tmp", + snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", sco.dbmt_tmp_dir, "backupdb", getpid ()); - if (run_child (argv, 1, inputfilepath, NULL, cubrid_err_file, NULL) < 0) + if (run_child (argv, 1, inputfilepath, NULL, arniadb_err_file, NULL) < 0) { /* backupdb */ strcpy (_dbmt_error, argv[0]); unlink (inputfilepath); - if (access (cubrid_err_file, F_OK) == 0) + if (access (arniadb_err_file, F_OK) == 0) { - unlink (cubrid_err_file); + unlink (arniadb_err_file); } return ERR_SYSTEM_CALL; } unlink (inputfilepath); - if (read_error_file (cubrid_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) + if (read_error_file (arniadb_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) { - if (access (cubrid_err_file, F_OK) == 0) + if (access (arniadb_err_file, F_OK) == 0) { - unlink (cubrid_err_file); + unlink (arniadb_err_file); } return ERR_WITH_MSG; } - if (access (cubrid_err_file, F_OK) == 0) + if (access (arniadb_err_file, F_OK) == 0) { - unlink (cubrid_err_file); + unlink (arniadb_err_file); } return ERR_NO_ERROR; } @@ -4562,8 +4562,8 @@ ts_unloaddb (nvplist *req, nvplist *res, char *_dbmt_error) char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; int ha_mode = 0; - char cmd_name[CUBRID_CMD_NAME_LEN]; - char cubrid_err_file[PATH_MAX]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; + char arniadb_err_file[PATH_MAX]; FILE *infile, *outfile; int i, flag = 0, no_class = 0, index_exist = 0, trigger_exist = 0; struct stat statbuf; @@ -4575,7 +4575,7 @@ ts_unloaddb (nvplist *req, nvplist *res, char *_dbmt_error) char *dbuser = NULL; char *dbpasswd = NULL; - cubrid_err_file[0] = '\0'; + arniadb_err_file[0] = '\0'; dbname = nv_get_val (req, "dbname"); if (dbname == NULL) @@ -4678,7 +4678,7 @@ ts_unloaddb (nvplist *req, nvplist *res, char *_dbmt_error) fclose (outfile); /* makeup command and execute */ - cubrid_cmd_name (cmd_name); + arniadb_cmd_name (cmd_name); argv[argc++] = cmd_name; argv[argc++] = UTIL_OPTION_UNLOADDB; if (db_mode == DB_SERVICE_MODE_NONE) @@ -4771,33 +4771,33 @@ ts_unloaddb (nvplist *req, nvplist *res, char *_dbmt_error) argv[argc++] = NULL; - snprintf (cubrid_err_file, PATH_MAX, "%s/%s.%u.err.tmp", + snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", sco.dbmt_tmp_dir, "unloaddb", getpid ()); - if (run_child (argv, 1, NULL, NULL, cubrid_err_file, NULL) < 0) + if (run_child (argv, 1, NULL, NULL, arniadb_err_file, NULL) < 0) { /* unloaddb */ strcpy (_dbmt_error, argv[0]); unlink (tmpfile); - if (access (cubrid_err_file, F_OK) == 0) + if (access (arniadb_err_file, F_OK) == 0) { - unlink (cubrid_err_file); + unlink (arniadb_err_file); } return ERR_SYSTEM_CALL; } - if (read_error_file (cubrid_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) + if (read_error_file (arniadb_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) { unlink (tmpfile); - if (access (cubrid_err_file, F_OK) == 0) + if (access (arniadb_err_file, F_OK) == 0) { - unlink (cubrid_err_file); + unlink (arniadb_err_file); } return ERR_WITH_MSG; } - if (access (cubrid_err_file, F_OK) == 0) + if (access (arniadb_err_file, F_OK) == 0) { - unlink (cubrid_err_file); + unlink (arniadb_err_file); } unlink (tmpfile); @@ -4828,7 +4828,7 @@ ts_unloaddb (nvplist *req, nvplist *res, char *_dbmt_error) /* save uploaded result file to 'unloaddb.info' file */ flag = 0; snprintf (infofile, PATH_MAX - 1, "%s/unloaddb.info", - sco.szCubrid_databases); + sco.szArniadb_databases); if ((infile = fopen (infofile, "rt")) == NULL) { outfile = fopen (infofile, "w"); @@ -4844,36 +4844,36 @@ ts_unloaddb (nvplist *req, nvplist *res, char *_dbmt_error) if (!strcmp (target, "both")) { fprintf (outfile, "schema %s/%s%s\n", targetdir, dbname, - CUBRID_UNLOAD_EXT_SCHEMA); + ARNIADB_UNLOAD_EXT_SCHEMA); fprintf (outfile, "object %s/%s%s\n", targetdir, dbname, - CUBRID_UNLOAD_EXT_OBJ); + ARNIADB_UNLOAD_EXT_OBJ); } else if (!strcmp (target, "schema")) { fprintf (outfile, "schema %s/%s%s\n", targetdir, dbname, - CUBRID_UNLOAD_EXT_SCHEMA); + ARNIADB_UNLOAD_EXT_SCHEMA); } else if (!strcmp (target, "object")) { fprintf (outfile, "object %s/%s%s\n", targetdir, dbname, - CUBRID_UNLOAD_EXT_OBJ); + ARNIADB_UNLOAD_EXT_OBJ); } /* check index file and append if exist */ snprintf (buf, sizeof (buf) - 1, "%s/%s%s", targetdir, dbname, - CUBRID_UNLOAD_EXT_INDEX); + ARNIADB_UNLOAD_EXT_INDEX); if (stat (buf, &statbuf) == 0) { fprintf (outfile, "index %s/%s%s\n", targetdir, dbname, - CUBRID_UNLOAD_EXT_INDEX); + ARNIADB_UNLOAD_EXT_INDEX); } /* check trigger file and append if exist */ snprintf (buf, sizeof (buf) - 1, "%s/%s%s", targetdir, dbname, - CUBRID_UNLOAD_EXT_TRIGGER); + ARNIADB_UNLOAD_EXT_TRIGGER); if (stat (buf, &statbuf) == 0) { fprintf (outfile, "trigger %s/%s%s\n", targetdir, dbname, - CUBRID_UNLOAD_EXT_TRIGGER); + ARNIADB_UNLOAD_EXT_TRIGGER); } fclose (outfile); } @@ -4903,37 +4903,37 @@ ts_unloaddb (nvplist *req, nvplist *res, char *_dbmt_error) if (!strcmp (target, "both")) { fprintf (outfile, "schema %s/%s%s\n", targetdir, dbname, - CUBRID_UNLOAD_EXT_SCHEMA); + ARNIADB_UNLOAD_EXT_SCHEMA); fprintf (outfile, "object %s/%s%s\n", targetdir, dbname, - CUBRID_UNLOAD_EXT_OBJ); + ARNIADB_UNLOAD_EXT_OBJ); } else if (!strcmp (target, "schema")) { fprintf (outfile, "schema %s/%s%s\n", targetdir, dbname, - CUBRID_UNLOAD_EXT_SCHEMA); + ARNIADB_UNLOAD_EXT_SCHEMA); } else if (!strcmp (target, "object")) { fprintf (outfile, "object %s/%s%s\n", targetdir, dbname, - CUBRID_UNLOAD_EXT_OBJ); + ARNIADB_UNLOAD_EXT_OBJ); } /* check index file and append if exist */ snprintf (temp, PATH_MAX - 1, "%s/%s%s", targetdir, dbname, - CUBRID_UNLOAD_EXT_INDEX); + ARNIADB_UNLOAD_EXT_INDEX); if (stat (temp, &statbuf) == 0) { fprintf (outfile, "index %s/%s%s\n", targetdir, dbname, - CUBRID_UNLOAD_EXT_INDEX); + ARNIADB_UNLOAD_EXT_INDEX); index_exist = 1; } /* check trigger file and append if exist */ snprintf (temp, PATH_MAX - 1, "%s/%s%s", targetdir, dbname, - CUBRID_UNLOAD_EXT_TRIGGER); + ARNIADB_UNLOAD_EXT_TRIGGER); if (stat (temp, &statbuf) == 0) { fprintf (outfile, "trigger %s/%s%s\n", targetdir, dbname, - CUBRID_UNLOAD_EXT_TRIGGER); + ARNIADB_UNLOAD_EXT_TRIGGER); trigger_exist = 1; } flag = 1; @@ -4942,7 +4942,7 @@ ts_unloaddb (nvplist *req, nvplist *res, char *_dbmt_error) if (!strcmp (target, "both") || !strcmp (target, "schema")) { snprintf (temp, PATH_MAX - 1, "%s/%s%s", targetdir, dbname, - CUBRID_UNLOAD_EXT_SCHEMA); + ARNIADB_UNLOAD_EXT_SCHEMA); if (!strcmp (n, "schema") && !strcmp (v, temp)) { continue; @@ -4951,7 +4951,7 @@ ts_unloaddb (nvplist *req, nvplist *res, char *_dbmt_error) if (!strcmp (target, "both") || !strcmp (target, "object")) { snprintf (temp, PATH_MAX - 1, "%s/%s%s", targetdir, dbname, - CUBRID_UNLOAD_EXT_OBJ); + ARNIADB_UNLOAD_EXT_OBJ); if (!strcmp (n, "object") && !strcmp (v, temp)) { continue; @@ -4960,7 +4960,7 @@ ts_unloaddb (nvplist *req, nvplist *res, char *_dbmt_error) if (index_exist) { snprintf (temp, PATH_MAX - 1, "%s/%s%s", targetdir, dbname, - CUBRID_UNLOAD_EXT_INDEX); + ARNIADB_UNLOAD_EXT_INDEX); if (!strcmp (n, "index") && !strcmp (v, temp)) { continue; @@ -4969,7 +4969,7 @@ ts_unloaddb (nvplist *req, nvplist *res, char *_dbmt_error) if (trigger_exist) { snprintf (temp, PATH_MAX - 1, "%s/%s%s", targetdir, dbname, - CUBRID_UNLOAD_EXT_TRIGGER); + ARNIADB_UNLOAD_EXT_TRIGGER); if (!strcmp (n, "trigger") && !strcmp (v, temp)) { continue; @@ -4983,36 +4983,36 @@ ts_unloaddb (nvplist *req, nvplist *res, char *_dbmt_error) if (!strcmp (target, "both")) { fprintf (outfile, "schema %s/%s%s\n", targetdir, dbname, - CUBRID_UNLOAD_EXT_SCHEMA); + ARNIADB_UNLOAD_EXT_SCHEMA); fprintf (outfile, "object %s/%s%s\n", targetdir, dbname, - CUBRID_UNLOAD_EXT_OBJ); + ARNIADB_UNLOAD_EXT_OBJ); } else if (!strcmp (target, "schema")) { fprintf (outfile, "schema %s/%s%s\n", targetdir, dbname, - CUBRID_UNLOAD_EXT_SCHEMA); + ARNIADB_UNLOAD_EXT_SCHEMA); } else if (!strcmp (target, "object")) { fprintf (outfile, "object %s/%s%s\n", targetdir, dbname, - CUBRID_UNLOAD_EXT_OBJ); + ARNIADB_UNLOAD_EXT_OBJ); } /* check index file and append if exist */ snprintf (temp, PATH_MAX - 1, "%s/%s%s", targetdir, dbname, - CUBRID_UNLOAD_EXT_INDEX); + ARNIADB_UNLOAD_EXT_INDEX); if (stat (temp, &statbuf) == 0) { fprintf (outfile, "index %s/%s%s\n", targetdir, dbname, - CUBRID_UNLOAD_EXT_INDEX); + ARNIADB_UNLOAD_EXT_INDEX); index_exist = 1; } /* check trigger file and append if exist */ snprintf (temp, PATH_MAX - 1, "%s/%s%s", targetdir, dbname, - CUBRID_UNLOAD_EXT_TRIGGER); + ARNIADB_UNLOAD_EXT_TRIGGER); if (stat (temp, &statbuf) == 0) { fprintf (outfile, "trigger %s/%s%s\n", targetdir, dbname, - CUBRID_UNLOAD_EXT_TRIGGER); + ARNIADB_UNLOAD_EXT_TRIGGER); trigger_exist = 1; } } @@ -5056,13 +5056,13 @@ ts_loaddb (nvplist *req, nvplist *res, char *_dbmt_error) T_DB_SERVICE_MODE db_mode; char *dbuser, *dbpasswd; - char cubrid_err_file[PATH_MAX]; + char arniadb_err_file[PATH_MAX]; int retval; - char cmd_name[CUBRID_CMD_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; const char *argv[32]; int argc = 0; - cubrid_err_file[0] = '\0'; + arniadb_err_file[0] = '\0'; if ((dbname = nv_get_val (req, "_DBNAME")) == NULL) { @@ -5102,7 +5102,7 @@ ts_loaddb (nvplist *req, nvplist *res, char *_dbmt_error) snprintf (tmpfile, PATH_MAX - 1, "%s/DBMT_task_%d.%d", sco.dbmt_tmp_dir, TS_LOADDB, (int) getpid ()); - cubrid_cmd_name (cmd_name); + arniadb_cmd_name (cmd_name); argc = 0; argv[argc++] = cmd_name; @@ -5200,15 +5200,15 @@ ts_loaddb (nvplist *req, nvplist *res, char *_dbmt_error) argv[argc++] = dbname; argv[argc++] = NULL; - snprintf (cubrid_err_file, PATH_MAX, "%s/%s.%u.err.tmp", + snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", sco.dbmt_tmp_dir, "loaddb", getpid ()); - retval = run_child (argv, 1, NULL, tmpfile, cubrid_err_file, NULL); /* loaddb */ + retval = run_child (argv, 1, NULL, tmpfile, arniadb_err_file, NULL); /* loaddb */ if (retval < 0) { - if (access (cubrid_err_file, F_OK) == 0) + if (access (arniadb_err_file, F_OK) == 0) { - unlink (cubrid_err_file); + unlink (arniadb_err_file); } strcpy (_dbmt_error, argv[0]); return ERR_SYSTEM_CALL; @@ -5216,9 +5216,9 @@ ts_loaddb (nvplist *req, nvplist *res, char *_dbmt_error) if (file_to_nvpairs (tmpfile, res) < 0) { - if (access (cubrid_err_file, F_OK) == 0) + if (access (arniadb_err_file, F_OK) == 0) { - unlink (cubrid_err_file); + unlink (arniadb_err_file); } strcpy (_dbmt_error, tmpfile); return ERR_TMPFILE_OPEN_FAIL; @@ -5226,11 +5226,11 @@ ts_loaddb (nvplist *req, nvplist *res, char *_dbmt_error) unlink (tmpfile); /* the error file may not exist, don't check the error of it. */ - file_to_nvpairs (cubrid_err_file, res); + file_to_nvpairs (arniadb_err_file, res); - if (access (cubrid_err_file, F_OK) == 0) + if (access (arniadb_err_file, F_OK) == 0) { - unlink (cubrid_err_file); + unlink (arniadb_err_file); } if (uStringEqualIgnoreCase (nv_get_val (req, "delete_orignal_files"), "y")) { @@ -5256,14 +5256,14 @@ ts_restoredb (nvplist *req, nvplist *res, char *_dbmt_error) { int retval = ERR_NO_ERROR; char *dbname, *date, *lv, *pathname, *partial, *recovery_path; - char cmd_name[CUBRID_CMD_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; const char *argv[17]; int argc = 0; T_DB_SERVICE_MODE db_mode; - char cubrid_err_file[PATH_MAX]; + char arniadb_err_file[PATH_MAX]; int status; - cubrid_err_file[0] = '\0'; + arniadb_err_file[0] = '\0'; dbname = nv_get_val (req, "dbname"); db_mode = uDatabaseMode (dbname, NULL); @@ -5284,7 +5284,7 @@ ts_restoredb (nvplist *req, nvplist *res, char *_dbmt_error) partial = nv_get_val (req, "partial"); recovery_path = nv_get_val (req, "recoverypath"); - cubrid_cmd_name (cmd_name); + arniadb_cmd_name (cmd_name); argv[argc++] = cmd_name; argv[argc++] = UTIL_OPTION_RESTOREDB; if ((date != NULL) && (strcmp (date, "none") != 0)) @@ -5332,32 +5332,32 @@ ts_restoredb (nvplist *req, nvplist *res, char *_dbmt_error) argv[argc++] = dbname; argv[argc++] = NULL; - snprintf (cubrid_err_file, PATH_MAX, "%s/%s.%u.err.tmp", + snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", sco.dbmt_tmp_dir, "restoredb", getpid ()); - if (run_child (argv, 1, NULL, NULL, cubrid_err_file, &status) < 0) + if (run_child (argv, 1, NULL, NULL, arniadb_err_file, &status) < 0) { strcpy_limit (_dbmt_error, argv[0], DBMT_ERROR_MSG_SIZE); - if (access (cubrid_err_file, F_OK) == 0) + if (access (arniadb_err_file, F_OK) == 0) { - unlink (cubrid_err_file); + unlink (arniadb_err_file); } return ERR_SYSTEM_CALL; } - if (status != 0 && read_error_file (cubrid_err_file, _dbmt_error, + if (status != 0 && read_error_file (arniadb_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) { - if (access (cubrid_err_file, F_OK) == 0) + if (access (arniadb_err_file, F_OK) == 0) { - unlink (cubrid_err_file); + unlink (arniadb_err_file); } return ERR_WITH_MSG; } - if (access (cubrid_err_file, F_OK) == 0) + if (access (arniadb_err_file, F_OK) == 0) { - unlink (cubrid_err_file); + unlink (arniadb_err_file); } return ERR_NO_ERROR; } @@ -5368,7 +5368,7 @@ ts_backup_vol_info (nvplist *req, nvplist *res, char *_dbmt_error) char *dbname, *lv, *pathname, buf[1024], tmpfile[PATH_MAX]; int ret; FILE *infile; - char cmd_name[CUBRID_CMD_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; const char *argv[10]; int argc = 0; @@ -5391,7 +5391,7 @@ ts_backup_vol_info (nvplist *req, nvplist *res, char *_dbmt_error) lv = nv_get_val (req, "level"); pathname = nv_get_val (req, "pathname"); - cubrid_cmd_name (cmd_name); + arniadb_cmd_name (cmd_name); argv[argc++] = cmd_name; argv[argc++] = UTIL_OPTION_RESTOREDB; argv[argc++] = "--" RESTORE_LIST_L; @@ -5450,7 +5450,7 @@ ts_get_dbsize (nvplist *req, nvplist *res, char *_dbmt_error) int no_tpage = 0, log_size = 0, baselen; struct stat statbuf; GeneralSpacedbResult *cmd_res; - T_CUBRID_MODE cubrid_mode; + T_ARNIADB_MODE arniadb_mode; #if defined(WINDOWS) char find_file[PATH_MAX]; WIN32_FIND_DATA data; @@ -5475,19 +5475,19 @@ ts_get_dbsize (nvplist *req, nvplist *res, char *_dbmt_error) return ERR_DBDIRNAME_NULL; } - cubrid_mode = + arniadb_mode = (uDatabaseMode (dbname, &ha_mode) == - DB_SERVICE_MODE_NONE) ? CUBRID_MODE_SA : CUBRID_MODE_CS; + DB_SERVICE_MODE_NONE) ? ARNIADB_MODE_SA : ARNIADB_MODE_CS; if (ha_mode != 0) { append_host_to_dbname (dbname_at_hostname, dbname, sizeof (dbname_at_hostname)); - cmd_res = cmd_spacedb (dbname_at_hostname, cubrid_mode); + cmd_res = cmd_spacedb (dbname_at_hostname, arniadb_mode); } else { - cmd_res = cmd_spacedb (dbname, cubrid_mode); + cmd_res = cmd_spacedb (dbname, arniadb_mode); } if (cmd_res == NULL || cmd_res->has_error()) @@ -5523,8 +5523,8 @@ ts_get_dbsize (nvplist *req, nvplist *res, char *_dbmt_error) cur_file = dp->d_name; #endif if (!strncmp (cur_file + baselen, "_lginf", 6) - || !strcmp (cur_file + baselen, CUBRID_ACT_LOG_EXT) - || !strncmp (cur_file + baselen, CUBRID_ARC_LOG_EXT, CUBRID_ARC_LOG_EXT_LEN)) + || !strcmp (cur_file + baselen, ARNIADB_ACT_LOG_EXT) + || !strncmp (cur_file + baselen, ARNIADB_ARC_LOG_EXT, ARNIADB_ARC_LOG_EXT_LEN)) { snprintf (strbuf, sizeof (strbuf) - 1, "%s/%s", dbdir, cur_file); stat (strbuf, &statbuf); @@ -5551,24 +5551,24 @@ tsGetEnvironment (nvplist *req, nvplist *res, char *_dbmt_error) char tmpfile[PATH_MAX]; char strbuf[1024]; FILE *infile; - char cmd_name[CUBRID_CMD_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; const char *argv[5]; - nv_add_nvp (res, "CUBRID", sco.szCubrid); - nv_add_nvp (res, "CUBRID_DATABASES", sco.szCubrid_databases); - nv_add_nvp (res, "CUBRID_DBMT", sco.szCubrid); - // nv_add_nvp (res, "CUBRID_CHARSET", getenv ("CUBRID_CHARSET")); + nv_add_nvp (res, "ARNIADB", sco.szArniadb); + nv_add_nvp (res, "ARNIADB_DATABASES", sco.szArniadb_databases); + nv_add_nvp (res, "ARNIADB_DBMT", sco.szArniadb); + // nv_add_nvp (res, "ARNIADB_CHARSET", getenv ("ARNIADB_CHARSET")); snprintf (tmpfile, PATH_MAX - 1, "%s/DBMT_task_015.%d", sco.dbmt_tmp_dir, (int) getpid ()); cmd_name[0] = '\0'; - snprintf (cmd_name, sizeof (cmd_name) - 1, "%s/%s%s", sco.szCubrid, - CUBRID_DIR_BIN, UTIL_CUBRID_REL_NAME); + snprintf (cmd_name, sizeof (cmd_name) - 1, "%s/%s%s", sco.szArniadb, + ARNIADB_DIR_BIN, UTIL_ARNIADB_REL_NAME); argv[0] = cmd_name; argv[1] = NULL; - run_child (argv, 1, NULL, tmpfile, NULL, NULL); /* cubrid_rel */ + run_child (argv, 1, NULL, tmpfile, NULL, NULL); /* arniadb_rel */ if ((infile = fopen (tmpfile, "r")) != NULL) { @@ -5577,23 +5577,23 @@ tsGetEnvironment (nvplist *req, nvplist *res, char *_dbmt_error) uRemoveCRLF (strbuf); fclose (infile); unlink (tmpfile); - nv_add_nvp (res, "CUBRIDVER", strbuf); + nv_add_nvp (res, "ARNIADBVER", strbuf); } else { - nv_add_nvp (res, "CUBRIDVER", "version information not available"); + nv_add_nvp (res, "ARNIADBVER", "version information not available"); } snprintf (tmpfile, PATH_MAX - 1, "%s/DBMT_task_015.%d", sco.dbmt_tmp_dir, (int) getpid ()); - snprintf (cmd_name, sizeof (cmd_name) - 1, "%s/bin/cubrid_broker%s", - sco.szCubrid, DBMT_EXE_EXT); + snprintf (cmd_name, sizeof (cmd_name) - 1, "%s/bin/arniadb_broker%s", + sco.szArniadb, DBMT_EXE_EXT); argv[0] = cmd_name; argv[1] = "--version"; argv[2] = NULL; - run_child (argv, 1, NULL, tmpfile, NULL, NULL); /* cubrid_broker --version */ + run_child (argv, 1, NULL, tmpfile, NULL, NULL); /* arniadb_broker --version */ if ((infile = fopen (tmpfile, "r")) != NULL) { @@ -6038,7 +6038,7 @@ ts_backupdb_info (nvplist *req, nvplist *res, char *_dbmt_error) } snprintf (vinf, sizeof (vinf), "%s/%s%s", log_dir, dbname, - CUBRID_BACKUP_INFO_EXT); + ARNIADB_BACKUP_INFO_EXT); if (access (vinf, F_OK) < 0) { @@ -6074,7 +6074,7 @@ ts_backupdb_info (nvplist *req, nvplist *res, char *_dbmt_error) } exit_success: - /* In CUBRID Manager, $db_dir/backup is default path. */ + /* In ARNIADB Manager, $db_dir/backup is default path. */ snprintf (db_backup_dir, sizeof (db_backup_dir), "%s/backup", db_dir); nv_add_nvp (res, "dbdir", db_backup_dir); @@ -6092,7 +6092,7 @@ ts_unloaddb_info (nvplist *req, nvplist *res, char *_dbmt_error) struct stat statbuf; snprintf (buf, sizeof (buf) - 1, "%s/unloaddb.info", - sco.szCubrid_databases); + sco.szArniadb_databases); if ((infile = fopen (buf, "rt")) == NULL) { return ERR_NO_ERROR; @@ -6519,7 +6519,7 @@ ts_get_log_info (nvplist *req, nvplist *res, char *_dbmt_error) } FREE_MEM (error_log_param); - snprintf (buf, sizeof (buf) - 1, "%s/cub_server.err", log_dir); + snprintf (buf, sizeof (buf) - 1, "%s/arn_server.err", log_dir); if (stat (buf, &statbuf) == 0) { nv_add_nvp (res, "open", "log"); @@ -6532,8 +6532,8 @@ ts_get_log_info (nvplist *req, nvplist *res, char *_dbmt_error) nv_add_nvp (res, "close", "log"); } - snprintf (find_file, PATH_MAX - 1, "%s/%s", sco.szCubrid, - CUBRID_ERROR_LOG_DIR); + snprintf (find_file, PATH_MAX - 1, "%s/%s", sco.szArniadb, + ARNIADB_ERROR_LOG_DIR); #if defined(WINDOWS) snprintf (&find_file[strlen (find_file)], PATH_MAX - strlen (find_file) - 1, "/*"); @@ -6570,8 +6570,8 @@ ts_get_log_info (nvplist *req, nvplist *res, char *_dbmt_error) { continue; } - snprintf (buf, sizeof (buf) - 1, "%s/%s/%s", sco.szCubrid, - CUBRID_ERROR_LOG_DIR, fname); + snprintf (buf, sizeof (buf) - 1, "%s/%s/%s", sco.szArniadb, + ARNIADB_ERROR_LOG_DIR, fname); if (stat (buf, &statbuf) == 0) { nv_add_nvp (res, "open", "log"); @@ -6848,7 +6848,7 @@ ts_get_tran_info (nvplist *req, nvplist *res, char *_dbmt_error) char errfile[PATH_MAX]; FILE *infile = NULL; char *tok[9]; - char cmd_name[CUBRID_CMD_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; const char *argv[10]; int argc = 0; int retval = 0; @@ -6881,7 +6881,7 @@ ts_get_tran_info (nvplist *req, nvplist *res, char *_dbmt_error) snprintf (errfile, PATH_MAX - 1, "%s/DBMT_task_%d.stderr.%d", sco.dbmt_tmp_dir, TS_GETTRANINFO, (int) getpid ()); - cubrid_cmd_name (cmd_name); + arniadb_cmd_name (cmd_name); argv[argc++] = cmd_name; argv[argc++] = UTIL_OPTION_TRANLIST; @@ -7075,7 +7075,7 @@ ts_killtran (nvplist *req, nvplist *res, char *_dbmt_error) char *type = NULL; char *param = NULL; char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; - char cmd_name[CUBRID_CMD_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; char task_name[TASKNAME_LEN]; const char *argv[10]; int ha_mode = 0; @@ -7111,7 +7111,7 @@ ts_killtran (nvplist *req, nvplist *res, char *_dbmt_error) return ERR_STANDALONE_MODE; } - cubrid_cmd_name (cmd_name); + arniadb_cmd_name (cmd_name); argv[argc++] = cmd_name; argv[argc++] = UTIL_OPTION_KILLTRAN; if (dbpasswd != NULL) @@ -7204,7 +7204,7 @@ ts_lockdb (nvplist *req, nvplist *res, char *_dbmt_error) { char buf[1024], tmpfile[PATH_MAX], tmpfile2[PATH_MAX], s[32]; char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; - char cmd_name[CUBRID_CMD_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; char task_name[TASKNAME_LEN]; const char *argv[10]; @@ -7240,7 +7240,7 @@ ts_lockdb (nvplist *req, nvplist *res, char *_dbmt_error) snprintf (tmpfile, PATH_MAX, "%s/DBMT_task_%d_1.%d.tmp", sco.dbmt_tmp_dir, TS_LOCKDB, (int) getpid ()); - cubrid_cmd_name (cmd_name); + arniadb_cmd_name (cmd_name); argv[argc++] = cmd_name; argv[argc++] = UTIL_OPTION_LOCKDB; argv[argc++] = "--" LOCK_OUTPUT_FILE_L; @@ -7336,7 +7336,7 @@ ts_get_backup_list (nvplist *req, nvplist *res, char *_dbmt_error) } snprintf (file, PATH_MAX - 1, "%s/%s%s", log_dir, dbname, - CUBRID_BACKUP_INFO_EXT); + ARNIADB_BACKUP_INFO_EXT); if ((infile = fopen (file, "rt")) != NULL) { while (fgets (buf, sizeof (buf), infile)) @@ -7514,7 +7514,7 @@ ts_load_access_log (nvplist *req, nvplist *res, char *_dbmt_error) log_full_dir[0] = '\0'; err_full_dir[0] = '\0'; - snprintf (root_dir, PATH_MAX, "%s/%s/", sco.szCubrid, DBMT_LOG_DIR); + snprintf (root_dir, PATH_MAX, "%s/%s/", sco.szArniadb, DBMT_LOG_DIR); _get_dir_list (all_files_list, root_dir, cms_process_name); @@ -7651,7 +7651,7 @@ _get_error_access_log_files (nvplist *req, nvplist *res, bool is_access_log) log_full_dir[0] = '\0'; - snprintf (root_dir, PATH_MAX, "%s/%s/", sco.szCubrid, DBMT_LOG_DIR); + snprintf (root_dir, PATH_MAX, "%s/%s/", sco.szArniadb, DBMT_LOG_DIR); _get_dir_list (all_files_list, root_dir, cms_process_name); log_files_list = _get_filtered_files_list (all_files_list, log_exp); @@ -7795,7 +7795,7 @@ ts_get_autobackupdb_error_log (nvplist *req, nvplist *res, end_time = nv_get_val (req, "end_time"); snprintf (logfile, PATH_MAX - 1, "%s/log/manager/auto_backupdb.log", - sco.szCubrid); + sco.szArniadb); if ((infile = fopen (logfile, "r")) == NULL) { return ERR_NO_ERROR; @@ -7856,7 +7856,7 @@ ts_get_autoexecquery_error_log (nvplist *req, nvplist *res, end_time = nv_get_val (req, "end_time"); snprintf (logfile, PATH_MAX - 1, "%s/log/manager/auto_execquery.log", - sco.szCubrid); + sco.szArniadb); if ((infile = fopen (logfile, "r")) == NULL) { return ERR_NO_ERROR; @@ -7916,15 +7916,15 @@ ts_trigger_operation (nvplist *req, nvplist *res, char *_dbmt_error) char *task, *dbname, *dbuser, *dbpasswd; char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; int ha_mode = 0; - char cmd_name[CUBRID_CMD_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; const char *argv[11]; char input_file[PATH_MAX]; - char cubrid_err_file[PATH_MAX]; + char arniadb_err_file[PATH_MAX]; int retval, argc; T_DB_SERVICE_MODE db_mode; input_file[0] = '\0'; - cubrid_err_file[0] = '\0'; + arniadb_err_file[0] = '\0'; task = nv_get_val (req, "task"); if (task != NULL) @@ -7951,8 +7951,8 @@ ts_trigger_operation (nvplist *req, nvplist *res, char *_dbmt_error) dbpasswd = nv_get_val (req, "_DBPASSWD"); cmd_name[0] = '\0'; - snprintf (cmd_name, sizeof (cmd_name) - 1, "%s/%s%s", sco.szCubrid, - CUBRID_DIR_BIN, UTIL_CSQL_NAME); + snprintf (cmd_name, sizeof (cmd_name) - 1, "%s/%s%s", sco.szArniadb, + ARNIADB_DIR_BIN, UTIL_ASQL_NAME); argc = 0; argv[argc++] = cmd_name; @@ -7969,20 +7969,20 @@ ts_trigger_operation (nvplist *req, nvplist *res, char *_dbmt_error) } argv[argc++] = NULL; - argv[argc++] = "--" CSQL_INPUT_FILE_L; + argv[argc++] = "--" ASQL_INPUT_FILE_L; argv[argc++] = input_file; if (dbuser) { - argv[argc++] = "--" CSQL_USER_L; + argv[argc++] = "--" ASQL_USER_L; argv[argc++] = dbuser; if (dbpasswd) { - argv[argc++] = "--" CSQL_PASSWORD_L; + argv[argc++] = "--" ASQL_PASSWORD_L; argv[argc++] = dbpasswd; } } - argv[argc++] = "--" CSQL_NO_AUTO_COMMIT_L; + argv[argc++] = "--" ASQL_NO_AUTO_COMMIT_L; for (; argc < 11; argc++) { @@ -8002,17 +8002,17 @@ ts_trigger_operation (nvplist *req, nvplist *res, char *_dbmt_error) if (db_mode == DB_SERVICE_MODE_CS) { - /* run csql command with -cs option */ - argv[2] = "--" CSQL_CS_MODE_L; + /* run asql command with -cs option */ + argv[2] = "--" ASQL_CS_MODE_L; } if (db_mode == DB_SERVICE_MODE_NONE) { - /* run csql command with -sa option */ - argv[2] = "--" CSQL_SA_MODE_L; + /* run asql command with -sa option */ + argv[2] = "--" ASQL_SA_MODE_L; } - /* csql -sa -i input_file dbname */ + /* asql -sa -i input_file dbname */ if (task != NULL) { if (strcmp (task, "addtrigger") == 0) @@ -8041,27 +8041,27 @@ ts_trigger_operation (nvplist *req, nvplist *res, char *_dbmt_error) } } - snprintf (cubrid_err_file, PATH_MAX, "%s/%s.%u.err.tmp", + snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", sco.dbmt_tmp_dir, "trigger_operation", getpid ()); SET_TRANSACTION_NO_WAIT_MODE_ENV (); - retval = run_child (argv, 1, NULL, NULL, cubrid_err_file, NULL); /* csql - trigger */ + retval = run_child (argv, 1, NULL, NULL, arniadb_err_file, NULL); /* asql - trigger */ if (strlen (input_file) > 0) { unlink (input_file); } - if (read_csql_error_file (cubrid_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) + if (read_asql_error_file (arniadb_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) { - if (access (cubrid_err_file, F_OK) == 0) + if (access (arniadb_err_file, F_OK) == 0) { - unlink (cubrid_err_file); + unlink (arniadb_err_file); } return ERR_WITH_MSG; } - if (access (cubrid_err_file, F_OK) == 0) + if (access (arniadb_err_file, F_OK) == 0) { - unlink (cubrid_err_file); + unlink (arniadb_err_file); } if (retval < 0) { @@ -8880,7 +8880,7 @@ ts_analyzecaslog (nvplist *cli_request, nvplist *cli_response, char tmpfileQ[PATH_MAX], tmpfileRes[PATH_MAX], tmpfileT[PATH_MAX], tmpfileanalyzeresult[PATH_MAX]; char *logfile, *option_t; - char cmd_name[CUBRID_CMD_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; char diag_err_file[PATH_MAX]; const char *argv[256]; char buf[1024], logbuf[2048]; @@ -8897,9 +8897,9 @@ ts_analyzecaslog (nvplist *cli_request, nvplist *cli_response, option_t = nv_get_val (cli_request, "option_t"); /* set prarameter with logfile and execute broker_log_top */ - /* execute at current directory and copy result to $CUBRID/tmp directory */ + /* execute at current directory and copy result to $ARNIADB/tmp directory */ snprintf (cmd_name, sizeof (cmd_name) - 1, "%s/bin/broker_log_top%s", - sco.szCubrid, DBMT_EXE_EXT); + sco.szArniadb, DBMT_EXE_EXT); arg_index = 0; argv[arg_index++] = cmd_name; if (option_t &&!strcmp (option_t, "yes")) @@ -9180,7 +9180,7 @@ ts_executecasrunner (nvplist *cli_request, nvplist *cli_response, FILE *flogfile, *fresfile2; char tmplogfilename[PATH_MAX], resfile[PATH_MAX], resfile2[PATH_MAX]; char log_converter_res[PATH_MAX]; - char cmd_name[CUBRID_CMD_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; const char *argv[25]; T_CM_BROKER_CONF uc_conf; char out_msg_file_env[1024]; @@ -9293,7 +9293,7 @@ ts_executecasrunner (nvplist *cli_request, nvplist *cli_response, snprintf (log_converter_res, PATH_MAX - 1, "%s/log_converted_%lu.q_res", sco.dbmt_tmp_dir, th_id); snprintf (cmd_name, sizeof (cmd_name) - 1, "%s/bin/broker_log_converter%s", - sco.szCubrid, DBMT_EXE_EXT); + sco.szArniadb, DBMT_EXE_EXT); i = 0; argv[i] = cmd_name; @@ -9310,7 +9310,7 @@ ts_executecasrunner (nvplist *cli_request, nvplist *cli_response, /* execute broker_log_runner through logfile that converted */ snprintf (cmd_name, sizeof (cmd_name) - 1, "%s/bin/broker_log_runner%s", - sco.szCubrid, DBMT_EXE_EXT); + sco.szArniadb, DBMT_EXE_EXT); i = 0; argv[i] = cmd_name; argv[++i] = "-I"; @@ -9340,7 +9340,7 @@ ts_executecasrunner (nvplist *cli_request, nvplist *cli_response, argv[++i] = NULL; snprintf (out_msg_file_env, sizeof (out_msg_file_env) - 1, - "CUBRID_MANAGER_OUT_MSG_FILE=%s", resfile2); + "ARNIADB_MANAGER_OUT_MSG_FILE=%s", resfile2); putenv (out_msg_file_env); if (run_child (argv, 1, NULL, NULL, NULL, NULL) < 0) @@ -9440,7 +9440,7 @@ ts_removecasrunnertmpfile (nvplist *cli_request, nvplist *cli_response, { char command[PATH_MAX]; char filename[PATH_MAX]; - char cubrid_tmp_path[PATH_MAX]; + char arniadb_tmp_path[PATH_MAX]; char *fullpath_with_filename = NULL; const char *casrunnertmp_short[] = @@ -9452,7 +9452,7 @@ ts_removecasrunnertmpfile (nvplist *cli_request, nvplist *cli_response, command[0] = '\0'; filename[0] = '\0'; - cubrid_tmp_path[0] = '\0'; + arniadb_tmp_path[0] = '\0'; fullpath_with_filename = nv_get_val (cli_request, "filename"); if (fullpath_with_filename == NULL) @@ -9461,14 +9461,14 @@ ts_removecasrunnertmpfile (nvplist *cli_request, nvplist *cli_response, return ERR_PARAM_MISSING; } - /* check permission : must under $CUBRID/tmp/ */ + /* check permission : must under $ARNIADB/tmp/ */ #if defined(WINDOWS) - snprintf (cubrid_tmp_path, PATH_MAX, "%s\\", sco.dbmt_tmp_dir); + snprintf (arniadb_tmp_path, PATH_MAX, "%s\\", sco.dbmt_tmp_dir); #else - snprintf (cubrid_tmp_path, PATH_MAX, "%s/", sco.dbmt_tmp_dir); + snprintf (arniadb_tmp_path, PATH_MAX, "%s/", sco.dbmt_tmp_dir); #endif - if (strstr (fullpath_with_filename, cubrid_tmp_path) == NULL) + if (strstr (fullpath_with_filename, arniadb_tmp_path) == NULL) { snprintf (diag_error, DBMT_ERROR_MSG_SIZE, "%s", fullpath_with_filename); @@ -9673,9 +9673,9 @@ cmd_dbmt_user_login (nvplist *in, nvplist *out, char *_dbmt_error) nv_add_nvp (out, "dbname", dbname); snprintf (outfile, sizeof (outfile) - 1, "%s/tmp/DBMT_user_login.%d", - sco.szCubrid, cmdid++); + sco.szArniadb, cmdid++); errcode = - run_csql_statement (statement, dbname, dbuser, dbpasswd, outfile, _dbmt_error); + run_asql_statement (statement, dbname, dbuser, dbpasswd, outfile, _dbmt_error); if (errcode != ERR_NO_ERROR) { return errcode; @@ -9912,14 +9912,14 @@ analyze_heartbeat_cmd_outfile (FILE *infile, char *_dbmt_error) } static char * -cub_admin_cmd_name (char *cmd_name, int buf_len) +arn_admin_cmd_name (char *cmd_name, int buf_len) { cmd_name[0] = '\0'; -#if !defined (DO_NOT_USE_CUBRIDENV) - snprintf (cmd_name, buf_len, "%s/%s%s", sco.szCubrid, CUBRID_DIR_BIN, +#if !defined (DO_NOT_USE_ARNIADBENV) + snprintf (cmd_name, buf_len, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ADMIN_NAME); #else - sprintf (cmd_name, buf_len, "%s/%s", CUBRID_BINDIR, UTIL_ADMIN_NAME); + sprintf (cmd_name, buf_len, "%s/%s", ARNIADB_BINDIR, UTIL_ADMIN_NAME); #endif return cmd_name; } @@ -9930,18 +9930,18 @@ cmd_heartbeat_deact (char *_dbmt_error) int retval = ERR_NO_ERROR; const char *argv[8]; int argc = 0; - char cmd_name[CUBRID_CMD_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; FILE *outputfile = NULL; char outputfilepath[PATH_MAX]; - char cubrid_err_file[PATH_MAX]; + char arniadb_err_file[PATH_MAX]; - cubrid_err_file[0] = '\0'; + arniadb_err_file[0] = '\0'; outputfilepath[0] = '\0'; - snprintf (cubrid_err_file, PATH_MAX, "%s/%s.%u.err.tmp", + snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", sco.dbmt_tmp_dir, "heartbeat_deact", getpid ()); - cubrid_cmd_name (cmd_name); + arniadb_cmd_name (cmd_name); argv[argc++] = cmd_name; argv[argc++] = PRINT_CMD_HEARTBEAT; argv[argc++] = PRINT_CMD_DEACT; @@ -9950,7 +9950,7 @@ cmd_heartbeat_deact (char *_dbmt_error) snprintf (outputfilepath, PATH_MAX - 1, "%s/DBMT_task_%d.%d", sco.dbmt_tmp_dir, TS_HEARTBEAT_DEACT, (int) getpid ()); - if (run_child (argv, 1, NULL, outputfilepath, cubrid_err_file, NULL) < 0) + if (run_child (argv, 1, NULL, outputfilepath, arniadb_err_file, NULL) < 0) { /* heartbeat deact */ strcpy (_dbmt_error, argv[0]); @@ -9958,7 +9958,7 @@ cmd_heartbeat_deact (char *_dbmt_error) goto rm_outputfile; } - if (read_error_file (cubrid_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) + if (read_error_file (arniadb_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) { retval = ERR_WITH_MSG; goto rm_outputfile; @@ -9984,9 +9984,9 @@ cmd_heartbeat_deact (char *_dbmt_error) rm_outputfile: unlink (outputfilepath); - if (access (cubrid_err_file, F_OK) == 0) + if (access (arniadb_err_file, F_OK) == 0) { - unlink (cubrid_err_file); + unlink (arniadb_err_file); } return retval; } @@ -9997,18 +9997,18 @@ cmd_heartbeat_act (char *_dbmt_error) int retval = ERR_NO_ERROR; const char *argv[8]; int argc = 0; - char cmd_name[CUBRID_CMD_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; FILE *outputfile = NULL; char outputfilepath[PATH_MAX]; - char cubrid_err_file[PATH_MAX]; + char arniadb_err_file[PATH_MAX]; outputfilepath[0] = '\0'; - cubrid_err_file[0] = '\0'; + arniadb_err_file[0] = '\0'; - snprintf (cubrid_err_file, PATH_MAX, "%s/%s.%u.err.tmp", + snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", sco.dbmt_tmp_dir, "cmd_heartbeat_act", getpid ()); - cubrid_cmd_name (cmd_name); + arniadb_cmd_name (cmd_name); argv[argc++] = cmd_name; argv[argc++] = PRINT_CMD_HEARTBEAT; argv[argc++] = PRINT_CMD_ACT; @@ -10017,7 +10017,7 @@ cmd_heartbeat_act (char *_dbmt_error) snprintf (outputfilepath, PATH_MAX - 1, "%s/DBMT_task_%d.%d", sco.dbmt_tmp_dir, TS_HEARTBEAT_ACT, (int) getpid ()); - if (run_child (argv, 1, NULL, outputfilepath, cubrid_err_file, NULL) < 0) + if (run_child (argv, 1, NULL, outputfilepath, arniadb_err_file, NULL) < 0) { /* heartbeat act */ strcpy (_dbmt_error, argv[0]); @@ -10025,7 +10025,7 @@ cmd_heartbeat_act (char *_dbmt_error) goto rm_outputfile; } - if (read_error_file (cubrid_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) + if (read_error_file (arniadb_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) { retval = ERR_WITH_MSG; goto rm_outputfile; @@ -10051,19 +10051,19 @@ cmd_heartbeat_act (char *_dbmt_error) rm_outputfile: unlink (outputfilepath); - if (access (cubrid_err_file, F_OK) == 0) + if (access (arniadb_err_file, F_OK) == 0) { - unlink (cubrid_err_file); + unlink (arniadb_err_file); } return retval; } static int -run_csql_statement (const char *sql_stat, char *dbname, char *dbuser, +run_asql_statement (const char *sql_stat, char *dbname, char *dbuser, char *dbpasswd, char *outfilepath, char *_dbmt_error) { char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; - char cmd_name[CUBRID_CMD_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; char task_name[TASKNAME_LEN]; const char *argv[15]; @@ -10077,8 +10077,8 @@ run_csql_statement (const char *sql_stat, char *dbname, char *dbuser, dbname_at_hostname[0] = '\0'; cmd_name[0] = '\0'; - snprintf (cmd_name, sizeof (cmd_name) - 1, "%s/%s%s", sco.szCubrid, - CUBRID_DIR_BIN, UTIL_CSQL_NAME); + snprintf (cmd_name, sizeof (cmd_name) - 1, "%s/%s%s", sco.szArniadb, + ARNIADB_DIR_BIN, UTIL_ASQL_NAME); if (!_isRegisteredDB (dbname)) { @@ -10097,19 +10097,19 @@ run_csql_statement (const char *sql_stat, char *dbname, char *dbuser, if (db_mode == DB_SERVICE_MODE_NONE) { - argv[argc++] = "--" CSQL_SA_MODE_L; + argv[argc++] = "--" ASQL_SA_MODE_L; } else { - argv[argc++] = "--" CSQL_CS_MODE_L; + argv[argc++] = "--" ASQL_CS_MODE_L; } if (dbuser != NULL) { - argv[argc++] = "--" CSQL_USER_L; + argv[argc++] = "--" ASQL_USER_L; argv[argc++] = dbuser; - argv[argc++] = "--" CSQL_PASSWORD_L; + argv[argc++] = "--" ASQL_PASSWORD_L; if (dbpasswd != NULL) { argv[argc++] = dbpasswd; @@ -10125,7 +10125,7 @@ run_csql_statement (const char *sql_stat, char *dbname, char *dbuser, return ERR_PARAM_MISSING; } - argv[argc++] = "--" CSQL_COMMAND_L; + argv[argc++] = "--" ASQL_COMMAND_L; argv[argc++] = sql_stat; if (ha_mode != 0) @@ -10143,7 +10143,7 @@ run_csql_statement (const char *sql_stat, char *dbname, char *dbuser, SET_TRANSACTION_NO_WAIT_MODE_ENV (); - strncpy (task_name, "csql", TASKNAME_LEN); + strncpy (task_name, "asql", TASKNAME_LEN); retval = _run_child (argv, 1, task_name, outfilepath, _dbmt_error); return retval; @@ -10175,9 +10175,9 @@ ts_user_verify (nvplist *req, nvplist *res, char *_dbmt_error) } /* - * using csql to verify the user's password. + * using asql to verify the user's password. */ - retval = run_csql_statement (sql_stat, dbname, dbuser, dbpasswd, NULL, _dbmt_error); /* csql */ + retval = run_asql_statement (sql_stat, dbname, dbuser, dbpasswd, NULL, _dbmt_error); /* asql */ return retval; } @@ -10228,7 +10228,7 @@ ts_get_standby_server_stat (nvplist *req, nvplist *res, char *_dbmt_error) goto func_return; } - retval = run_csql_statement (sql_stat, dbname, dbuser, dbpasswd, output_file, _dbmt_error); /* csql */ + retval = run_asql_statement (sql_stat, dbname, dbuser, dbpasswd, output_file, _dbmt_error); /* asql */ if (retval != ERR_NO_ERROR) { @@ -10356,7 +10356,7 @@ cmd_get_db_mode (T_DB_MODE_INFO *dbmodeinfo, char *dbname, char *_dbmt_error) if (ha_mode == 0) { - /* To CUBRID Client, the SA and NONE mode all means the database is stopped. */ + /* To ARNIADB Client, the SA and NONE mode all means the database is stopped. */ if (dbmode == DB_SERVICE_MODE_SA || dbmode == DB_SERVICE_MODE_NONE) { strcpy_limit (server_mode, "stopped", sizeof (server_mode)); @@ -10469,14 +10469,14 @@ cmd_changemode (char *dbname, char *modify, char *force, int argc = 0; int ha_mode = 0; char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; - char cmd_name[CUBRID_CMD_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; T_DB_SERVICE_MODE dbmode; - char cubrid_err_file[PATH_MAX]; + char arniadb_err_file[PATH_MAX]; FILE *outputfile; char tmpfilepath[PATH_MAX]; int retval = ERR_NO_ERROR; - cubrid_err_file[0] = '\0'; + arniadb_err_file[0] = '\0'; if (dbname == NULL) { @@ -10491,12 +10491,12 @@ cmd_changemode (char *dbname, char *modify, char *force, return ERR_STANDALONE_MODE; } - snprintf (cubrid_err_file, PATH_MAX, "%s/%s.%u.err.tmp", + snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", sco.dbmt_tmp_dir, "changemode", getpid ()); snprintf (tmpfilepath, PATH_MAX - 1, "%s/DBMT_task_%d.%d", sco.dbmt_tmp_dir, TS_CHANGEMODE, (int) getpid ()); - cubrid_cmd_name (cmd_name); + arniadb_cmd_name (cmd_name); argv[argc++] = cmd_name; argv[argc++] = UTIL_OPTION_CHANGEMODE; @@ -10524,14 +10524,14 @@ cmd_changemode (char *dbname, char *modify, char *force, argv[argc++] = NULL; - if (run_child (argv, 1, NULL, tmpfilepath, cubrid_err_file, NULL) < 0) /* changemode */ + if (run_child (argv, 1, NULL, tmpfilepath, arniadb_err_file, NULL) < 0) /* changemode */ { strcpy_limit (_dbmt_error, argv[0], DBMT_ERROR_MSG_SIZE); retval = ERR_SYSTEM_CALL; goto error_return; } - if (read_error_file (cubrid_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) + if (read_error_file (arniadb_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) { retval = ERR_WITH_MSG; goto error_return; @@ -10559,17 +10559,17 @@ cmd_changemode (char *dbname, char *modify, char *force, fclose (outputfile); unlink (tmpfilepath); - if (access (cubrid_err_file, F_OK) == 0) + if (access (arniadb_err_file, F_OK) == 0) { - unlink (cubrid_err_file); + unlink (arniadb_err_file); } return ERR_NO_ERROR; error_return: unlink (tmpfilepath); - if (access (cubrid_err_file, F_OK) == 0) + if (access (arniadb_err_file, F_OK) == 0) { - unlink (cubrid_err_file); + unlink (arniadb_err_file); } return retval; } @@ -10583,7 +10583,7 @@ ts_role_change (nvplist *req, nvplist *res, char *_dbmt_error) FILE *infile = NULL; char *tok[8]; const char *cmd_argv[8]; - char cub_admin_cmd[CUBRID_CMD_NAME_LEN]; + char arn_admin_cmd[ARNIADB_CMD_NAME_LEN]; char buf[2048] = { 0 }; const char *argv[] = @@ -10650,9 +10650,9 @@ ts_role_change (nvplist *req, nvplist *res, char *_dbmt_error) { /* restart applylogdb & copylogdb processes. */ string_tokenize2 (buf, tok, 8, ' '); - cub_admin_cmd_name (cub_admin_cmd, sizeof (cub_admin_cmd)); + arn_admin_cmd_name (arn_admin_cmd, sizeof (arn_admin_cmd)); - cmd_argv[0] = cub_admin_cmd; + cmd_argv[0] = arn_admin_cmd; for (i = 1; tok[i] != NULL; i++) { @@ -10665,7 +10665,7 @@ ts_role_change (nvplist *req, nvplist *res, char *_dbmt_error) goto error_return; } } - else if (strstr (buf, "cub_server") != NULL) + else if (strstr (buf, "arn_server") != NULL) { /* restart database server processes. */ string_tokenize2 (buf, tok, 3, ' '); @@ -10872,8 +10872,8 @@ ts_write_and_save_conf (nvplist *req, nvplist *res, char *_dbmt_error) int ts_run_sql_statement (nvplist *req, nvplist *res, char *_dbmt_error) { - T_CUBRID_MODE mode; - T_CSQL_RESULT *csql_res = NULL; + T_ARNIADB_MODE mode; + T_ASQL_RESULT *asql_res = NULL; int retval = ERR_NO_ERROR; char *dbname, *uid, *passwd; char *infile; @@ -10895,23 +10895,23 @@ ts_run_sql_statement (nvplist *req, nvplist *res, char *_dbmt_error) mode = (uDatabaseMode (dbname, NULL) == - DB_SERVICE_MODE_NONE ? CUBRID_MODE_SA : CUBRID_MODE_CS); + DB_SERVICE_MODE_NONE ? ARNIADB_MODE_SA : ARNIADB_MODE_CS); - csql_res = cmd_csql (dbname, uid, passwd, mode, infile, command, error_continue); /* csql */ + asql_res = cmd_asql (dbname, uid, passwd, mode, infile, command, error_continue); /* asql */ - if (csql_res == NULL) + if (asql_res == NULL) { - strcpy_limit (_dbmt_error, "Error occur when execurating csql.", + strcpy_limit (_dbmt_error, "Error occur when execurating asql.", DBMT_ERROR_MSG_SIZE); return ERR_WITH_MSG; } - if (strlen (csql_res->err_msg) != 0) + if (strlen (asql_res->err_msg) != 0) { - strcpy_limit (_dbmt_error, csql_res->err_msg, DBMT_ERROR_MSG_SIZE); + strcpy_limit (_dbmt_error, asql_res->err_msg, DBMT_ERROR_MSG_SIZE); retval = ERR_WITH_MSG; } - free (csql_res); + free (asql_res); return retval; } @@ -11124,10 +11124,10 @@ ts_remove_files (nvplist *req, nvplist *res, char *_dbmt_error) path); return ERR_WITH_MSG; } - if (*path == '+' && * (path + 1) == 'T') // for CUBRID/tmp + if (*path == '+' && * (path + 1) == 'T') // for ARNIADB/tmp { snprintf (fullpath, sizeof (fullpath) - 1, "%s/tmp/%s", - sco.szCubrid, (path + 2)); + sco.szArniadb, (path + 2)); } else { @@ -11344,29 +11344,29 @@ static int cmd_heartbeat_list (T_HA_SERVER_INFO_ALL **all_info, int get_all_dbmode, char *dblist, char *_dbmt_error) { - char cmd_name[CUBRID_CMD_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; const char *argv[6]; int argc = 0; - char cubrid_err_file[PATH_MAX]; + char arniadb_err_file[PATH_MAX]; char outputfilepath[PATH_MAX]; int retval = ERR_NO_ERROR; FILE *tmpfile = NULL; - cubrid_err_file[0] = '\0'; + arniadb_err_file[0] = '\0'; - cubrid_cmd_name (cmd_name); + arniadb_cmd_name (cmd_name); argv[argc++] = cmd_name; argv[argc++] = PRINT_CMD_HEARTBEAT; argv[argc++] = PRINT_CMD_LIST; argv[argc++] = NULL; - snprintf (cubrid_err_file, PATH_MAX, "%s/%s.%u.err.tmp", + snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", sco.dbmt_tmp_dir, "heartbeat_list", getpid ()); snprintf (outputfilepath, PATH_MAX - 1, "%s/DBMT_task_%d.%d", sco.dbmt_tmp_dir, TS_HEARTBEAT_LIST, (int) getpid ()); - if (run_child (argv, 1, NULL, outputfilepath, cubrid_err_file, NULL) < 0) + if (run_child (argv, 1, NULL, outputfilepath, arniadb_err_file, NULL) < 0) { /* heartbeat list */ strcpy (_dbmt_error, argv[0]); @@ -11374,7 +11374,7 @@ cmd_heartbeat_list (T_HA_SERVER_INFO_ALL **all_info, int get_all_dbmode, goto rm_tmpfile; } - if (read_error_file (cubrid_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) + if (read_error_file (arniadb_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) { retval = ERR_WITH_MSG; goto rm_tmpfile; @@ -11401,9 +11401,9 @@ cmd_heartbeat_list (T_HA_SERVER_INFO_ALL **all_info, int get_all_dbmode, rm_tmpfile: unlink (outputfilepath); - if (access (cubrid_err_file, F_OK) == 0) + if (access (arniadb_err_file, F_OK) == 0) { - unlink (cubrid_err_file); + unlink (arniadb_err_file); } return retval; } @@ -12319,17 +12319,17 @@ uca_conf_write (T_CM_BROKER_CONF *uc_conf, char *del_broker, } } - cm_get_broker_file (UC_FID_CUBRID_BROKER_CONF, buf); + cm_get_broker_file (UC_FID_ARNIADB_BROKER_CONF, buf); if (stat (buf, &statbuf) < 0) { - cm_get_broker_file (UC_FID_CUBRID_CAS_CONF, buf); + cm_get_broker_file (UC_FID_ARNIADB_CAS_CONF, buf); if (stat (buf, &statbuf) < 0) { cm_get_broker_file (UC_FID_UNICAS_CONF, buf); if (stat (buf, &statbuf) < 0) { - cm_get_broker_file (UC_FID_CUBRID_BROKER_CONF, buf); + cm_get_broker_file (UC_FID_ARNIADB_BROKER_CONF, buf); } } } @@ -12427,13 +12427,13 @@ _tsParseSpacedb (nvplist *req, nvplist *res, char *dbname, if (strncmp (fname, dbname, baselen) == 0) { - if (!strcmp (fname + baselen, CUBRID_ACT_LOG_EXT)) + if (!strcmp (fname + baselen, ARNIADB_ACT_LOG_EXT)) { _ts_gen_spaceinfo (res, fname, dbdir, "Active_log", logpagesize); } - else if (!strncmp (fname + baselen, CUBRID_ARC_LOG_EXT, - CUBRID_ARC_LOG_EXT_LEN)) + else if (!strncmp (fname + baselen, ARNIADB_ARC_LOG_EXT, + ARNIADB_ARC_LOG_EXT_LEN)) { _ts_gen_spaceinfo (res, fname, dbdir, "Archive_log", logpagesize); @@ -13058,7 +13058,7 @@ get_broker_info_from_filename (char *path, char *br_name, int *as_id) return -1; } path_len = (int) strlen (path); - if (strncmp (path, sco.szCubrid, strlen (sco.szCubrid)) != 0 || + if (strncmp (path, sco.szArniadb, strlen (sco.szArniadb)) != 0 || path_len <= sql_log_ext_len || strcmp (path + (path_len - sql_log_ext_len), sql_log_ext) != 0) { @@ -13140,17 +13140,17 @@ get_dbitemdir (char *item_dir, size_t item_dir_size, char *dbname, { return -1; } -#if !defined (DO_NOT_USE_CUBRIDENV) - envpath = sco.szCubrid_databases; +#if !defined (DO_NOT_USE_ARNIADBENV) + envpath = sco.szArniadb_databases; #else - envpath = CUBRID_VARDIR; + envpath = ARNIADB_VARDIR; #endif if ((envpath == NULL) || (strlen (envpath) == 0)) { return -1; } snprintf (db_txt, sizeof (db_txt) - 1, "%s/%s", envpath, - CUBRID_DATABASE_TXT); + ARNIADB_DATABASE_TXT); databases_txt = fopen (db_txt, "r"); /*set the patten to get dir from databases.txt. */ @@ -13225,7 +13225,7 @@ cm_get_abs_file_path (const char *filename, char *buf) return buf; } #endif - sprintf (buf, "%s/%s", getenv ("CUBRID"), filename); + sprintf (buf, "%s/%s", getenv ("ARNIADB"), filename); return buf; } @@ -13354,7 +13354,7 @@ alter_dblocation (const char *dbname, const char *new_dbpath) char *tok[4]; snprintf (dblocation_info_path, PATH_MAX - 1, "%s/%s", - sco.szCubrid_databases, CUBRID_DATABASE_TXT); + sco.szArniadb_databases, ARNIADB_DATABASE_TXT); snprintf (tmpfile_path, PATH_MAX - 1, "%s/DBMT_util_dblocation.%d", sco.dbmt_tmp_dir, (int) getpid ()); @@ -13651,7 +13651,7 @@ ts_get_shard_info (nvplist *req, nvplist *res, char *_dbmt_error) char stderr_log_file[512]; int pid, argc = 0; int ret_val; - char cmd_name[CUBRID_CMD_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; const char *argv[6]; static int reqid = 0; @@ -13661,10 +13661,10 @@ ts_get_shard_info (nvplist *req, nvplist *res, char *_dbmt_error) sprintf (stderr_log_file, "%s/cmshardinfo2.%d.err", sco.dbmt_tmp_dir, reqid); cmd_name[0] = '\0'; -#if !defined (DO_NOT_USE_CUBRIDENV) - sprintf (cmd_name, "%s/%s%s", sco.szCubrid, CUBRID_DIR_BIN, UTIL_CUBRID); +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ARNIADB); #else - sprintf (cmd_name, "%s/%s", CUBRID_BINDIR, UTIL_CUBRID); + sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_ARNIADB); #endif argv[argc++] = cmd_name; @@ -13798,7 +13798,7 @@ ts_get_shard_status (nvplist *req, nvplist *res, char *_dbmt_error) char stderr_log_file[512]; int pid, argc = 0; int ret_val; - char cmd_name[CUBRID_CMD_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; const char *argv[6]; char *sname; static int reqid = 0; @@ -13814,10 +13814,10 @@ ts_get_shard_status (nvplist *req, nvplist *res, char *_dbmt_error) sprintf (stderr_log_file, "%s/cmshardstatus2.%d.err", sco.dbmt_tmp_dir, reqid); cmd_name[0] = '\0'; -#if !defined (DO_NOT_USE_CUBRIDENV) - sprintf (cmd_name, "%s/%s%s", sco.szCubrid, CUBRID_DIR_BIN, UTIL_CUBRID); +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ARNIADB); #else - sprintf (cmd_name, "%s/%s", CUBRID_BINDIR, UTIL_CUBRID); + sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_ARNIADB); #endif argv[argc++] = cmd_name; @@ -13935,7 +13935,7 @@ ts_shard_start (nvplist *req, nvplist *res, char *err_buf) char stderr_log_file[512]; int pid, argc = 0; int ret_val; - char cmd_name[CUBRID_CMD_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; const char *argv[5]; char *sname = NULL; @@ -13947,10 +13947,10 @@ ts_shard_start (nvplist *req, nvplist *res, char *err_buf) (int) getpid ()); cmd_name[0] = '\0'; -#if !defined (DO_NOT_USE_CUBRIDENV) - sprintf (cmd_name, "%s/%s%s", sco.szCubrid, CUBRID_DIR_BIN, UTIL_CUBRID); +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ARNIADB); #else - sprintf (cmd_name, "%s/%s", CUBRID_BINDIR, UTIL_CUBRID); + sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_ARNIADB); #endif argv[argc++] = cmd_name; @@ -14001,7 +14001,7 @@ ts_shard_stop (nvplist *req, nvplist *res, char *err_buf) char stderr_log_file[512]; int pid, argc = 0; int ret_val; - char cmd_name[CUBRID_CMD_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; const char *argv[5]; char *sname = NULL; @@ -14013,10 +14013,10 @@ ts_shard_stop (nvplist *req, nvplist *res, char *err_buf) (int) getpid ()); cmd_name[0] = '\0'; -#if !defined (DO_NOT_USE_CUBRIDENV) - sprintf (cmd_name, "%s/%s%s", sco.szCubrid, CUBRID_DIR_BIN, UTIL_CUBRID); +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ARNIADB); #else - sprintf (cmd_name, "%s/%s", CUBRID_BINDIR, UTIL_CUBRID); + sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_ARNIADB); #endif argv[argc++] = cmd_name; @@ -14135,7 +14135,7 @@ ts_broker_changer (nvplist *req, nvplist *res, char *_dbmt_error) char stdout_log_file[512]; char stderr_log_file[512]; - char cmd_name[CUBRID_CMD_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; const char *argv[6]; char *bname = NULL; @@ -14174,11 +14174,11 @@ ts_broker_changer (nvplist *req, nvplist *res, char *_dbmt_error) (int) getpid ()); cmd_name[0] = '\0'; -#if !defined (DO_NOT_USE_CUBRIDENV) - sprintf (cmd_name, "%s/%s%s", sco.szCubrid, CUBRID_DIR_BIN, +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_BROKER_CHANGER); #else - sprintf (cmd_name, "%s/%s", CUBRID_BINDIR, UTIL_BROKER_CHANGER); + sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_BROKER_CHANGER); #endif argv[argc++] = cmd_name; @@ -14565,7 +14565,7 @@ ts_ha_start (nvplist *req, nvplist *res, char *_dbmt_error) { char stdout_log_file[512]; char stderr_log_file[512]; - char cmd_name[CUBRID_CMD_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; const char *argv[6]; char *dbname = NULL; @@ -14582,10 +14582,10 @@ ts_ha_start (nvplist *req, nvplist *res, char *_dbmt_error) (int) getpid ()); cmd_name[0] = '\0'; -#if !defined (DO_NOT_USE_CUBRIDENV) - sprintf (cmd_name, "%s/%s%s", sco.szCubrid, CUBRID_DIR_BIN, UTIL_CUBRID); +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ARNIADB); #else - sprintf (cmd_name, "%s/%s", CUBRID_BINDIR, UTIL_CUBRID); + sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_ARNIADB); #endif argv[argc++] = cmd_name; @@ -14599,7 +14599,7 @@ ts_ha_start (nvplist *req, nvplist *res, char *_dbmt_error) } argv[argc] = NULL; - // run "cubrid heartbeat start [dbname]" + // run "arniadb heartbeat start [dbname]" pid = run_child (argv, 1, NULL, stdout_log_file, stderr_log_file, NULL); if (pid < 0) @@ -14627,7 +14627,7 @@ ts_ha_stop (nvplist *req, nvplist *res, char *_dbmt_error) { char stdout_log_file[512]; char stderr_log_file[512]; - char cmd_name[CUBRID_CMD_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; const char *argv[6]; char *dbname = NULL; @@ -14645,10 +14645,10 @@ ts_ha_stop (nvplist *req, nvplist *res, char *_dbmt_error) (int) getpid ()); cmd_name[0] = '\0'; -#if !defined (DO_NOT_USE_CUBRIDENV) - sprintf (cmd_name, "%s/%s%s", sco.szCubrid, CUBRID_DIR_BIN, UTIL_CUBRID); +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ARNIADB); #else - sprintf (cmd_name, "%s/%s", CUBRID_BINDIR, UTIL_CUBRID); + sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_ARNIADB); #endif argv[argc++] = cmd_name; @@ -14662,7 +14662,7 @@ ts_ha_stop (nvplist *req, nvplist *res, char *_dbmt_error) } argv[argc] = NULL; - // run "cubrid heartbeat stop [dbname]" + // run "arniadb heartbeat stop [dbname]" pid = run_child (argv, 1, NULL, stdout_log_file, stderr_log_file, NULL); if (pid < 0) @@ -14690,7 +14690,7 @@ ts_ha_status (nvplist *req, nvplist *res, char *_dbmt_error) { char stdout_log_file[512]; char stderr_log_file[512]; - char cmd_name[CUBRID_CMD_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; const char *argv[6]; int argc = 0; int pid; @@ -14703,10 +14703,10 @@ ts_ha_status (nvplist *req, nvplist *res, char *_dbmt_error) (int) getpid ()); cmd_name[0] = '\0'; -#if !defined (DO_NOT_USE_CUBRIDENV) - sprintf (cmd_name, "%s/%s%s", sco.szCubrid, CUBRID_DIR_BIN, UTIL_CUBRID); +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ARNIADB); #else - sprintf (cmd_name, "%s/%s", CUBRID_BINDIR, UTIL_CUBRID); + sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_ARNIADB); #endif argv[argc++] = cmd_name; @@ -14714,7 +14714,7 @@ ts_ha_status (nvplist *req, nvplist *res, char *_dbmt_error) argv[argc++] = PRINT_CMD_STATUS; argv[argc] = NULL; - // run "cubrid heartbeat status" + // run "arniadb heartbeat status" pid = run_child (argv, 1, NULL, stdout_log_file, stderr_log_file, NULL); if (pid < 0) @@ -14757,7 +14757,7 @@ ts_ha_reload (nvplist *req, nvplist *res, char *_dbmt_error) char stdout_log_file[512]; char stderr_log_file[512]; - char cmd_name[CUBRID_CMD_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; const char *argv[6]; int argc = 0; @@ -14771,10 +14771,10 @@ ts_ha_reload (nvplist *req, nvplist *res, char *_dbmt_error) (int) getpid ()); cmd_name[0] = '\0'; -#if !defined (DO_NOT_USE_CUBRIDENV) - sprintf (cmd_name, "%s/%s%s", sco.szCubrid, CUBRID_DIR_BIN, UTIL_CUBRID); +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ARNIADB); #else - sprintf (cmd_name, "%s/%s", CUBRID_BINDIR, UTIL_CUBRID); + sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_ARNIADB); #endif argv[argc++] = cmd_name; @@ -14782,7 +14782,7 @@ ts_ha_reload (nvplist *req, nvplist *res, char *_dbmt_error) argv[argc++] = PRINT_CMD_RELOAD; argv[argc] = NULL; - // run "cubrid heartbeat reload" + // run "arniadb heartbeat reload" pid = run_child (argv, 1, NULL, stdout_log_file, stderr_log_file, NULL); if (pid < 0) @@ -14812,7 +14812,7 @@ ts_ha_copylogdb (nvplist *req, nvplist *res, char *_dbmt_error) char stdout_log_file[512]; char stderr_log_file[512]; - char cmd_name[CUBRID_CMD_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; const char *argv[7]; char *dbname = NULL; @@ -14853,10 +14853,10 @@ ts_ha_copylogdb (nvplist *req, nvplist *res, char *_dbmt_error) (int) getpid ()); cmd_name[0] = '\0'; -#if !defined (DO_NOT_USE_CUBRIDENV) - sprintf (cmd_name, "%s/%s%s", sco.szCubrid, CUBRID_DIR_BIN, UTIL_CUBRID); +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ARNIADB); #else - sprintf (cmd_name, "%s/%s", CUBRID_BINDIR, UTIL_CUBRID); + sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_ARNIADB); #endif argv[argc++] = cmd_name; @@ -14867,7 +14867,7 @@ ts_ha_copylogdb (nvplist *req, nvplist *res, char *_dbmt_error) argv[argc++] = peer_node; argv[argc] = NULL; - // run "cubrid heartbeat copylogdb dbname peer_node" + // run "arniadb heartbeat copylogdb dbname peer_node" pid = run_child (argv, 1, NULL, stdout_log_file, stderr_log_file, NULL); if (pid < 0) @@ -14896,7 +14896,7 @@ ts_ha_applylogdb (nvplist *req, nvplist *res, char *_dbmt_error) char stdout_log_file[512]; char stderr_log_file[512]; - char cmd_name[CUBRID_CMD_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; const char *argv[7]; char *dbname = NULL; @@ -14937,10 +14937,10 @@ ts_ha_applylogdb (nvplist *req, nvplist *res, char *_dbmt_error) (int) getpid ()); cmd_name[0] = '\0'; -#if !defined (DO_NOT_USE_CUBRIDENV) - sprintf (cmd_name, "%s/%s%s", sco.szCubrid, CUBRID_DIR_BIN, UTIL_CUBRID); +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ARNIADB); #else - sprintf (cmd_name, "%s/%s", CUBRID_BINDIR, UTIL_CUBRID); + sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_ARNIADB); #endif argv[argc++] = cmd_name; @@ -14951,7 +14951,7 @@ ts_ha_applylogdb (nvplist *req, nvplist *res, char *_dbmt_error) argv[argc++] = peer_node; argv[argc] = NULL; - // run "cubrid heartbeat applylogdb dbname peer_node" + // run "arniadb heartbeat applylogdb dbname peer_node" pid = run_child (argv, 1, NULL, stdout_log_file, stderr_log_file, NULL); if (pid < 0) @@ -14983,10 +14983,10 @@ ts_ha_applylogdb (nvplist *req, nvplist *res, char *_dbmt_error) FILE *fin; -#if !defined (DO_NOT_USE_CUBRIDENV) - snprintf (cm_conf_file, PATH_MAX - 1, "%s/conf/%s", sco.szCubrid, CUBRID_DBMT_CONF); +#if !defined (DO_NOT_USE_ARNIADBENV) + snprintf (cm_conf_file, PATH_MAX - 1, "%s/conf/%s", sco.szArniadb, ARNIADB_DBMT_CONF); #else - snprintf (cm_conf_file, PATH_MAX - 1, "%s/%s", CUBRID_CONFDIR, CUBRID_DBMT_CONF); + snprintf (cm_conf_file, PATH_MAX - 1, "%s/%s", ARNIADB_CONFDIR, ARNIADB_DBMT_CONF); #endif fin = fopen(cm_conf_file, "r"); @@ -15044,7 +15044,7 @@ _write_auto_update_log (char *line_buf, int is_success) FILE *fin = NULL; - sprintf (log_path, "%s/log/manager/cms.update.log", sco.szCubrid); + sprintf (log_path, "%s/log/manager/cms.update.log", sco.szArniadb); fin = fopen (log_path, "a"); @@ -15085,7 +15085,7 @@ ts_is_update_success (nvplist *req, nvplist *res, char *_dbmt_error) while (fgets (line_buf, LINE_MAX, fin) != NULL) { - if (strstr (line_buf, "CUBRID Manager Server is updated.") != NULL) + if (strstr (line_buf, "ARNIADB Manager Server is updated.") != NULL) { nv_add_nvp (res, "autoupdate_success", "success"); @@ -15231,10 +15231,10 @@ ts_list_dir (nvplist *req, nvplist *res, char *_dbmt_error) } nv_add_nvp (res, "path", path); -#if !defined (DO_NOT_USE_CUBRIDENV) - snprintf (full_path, PATH_MAX, "%s/%s/", sco.szCubrid, path); +#if !defined (DO_NOT_USE_ARNIADBENV) + snprintf (full_path, PATH_MAX, "%s/%s/", sco.szArniadb, path); #else - sprintf (full_path, "%s/%s/", CUBRID, path); + sprintf (full_path, "%s/%s/", ARNIADB, path); #endif #if defined(WINDOWS) @@ -15374,7 +15374,7 @@ int ts_monitor_process (nvplist *req, nvplist *res, char *_dbmt_error) { // processes need monitoring - const char process_name[][PATH_MAX] = {"cub_master", 0}; + const char process_name[][PATH_MAX] = {"arn_master", 0}; char exist[15]; int i = 0; @@ -15631,7 +15631,7 @@ _make_cert (nvplist *req, X509 **x509p, EVP_PKEY **pkeyp, int bits, && (organizational_unit_name == NULL) && (common_name == NULL) && (email_addr == NULL)) { - snprintf (user_info, PATH_MAX, "CUBRID Manger Server Group."); + snprintf (user_info, PATH_MAX, "ARNIADB Manger Server Group."); _add_issuer_info (name, "OU", user_info); } /* Its self signed so set the issuer name to be the same as the @@ -15656,7 +15656,7 @@ _make_cert (nvplist *req, X509 **x509p, EVP_PKEY **pkeyp, int bits, nid_netscape_cert_type); snprintf (nid_netscape_comment, PATH_MAX, - "CUBRID Manager server comment extension"); + "ARNIADB Manager server comment extension"); _add_extensions (x509_local, NID_netscape_comment, nid_netscape_comment); if (X509_sign (x509_local, pub_key, EVP_md5 ()) == 0) @@ -15901,7 +15901,7 @@ ts_start_statdump (nvplist *req, nvplist *res, char *_dbmt_error) } strcpy (statdump_daemon[slot].dbname, db_name); interval = atoi (interval_str); - cubrid_cmd_name (path); + arniadb_cmd_name (path); argv[argc++] = path; argv[argc++] = "statdump"; diff --git a/server/src/cm_job_task.h b/server/src/cm_job_task.h index 1c35222..72d297d 100644 --- a/server/src/cm_job_task.h +++ b/server/src/cm_job_task.h @@ -43,8 +43,8 @@ #define SET_TRANSACTION_NO_WAIT_MODE_ENV() \ do { \ - putenv((char *) "CUBRID_LOCK_TIMEOUT_IN_SECS=1"); \ - putenv((char *) "CUBRID_ISOLATION_LEVEL=TRAN_READ_COMMITTED"); \ + putenv((char *) "ARNIADB_LOCK_TIMEOUT_IN_SECS=1"); \ + putenv((char *) "ARNIADB_ISOLATION_LEVEL=TRAN_READ_COMMITTED"); \ } while (0) typedef enum diff --git a/server/src/cm_log.h b/server/src/cm_log.h index ba4e9c1..01a2ac0 100644 --- a/server/src/cm_log.h +++ b/server/src/cm_log.h @@ -255,7 +255,7 @@ class CLog long oldest_time = LONG_MAX; char log_path[PATH_MAX]; - snprintf (log_path, PATH_MAX, "%s/%s", sco.szCubrid, DBMT_LOG_DIR); + snprintf (log_path, PATH_MAX, "%s/%s", sco.szArniadb, DBMT_LOG_DIR); if (files_list.empty() == true) { @@ -342,11 +342,11 @@ class CLog char log_path[PATH_MAX]; list < string > log_files_list; - string error_log_name = "cub_manager.err"; - string log_name = "cub_manager.log"; + string error_log_name = "arn_manager.err"; + string log_name = "arn_manager.log"; log_path[0] = '\0'; - snprintf (log_path, PATH_MAX, "%s/%s", sco.szCubrid, DBMT_LOG_DIR); + snprintf (log_path, PATH_MAX, "%s/%s", sco.szArniadb, DBMT_LOG_DIR); //check log level if (iPriority > _logLevel ()) @@ -461,7 +461,7 @@ class CLog // init open file - close them firstly _init_file_hander (); - // then move the cub_manager.log into new name log file. + // then move the arn_manager.log into new name log file. _backup_log_files (log_path, error_log_name, log_name); // remove the oldest file diff --git a/server/src/cm_server_autoupdate.cpp b/server/src/cm_server_autoupdate.cpp index 2fdbaa0..59fbaca 100644 --- a/server/src/cm_server_autoupdate.cpp +++ b/server/src/cm_server_autoupdate.cpp @@ -196,29 +196,29 @@ generate_update_script (char *patch_name, char *url, char *path, // backup fprintf (fout, "md %sbackup\n", path); fprintf (fout, - "if exist %s\\bin\\cub_manager.exe copy /y %s\\bin\\cub_manager.exe %sbackup\\.\n", - sco.szCubrid, sco.szCubrid, path); + "if exist %s\\bin\\arn_manager.exe copy /y %s\\bin\\arn_manager.exe %sbackup\\.\n", + sco.szArniadb, sco.szArniadb, path); fprintf (fout, "if exist %s\\bin\\cm_admin.exe copy /y %s\\bin\\cm_admin.exe %sbackup\\.\n", - sco.szCubrid, sco.szCubrid, path); + sco.szArniadb, sco.szArniadb, path); - fprintf (fout, "cubrid service stop\n"); - fprintf (fout, "cub_manager stop\n"); + fprintf (fout, "arniadb service stop\n"); + fprintf (fout, "arn_manager stop\n"); //update - fprintf (fout, "if exist %s\\cub_* copy /y %s\\cub_* %s\\bin\\.\n", - zip_folder, zip_folder, sco.szCubrid); + fprintf (fout, "if exist %s\\arn_* copy /y %s\\arn_* %s\\bin\\.\n", + zip_folder, zip_folder, sco.szArniadb); fprintf (fout, "if exist %s\\cm_admin copy /y %s\\cm_admin.exe %s\\bin\\.\n", - zip_folder, zip_folder, sco.szCubrid); + zip_folder, zip_folder, sco.szArniadb); fprintf (fout, "for /f %%%%c in ('dir /b %s\\conf\\') do type %s\\conf\\%%%%c >> %s\\conf\\%%%%c\n", - zip_folder, zip_folder, sco.szCubrid); + zip_folder, zip_folder, sco.szArniadb); fprintf (fout, "ping 127.0.0.1 -n 40 -w 1000 > nul\n"); - fprintf (fout, "cubrid service start\n"); - fprintf (fout, "cub_manager start\n"); - fprintf (fout, "echo \"CUBRID Manager Server is updated.\"", path); + fprintf (fout, "arniadb service start\n"); + fprintf (fout, "arn_manager start\n"); + fprintf (fout, "echo \"ARNIADB Manager Server is updated.\"", path); fclose (fout); @@ -260,27 +260,27 @@ generate_update_script (char *patch_name, char *url, char *path, fprintf (fout, "mkdir %sbackup\n", path); fprintf (fout, - "cp %s/bin/cm_admin %s/bin/cub_manager %sbackup/.\n", - sco.szCubrid, sco.szCubrid, path); + "cp %s/bin/cm_admin %s/bin/arn_manager %sbackup/.\n", + sco.szArniadb, sco.szArniadb, path); fprintf (fout, - "if [ -e %spatch/cub_manager ]; then\n", path); - fprintf (fout, "\tcp %spatch/cub_* %s/bin/. -f\nfi\n", path, sco.szCubrid); + "if [ -e %spatch/arn_manager ]; then\n", path); + fprintf (fout, "\tcp %spatch/arn_* %s/bin/. -f\nfi\n", path, sco.szArniadb); fprintf (fout, "if [ -e %spatch/cm_admin ]; then\n", path); fprintf (fout, "\tcp %spatch/cm_admin %s/bin/. -f\nfi\n", path, - sco.szCubrid); + sco.szArniadb); fprintf (fout, "if [ -d %spatch/conf ]; then\n", path); fprintf (fout, "\tfor conf_file in $(ls %spatch/conf)\n\tdo\n", path); - fprintf (fout, "\t\tcp %s/conf/$conf_file %sbackup/.\n", sco.szCubrid, + fprintf (fout, "\t\tcp %s/conf/$conf_file %sbackup/.\n", sco.szArniadb, path); fprintf (fout, "\t\tcat %spatch/conf/$conf_file >> %s/conf/$conf_file\n\tdone\nfi\n", - path, sco.szCubrid); + path, sco.szArniadb); - fprintf (fout, "cubrid service restart\n"); - fprintf (fout, "echo \"CUBRID Manager Server is updated.n"); + fprintf (fout, "arniadb service restart\n"); + fprintf (fout, "echo \"ARNIADB Manager Server is updated.n"); fclose (fout); diff --git a/server/src/cm_server_autoupdate.h b/server/src/cm_server_autoupdate.h index 227b887..2eb0cc3 100644 --- a/server/src/cm_server_autoupdate.h +++ b/server/src/cm_server_autoupdate.h @@ -3,14 +3,14 @@ #ifdef WINDOWS -#define DEFAULT_UPDATE_HOST_NAME "jira.cubrid.org" +#define DEFAULT_UPDATE_HOST_NAME "jira.arniadb.org" #define DEFAULT_UPDATE_REMOTE_PATH "/secure/attachment/14895/" #define DOWNLOAD_BUFFER 16384 #define SHELL_NAME "auto_update.bat" #else -#define DEFAULT_PATCH_URL "http://jira.cubrid.org/secure/attachment/14806/patch_9.1.0001.zip" +#define DEFAULT_PATCH_URL "http://jira.arniadb.org/secure/attachment/14806/patch_9.1.0001.zip" #define SHELL_NAME "auto_update.sh" #endif diff --git a/server/src/cm_server_extend_interface.cpp b/server/src/cm_server_extend_interface.cpp index ba30018..096137f 100644 --- a/server/src/cm_server_extend_interface.cpp +++ b/server/src/cm_server_extend_interface.cpp @@ -279,7 +279,7 @@ bool write_json_to_file (string filepath, Json::Value &root) return FALSE; } -int ext_cub_broker_start (Json::Value &request, Json::Value &response) +int ext_arn_broker_start (Json::Value &request, Json::Value &response) { string task = request["task"].asString(); nvplist *cli_request, *cli_response; @@ -515,7 +515,7 @@ ext_autojobs_log (const char *service, const char *serv_name, const char *errmsg tt = time (&tt); - snprintf (logfile, MAX_PATH, "%s/%s/autojobs.log", sco.szCubrid, DBMT_LOG_DIR); + snprintf (logfile, MAX_PATH, "%s/%s/autojobs.log", sco.szArniadb, DBMT_LOG_DIR); outfile = fopen (logfile, "a"); if (outfile == NULL) @@ -601,7 +601,7 @@ int ext_exec_brokers_auto_start (const Json::Value &autobrokers, Json::Value &r if (activebrokers["brokerstatus"].asString() == "OFF") { request["task"] = "startbroker"; - ext_cub_broker_start (request, response); + ext_arn_broker_start (request, response); if (response["status"] != "success") { @@ -625,7 +625,7 @@ int ext_exec_brokers_auto_start (const Json::Value &autobrokers, Json::Value &r { request["task"] = "broker_start"; request["bname"] = bname; - ext_cub_broker_start (request, response); + ext_arn_broker_start (request, response); if (response["status"] != "success") { @@ -748,7 +748,7 @@ string build_report_log (Json::Value &report) default: break; } - report_log += "
See More Detail Log: CUBRID Web Manager"; + report_log += "
See More Detail Log: ARNIADB Web Manager"; return report_log; } @@ -823,7 +823,7 @@ int ext_exec_mail_report (Json::Value &mailreport, Json::Value &response) log_request["start_time"] = prev_exec; log_request["end_time"] = format_time; - mailhead = "Log Report for CUBRID"; + mailhead = "Log Report for ARNIADB"; log_response["dbname"] = mailreport[i]["dbname"].asString(); log_response["url_prefix"] = mailreport[i]["url_prefix"].asString(); @@ -951,7 +951,7 @@ int ext_get_db_err_log (Json::Value &request, Json::Value &response) return build_server_header (response, ERR_DBDIRNAME_NULL, "Can not find the directory!"); } - snprintf (find_file, PATH_MAX - 1, "%s/%s", sco.szCubrid, CUBRID_ERROR_LOG_DIR); + snprintf (find_file, PATH_MAX - 1, "%s/%s", sco.szArniadb, ARNIADB_ERROR_LOG_DIR); #if defined(WINDOWS) snprintf (&find_file[strlen (find_file)], PATH_MAX - strlen (find_file) - 1, "/*"); if ((handle = FindFirstFile (find_file, &data)) == INVALID_HANDLE_VALUE) @@ -982,7 +982,7 @@ int ext_get_db_err_log (Json::Value &request, Json::Value &response) { continue; } - snprintf (buf, sizeof (buf) - 1, "%s/%s/%s", sco.szCubrid, CUBRID_ERROR_LOG_DIR, fname); + snprintf (buf, sizeof (buf) - 1, "%s/%s/%s", sco.szArniadb, ARNIADB_ERROR_LOG_DIR, fname); if (stat (buf, &statbuf) == 0) { time_to_str (statbuf.st_mtime, "%4d/%02d/%02d %02d:%02d:%02d", format_time, TIME_STR_FMT_DATE_TIME); @@ -1040,11 +1040,11 @@ int ext_get_broker_start_log (Json::Value &request, Json::Value &response) string format_time, strlog; int logsize = 0; - snprintf (log_file, PATH_MAX - 1, "%s/%s/cubrid_broker.log", sco.szCubrid, CUBRID_BROKER_LOG_DIR); + snprintf (log_file, PATH_MAX - 1, "%s/%s/arniadb_broker.log", sco.szArniadb, ARNIADB_BROKER_LOG_DIR); fd = fopen (log_file, "r"); if (fd == NULL) { - return build_server_header (response, ERR_WITH_MSG, "Can't find cubrid_broker.log"); + return build_server_header (response, ERR_WITH_MSG, "Can't find arniadb_broker.log"); } if (request["start_time"] != Json::Value::null) @@ -1159,7 +1159,7 @@ int ext_write_private_data (Json::Value &request, Json::Value &response) build_server_header (response, ERR_PARAM_MISSING, "Parameter(confname) missing in the request")); confname= request["confname"].asString(); - snprintf (conf_path, PATH_MAX, "%s/%s/%s", sco.szCubrid, DBMT_LOG_DIR, confname.c_str()); + snprintf (conf_path, PATH_MAX, "%s/%s/%s", sco.szArniadb, DBMT_LOG_DIR, confname.c_str()); outfile = fopen (conf_path, "w"); if (outfile == NULL) @@ -1186,7 +1186,7 @@ int ext_read_private_data (Json::Value &request, Json::Value &response) build_server_header (response, ERR_PARAM_MISSING, "Parameter(confname) missing in the request")); confname= request["confname"].asString(); - snprintf (conf_path, PATH_MAX, "%s/%s/%s", sco.szCubrid, DBMT_LOG_DIR, confname.c_str()); + snprintf (conf_path, PATH_MAX, "%s/%s/%s", sco.szArniadb, DBMT_LOG_DIR, confname.c_str()); infile = fopen (conf_path, "r"); if (infile == NULL) @@ -1517,7 +1517,7 @@ int ext_get_ha_apply_info (Json::Value &request, Json::Value &response) string dbname; string str_result[8]; - char cmd_name[CUBRID_CMD_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; const char *argv[9]; char stdout_log_file[512]; char stderr_log_file[512]; @@ -1540,7 +1540,7 @@ int ext_get_ha_apply_info (Json::Value &request, Json::Value &response) remote_host_name = request["remotehostname"].asString(); dbname = request["dbname"].asString(); - cubrid_cmd_name (cmd_name); + arniadb_cmd_name (cmd_name); argv[0] = cmd_name; argv[1] = opt_applyinfo.c_str(); @@ -1632,7 +1632,7 @@ int ext_add_dbmt_user_new (Json::Value &request, Json::Value &response) if (strcmp (dbmt_user.user_info[i].user_name, user_id.c_str()) == 0) { dbmt_user_free (&dbmt_user); - sprintf (dbmt_error, "CUBRID Manager user(%s) already exist.", user_id.c_str()); + sprintf (dbmt_error, "ARNIADB Manager user(%s) already exist.", user_id.c_str()); return build_server_header (response, ERR_DBMTUSER_EXIST, dbmt_error); } } @@ -2205,7 +2205,7 @@ int ext_ut_add_dblist_to_response (Json::Value &response, bool is_add_dbpath) Json::Value dblist; Json::Value dbs; - snprintf (dbtxt_file, PATH_MAX-1, "%s/%s", sco.szCubrid_databases, CUBRID_DATABASE_TXT); + snprintf (dbtxt_file, PATH_MAX-1, "%s/%s", sco.szArniadb_databases, ARNIADB_DATABASE_TXT); if (access (dbtxt_file, F_OK) == 0) { in_file.open (dbtxt_file, ios::in); diff --git a/server/src/cm_server_extend_interface.h b/server/src/cm_server_extend_interface.h index b59bb68..9e6e22d 100644 --- a/server/src/cm_server_extend_interface.h +++ b/server/src/cm_server_extend_interface.h @@ -59,7 +59,7 @@ int ext_set_auto_start (Json::Value &request, Json::Value &response); int ext_get_auto_start (Json::Value &request, Json::Value &response); int ext_exec_auto_start (Json::Value &request, Json::Value &response); int ext_exec_auto_jobs (Json::Value &request, Json::Value &response); -int ext_cub_broker_start (Json::Value &request, Json::Value &response); +int ext_arn_broker_start (Json::Value &request, Json::Value &response); int ext_get_db_err_log (Json::Value &request, Json::Value &response); int ext_get_broker_start_log (Json::Value &request, Json::Value &response); int ext_send_mail (Json::Value &request, Json::Value &response); diff --git a/server/src/cm_server_interface.cpp b/server/src/cm_server_interface.cpp index 81505d3..f44f088 100644 --- a/server/src/cm_server_interface.cpp +++ b/server/src/cm_server_interface.cpp @@ -51,14 +51,14 @@ extern T_EMGR_VERSION CLIENT_VERSION; typedef struct { - char cubrid[MAX_PATH]; /*cubrid home; CUBRID=/root/CUBRID */ - char cubrid_databases[MAX_PATH]; /*cubrid databases home,default $(cubrid home)/databases */ - char cubrid_err_log[MAX_PATH]; /*cubrid err log, use for save cmd log */ - // char cubrid_charset[MAX_PATH]; -} cubrid_env_t; + char arniadb[MAX_PATH]; /*arniadb home; ARNIADB=/root/ARNIADB */ + char arniadb_databases[MAX_PATH]; /*arniadb databases home,default $(arniadb home)/databases */ + char arniadb_err_log[MAX_PATH]; /*arniadb err log, use for save cmd log */ + // char arniadb_charset[MAX_PATH]; +} arniadb_env_t; mutex_t cm_mutex; -/*global cubrid env*/ -cubrid_env_t cub_httpd_env; +/*global arniadb env*/ +arniadb_env_t arn_httpd_env; /** * @brief initial monitoring stat information @@ -68,10 +68,10 @@ cubrid_env_t cub_httpd_env; int mon_stat_init (void) { -#if !defined (DO_NOT_USE_CUBRIDENV) - sprintf (sco.sMonStatDataPath, "%s/%s", sco.szCubrid, DBMT_MON_DATA_DIR); +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (sco.sMonStatDataPath, "%s/%s", sco.szArniadb, DBMT_MON_DATA_DIR); #else - sprintf (sco.sMonStatDataPath, "%s", CUBRID_MONDATADIR); + sprintf (sco.sMonStatDataPath, "%s", ARNIADB_MONDATADIR); #endif if (access (sco.sMonStatDataPath, F_OK) < 0) @@ -93,28 +93,28 @@ mon_stat_init (void) } void -cub_cm_init_env () +arn_cm_init_env () { char conf_name[256]; char tmpstrbuf[DBMT_ERROR_MSG_SIZE]; char process_name[PATH_MAX]; - char default_cubrid_lang_type[PATH_MAX]; - char default_cubrid_lang_msg_type[PATH_MAX]; + char default_arniadb_lang_type[PATH_MAX]; + char default_arniadb_lang_msg_type[PATH_MAX]; tmpstrbuf[0]= '\0'; // char *charset = NULL; snprintf (process_name, PATH_MAX, "%s", CMS_NAME); - snprintf (default_cubrid_lang_type, PATH_MAX, "CUBRID_LANG=en_US"); - snprintf (default_cubrid_lang_msg_type, PATH_MAX, "CUBRID_MSG_LANG=en_US"); + snprintf (default_arniadb_lang_type, PATH_MAX, "ARNIADB_LANG=en_US"); + snprintf (default_arniadb_lang_msg_type, PATH_MAX, "ARNIADB_MSG_LANG=en_US"); sys_config_init (); uReadEnvVariables (process_name); if (uReadSystemConfig () < 0) { - snprintf (tmpstrbuf, DBMT_ERROR_MSG_SIZE, "CUBRID Manager Server : Cannot find the configuration file[%s].\n", + snprintf (tmpstrbuf, DBMT_ERROR_MSG_SIZE, "ARNIADB Manager Server : Cannot find the configuration file[%s].\n", conf_get_dbmt_file (FID_DBMT_CONF, conf_name)); - ut_record_cubrid_utility_log_stderr (tmpstrbuf); + ut_record_arniadb_utility_log_stderr (tmpstrbuf); exit (1); } make_default_env (); @@ -122,43 +122,43 @@ cub_cm_init_env () /* check system configuration */ if (uCheckSystemConfig (process_name) < 0) { - ut_record_cubrid_utility_log_stderr ("CUBRID Manager Server : Error while checking system configuration file.\n"); + ut_record_arniadb_utility_log_stderr ("ARNIADB Manager Server : Error while checking system configuration file.\n"); exit (1); } if (mon_stat_init () < 0) { - ut_record_cubrid_utility_log_stderr ("CUBRID Manager Server : Error while checking monitoring data.\n"); + ut_record_arniadb_utility_log_stderr ("ARNIADB Manager Server : Error while checking monitoring data.\n"); exit (1); } - memset (&cub_httpd_env, 0, sizeof (cubrid_env_t)); - putenv (default_cubrid_lang_type); /* set as default language type */ - putenv (default_cubrid_lang_msg_type); /* set as default language type */ - //putenv ("CUBRID_CHARSET=en_US"); /* set as default language type */ + memset (&arn_httpd_env, 0, sizeof (arniadb_env_t)); + putenv (default_arniadb_lang_type); /* set as default language type */ + putenv (default_arniadb_lang_msg_type); /* set as default language type */ + //putenv ("ARNIADB_CHARSET=en_US"); /* set as default language type */ - snprintf (cub_httpd_env.cubrid_err_log, MAX_PATH, - "CUBRID_ERROR_LOG=%s/cmclt.%d.err", sco.dbmt_tmp_dir, (int) getpid ()); - putenv (cub_httpd_env.cubrid_err_log); + snprintf (arn_httpd_env.arniadb_err_log, MAX_PATH, + "ARNIADB_ERROR_LOG=%s/cmclt.%d.err", sco.dbmt_tmp_dir, (int) getpid ()); + putenv (arn_httpd_env.arniadb_err_log); - snprintf (cub_httpd_env.cubrid, MAX_PATH, "CUBRID=%s", sco.szCubrid); - putenv (cub_httpd_env.cubrid); + snprintf (arn_httpd_env.arniadb, MAX_PATH, "ARNIADB=%s", sco.szArniadb); + putenv (arn_httpd_env.arniadb); - snprintf (cub_httpd_env.cubrid_databases, MAX_PATH, "CUBRID_DATABASES=%s", - sco.szCubrid_databases); - putenv (cub_httpd_env.cubrid_databases); + snprintf (arn_httpd_env.arniadb_databases, MAX_PATH, "ARNIADB_DATABASES=%s", + sco.szArniadb_databases); + putenv (arn_httpd_env.arniadb_databases); - /* charset = getenv ("CUBRID_CHARSET"); + /* charset = getenv ("ARNIADB_CHARSET"); if (charset != NULL) { - snprintf (cub_httpd_env.cubrid_charset, MAX_PATH, "CUBRID_CHARSET=%s", + snprintf (arn_httpd_env.arniadb_charset, MAX_PATH, "ARNIADB_CHARSET=%s", charset); } else { - snprintf (cub_httpd_env.cubrid_charset, MAX_PATH, - "CUBRID_CHARSET=en_US"); - putenv (cub_httpd_env.cubrid_charset); + snprintf (arn_httpd_env.arniadb_charset, MAX_PATH, + "ARNIADB_CHARSET=en_US"); + putenv (arn_httpd_env.arniadb_charset); } */ mutex_init (cm_mutex); @@ -166,7 +166,7 @@ cub_cm_init_env () } void -cub_cm_destory_env () +arn_cm_destory_env () { mutex_destory (cm_mutex); } @@ -288,26 +288,26 @@ ch_process_request (nvplist *req, nvplist *res) /* if (charset != NULL) { - snprintf (charsetenv, PATH_MAX, "CUBRID_CHARSET=%s", charset); + snprintf (charsetenv, PATH_MAX, "ARNIADB_CHARSET=%s", charset); putenv (charsetenv); } */ - /* record the start time of running cub_manager */ + /* record the start time of running arn_manager */ gettimeofday (&task_begin, NULL); retval = (*task_func) (req, res, _dbmt_error); - /* record the end time of running cub_manager */ + /* record the end time of running arn_manager */ gettimeofday (&task_end, NULL); /* if (charset != NULL) { - putenv (cub_httpd_env.cubrid_charset); + putenv (arn_httpd_env.arniadb_charset); } */ - /* caculate the running time of cub_manager. */ + /* caculate the running time of arn_manager. */ _ut_timeval_diff (&task_begin, &task_end, &elapsed_msec); - /* add cub_manager task running time to response. */ + /* add arn_manager task running time to response. */ snprintf (elapsed_time_str, sizeof (elapsed_time_str), "%d ms", elapsed_msec); nv_add_nvp (res, "__EXEC_TIME", elapsed_time_str); @@ -432,7 +432,7 @@ dump_nvplist (nvplist *root, char *dumpfile) int -cub_cm_extend_request (Json::Value &request, Json::Value &response) +arn_cm_extend_request (Json::Value &request, Json::Value &response) { T_EXT_TASK_FUNC task_func = NULL; string task; @@ -676,7 +676,7 @@ cm_execute_request_async (Json::Value &request, Json::Value &response, #endif int -cub_check_async_status (Json::Value &request, Json::Value &response) +arn_check_async_status (Json::Value &request, Json::Value &response) { string task; unsigned int uuid; @@ -715,7 +715,7 @@ cub_check_async_status (Json::Value &request, Json::Value &response) } int -cub_cm_request_handler (Json::Value &request, Json::Value &response) +arn_cm_request_handler (Json::Value &request, Json::Value &response) { mutex_lock (cm_mutex); @@ -740,12 +740,12 @@ cub_cm_request_handler (Json::Value &request, Json::Value &response) return 1; } - if (cub_check_async_status (request, response)) + if (arn_check_async_status (request, response)) { mutex_unlock (cm_mutex); return 1; } - if (cub_cm_extend_request (request, response)) + if (arn_cm_extend_request (request, response)) { mutex_unlock (cm_mutex); return 1; diff --git a/server/src/cm_server_interface.h b/server/src/cm_server_interface.h index 41ee208..60ba045 100644 --- a/server/src/cm_server_interface.h +++ b/server/src/cm_server_interface.h @@ -27,7 +27,7 @@ #include "cm_job_task.h" #include "cm_server_util.h" -int cub_cm_request_handler (Json::Value &request, Json::Value &response); -void cub_cm_init_env (); +int arn_cm_request_handler (Json::Value &request, Json::Value &response); +void arn_cm_init_env (); #endif /* */ diff --git a/server/src/cm_server_stat.c b/server/src/cm_server_stat.c index cb67ae0..f30be6b 100644 --- a/server/src/cm_server_stat.c +++ b/server/src/cm_server_stat.c @@ -91,7 +91,7 @@ record_system_info (sys_stat *sstat) } void -record_cubrid_proc_info (userdata *ud) +record_arniadb_proc_info (userdata *ud) { #ifdef HOST_MONITOR_PROC int i, fd; diff --git a/server/src/cm_server_stat.h b/server/src/cm_server_stat.h index a01320d..69aa6e6 100644 --- a/server/src/cm_server_stat.h +++ b/server/src/cm_server_stat.h @@ -93,7 +93,7 @@ typedef struct } userdata; void record_system_info (sys_stat *sstat); -void record_cubrid_proc_info (userdata *ud); +void record_arniadb_proc_info (userdata *ud); void record_unicas_proc_info (int casv[], cas_stat casb[]); #endif /* _CM_SERVER_STAT_H_ */ diff --git a/server/src/cm_server_util.cpp b/server/src/cm_server_util.cpp index 881f62b..9a32eed 100644 --- a/server/src/cm_server_util.cpp +++ b/server/src/cm_server_util.cpp @@ -289,7 +289,7 @@ static bool is_process_running (const char *process_name, unsigned int sleep_tim /** * is_process_running is to check process running or not by checking pid -* process_name: the name of process that must be in $CUBRID/bin +* process_name: the name of process that must be in $ARNIADB/bin * sleep_time: millisecond */ static bool @@ -300,11 +300,11 @@ is_process_running (const char *process_name, unsigned int sleep_time) SLEEP_MILISEC (0, sleep_time); -#if !defined (DO_NOT_USE_CUBRIDENV) - sprintf (cmd, "%s/%s/%s getpid", sco.szCubrid, CUBRID_DIR_BIN, +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (cmd, "%s/%s/%s getpid", sco.szArniadb, ARNIADB_DIR_BIN, process_name); #else - sprintf (cmd, "%s/%s getpid", CUBRID_BINDIR, process_name); + sprintf (cmd, "%s/%s getpid", ARNIADB_BINDIR, process_name); #endif input = popen (cmd, "r"); if (input == NULL) @@ -1151,8 +1151,8 @@ ut_get_dblist (nvplist *res, char dbdir_flag) unsigned char ip_addr[4]; char *token = NULL; - snprintf (file, PATH_MAX - 1, "%s/%s", sco.szCubrid_databases, - CUBRID_DATABASE_TXT); + snprintf (file, PATH_MAX - 1, "%s/%s", sco.szArniadb_databases, + ARNIADB_DATABASE_TXT); if ((infile = fopen (file, "rt")) == NULL) { return ERR_DATABASETXT_OPEN; @@ -2157,8 +2157,8 @@ make_default_env (void) FILE *fd; /* create log/manager directory */ -#if !defined (DO_NOT_USE_CUBRIDENV) - sprintf (strbuf, "%s/%s", sco.szCubrid, DBMT_LOG_DIR); +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (strbuf, "%s/%s", sco.szArniadb, DBMT_LOG_DIR); #else sprintf (strbuf, "%s", DBMT_LOG_DIR); #endif @@ -2168,8 +2168,8 @@ make_default_env (void) } /* create var/manager direcory */ -#if !defined (DO_NOT_USE_CUBRIDENV) - sprintf (strbuf, "%s/%s", sco.szCubrid, DBMT_PID_DIR); +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (strbuf, "%s/%s", sco.szArniadb, DBMT_PID_DIR); #else sprintf (strbuf, "%s", DBMT_PID_DIR); #endif @@ -2179,14 +2179,14 @@ make_default_env (void) } /* create databases directory */ - sprintf (strbuf, "%s", sco.szCubrid_databases); + sprintf (strbuf, "%s", sco.szArniadb_databases); if ((retval = uCreateDir (strbuf)) != ERR_NO_ERROR) { return retval; } /* if databases.txt file doesn't exist, create 0 byte file. */ - sprintf (strbuf, "%s/%s", sco.szCubrid_databases, CUBRID_DATABASE_TXT); + sprintf (strbuf, "%s/%s", sco.szArniadb_databases, ARNIADB_DATABASE_TXT); if (access (strbuf, F_OK) < 0) { if ((fd = fopen (strbuf, "a")) == NULL) @@ -2280,7 +2280,7 @@ uGenerateStatus (nvplist *req, nvplist *res, int retval, sprintf (strbuf, "Invalid request format"); break; case ERR_DATABASETXT_OPEN: - sprintf (strbuf, "'%s' open error", CUBRID_DATABASE_TXT); + sprintf (strbuf, "'%s' open error", ARNIADB_DATABASE_TXT); break; case ERR_USER_CAPABILITY: sprintf (strbuf, "Failed to get user profile for '%s'", _dbmt_error); @@ -2317,7 +2317,7 @@ uGenerateStatus (nvplist *req, nvplist *res, int retval, sprintf (strbuf, "Database(%s) does not exist", _dbmt_error); break; case ERR_DBMTUSER_EXIST: - sprintf (strbuf, "CUBRID Manager user(%s) already exist", _dbmt_error); + sprintf (strbuf, "ARNIADB Manager user(%s) already exist", _dbmt_error); break; case ERR_DIROPENFAIL: sprintf (strbuf, "Failed to read directory(%s)", _dbmt_error); @@ -3760,7 +3760,7 @@ ut_get_host_stat (T_CMS_HOST_STAT *stat, char *_dbmt_error) #endif // WINDOWS int -ut_record_cubrid_utility_log_stderr (const char *msg) +ut_record_arniadb_utility_log_stderr (const char *msg) { if (msg == NULL) { @@ -3775,7 +3775,7 @@ ut_record_cubrid_utility_log_stderr (const char *msg) } int -ut_record_cubrid_utility_log_stdout (const char *msg) +ut_record_arniadb_utility_log_stdout (const char *msg) { if (msg == NULL) { diff --git a/server/src/cm_server_util.h b/server/src/cm_server_util.h index 93ffcad..23c1992 100644 --- a/server/src/cm_server_util.h +++ b/server/src/cm_server_util.h @@ -208,8 +208,8 @@ int remove_extra_subdir (const char *dirpath, const char *pattern, int ut_get_filename (char *fullpath, int with_ext, char *ret_filename); int ut_get_host_stat (T_CMS_HOST_STAT *stat, char *_dbmt_error); int ut_get_proc_stat (T_CMS_PROC_STAT *stat, int pid); -int ut_record_cubrid_utility_log_stderr (const char *msg); -int ut_record_cubrid_utility_log_stdout (const char *msg); +int ut_record_arniadb_utility_log_stderr (const char *msg); +int ut_record_arniadb_utility_log_stdout (const char *msg); int run_child_linux (const char *pname, const char *const argv[], int wait_flag, const char *stdin_file, char *stdout_file, char *stderr_file, int *exit_status); diff --git a/server/src/cm_user.cpp b/server/src/cm_user.cpp index ed429c9..47bd8a7 100644 --- a/server/src/cm_user.cpp +++ b/server/src/cm_user.cpp @@ -37,10 +37,10 @@ #include "cm_server_util.h" #include "cm_user.h" -#define CUBRID_PASS_OPEN_TAG "<<<:" -#define CUBRID_PASS_OPEN_TAG_LEN strlen(CUBRID_PASS_OPEN_TAG) -#define CUBRID_PASS_CLOSE_TAG ">>>:" -#define CUBRID_PASS_CLOSE_TAG_LEN strlen(CUBRID_PASS_CLOSE_TAG) +#define ARNIADB_PASS_OPEN_TAG "<<<:" +#define ARNIADB_PASS_OPEN_TAG_LEN strlen(ARNIADB_PASS_OPEN_TAG) +#define ARNIADB_PASS_CLOSE_TAG ">>>:" +#define ARNIADB_PASS_CLOSE_TAG_LEN strlen(ARNIADB_PASS_CLOSE_TAG) T_USER_TOKEN_INFO *user_token_info = NULL; @@ -70,11 +70,11 @@ dbmt_user_read (T_DBMT_USER *dbmt_user, char *_dbmt_error) return ERR_TMPFILE_OPEN_FAIL; } - fp = fopen (conf_get_dbmt_file (FID_DBMT_CUBRID_PASS, strbuf), "r"); + fp = fopen (conf_get_dbmt_file (FID_DBMT_ARNIADB_PASS, strbuf), "r"); if (fp == NULL) { strcpy (_dbmt_error, - conf_get_dbmt_file2 (FID_DBMT_CUBRID_PASS, strbuf)); + conf_get_dbmt_file2 (FID_DBMT_ARNIADB_PASS, strbuf)); retval = ERR_FILE_OPEN_FAIL; goto read_dbmt_user_error; } @@ -83,9 +83,9 @@ dbmt_user_read (T_DBMT_USER *dbmt_user, char *_dbmt_error) while (fgets (strbuf, sizeof (strbuf), fp)) { ut_trim (strbuf); - if (strncmp (strbuf, CUBRID_PASS_OPEN_TAG, CUBRID_PASS_OPEN_TAG_LEN) == 0) + if (strncmp (strbuf, ARNIADB_PASS_OPEN_TAG, ARNIADB_PASS_OPEN_TAG_LEN) == 0) { - snprintf (cur_user, sizeof (cur_user) - 1, "%s", strbuf + CUBRID_PASS_OPEN_TAG_LEN); + snprintf (cur_user, sizeof (cur_user) - 1, "%s", strbuf + ARNIADB_PASS_OPEN_TAG_LEN); if (cur_user[0] == '\0') { continue; @@ -120,11 +120,11 @@ dbmt_user_read (T_DBMT_USER *dbmt_user, char *_dbmt_error) continue; } - if (strncmp (strbuf, CUBRID_PASS_CLOSE_TAG, CUBRID_PASS_CLOSE_TAG_LEN) == 0) + if (strncmp (strbuf, ARNIADB_PASS_CLOSE_TAG, ARNIADB_PASS_CLOSE_TAG_LEN) == 0) { - if (strcmp (strbuf + CUBRID_PASS_CLOSE_TAG_LEN, cur_user) != 0) + if (strcmp (strbuf + ARNIADB_PASS_CLOSE_TAG_LEN, cur_user) != 0) { - strcpy (_dbmt_error, conf_get_dbmt_file2 (FID_DBMT_CUBRID_PASS, + strcpy (_dbmt_error, conf_get_dbmt_file2 (FID_DBMT_ARNIADB_PASS, strbuf)); retval = ERR_FILE_INTEGRITY; goto read_dbmt_user_error; @@ -239,7 +239,7 @@ dbmt_user_read (T_DBMT_USER *dbmt_user, char *_dbmt_error) if (num_dbmt_user < 1) { strcpy (_dbmt_error, - conf_get_dbmt_file2 (FID_DBMT_CUBRID_PASS, strbuf)); + conf_get_dbmt_file2 (FID_DBMT_ARNIADB_PASS, strbuf)); retval = ERR_FILE_INTEGRITY; goto read_dbmt_user_error; } @@ -335,10 +335,10 @@ dbmt_user_write_auth (T_DBMT_USER *dbmt_user, char *_dbmt_error) char strbuf[1024]; int lock_fd; -#if !defined (DO_NOT_USE_CUBRIDENV) - sprintf (tmpfile, "%s/tmp/DBMT_util_pass.%d", sco.szCubrid, (int) getpid ()); +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (tmpfile, "%s/tmp/DBMT_util_pass.%d", sco.szArniadb, (int) getpid ()); #else - sprintf (tmpfile, "%s/DBMT_util_pass.%d", CUBRID_TMPDIR, (int) getpid ()); + sprintf (tmpfile, "%s/DBMT_util_pass.%d", ARNIADB_TMPDIR, (int) getpid ()); #endif fp = fopen (tmpfile, "w"); if (fp == NULL) @@ -352,7 +352,7 @@ dbmt_user_write_auth (T_DBMT_USER *dbmt_user, char *_dbmt_error) continue; } - fprintf (fp, "%s%s\n", CUBRID_PASS_OPEN_TAG, + fprintf (fp, "%s%s\n", ARNIADB_PASS_OPEN_TAG, dbmt_user->user_info[i].user_name); for (j = 0; j < dbmt_user->user_info[i].num_authinfo; j++) { @@ -375,7 +375,7 @@ dbmt_user_write_auth (T_DBMT_USER *dbmt_user, char *_dbmt_error) dbmt_user->user_info[i].dbinfo[j].uid, dbmt_user->user_info[i].dbinfo[j].broker_address); } - fprintf (fp, "%s%s\n", CUBRID_PASS_CLOSE_TAG, + fprintf (fp, "%s%s\n", ARNIADB_PASS_CLOSE_TAG, dbmt_user->user_info[i].user_name); } fclose (fp); @@ -386,7 +386,7 @@ dbmt_user_write_auth (T_DBMT_USER *dbmt_user, char *_dbmt_error) unlink (tmpfile); return ERR_TMPFILE_OPEN_FAIL; } - move_file (tmpfile, conf_get_dbmt_file (FID_DBMT_CUBRID_PASS, strbuf)); + move_file (tmpfile, conf_get_dbmt_file (FID_DBMT_ARNIADB_PASS, strbuf)); uRemoveLockFile (lock_fd); return ERR_NO_ERROR; @@ -456,10 +456,10 @@ dbmt_user_write_pass (T_DBMT_USER *dbmt_user, char *_dbmt_error) FILE *fp; int i, lock_fd; -#if !defined (DO_NOT_USE_CUBRIDENV) - sprintf (tmpfile, "%s/tmp/DBMT_util_pass.%d", sco.szCubrid, (int) getpid ()); +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (tmpfile, "%s/tmp/DBMT_util_pass.%d", sco.szArniadb, (int) getpid ()); #else - sprintf (tmpfile, "%s/DBMT_util_pass.%d", CUBRID_TMPDIR, (int) getpid ()); + sprintf (tmpfile, "%s/DBMT_util_pass.%d", ARNIADB_TMPDIR, (int) getpid ()); #endif fp = fopen (tmpfile, "w"); diff --git a/server/test/cm_mon_data/dump_data.py b/server/test/cm_mon_data/dump_data.py index 025e31e..eef9a4d 100644 --- a/server/test/cm_mon_data/dump_data.py +++ b/server/test/cm_mon_data/dump_data.py @@ -14,7 +14,7 @@ volname = "demodb" # globe -dpath = "/home/liuhj/CUBRID/var/manager/mon_data/" +dpath = "/home/liuhj/ARNIADB/var/manager/mon_data/" def dump_mod_data(filename, pos, size): diff --git a/server/test/hudsonbuild.sh b/server/test/hudsonbuild.sh index 58e0cee..d929171 100644 --- a/server/test/hudsonbuild.sh +++ b/server/test/hudsonbuild.sh @@ -2,33 +2,33 @@ make clean mkdir -p log -cub_js stop -cub_auto stop +arn_js stop +arn_auto stop -valgrind --leak-check=full --log-file=./log/cmserver_auto.valgrind.log cub_auto start -valgrind --leak-check=full --log-file=./log/cmserver_js.valgrind.log cub_js start +valgrind --leak-check=full --log-file=./log/cmserver_auto.valgrind.log arn_auto start +valgrind --leak-check=full --log-file=./log/cmserver_js.valgrind.log arn_js start -cub_cmserver stop +arn_cmserver stop sleep 3 -valgrind --leak-check=full --log-file=./log/cmserver_cmserver.valgrind.log cub_cmserver start +valgrind --leak-check=full --log-file=./log/cmserver_cmserver.valgrind.log arn_cmserver start sed -i -e '/invalid file descriptor .* in syscall close/d' -e '/to select an alternative log fd/d' ./log/cmserver_*.valgrind.log* -cubrid deletedb anotherdb #remove legacy test database -cubrid deletedb alatestdb #remove legacy test database -cubrid deletedb copydb #remove legacy test database -cubrid deletedb destinationdb #remove legacy test database +arniadb deletedb anotherdb #remove legacy test database +arniadb deletedb alatestdb #remove legacy test database +arniadb deletedb copydb #remove legacy test database +arniadb deletedb destinationdb #remove legacy test database make test -cub_js stop #must stop before 'make lcov' -cub_auto stop #must stop before 'make lcov' +arn_js stop #must stop before 'make lcov' +arn_auto stop #must stop before 'make lcov' sleep 5 make lcov -cubrid deletedb anotherdb #remove legacy test database -cubrid deletedb copydb #remove legacy test database -cubrid deletedb destinationdb #remove legacy test database -cubrid deletedb alatestdb #remove legacy test database +arniadb deletedb anotherdb #remove legacy test database +arniadb deletedb copydb #remove legacy test database +arniadb deletedb destinationdb #remove legacy test database +arniadb deletedb alatestdb #remove legacy test database diff --git a/server/test/task_list.txt b/server/test/task_list.txt index 063782f..b4f3f7a 100644 --- a/server/test/task_list.txt +++ b/server/test/task_list.txt @@ -141,7 +141,7 @@ getdbmode // tasks set conf files setsysparam_cmconf -//setsysparam_cubridconf +//setsysparam_arniadbconf //broker_setparam getdiagdata killprocess diff --git a/server/test/task_test_case/addbackupinfo b/server/test/task_test_case/addbackupinfo index fd24534..d220c60 100644 --- a/server/test/task_test_case/addbackupinfo +++ b/server/test/task_test_case/addbackupinfo @@ -2,7 +2,7 @@ task:addbackupinfo token:cdfb4c5717170c5e51196b3bf16112949ea2e1dcf05030c13351f8d4306356bf7926f07dd201b6aa dbname:alatestdb backupid:qw -path:$CUBRID_DATABASES/alatestdb/backup +path:$ARNIADB_DATABASES/alatestdb/backup period_type:Special period_date:$AUTO_DATE time:$AUTO_TIME diff --git a/server/test/task_test_case/addvoldb_nullpurpose b/server/test/task_test_case/addvoldb_nullpurpose index 18bbe83..feac6cf 100644 --- a/server/test/task_test_case/addvoldb_nullpurpose +++ b/server/test/task_test_case/addvoldb_nullpurpose @@ -2,7 +2,7 @@ task:addvoldb token:cdfb4c5717170c5e51196b3bf16112949ea2e1dcf05030c13351f8d4306356bf7926f07dd201b6aa dbname:alatestdb volname: -path:$CUBRID_DATABASES/alatestdb +path:$ARNIADB_DATABASES/alatestdb numberofpages:100 size_need_mb:0.391(MB) diff --git a/server/test/task_test_case/addvoldb_nullsize b/server/test/task_test_case/addvoldb_nullsize index da720ed..2be80c9 100644 --- a/server/test/task_test_case/addvoldb_nullsize +++ b/server/test/task_test_case/addvoldb_nullsize @@ -3,7 +3,7 @@ token:cdfb4c5717170c5e51196b3bf16112949ea2e1dcf05030c13351f8d4306356bf7926f07dd2 dbname:alatestdb volname: purpose:generic -path:$CUBRID_DATABASES/alatestdb +path:$ARNIADB_DATABASES/alatestdb numberofpages:100 diff --git a/server/test/task_test_case/analyzecaslog b/server/test/task_test_case/analyzecaslog index c996e8f..e5c941c 100644 --- a/server/test/task_test_case/analyzecaslog +++ b/server/test/task_test_case/analyzecaslog @@ -1,7 +1,7 @@ task:analyzecaslog token:cdfb4c5717170c5e9c6856b4d1c61ee8132bcc7d82bd609066ed9ece2554c47f7926f07dd201b6aa open:logfilelist -logfile:$CUBRID/log/broker/sql_log/query_editor_1.sql.log +logfile:$ARNIADB/log/broker/sql_log/query_editor_1.sql.log close:logfilelist option_t:yes diff --git a/server/test/task_test_case/analyzecaslog_option_no b/server/test/task_test_case/analyzecaslog_option_no index 2f461db..0708589 100644 --- a/server/test/task_test_case/analyzecaslog_option_no +++ b/server/test/task_test_case/analyzecaslog_option_no @@ -1,7 +1,7 @@ task:analyzecaslog token:cdfb4c5717170c5e9c6856b4d1c61ee8132bcc7d82bd609066ed9ece2554c47f7926f07dd201b6aa open:logfilelist -logfile:$CUBRID/log/broker/sql_log/query_editor_1.sql.log +logfile:$ARNIADB/log/broker/sql_log/query_editor_1.sql.log close:logfilelist option_t:no diff --git a/server/test/task_test_case/applylogdb b/server/test/task_test_case/applylogdb index 3a64927..46a8354 100644 --- a/server/test/task_test_case/applylogdb +++ b/server/test/task_test_case/applylogdb @@ -2,5 +2,5 @@ task:applylogdb token:cdfb4c5717170c5ebd99d3152b799ba8c8960905fd00c5b4d503c6215bcffe1d7926f07dd201b6aa dbname:demodb la_max_mem_size:200 -logpath:$CUBRID_DATABASES/applylogdb +logpath:$ARNIADB_DATABASES/applylogdb diff --git a/server/test/task_test_case/backupdb b/server/test/task_test_case/backupdb index 6aca328..2a13784 100644 --- a/server/test/task_test_case/backupdb +++ b/server/test/task_test_case/backupdb @@ -3,7 +3,7 @@ token:cdfb4c5717170c5e237a227a2ceeccc6ae9e10c16754fb85371c0d74fa0d9d577926f07dd2 dbname:alatestdb level:0 volname:alatestdb_backup_lv0 -backupdir:$CUBRID_DATABASES/alatestdb/backup +backupdir:$ARNIADB_DATABASES/alatestdb/backup removelog:n check:y mt:0 diff --git a/server/test/task_test_case/backupdb_nullname b/server/test/task_test_case/backupdb_nullname index 71338b1..e5f5800 100644 --- a/server/test/task_test_case/backupdb_nullname +++ b/server/test/task_test_case/backupdb_nullname @@ -2,7 +2,7 @@ task:backupdb token:cdfb4c5717170c5e237a227a2ceeccc6ae9e10c16754fb85371c0d74fa0d9d577926f07dd201b6aa level:0 volname:alatestdb_backup_lv0 -backupdir:$CUBRID_DATABASES/alatestdb/backup +backupdir:$ARNIADB_DATABASES/alatestdb/backup removelog:n check:y mt:0 diff --git a/server/test/task_test_case/backupdb_rep b/server/test/task_test_case/backupdb_rep index 1589590..171fa15 100644 --- a/server/test/task_test_case/backupdb_rep +++ b/server/test/task_test_case/backupdb_rep @@ -3,7 +3,7 @@ token:cdfb4c5717170c5e237a227a2ceeccc6ae9e10c16754fb85371c0d74fa0d9d577926f07dd2 dbname:alatestdb level:0 volname:alatestdb_backup_lv0 -backupdir:$CUBRID_DATABASES/alatestdb/backup +backupdir:$ARNIADB_DATABASES/alatestdb/backup removelog:n check:y mt:0 diff --git a/server/test/task_test_case/backupvolinfo b/server/test/task_test_case/backupvolinfo index 5da5998..890d504 100644 --- a/server/test/task_test_case/backupvolinfo +++ b/server/test/task_test_case/backupvolinfo @@ -2,7 +2,7 @@ task:backupvolinfo token:cdfb4c5717170c5e9c6856b4d1c61ee8132bcc7d82bd609066ed9ece2554c47f7926f07dd201b6aa dbname:alatestdb level:0 -pathname:$CUBRID_DATABASES/alatestdb/backup/alatestdb_backup_lv0 +pathname:$ARNIADB_DATABASES/alatestdb/backup/alatestdb_backup_lv0 diff --git a/server/test/task_test_case/broker_setparam b/server/test/task_test_case/broker_setparam index 4878d8c..e13ce33 100644 --- a/server/test/task_test_case/broker_setparam +++ b/server/test/task_test_case/broker_setparam @@ -20,7 +20,7 @@ confdata: confdata:# confdata:[broker] confdata:MASTER_SHM_ID=30001 -confdata:ADMIN_LOG_FILE=log/broker/cubrid_broker.log +confdata:ADMIN_LOG_FILE=log/broker/arniadb_broker.log confdata: confdata: confdata:[%broker1] diff --git a/server/test/task_test_case/checkdir b/server/test/task_test_case/checkdir index 09c8cd1..0fa76b1 100644 --- a/server/test/task_test_case/checkdir +++ b/server/test/task_test_case/checkdir @@ -1,4 +1,4 @@ task:checkdir token:cdfb4c5717170c5e237a227a2ceeccc6ae9e10c16754fb85371c0d74fa0d9d577926f07dd201b6aa -dir:$CUBRID_DATABASES +dir:$ARNIADB_DATABASES diff --git a/server/test/task_test_case/checkfile b/server/test/task_test_case/checkfile index 7b385a2..9437d0e 100644 --- a/server/test/task_test_case/checkfile +++ b/server/test/task_test_case/checkfile @@ -1,4 +1,4 @@ task:checkfile token:cdfb4c5717170c5e237a227a2ceeccc6ae9e10c16754fb85371c0d74fa0d9d577926f07dd201b6aa -file:$CUBRID/log/manager/cub_auto.access.log +file:$ARNIADB/log/manager/arn_auto.access.log diff --git a/server/test/task_test_case/class b/server/test/task_test_case/class index 7e0fa6d..22b3d97 100644 --- a/server/test/task_test_case/class +++ b/server/test/task_test_case/class @@ -4,7 +4,7 @@ dbname:demodb classname:athlete _STAMP:32 _SVRTYPE:fsvr -_PROGNAME:cub_js +_PROGNAME:arn_js _CLIENTIP:127.0.0.1 _CLIENTPORT:60375 _ID:admin diff --git a/server/test/task_test_case/classinfo b/server/test/task_test_case/classinfo index 8ce7abf..4c5d8f2 100644 --- a/server/test/task_test_case/classinfo +++ b/server/test/task_test_case/classinfo @@ -4,7 +4,7 @@ dbname:demodb dbstatus:on _STAMP:22 _SVRTYPE:fsvr -_PROGNAME:cub_js +_PROGNAME:arn_js _CLIENTIP:127.0.0.1 _CLIENTPORT:58839 _ID:admin diff --git a/server/test/task_test_case/copydb b/server/test/task_test_case/copydb index f1d6506..666b432 100644 --- a/server/test/task_test_case/copydb +++ b/server/test/task_test_case/copydb @@ -2,9 +2,9 @@ task:copydb token:cdfb4c5717170c5edfc2912f2940ab35013dd1336cf7d77e4cfaae281cffa1417926f07dd201b6aa srcdbname:alatestdb destdbname:destinationdb -destdbpath:$CUBRID_DATABASES/destinationdb -exvolpath:$CUBRID_DATABASES/destinationdb -logpath:$CUBRID_DATABASES/destinationdb +destdbpath:$ARNIADB_DATABASES/destinationdb +exvolpath:$ARNIADB_DATABASES/destinationdb +logpath:$ARNIADB_DATABASES/destinationdb overwrite:y move:n advanced:off diff --git a/server/test/task_test_case/copydb_advance b/server/test/task_test_case/copydb_advance index c655e45..064a40a 100644 --- a/server/test/task_test_case/copydb_advance +++ b/server/test/task_test_case/copydb_advance @@ -2,13 +2,13 @@ task:copydb token:cdfb4c5717170c5edfc2912f2940ab35013dd1336cf7d77e4cfaae281cffa1417926f07dd201b6aa srcdbname:copydb destdbname:destinationdb1 -destdbpath:$CUBRID_DATABASES/destinationdb1 -exvolpath:$CUBRID_DATABASES/destinationdb1 -logpath:$CUBRID_DATABASES/destinationdb1 +destdbpath:$ARNIADB_DATABASES/destinationdb1 +exvolpath:$ARNIADB_DATABASES/destinationdb1 +logpath:$ARNIADB_DATABASES/destinationdb1 overwrite:y move:y advanced:on open:volume -$CUBRID_DATABASES/copydb/copydb:$CUBRID_DATABASES/destinationdb1/destinationdb1 +$ARNIADB_DATABASES/copydb/copydb:$ARNIADB_DATABASES/destinationdb1/destinationdb1 close:volume diff --git a/server/test/task_test_case/copydb_nulldest b/server/test/task_test_case/copydb_nulldest index 514e913..8f7584c 100644 --- a/server/test/task_test_case/copydb_nulldest +++ b/server/test/task_test_case/copydb_nulldest @@ -1,9 +1,9 @@ task:copydb token:cdfb4c5717170c5edfc2912f2940ab35013dd1336cf7d77e4cfaae281cffa1417926f07dd201b6aa srcdbname:alatestdb -destdbpath:$CUBRID_DATABASES/destinationdb -exvolpath:$CUBRID_DATABASES/destinationdb -logpath:$CUBRID_DATABASES/destinationdb +destdbpath:$ARNIADB_DATABASES/destinationdb +exvolpath:$ARNIADB_DATABASES/destinationdb +logpath:$ARNIADB_DATABASES/destinationdb overwrite:y move:n advanced:off diff --git a/server/test/task_test_case/copydb_nulldestpath b/server/test/task_test_case/copydb_nulldestpath index cde8d71..55f028a 100644 --- a/server/test/task_test_case/copydb_nulldestpath +++ b/server/test/task_test_case/copydb_nulldestpath @@ -2,8 +2,8 @@ task:copydb token:cdfb4c5717170c5edfc2912f2940ab35013dd1336cf7d77e4cfaae281cffa1417926f07dd201b6aa srcdbname:alatestdb destdbname:destinationdb -exvolpath:$CUBRID_DATABASES/destinationdb -logpath:$CUBRID_DATABASES/destinationdb +exvolpath:$ARNIADB_DATABASES/destinationdb +logpath:$ARNIADB_DATABASES/destinationdb overwrite:y move:n advanced:off diff --git a/server/test/task_test_case/copydb_nullexvolpath b/server/test/task_test_case/copydb_nullexvolpath index 73134d7..6b58d00 100644 --- a/server/test/task_test_case/copydb_nullexvolpath +++ b/server/test/task_test_case/copydb_nullexvolpath @@ -2,8 +2,8 @@ task:copydb token:cdfb4c5717170c5edfc2912f2940ab35013dd1336cf7d77e4cfaae281cffa1417926f07dd201b6aa srcdbname:alatestdb destdbname:destinationdb -destdbpath:$CUBRID_DATABASES/destinationdb -logpath:$CUBRID_DATABASES/destinationdb +destdbpath:$ARNIADB_DATABASES/destinationdb +logpath:$ARNIADB_DATABASES/destinationdb overwrite:y move:n advanced:off diff --git a/server/test/task_test_case/copydb_nulllogpath b/server/test/task_test_case/copydb_nulllogpath index 8a4b526..ece9439 100644 --- a/server/test/task_test_case/copydb_nulllogpath +++ b/server/test/task_test_case/copydb_nulllogpath @@ -2,8 +2,8 @@ task:copydb token:cdfb4c5717170c5edfc2912f2940ab35013dd1336cf7d77e4cfaae281cffa1417926f07dd201b6aa srcdbname:alatestdb destdbname:destinationdb -destdbpath:$CUBRID_DATABASES/destinationdb -exvolpath:$CUBRID_DATABASES/destinationdb +destdbpath:$ARNIADB_DATABASES/destinationdb +exvolpath:$ARNIADB_DATABASES/destinationdb overwrite:y move:n advanced:off diff --git a/server/test/task_test_case/copydb_nullop b/server/test/task_test_case/copydb_nullop index da8e369..4f9c2d1 100644 --- a/server/test/task_test_case/copydb_nullop +++ b/server/test/task_test_case/copydb_nullop @@ -2,9 +2,9 @@ task:copydb token:cdfb4c5717170c5edfc2912f2940ab35013dd1336cf7d77e4cfaae281cffa1417926f07dd201b6aa srcdbname:copydb destdbname:destinationdb1 -destdbpath:$CUBRID_DATABASES/destinationdb1 -exvolpath:$CUBRID_DATABASES/destinationdb1 -logpath:$CUBRID_DATABASES/destinationdb1 +destdbpath:$ARNIADB_DATABASES/destinationdb1 +exvolpath:$ARNIADB_DATABASES/destinationdb1 +logpath:$ARNIADB_DATABASES/destinationdb1 overwrite:y move:y advanced:on diff --git a/server/test/task_test_case/copydb_nullsrc b/server/test/task_test_case/copydb_nullsrc index 2941e4e..e06e671 100644 --- a/server/test/task_test_case/copydb_nullsrc +++ b/server/test/task_test_case/copydb_nullsrc @@ -1,9 +1,9 @@ task:copydb token:cdfb4c5717170c5edfc2912f2940ab35013dd1336cf7d77e4cfaae281cffa1417926f07dd201b6aa destdbname:destinationdb -destdbpath:$CUBRID_DATABASES/destinationdb -exvolpath:$CUBRID_DATABASES/destinationdb -logpath:$CUBRID_DATABASES/destinationdb +destdbpath:$ARNIADB_DATABASES/destinationdb +exvolpath:$ARNIADB_DATABASES/destinationdb +logpath:$ARNIADB_DATABASES/destinationdb overwrite:y move:n advanced:off diff --git a/server/test/task_test_case/copylogdb b/server/test/task_test_case/copylogdb index d28b33a..9b62ced 100644 --- a/server/test/task_test_case/copylogdb +++ b/server/test/task_test_case/copylogdb @@ -2,6 +2,6 @@ task:copylogdb token:cdfb4c5717170c5ed4a061e37572161dc895920ae8799faa38ebb2358d27b4717926f07dd201b6aa dbname:demodb mode:sync -logpath:$CUBRID_DATABASES/copylogdb +logpath:$ARNIADB_DATABASES/copylogdb hostname:localhost diff --git a/server/test/task_test_case/createdb b/server/test/task_test_case/createdb index 8330b97..0fbe4ba 100644 --- a/server/test/task_test_case/createdb +++ b/server/test/task_test_case/createdb @@ -5,10 +5,10 @@ numpage:10240 pagesize:4096 logsize:10240 logpagesize:4096 -genvolpath:$CUBRID_DATABASES/alatestdb -logvolpath:$CUBRID_DATABASES/alatestdb +genvolpath:$ARNIADB_DATABASES/alatestdb +logvolpath:$ARNIADB_DATABASES/alatestdb open:exvol -alatestdb_data_x001:data;100;$CUBRID_DATABASES/alatestdb +alatestdb_data_x001:data;100;$ARNIADB_DATABASES/alatestdb close:exvol overwrite_config_file:YES diff --git a/server/test/task_test_case/createdb_accesslog b/server/test/task_test_case/createdb_accesslog index 2e03780..676a53f 100644 --- a/server/test/task_test_case/createdb_accesslog +++ b/server/test/task_test_case/createdb_accesslog @@ -8,7 +8,7 @@ logpagesize:4096 genvolpath:errpath logvolpath:/root open:exvol -alatestdb_data_x001:data;100;$CUBRID_DATABASES/alatestdb +alatestdb_data_x001:data;100;$ARNIADB_DATABASES/alatestdb close:exvol overwrite_config_file:YES diff --git a/server/test/task_test_case/createdb_errlogpath b/server/test/task_test_case/createdb_errlogpath index 0f894f0..fb99daf 100644 --- a/server/test/task_test_case/createdb_errlogpath +++ b/server/test/task_test_case/createdb_errlogpath @@ -8,7 +8,7 @@ logpagesize:4096 genvolpath:errpath logvolpath: open:exvol -alatestdb_data_x001:data;100;$CUBRID_DATABASES/alatestdb +alatestdb_data_x001:data;100;$ARNIADB_DATABASES/alatestdb close:exvol overwrite_config_file:YES diff --git a/server/test/task_test_case/createdb_errlogpath1 b/server/test/task_test_case/createdb_errlogpath1 index d6890a8..620612c 100644 --- a/server/test/task_test_case/createdb_errlogpath1 +++ b/server/test/task_test_case/createdb_errlogpath1 @@ -8,7 +8,7 @@ logpagesize:4096 genvolpath:errpath logvolpath:errpath open:exvol -alatestdb_data_x001:data;100;$CUBRID_DATABASES/alatestdb +alatestdb_data_x001:data;100;$ARNIADB_DATABASES/alatestdb close:exvol overwrite_config_file:YES diff --git a/server/test/task_test_case/createdb_errvolpath b/server/test/task_test_case/createdb_errvolpath index d366aa4..75fdc51 100644 --- a/server/test/task_test_case/createdb_errvolpath +++ b/server/test/task_test_case/createdb_errvolpath @@ -6,9 +6,9 @@ pagesize:4096 logsize:10240 logpagesize:4096 genvolpath:errpath -logvolpath:$CUBRID_DATABASES/alatestdb +logvolpath:$ARNIADB_DATABASES/alatestdb open:exvol -alatestdb_data_x001:data;100;$CUBRID_DATABASES/alatestdb +alatestdb_data_x001:data;100;$ARNIADB_DATABASES/alatestdb close:exvol overwrite_config_file:YES diff --git a/server/test/task_test_case/createdb_fail_with_dup_name b/server/test/task_test_case/createdb_fail_with_dup_name index 726b223..71d39e0 100644 --- a/server/test/task_test_case/createdb_fail_with_dup_name +++ b/server/test/task_test_case/createdb_fail_with_dup_name @@ -4,8 +4,8 @@ dbname:alatestdb numpage:10240 pagesize:4096 logsize:10240 -genvolpath:$CUBRID_DATABASES/alatestdb -logvolpath:$CUBRID_DATABASES/alatestdb +genvolpath:$ARNIADB_DATABASES/alatestdb +logvolpath:$ARNIADB_DATABASES/alatestdb open:exvol close:exvol overwrite_config_file:YES diff --git a/server/test/task_test_case/createdb_for_copydb b/server/test/task_test_case/createdb_for_copydb index 27de783..5914063 100644 --- a/server/test/task_test_case/createdb_for_copydb +++ b/server/test/task_test_case/createdb_for_copydb @@ -5,8 +5,8 @@ numpage:10240 pagesize:4096 logpagesize:4096 logsize:10240 -genvolpath:$CUBRID_DATABASES/copydb -logvolpath:$CUBRID_DATABASES/copydb +genvolpath:$ARNIADB_DATABASES/copydb +logvolpath:$ARNIADB_DATABASES/copydb open:exvol close:exvol overwrite_config_file:YES diff --git a/server/test/task_test_case/createuser b/server/test/task_test_case/createuser index 5f56acd..2831361 100644 --- a/server/test/task_test_case/createuser +++ b/server/test/task_test_case/createuser @@ -10,7 +10,7 @@ open:authorization close:authorization _STAMP:30 _SVRTYPE:fsvr -_PROGNAME:cub_js +_PROGNAME:arn_js _CLIENTIP:127.0.0.1 _CLIENTPORT:59863 _ID:admin diff --git a/server/test/task_test_case/dbmtuserlogin b/server/test/task_test_case/dbmtuserlogin index 043ec73..441426c 100644 --- a/server/test/task_test_case/dbmtuserlogin +++ b/server/test/task_test_case/dbmtuserlogin @@ -6,7 +6,7 @@ dbuser:dba dbpasswd: _STAMP:34 _SVRTYPE:fsvr -_PROGNAME:cub_js +_PROGNAME:arn_js _CLIENTIP:127.0.0.1 _CLIENTPORT:60887 _ID:admin diff --git a/server/test/task_test_case/deleteuser b/server/test/task_test_case/deleteuser index ec42bea..648db4c 100644 --- a/server/test/task_test_case/deleteuser +++ b/server/test/task_test_case/deleteuser @@ -4,7 +4,7 @@ dbname:demodb username:yifan _STAMP:31 _SVRTYPE:fsvr -_PROGNAME:cub_js +_PROGNAME:arn_js _CLIENTIP:127.0.0.1 _CLIENTPORT:60119 _ID:admin diff --git a/server/test/task_test_case/getcaslogtopresult b/server/test/task_test_case/getcaslogtopresult index ced4561..17df273 100644 --- a/server/test/task_test_case/getcaslogtopresult +++ b/server/test/task_test_case/getcaslogtopresult @@ -1,6 +1,6 @@ task:getcaslogtopresult token:cdfb4c5717170c5e9c6856b4d1c61ee8132bcc7d82bd609066ed9ece2554c47f7926f07dd201b6aa -filename:$CUBRID/tmp/analyzelog_1.res +filename:$ARNIADB/tmp/analyzelog_1.res qindex:[Q14] diff --git a/server/test/task_test_case/gettriggerinfo b/server/test/task_test_case/gettriggerinfo index b25e41d..f75d0ca 100644 --- a/server/test/task_test_case/gettriggerinfo +++ b/server/test/task_test_case/gettriggerinfo @@ -3,7 +3,7 @@ token:cdfb4c5717170c5ed30ef86644baf8151531ce5adff4a1f9a54711c51e0f50767926f07dd2 dbname:demodb _STAMP:23 _SVRTYPE:fsvr -_PROGNAME:cub_js +_PROGNAME:arn_js _CLIENTIP:127.0.0.1 _CLIENTPORT:59095 _ID:admin diff --git a/server/test/task_test_case/loaddb b/server/test/task_test_case/loaddb index ef79f3d..5599978 100644 --- a/server/test/task_test_case/loaddb +++ b/server/test/task_test_case/loaddb @@ -7,8 +7,8 @@ user:dba estimated:none oiduse:yes nolog:no -schema:$CUBRID_DATABASES/demodb/demodb_schema -object:$CUBRID_DATABASES/demodb/demodb_objects +schema:$ARNIADB_DATABASES/demodb/demodb_schema +object:$ARNIADB_DATABASES/demodb/demodb_objects index:none errorcontrolfile:none ignoreclassfile:none diff --git a/server/test/task_test_case/optimizedb b/server/test/task_test_case/optimizedb index 83ecef9..715f717 100644 --- a/server/test/task_test_case/optimizedb +++ b/server/test/task_test_case/optimizedb @@ -4,7 +4,7 @@ dbname:alatestdb classname: _STAMP:21 _SVRTYPE:fsvr -_PROGNAME:cub_js +_PROGNAME:arn_js _CLIENTIP:192.168.0.1 _CLIENTPORT:2575 _ID:admin diff --git a/server/test/task_test_case/removecasrunnertmpfile b/server/test/task_test_case/removecasrunnertmpfile index 9780a41..c32e405 100644 --- a/server/test/task_test_case/removecasrunnertmpfile +++ b/server/test/task_test_case/removecasrunnertmpfile @@ -1,6 +1,6 @@ task:removecasrunnertmpfile token:cdfb4c5717170c5e9c6856b4d1c61ee8132bcc7d82bd609066ed9ece2554c47f7926f07dd201b6aa -filename:$CUBRID/tmp/log_run_1.res.0 +filename:$ARNIADB/tmp/log_run_1.res.0 diff --git a/server/test/task_test_case/removefiles b/server/test/task_test_case/removefiles index b736c72..0904127 100644 --- a/server/test/task_test_case/removefiles +++ b/server/test/task_test_case/removefiles @@ -1,3 +1,3 @@ task:removefiles token:cdfb4c5717170c5e9c6856b4d1c61ee8132bcc7d82bd609066ed9ece2554c47f7926f07dd201b6aa -files:$CUBRID/tmp/test.err +files:$ARNIADB/tmp/test.err diff --git a/server/test/task_test_case/removelog b/server/test/task_test_case/removelog index 9417f97..fd8b5e4 100644 --- a/server/test/task_test_case/removelog +++ b/server/test/task_test_case/removelog @@ -1,7 +1,7 @@ task:removelog token:cdfb4c5717170c5e9c6856b4d1c61ee8132bcc7d82bd609066ed9ece2554c47f7926f07dd201b6aa open:files -path:$CUBRID/log/manager/cub_js.access.log +path:$ARNIADB/log/manager/arn_js.access.log close:files diff --git a/server/test/task_test_case/renamedb b/server/test/task_test_case/renamedb index 6343ce4..10f4b3d 100644 --- a/server/test/task_test_case/renamedb +++ b/server/test/task_test_case/renamedb @@ -5,7 +5,7 @@ rename:anotherdb exvolpath:none advanced:on open:volume -$CUBRID_DATABASES/destinationdb/destinationdb:$CUBRID_DATABASES/anotherdb/anotherdb +$ARNIADB_DATABASES/destinationdb/destinationdb:$ARNIADB_DATABASES/anotherdb/anotherdb close:volume forcedel:y diff --git a/server/test/task_test_case/renamedb_adoff b/server/test/task_test_case/renamedb_adoff index fc9d4b8..2227bb4 100644 --- a/server/test/task_test_case/renamedb_adoff +++ b/server/test/task_test_case/renamedb_adoff @@ -5,7 +5,7 @@ rename:anotherdb exvolpath:/root/testpass advanced:off open:volume -$CUBRID_DATABASES/destinationdb/destinationdb:$CUBRID_DATABASES/anotherdb/anotherdb +$ARNIADB_DATABASES/destinationdb/destinationdb:$ARNIADB_DATABASES/anotherdb/anotherdb close:volume forcedel:y diff --git a/server/test/task_test_case/renamedb_nullrename b/server/test/task_test_case/renamedb_nullrename index 573a631..f3ad5a6 100644 --- a/server/test/task_test_case/renamedb_nullrename +++ b/server/test/task_test_case/renamedb_nullrename @@ -4,7 +4,7 @@ dbname:destinationdb exvolpath:none advanced:on open:volume -$CUBRID_DATABASES/destinationdb/destinationdb:$CUBRID_DATABASES/anotherdb/anotherdb +$ARNIADB_DATABASES/destinationdb/destinationdb:$ARNIADB_DATABASES/anotherdb/anotherdb close:volume forcedel:y diff --git a/server/test/task_test_case/resetlog b/server/test/task_test_case/resetlog index 0af68b5..cc35be1 100644 --- a/server/test/task_test_case/resetlog +++ b/server/test/task_test_case/resetlog @@ -1,6 +1,6 @@ task:resetlog token:cdfb4c5717170c5e9c6856b4d1c61ee8132bcc7d82bd609066ed9ece2554c47f7926f07dd201b6aa -path:$CUBRID/log/broker/cubrid_broker.log +path:$ARNIADB/log/broker/arniadb_broker.log diff --git a/server/test/task_test_case/restoredb b/server/test/task_test_case/restoredb index 09ea70a..3f5cff9 100644 --- a/server/test/task_test_case/restoredb +++ b/server/test/task_test_case/restoredb @@ -4,6 +4,6 @@ dbname:alatestdb date:none level:0 partial:y -pathname:$CUBRID_DATABASES/alatestdb/backup/alatestdb_backup_lv0 -recoverypath:$CUBRID_DATABASES/alatestdb +pathname:$ARNIADB_DATABASES/alatestdb/backup/alatestdb_backup_lv0 +recoverypath:$ARNIADB_DATABASES/alatestdb diff --git a/server/test/task_test_case/setbackupinfo b/server/test/task_test_case/setbackupinfo index 65894f4..2eeea0f 100644 --- a/server/test/task_test_case/setbackupinfo +++ b/server/test/task_test_case/setbackupinfo @@ -2,7 +2,7 @@ task:setbackupinfo token:cdfb4c5717170c5e9c6856b4d1c61ee8132bcc7d82bd609066ed9ece2554c47f7926f07dd201b6aa dbname:alatestdb backupid:qw -path:$CUBRID_DATABASES/alatestdb/backup +path:$ARNIADB_DATABASES/alatestdb/backup period_type:Special period_date:$AUTO_DATE time:$AUTO_TIME diff --git a/server/test/task_test_case/setsysparam b/server/test/task_test_case/setsysparam index f83c2c5..beda303 100644 --- a/server/test/task_test_case/setsysparam +++ b/server/test/task_test_case/setsysparam @@ -1,6 +1,6 @@ task:setsysparam token:cdfb4c5717170c5e9c6856b4d1c61ee8132bcc7d82bd609066ed9ece2554c47f7926f07dd201b6aa -confname:cubridconf +confname:arniadbconf confdata: confdata:# confdata:# Copyright (C) 2009 Search Solution Corporation. All rights reserved by Search Solution. @@ -21,19 +21,19 @@ confdata: confdata:# confdata:# $Id$ confdata:# -confdata:# cubrid.conf +confdata:# arniadb.conf confdata:# -confdata:# For complete information on parameters, see the CUBRID +confdata:# For complete information on parameters, see the ARNIADB confdata:# Database Administration Guide chapter on System Parameters confdata: -confdata:# Service section - a section for 'cubrid service' command +confdata:# Service section - a section for 'arniadb service' command confdata:[service] confdata: -confdata:# The list of processes to be started automatically by 'cubrid service start' command +confdata:# The list of processes to be started automatically by 'arniadb service start' command confdata:# Any combinations are available with server, broker and manager. confdata:service=server,broker,manager confdata: -confdata:# The list of database servers in all by 'cubrid service start' command. +confdata:# The list of database servers in all by 'arniadb service start' command. confdata:# This property is effective only when the above 'service' property contains 'server' keyword. confdata:server=demodb confdata: @@ -84,8 +84,8 @@ confdata:# For other aliases, or for more information on the levels, see the confdata:# System Parameters chapter in the Database Administration Guide. confdata:isolation_level="TRAN_REP_CLASS_UNCOMMIT_INSTANCE" confdata: -confdata:# TCP port id for the CUBRID programs (used by all clients). -confdata:cubrid_port_id=1527 +confdata:# TCP port id for the ARNIADB programs (used by all clients). +confdata:arniadb_port_id=1527 confdata: confdata:# The maximum number of concurrent client connections the server will accept. confdata:# This value also means the total # of concurrent transactions. diff --git a/server/test/task_test_case/setsysparam_cubridconf b/server/test/task_test_case/setsysparam_arniadbconf similarity index 87% rename from server/test/task_test_case/setsysparam_cubridconf rename to server/test/task_test_case/setsysparam_arniadbconf index 732f49c..4ef790c 100644 --- a/server/test/task_test_case/setsysparam_cubridconf +++ b/server/test/task_test_case/setsysparam_arniadbconf @@ -1,6 +1,6 @@ task:setsysparam token:cdfb4c5717170c5e9c6856b4d1c61ee8132bcc7d82bd609066ed9ece2554c47f7926f07dd201b6aa -confname:cubridconf +confname:arniadbconf confdata: confdata:# confdata:# Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. @@ -19,19 +19,19 @@ confdata:# along with this program; if not, write to the Free Software confdata:# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA confdata:# confdata: -confdata:# For complete information on parameters, see the CUBRID +confdata:# For complete information on parameters, see the ARNIADB confdata:# Database Administration Guide chapter on System Parameters confdata: -confdata:# cubrid.conf +confdata:# arniadb.conf confdata: -confdata:# Service section - a section for 'cubrid service' command +confdata:# Service section - a section for 'arniadb service' command confdata:[service] confdata: -confdata:# The list of processes to be started automatically by 'cubrid service start' command +confdata:# The list of processes to be started automatically by 'arniadb service start' command confdata:# Any combinations are available with server, broker, manager and heartbeat. confdata:service=server,broker,manager confdata: -confdata:# The list of database servers in all by 'cubrid service start' command. +confdata:# The list of database servers in all by 'arniadb service start' command. confdata:# This property is effective only when the above 'service' property contains 'server' keyword. confdata:#server=foo,bar confdata: @@ -57,8 +57,8 @@ confdata:# The maximum number of concurrent client connections the server will a confdata:# This value also means the total # of concurrent transactions. confdata:max_clients=100 -# TCP port id for the CUBRID programs (used by all clients). -cubrid_port_id=1523 +# TCP port id for the ARNIADB programs (used by all clients). +arniadb_port_id=1523 # The createdb and addvoldb create a volume file of 'db_volume_size' size # if don't have any options about size. diff --git a/server/test/task_test_case/unloaddb b/server/test/task_test_case/unloaddb index 17dcfa5..f51525a 100644 --- a/server/test/task_test_case/unloaddb +++ b/server/test/task_test_case/unloaddb @@ -1,7 +1,7 @@ task:unloaddb token:cdfb4c5717170c5e34919b640249979f8375a218acf865b0b8100f0f25c069587926f07dd201b6aa dbname:demodb -targetdir:$CUBRID_DATABASES/demodb +targetdir:$ARNIADB_DATABASES/demodb usehash:no hashdir:none target:both diff --git a/server/test/task_test_case/unloaddb_advance b/server/test/task_test_case/unloaddb_advance index 4eaa654..eb5c289 100644 --- a/server/test/task_test_case/unloaddb_advance +++ b/server/test/task_test_case/unloaddb_advance @@ -1,7 +1,7 @@ task:unloaddb token:cdfb4c5717170c5e34919b640249979f8375a218acf865b0b8100f0f25c069587926f07dd201b6aa dbname:demodb -targetdir:$CUBRID_DATABASES/demodb +targetdir:$ARNIADB_DATABASES/demodb usehash:yes hashdir:none target:both diff --git a/server/test/task_test_case/unloaddb_nullname b/server/test/task_test_case/unloaddb_nullname index e91a2fe..5983c4f 100644 --- a/server/test/task_test_case/unloaddb_nullname +++ b/server/test/task_test_case/unloaddb_nullname @@ -1,6 +1,6 @@ task:unloaddb token:cdfb4c5717170c5e34919b640249979f8375a218acf865b0b8100f0f25c069587926f07dd201b6aa -targetdir:$CUBRID_DATABASES/demodb +targetdir:$ARNIADB_DATABASES/demodb usehash:no hashdir:none target:both diff --git a/server/test/task_test_case/unloaddb_nulltarget b/server/test/task_test_case/unloaddb_nulltarget index 1000482..8818579 100644 --- a/server/test/task_test_case/unloaddb_nulltarget +++ b/server/test/task_test_case/unloaddb_nulltarget @@ -1,7 +1,7 @@ task:unloaddb token:cdfb4c5717170c5e34919b640249979f8375a218acf865b0b8100f0f25c069587926f07dd201b6aa dbname:demodb -targetdir:$CUBRID_DATABASES/demodb +targetdir:$ARNIADB_DATABASES/demodb usehash:no hashdir:none open:class diff --git a/server/test/task_test_case/updateattribute b/server/test/task_test_case/updateattribute index 129aa95..d49f0ca 100644 --- a/server/test/task_test_case/updateattribute +++ b/server/test/task_test_case/updateattribute @@ -4,7 +4,7 @@ dbname:demodb classname:athlete _STAMP:32 _SVRTYPE:fsvr -_PROGNAME:cub_js +_PROGNAME:arn_js _CLIENTIP:127.0.0.1 _CLIENTPORT:60375 _ID:admin diff --git a/server/test/task_test_case/userinfo b/server/test/task_test_case/userinfo index 30df4a7..e602ac9 100644 --- a/server/test/task_test_case/userinfo +++ b/server/test/task_test_case/userinfo @@ -3,7 +3,7 @@ token:cdfb4c5717170c5ed30ef86644baf8151531ce5adff4a1f9a54711c51e0f50767926f07dd2 dbname:demodb _STAMP:35 _SVRTYPE:fsvr -_PROGNAME:cub_js +_PROGNAME:arn_js _CLIENTIP:127.0.0.1 _CLIENTPORT:61143 _ID:admin diff --git a/server/test/task_test_case/viewlog b/server/test/task_test_case/viewlog index 9dc9fa2..09debc6 100644 --- a/server/test/task_test_case/viewlog +++ b/server/test/task_test_case/viewlog @@ -1,7 +1,7 @@ task:viewlog token:cdfb4c5717170c5e9c6856b4d1c61ee8132bcc7d82bd609066ed9ece2554c47f7926f07dd201b6aa dbname:demodb -path:$CUBRID/log/manager/cub_js.access.log +path:$ARNIADB/log/manager/arn_js.access.log start:1 end:1000 diff --git a/server/test/task_test_case_json/addvoldb.txt b/server/test/task_test_case_json/addvoldb.txt index a3f90b4..53ef410 100644 --- a/server/test/task_test_case_json/addvoldb.txt +++ b/server/test/task_test_case_json/addvoldb.txt @@ -3,6 +3,6 @@ "dbname":"alatestdb", "volname":"", "purpose":"generic", -"path":"$CUBRID_DATABASES/alatestdb", +"path":"$ARNIADB_DATABASES/alatestdb", "numberofpages":"100", -"size_need_mb":"0.391(MB)"} \ No newline at end of file +"size_need_mb":"0.391(MB)"} diff --git a/server/test/task_test_case_json/analyzecaslog.txt b/server/test/task_test_case_json/analyzecaslog.txt index 27a1d4f..f0862ff 100644 --- a/server/test/task_test_case_json/analyzecaslog.txt +++ b/server/test/task_test_case_json/analyzecaslog.txt @@ -1,4 +1,4 @@ {"task":"analyzecaslog", "token":"cdfb4c5717170c5e9c6856b4d1c61ee8132bcc7d82bd609066ed9ece2554c47f7926f07dd201b6aa", -"logfilelist":[{"logfile":"$CUBRID/log/broker/sql_log/query_editor_1.sql.log"}], -"option_t":"yes"} \ No newline at end of file +"logfilelist":[{"logfile":"$ARNIADB/log/broker/sql_log/query_editor_1.sql.log"}], +"option_t":"yes"} diff --git a/server/test/task_test_case_json/analyzecaslog_option_no.txt b/server/test/task_test_case_json/analyzecaslog_option_no.txt index 036f3f1..959ff6e 100644 --- a/server/test/task_test_case_json/analyzecaslog_option_no.txt +++ b/server/test/task_test_case_json/analyzecaslog_option_no.txt @@ -1,4 +1,4 @@ {"task":"analyzecaslog", "token":"cdfb4c5717170c5e9c6856b4d1c61ee8132bcc7d82bd609066ed9ece2554c47f7926f07dd201b6aa", -"logfilelist":[{"logfile":"$CUBRID/log/broker/sql_log/query_editor_1.sql.log"}], -"option_t":"no"} \ No newline at end of file +"logfilelist":[{"logfile":"$ARNIADB/log/broker/sql_log/query_editor_1.sql.log"}], +"option_t":"no"} diff --git a/server/test/task_test_case_json/applylogdb.txt b/server/test/task_test_case_json/applylogdb.txt index ae9f10d..b63bcd6 100644 --- a/server/test/task_test_case_json/applylogdb.txt +++ b/server/test/task_test_case_json/applylogdb.txt @@ -2,4 +2,4 @@ "token":"cdfb4c5717170c5ebd99d3152b799ba8c8960905fd00c5b4d503c6215bcffe1d7926f07dd201b6aa", "dbname":"demodb", "la_max_mem_size":"200", -"logpath":"$CUBRID_DATABASES/applylogdb"} \ No newline at end of file +"logpath":"$ARNIADB_DATABASES/applylogdb"} diff --git a/server/test/task_test_case_json/backupdb.txt b/server/test/task_test_case_json/backupdb.txt index f8605c7..c86c709 100644 --- a/server/test/task_test_case_json/backupdb.txt +++ b/server/test/task_test_case_json/backupdb.txt @@ -3,9 +3,9 @@ "dbname":"alatestdb", "level":"0", "volname":"alatestdb_backup_lv0", -"backupdir":"$CUBRID_DATABASES/alatestdb/backup", +"backupdir":"$ARNIADB_DATABASES/alatestdb/backup", "removelog":"n", "check":"y", "mt":"0", "zip":"y", -"safereplication":"n"} \ No newline at end of file +"safereplication":"n"} diff --git a/server/test/task_test_case_json/backupvolinfo.txt b/server/test/task_test_case_json/backupvolinfo.txt index ea863ee..b6213a1 100644 --- a/server/test/task_test_case_json/backupvolinfo.txt +++ b/server/test/task_test_case_json/backupvolinfo.txt @@ -2,4 +2,4 @@ "token":"cdfb4c5717170c5e9c6856b4d1c61ee8132bcc7d82bd609066ed9ece2554c47f7926f07dd201b6aa", "dbname":"alatestdb", "level":"0", -"pathname":"$CUBRID_DATABASES/alatestdb/backup/alatestdb_backup_lv0"} \ No newline at end of file +"pathname":"$ARNIADB_DATABASES/alatestdb/backup/alatestdb_backup_lv0"} diff --git a/server/test/task_test_case_json/broker_setparam.txt b/server/test/task_test_case_json/broker_setparam.txt index 2296260..730a730 100644 --- a/server/test/task_test_case_json/broker_setparam.txt +++ b/server/test/task_test_case_json/broker_setparam.txt @@ -20,7 +20,7 @@ "#", "[broker]", "MASTER_SHM_ID=30001", -"ADMIN_LOG_FILE=log/broker/cubrid_broker.log", +"ADMIN_LOG_FILE=log/broker/arniadb_broker.log", "", "", "[%broker1]", @@ -51,4 +51,4 @@ "SQL_LOG_MAX_SIZE=100000", "LOG_BACKUP=OFF", "MAX_STRING_LENGTH=-1", -"ACCESS_LOG=ON"]} \ No newline at end of file +"ACCESS_LOG=ON"]} diff --git a/server/test/task_test_case_json/checkdir.txt b/server/test/task_test_case_json/checkdir.txt index b974971..1b690af 100644 --- a/server/test/task_test_case_json/checkdir.txt +++ b/server/test/task_test_case_json/checkdir.txt @@ -1,3 +1,3 @@ {"task":"checkdir", "token":"cdfb4c5717170c5e237a227a2ceeccc6ae9e10c16754fb85371c0d74fa0d9d577926f07dd201b6aa", -"dir":"$CUBRID_DATABASES"} \ No newline at end of file +"dir":"$ARNIADB_DATABASES"} diff --git a/server/test/task_test_case_json/checkfile.txt b/server/test/task_test_case_json/checkfile.txt index e339395..1120597 100644 --- a/server/test/task_test_case_json/checkfile.txt +++ b/server/test/task_test_case_json/checkfile.txt @@ -1,3 +1,3 @@ {"task":"checkfile", "token":"cdfb4c5717170c5e237a227a2ceeccc6ae9e10c16754fb85371c0d74fa0d9d577926f07dd201b6aa", -"file":"$CUBRID/log/manager/cub_auto.access.log"} \ No newline at end of file +"file":"$ARNIADB/log/manager/arn_auto.access.log"} diff --git a/server/test/task_test_case_json/copydb.txt b/server/test/task_test_case_json/copydb.txt index 711bdbd..1acd0bc 100644 --- a/server/test/task_test_case_json/copydb.txt +++ b/server/test/task_test_case_json/copydb.txt @@ -2,9 +2,9 @@ "token":"cdfb4c5717170c5edfc2912f2940ab35013dd1336cf7d77e4cfaae281cffa1417926f07dd201b6aa", "srcdbname":"alatestdb", "destdbname":"destinationdb", -"destdbpath":"$CUBRID_DATABASES/destinationdb", -"exvolpath":"$CUBRID_DATABASES/destinationdb", -"logpath":"$CUBRID_DATABASES/destinationdb", +"destdbpath":"$ARNIADB_DATABASES/destinationdb", +"exvolpath":"$ARNIADB_DATABASES/destinationdb", +"logpath":"$ARNIADB_DATABASES/destinationdb", "overwrite":"y", "move":"n", -"advanced":"off"} \ No newline at end of file +"advanced":"off"} diff --git a/server/test/task_test_case_json/copydb_advance.txt b/server/test/task_test_case_json/copydb_advance.txt index 88ababa..7dd29ff 100644 --- a/server/test/task_test_case_json/copydb_advance.txt +++ b/server/test/task_test_case_json/copydb_advance.txt @@ -2,12 +2,12 @@ "token":"cdfb4c5717170c5edfc2912f2940ab35013dd1336cf7d77e4cfaae281cffa1417926f07dd201b6aa", "srcdbname":"copydb", "destdbname":"destinationdb1", -"destdbpath":"$CUBRID_DATABASES/destinationdb1", -"exvolpath":"$CUBRID_DATABASES/destinationdb1", -"logpath":"$CUBRID_DATABASES/destinationdb1", +"destdbpath":"$ARNIADB_DATABASES/destinationdb1", +"exvolpath":"$ARNIADB_DATABASES/destinationdb1", +"logpath":"$ARNIADB_DATABASES/destinationdb1", "overwrite":"y", "move":"y", "advanced":"on", "volume":[{ -"$CUBRID_DATABASES/copydb/copydb":"$CUBRID_DATABASES/destinationdb1/destinationdb1"}] -} \ No newline at end of file +"$ARNIADB_DATABASES/copydb/copydb":"$ARNIADB_DATABASES/destinationdb1/destinationdb1"}] +} diff --git a/server/test/task_test_case_json/copyfolder.txt b/server/test/task_test_case_json/copyfolder.txt index 6a564d3..f089f7d 100644 --- a/server/test/task_test_case_json/copyfolder.txt +++ b/server/test/task_test_case_json/copyfolder.txt @@ -1,4 +1,4 @@ {"task":"copyfolder", "token":"cdfb4c5717170c5edfc2912f2940ab35013dd1336cf7d77e4cfaae281cffa1417926f07dd201b6aa", -"srcdir":"$CUBRID/tmp", -"destdir":"$CUBRID/tmp1"} \ No newline at end of file +"srcdir":"$ARNIADB/tmp", +"destdir":"$ARNIADB/tmp1"} diff --git a/server/test/task_test_case_json/copylogdb.txt b/server/test/task_test_case_json/copylogdb.txt index 66cb70f..4f2e11d 100644 --- a/server/test/task_test_case_json/copylogdb.txt +++ b/server/test/task_test_case_json/copylogdb.txt @@ -2,5 +2,5 @@ "token":"cdfb4c5717170c5ed4a061e37572161dc895920ae8799faa38ebb2358d27b4717926f07dd201b6aa", "dbname":"demodb", "mode":"sync", -"logpath":"$CUBRID_DATABASES/copylogdb", -"hostname":"localhost"} \ No newline at end of file +"logpath":"$ARNIADB_DATABASES/copylogdb", +"hostname":"localhost"} diff --git a/server/test/task_test_case_json/createdb.txt b/server/test/task_test_case_json/createdb.txt index b0a7576..93c8230 100644 --- a/server/test/task_test_case_json/createdb.txt +++ b/server/test/task_test_case_json/createdb.txt @@ -5,7 +5,7 @@ "pagesize":"4096", "logsize":"10240", "logpagesize":"4096", -"genvolpath":"$CUBRID_DATABASES/alatestdb", -"logvolpath":"$CUBRID_DATABASES/alatestdb", -"exvol":[{"alatestdb_data_x001":"data;100;$CUBRID_DATABASES/alatestdb"}], -"overwrite_config_file":"YES"} \ No newline at end of file +"genvolpath":"$ARNIADB_DATABASES/alatestdb", +"logvolpath":"$ARNIADB_DATABASES/alatestdb", +"exvol":[{"alatestdb_data_x001":"data;100;$ARNIADB_DATABASES/alatestdb"}], +"overwrite_config_file":"YES"} diff --git a/server/test/task_test_case_json/createdb_fail_with_dup_name.txt b/server/test/task_test_case_json/createdb_fail_with_dup_name.txt index a47887f..8d9e6a9 100644 --- a/server/test/task_test_case_json/createdb_fail_with_dup_name.txt +++ b/server/test/task_test_case_json/createdb_fail_with_dup_name.txt @@ -5,7 +5,7 @@ "pagesize":"4096", "logsize":"10240", "logpagesize":"4096", -"genvolpath":"$CUBRID_DATABASES/alatestdb", -"logvolpath":"$CUBRID_DATABASES/alatestdb", +"genvolpath":"$ARNIADB_DATABASES/alatestdb", +"logvolpath":"$ARNIADB_DATABASES/alatestdb", "exvol":{}, -"overwrite_config_file":"YES"} \ No newline at end of file +"overwrite_config_file":"YES"} diff --git a/server/test/task_test_case_json/createdb_for_copydb.txt b/server/test/task_test_case_json/createdb_for_copydb.txt index 52b144f..c202e1f 100644 --- a/server/test/task_test_case_json/createdb_for_copydb.txt +++ b/server/test/task_test_case_json/createdb_for_copydb.txt @@ -5,7 +5,7 @@ "pagesize":"4096", "logpagesize":"4096", "logsize":"10240", -"genvolpath":"$CUBRID_DATABASES/copydb", -"logvolpath":"$CUBRID_DATABASES/copydb", +"genvolpath":"$ARNIADB_DATABASES/copydb", +"logvolpath":"$ARNIADB_DATABASES/copydb", "exvol":[], -"overwrite_config_file":"YES"} \ No newline at end of file +"overwrite_config_file":"YES"} diff --git a/server/test/task_test_case_json/deletefolder.txt b/server/test/task_test_case_json/deletefolder.txt index f5ef0d3..1e0bd9a 100644 --- a/server/test/task_test_case_json/deletefolder.txt +++ b/server/test/task_test_case_json/deletefolder.txt @@ -1,3 +1,3 @@ {"task":"deletefolder", "token":"cdfb4c5717170c5edfc2912f2940ab35013dd1336cf7d77e4cfaae281cffa1417926f07dd201b6aa", -"srcdir":"$CUBRID/tmp1"} \ No newline at end of file +"srcdir":"$ARNIADB/tmp1"} diff --git a/server/test/task_test_case_json/getallsysparam.txt b/server/test/task_test_case_json/getallsysparam.txt index e8793fc..53a1f4d 100644 --- a/server/test/task_test_case_json/getallsysparam.txt +++ b/server/test/task_test_case_json/getallsysparam.txt @@ -1,3 +1,3 @@ {"task":"getallsysparam", "token":"cdfb4c5717170c5e237a227a2ceeccc6ae9e10c16754fb85371c0d74fa0d9d577926f07dd201b6aa", -"confname":"cubridconf"} \ No newline at end of file +"confname":"arniadbconf"} diff --git a/server/test/task_test_case_json/getcaslogtopresult.txt b/server/test/task_test_case_json/getcaslogtopresult.txt index faff5cb..66115ba 100644 --- a/server/test/task_test_case_json/getcaslogtopresult.txt +++ b/server/test/task_test_case_json/getcaslogtopresult.txt @@ -1,4 +1,4 @@ {"task":"getcaslogtopresult", "token":"cdfb4c5717170c5e9c6856b4d1c61ee8132bcc7d82bd609066ed9ece2554c47f7926f07dd201b6aa", -"filename":"$CUBRID/tmp/analyzelog_1.res", -"qindex":"[Q14]"} \ No newline at end of file +"filename":"$ARNIADB/tmp/analyzelog_1.res", +"qindex":"[Q14]"} diff --git a/server/test/task_test_case_json/getenvvarbyname.txt b/server/test/task_test_case_json/getenvvarbyname.txt index 361529c..f74a143 100644 --- a/server/test/task_test_case_json/getenvvarbyname.txt +++ b/server/test/task_test_case_json/getenvvarbyname.txt @@ -1,3 +1,3 @@ {"task":"getenvvarbyname", "token":"cdfb4c5717170c5e9c6856b4d1c61ee8132bcc7d82bd609066ed9ece2554c47f7926f07dd201b6aa", -"envvar":"CUBRID"} \ No newline at end of file +"envvar":"ARNIADB"} diff --git a/server/test/task_test_case_json/getfiletotallinenum.txt b/server/test/task_test_case_json/getfiletotallinenum.txt index d88f383..b75c50f 100644 --- a/server/test/task_test_case_json/getfiletotallinenum.txt +++ b/server/test/task_test_case_json/getfiletotallinenum.txt @@ -1,3 +1,3 @@ {"task":"getfiletotallinenum", "token":"cdfb4c5717170c5edfc2912f2940ab35013dd1336cf7d77e4cfaae281cffa1417926f07dd201b6aa", -"filepath":"$CUBRID/conf/cm.conf"} \ No newline at end of file +"filepath":"$ARNIADB/conf/cm.conf"} diff --git a/server/test/task_test_case_json/getfolderswithkeyword.txt b/server/test/task_test_case_json/getfolderswithkeyword.txt index b43e251..c1c12e5 100644 --- a/server/test/task_test_case_json/getfolderswithkeyword.txt +++ b/server/test/task_test_case_json/getfolderswithkeyword.txt @@ -1,4 +1,4 @@ {"task":"getfolderswithkeyword", "token":"cdfb4c5717170c5edfc2912f2940ab35013dd1336cf7d77e4cfaae281cffa1417926f07dd201b6aa", -"search_folder":"$CUBRID/tmp1", -"keyword":"res"} \ No newline at end of file +"search_folder":"$ARNIADB/tmp1", +"keyword":"res"} diff --git a/server/test/task_test_case_json/loaddb.txt b/server/test/task_test_case_json/loaddb.txt index 1717e73..6e8f929 100644 --- a/server/test/task_test_case_json/loaddb.txt +++ b/server/test/task_test_case_json/loaddb.txt @@ -7,9 +7,9 @@ "estimated":"none", "oiduse":"yes", "nolog":"no", -"schema":"$CUBRID_DATABASES/demodb/demodb_schema", -"object":"$CUBRID_DATABASES/demodb/demodb_objects", +"schema":"$ARNIADB_DATABASES/demodb/demodb_schema", +"object":"$ARNIADB_DATABASES/demodb/demodb_objects", "index":"none", "errorcontrolfile":"none", "ignoreclassfile":"none", -"delete_orignal_files":"y"} \ No newline at end of file +"delete_orignal_files":"y"} diff --git a/server/test/task_test_case_json/removecasrunnertmpfile.txt b/server/test/task_test_case_json/removecasrunnertmpfile.txt index b7f4da7..c11e8cd 100644 --- a/server/test/task_test_case_json/removecasrunnertmpfile.txt +++ b/server/test/task_test_case_json/removecasrunnertmpfile.txt @@ -1,3 +1,3 @@ {"task":"removecasrunnertmpfile", "token":"cdfb4c5717170c5e9c6856b4d1c61ee8132bcc7d82bd609066ed9ece2554c47f7926f07dd201b6aa", -"filename":"$CUBRID/tmp/log_run_1.res.0"} \ No newline at end of file +"filename":"$ARNIADB/tmp/log_run_1.res.0"} diff --git a/server/test/task_test_case_json/removelog.txt b/server/test/task_test_case_json/removelog.txt index 3cb846e..83bdcb1 100644 --- a/server/test/task_test_case_json/removelog.txt +++ b/server/test/task_test_case_json/removelog.txt @@ -1,4 +1,4 @@ {"task":"removelog", "token":"cdfb4c5717170c5e9c6856b4d1c61ee8132bcc7d82bd609066ed9ece2554c47f7926f07dd201b6aa", -"files":[{"path":"$CUBRID/log/manager/cub_js.access.log"}] -} \ No newline at end of file +"files":[{"path":"$ARNIADB/log/manager/arn_js.access.log"}] +} diff --git a/server/test/task_test_case_json/renamedb.txt b/server/test/task_test_case_json/renamedb.txt index 5114627..c3a033c 100644 --- a/server/test/task_test_case_json/renamedb.txt +++ b/server/test/task_test_case_json/renamedb.txt @@ -4,5 +4,5 @@ "rename":"anotherdb", "exvolpath":"none", "advanced":"on", -"volume":[{"$CUBRID_DATABASES/destinationdb/destinationdb":"$CUBRID_DATABASES/anotherdb/anotherdb"}], -"forcedel":"y"} \ No newline at end of file +"volume":[{"$ARNIADB_DATABASES/destinationdb/destinationdb":"$ARNIADB_DATABASES/anotherdb/anotherdb"}], +"forcedel":"y"} diff --git a/server/test/task_test_case_json/resetlog.txt b/server/test/task_test_case_json/resetlog.txt index 10cba4c..c39afb5 100644 --- a/server/test/task_test_case_json/resetlog.txt +++ b/server/test/task_test_case_json/resetlog.txt @@ -1,3 +1,3 @@ {"task":"resetlog", "token":"cdfb4c5717170c5e9c6856b4d1c61ee8132bcc7d82bd609066ed9ece2554c47f7926f07dd201b6aa", -"path":"$CUBRID/log/broker/cubrid_broker.log"} \ No newline at end of file +"path":"$ARNIADB/log/broker/arniadb_broker.log"} diff --git a/server/test/task_test_case_json/restoredb.txt b/server/test/task_test_case_json/restoredb.txt index 27e5170..43ab892 100644 --- a/server/test/task_test_case_json/restoredb.txt +++ b/server/test/task_test_case_json/restoredb.txt @@ -4,5 +4,5 @@ "date":"none", "level":"0", "partial":"y", -"pathname":"$CUBRID_DATABASES/alatestdb/backup/alatestdb_backup_lv0", -"recoverypath":"$CUBRID_DATABASES/alatestdb"} \ No newline at end of file +"pathname":"$ARNIADB_DATABASES/alatestdb/backup/alatestdb_backup_lv0", +"recoverypath":"$ARNIADB_DATABASES/alatestdb"} diff --git a/server/test/task_test_case_json/setbackupinfo.txt b/server/test/task_test_case_json/setbackupinfo.txt index 001bfd8..4dc2629 100644 --- a/server/test/task_test_case_json/setbackupinfo.txt +++ b/server/test/task_test_case_json/setbackupinfo.txt @@ -2,7 +2,7 @@ "token":"cdfb4c5717170c5e9c6856b4d1c61ee8132bcc7d82bd609066ed9ece2554c47f7926f07dd201b6aa", "dbname":"alatestdb", "backupid":"qw", -"path":"$CUBRID_DATABASES/alatestdb/backup", +"path":"$ARNIADB_DATABASES/alatestdb/backup", "period_type":"Special", "period_date":"$AUTO_DATE", "time":"$AUTO_TIME", @@ -13,4 +13,4 @@ "onoff":"ON", "zip":"y", "check":"y", -"mt":"0"} \ No newline at end of file +"mt":"0"} diff --git a/server/test/task_test_case_json/setsysparam.txt b/server/test/task_test_case_json/setsysparam.txt index d703d86..c96553d 100644 --- a/server/test/task_test_case_json/setsysparam.txt +++ b/server/test/task_test_case_json/setsysparam.txt @@ -1,6 +1,6 @@ {"task":"setsysparam", "token":"cdfb4c5717170c5e9c6856b4d1c61ee8132bcc7d82bd609066ed9ece2554c47f7926f07dd201b6aa", -"confname":"cubridconf", +"confname":"arniadbconf", "confdata":[ "#", "# Copyright (C) 2009 Search Solution Corporation. All rights reserved by Search Solution.", @@ -21,19 +21,19 @@ "#", "# $Id$", "#", -"# cubrid.conf", +"# arniadb.conf", "#", -"# For complete information on parameters, see the CUBRID", +"# For complete information on parameters, see the ARNIADB", "# Database Administration Guide chapter on System Parameters", "", -"# Service section - a section for 'cubrid service' command", +"# Service section - a section for 'arniadb service' command", "[service]", "", -"# The list of processes to be started automatically by 'cubrid service start' command", +"# The list of processes to be started automatically by 'arniadb service start' command", "# Any combinations are available with server, broker and manager.", "service=server,broker,manager", "", -"# The list of database servers in all by 'cubrid service start' command.", +"# The list of database servers in all by 'arniadb service start' command.", "# This property is effective only when the above 'service' property contains 'server' keyword.", "server=demodb", "", @@ -56,5 +56,5 @@ "# This value also means the total # of concurrent transactions.", "max_clients=100", "", -"# TCP port id for the CUBRID programs (used by all clients).", -"cubrid_port_id=1523"]} \ No newline at end of file +"# TCP port id for the ARNIADB programs (used by all clients).", +"arniadb_port_id=1523"]} diff --git a/server/test/task_test_case_json/setsysparam_cubridconf.txt b/server/test/task_test_case_json/setsysparam_arniadbconf.txt similarity index 82% rename from server/test/task_test_case_json/setsysparam_cubridconf.txt rename to server/test/task_test_case_json/setsysparam_arniadbconf.txt index d703d86..c96553d 100644 --- a/server/test/task_test_case_json/setsysparam_cubridconf.txt +++ b/server/test/task_test_case_json/setsysparam_arniadbconf.txt @@ -1,6 +1,6 @@ {"task":"setsysparam", "token":"cdfb4c5717170c5e9c6856b4d1c61ee8132bcc7d82bd609066ed9ece2554c47f7926f07dd201b6aa", -"confname":"cubridconf", +"confname":"arniadbconf", "confdata":[ "#", "# Copyright (C) 2009 Search Solution Corporation. All rights reserved by Search Solution.", @@ -21,19 +21,19 @@ "#", "# $Id$", "#", -"# cubrid.conf", +"# arniadb.conf", "#", -"# For complete information on parameters, see the CUBRID", +"# For complete information on parameters, see the ARNIADB", "# Database Administration Guide chapter on System Parameters", "", -"# Service section - a section for 'cubrid service' command", +"# Service section - a section for 'arniadb service' command", "[service]", "", -"# The list of processes to be started automatically by 'cubrid service start' command", +"# The list of processes to be started automatically by 'arniadb service start' command", "# Any combinations are available with server, broker and manager.", "service=server,broker,manager", "", -"# The list of database servers in all by 'cubrid service start' command.", +"# The list of database servers in all by 'arniadb service start' command.", "# This property is effective only when the above 'service' property contains 'server' keyword.", "server=demodb", "", @@ -56,5 +56,5 @@ "# This value also means the total # of concurrent transactions.", "max_clients=100", "", -"# TCP port id for the CUBRID programs (used by all clients).", -"cubrid_port_id=1523"]} \ No newline at end of file +"# TCP port id for the ARNIADB programs (used by all clients).", +"arniadb_port_id=1523"]} diff --git a/server/test/task_test_case_json/unloaddb.txt b/server/test/task_test_case_json/unloaddb.txt index b05c22d..d982a36 100644 --- a/server/test/task_test_case_json/unloaddb.txt +++ b/server/test/task_test_case_json/unloaddb.txt @@ -1,7 +1,7 @@ {"task":"unloaddb", "token":"cdfb4c5717170c5e34919b640249979f8375a218acf865b0b8100f0f25c069587926f07dd201b6aa", "dbname":"demodb", -"targetdir":"$CUBRID_DATABASES/demodb", +"targetdir":"$ARNIADB_DATABASES/demodb", "usehash":"no", "hashdir":"none", "target":"both", @@ -12,4 +12,4 @@ "estimate":"none", "prefix":"none", "cach":"none", -"lofile":"none"} \ No newline at end of file +"lofile":"none"} diff --git a/server/test/task_test_case_json/viewlog.txt b/server/test/task_test_case_json/viewlog.txt index 1570efc..b8f056f 100644 --- a/server/test/task_test_case_json/viewlog.txt +++ b/server/test/task_test_case_json/viewlog.txt @@ -1,6 +1,6 @@ {"task":"viewlog", "token":"cdfb4c5717170c5e9c6856b4d1c61ee8132bcc7d82bd609066ed9ece2554c47f7926f07dd201b6aa", "dbname":"demodb", -"path":"$CUBRID/log/manager/cub_js.access.log", +"path":"$ARNIADB/log/manager/arn_js.access.log", "start":"1", -"end":"1000"} \ No newline at end of file +"end":"1000"} diff --git a/server/test/task_test_config/cm_conf/cubrid_broker.conf b/server/test/task_test_config/cm_conf/arniadb_broker.conf similarity index 96% rename from server/test/task_test_config/cm_conf/cubrid_broker.conf rename to server/test/task_test_config/cm_conf/arniadb_broker.conf index 713936a..0ef306f 100644 --- a/server/test/task_test_config/cm_conf/cubrid_broker.conf +++ b/server/test/task_test_config/cm_conf/arniadb_broker.conf @@ -18,7 +18,7 @@ [broker] MASTER_SHM_ID =30001 -ADMIN_LOG_FILE =log/broker/cubrid_broker.log +ADMIN_LOG_FILE =log/broker/arniadb_broker.log [%query_editor] SERVICE =ON diff --git a/server/test/task_test_config/cm_conf/cm.conf b/server/test/task_test_config/cm_conf/cm.conf index 0f19812..7f35e03 100644 --- a/server/test/task_test_config/cm_conf/cm.conf +++ b/server/test/task_test_config/cm_conf/cm.conf @@ -1,10 +1,10 @@ # cm.conf -# -- CUBRID database management tool server configuration file +# -- ARNIADB database management tool server configuration file # # # When server starts, it looks for the environment variable -# 'CUBRID_MANAGER' and use it to locate this file. It is assumed that -# 'CUBRID_MANAGER' is the root directory of all CUBRID Manager related files. +# 'ARNIADB_MANAGER' and use it to locate this file. It is assumed that +# 'ARNIADB_MANAGER' is the root directory of all ARNIADB Manager related files. # # @@ -19,7 +19,7 @@ port_auto_server=8001 monitor_interval=1 # -# Allowing Multiple connection with one CUBRID Manager user. +# Allowing Multiple connection with one ARNIADB Manager user. # allow_user_multi_connection=YES allow_user_multi_connection=NO @@ -45,4 +45,4 @@ support_web_manager=1 # server_long_query_time=10 -error_log=log/cubrid_error.log +error_log=log/arniadb_error.log diff --git a/server/test/task_test_config/ha_conf/README.txt b/server/test/task_test_config/ha_conf/README.txt index ea7bfe2..2751370 100644 --- a/server/test/task_test_config/ha_conf/README.txt +++ b/server/test/task_test_config/ha_conf/README.txt @@ -1 +1 @@ -The folder is used to keep the HA-config file "cubrid.conf" +The folder is used to keep the HA-config file "arniadb.conf" diff --git a/server/test/task_test_config/ha_conf/cubrid.conf b/server/test/task_test_config/ha_conf/arniadb.conf similarity index 88% rename from server/test/task_test_config/ha_conf/cubrid.conf rename to server/test/task_test_config/ha_conf/arniadb.conf index 9651bf6..44b79d7 100644 --- a/server/test/task_test_config/ha_conf/cubrid.conf +++ b/server/test/task_test_config/ha_conf/arniadb.conf @@ -18,19 +18,19 @@ # # $Id$ # -# cubrid.conf +# arniadb.conf # -# For complete information on parameters, see the CUBRID +# For complete information on parameters, see the ARNIADB # Database Administration Guide chapter on System Parameters -# Service section - a section for 'cubrid service' command +# Service section - a section for 'arniadb service' command [service] -# The list of processes to be started automatically by 'cubrid service start' command +# The list of processes to be started automatically by 'arniadb service start' command # Any combinations are available with server, broker and manager. service=server,broker,manager -# The list of database servers in all by 'cubrid service start' command. +# The list of database servers in all by 'arniadb service start' command. # # This property is effective only when the above 'service' property contains 'server' keyword. server=demodb @@ -68,8 +68,8 @@ checkpoint_interval_in_mins=720 # System Parameters chapter in the Database Administration Guide. isolation_level="TRAN_REP_CLASS_UNCOMMIT_INSTANCE" -# TCP port id for the CUBRID programs (used by all clients). -cubrid_port_id=1523 +# TCP port id for the ARNIADB programs (used by all clients). +arniadb_port_id=1523 # The maximum number of concurrent client connections the server will accept. # This value also means the total # of concurrent transactions. diff --git a/server/test/task_test_config/orign/README.txt b/server/test/task_test_config/orign/README.txt index e1eaa3b..82e66a1 100644 --- a/server/test/task_test_config/orign/README.txt +++ b/server/test/task_test_config/orign/README.txt @@ -1 +1 @@ -The folder is used to keep the original config file "cubrid.conf" +The folder is used to keep the original config file "arniadb.conf" diff --git a/server/test/task_test_config/tmp_file_for_test/analyzelog_1.res b/server/test/task_test_config/tmp_file_for_test/analyzelog_1.res index 00c9b99..3cce6b8 100644 --- a/server/test/task_test_config/tmp_file_for_test/analyzelog_1.res +++ b/server/test/task_test_config/tmp_file_for_test/analyzelog_1.res @@ -1,16 +1,16 @@ [Q1] -/home/yangming/cubrid/log/broker/sql_log/query_editor_1.sql.log:1 +/home/yangming/arniadb/log/broker/sql_log/query_editor_1.sql.log:1 06/13 10:40:00.166 (0) CAS STARTED pid 13006 06/13 10:44:13.429 (0) CAS TERMINATED pid 13006 06/13 10:44:19.030 (0) CAS STARTED pid 13767 06/17 11:18:16.894 (0) CLIENT IP 192.168.0.1 -06/17 11:18:16.911 (0) connect db ha_test@192.168.0.1 user dba url jdbc:cubrid:192.168.0.1:45000:ha_test@192.168.0.1:dba::charset=GBK +06/17 11:18:16.911 (0) connect db ha_test@192.168.0.1 user dba url jdbc:arniadb:192.168.0.1:45000:ha_test@192.168.0.1:dba::charset=GBK 06/17 11:18:16.911 (0) DEFAULT isolation_level 3, lock_timeout -1 06/17 11:18:16.912 (0) get_version 06/17 11:18:16.912 (0) auto_commit 06/17 11:18:16.912 (0) auto_commit 0 06/17 11:18:16.912 (0) *** elapsed time 0.001 -/home/yangming/cubrid/log/broker/sql_log/query_editor_1.sql.log:12 +/home/yangming/arniadb/log/broker/sql_log/query_editor_1.sql.log:12 06/17 11:18:16.936 (1) prepare 0 select class_name,owner_name,class_type,is_system_class,partitioned from db_class as a where LOWER(a.class_name) not in (select LOWER(partition_class_name) from db_partition) and is_system_class='NO' and class_type='CLASS' 06/17 11:18:16.993 (1) prepare srv_h_id 1 @@ -20,7 +20,7 @@ select class_name,owner_name,class_type,is_system_class,partitioned from db_clas 06/17 11:18:17.026 (0) disconnect 06/17 11:18:17.026 (0) STATE idle 06/17 11:18:52.616 (0) CLIENT IP 192.168.0.1 -06/17 11:18:52.617 (0) connect db ha_test@192.168.0.1 user dba url jdbc:cubrid:192.168.0.1:45000:ha_test@192.168.0.1:dba::charset=GBK +06/17 11:18:52.617 (0) connect db ha_test@192.168.0.1 user dba url jdbc:arniadb:192.168.0.1:45000:ha_test@192.168.0.1:dba::charset=GBK 06/17 11:18:52.617 (0) DEFAULT isolation_level 3, lock_timeout -1 06/17 11:18:52.618 (0) get_version 06/17 11:18:52.618 (0) auto_commit diff --git a/server/test/test_tasks.php b/server/test/test_tasks.php index 4e97799..844aaa1 100644 --- a/server/test/test_tasks.php +++ b/server/test/test_tasks.php @@ -13,10 +13,10 @@ echo "usage: php test_tasks.php \n"; exit; } -$cubrid_env = getenv('CUBRID'); -$cubrid_database_env = getenv('CUBRID_DATABASES'); -if(!$cubrid_env || !$cubrid_database_env){ - echo "cubrid related environment variable not set.\n"; +$arniadb_env = getenv('ARNIADB'); +$arniadb_database_env = getenv('ARNIADB_DATABASES'); +if(!$arniadb_env || !$arniadb_database_env){ + echo "arniadb related environment variable not set.\n"; exit; } @@ -28,9 +28,9 @@ } $task_seq = array( - "cmd,cub_js", - "cmd,cub_auto", - "cmd,cub_auto --version", + "cmd,arn_js", + "cmd,arn_auto", + "cmd,arn_auto --version", "login_nullid,failure", "login_notask,failure", "login_nouser,failure", @@ -236,7 +236,7 @@ // tasks set conf files //"setsysparam_cmconf,success", - //"setsysparam_cubridconf,success", + //"setsysparam_arniadbconf,success", //"broker_setparam,success", "createftprocess,success", @@ -253,7 +253,7 @@ $ntask_failed = 0; $ntask_success = 0; -/* connect cub_auto process to get valid token */ +/* connect arn_auto process to get valid token */ $sock_auto = socket_create (AF_INET, SOCK_STREAM, SOL_TCP); if ($sock_auto < 0) @@ -264,7 +264,7 @@ $token = get_token($sock_auto); #echo "token = ".$token."\n"; -/* connect cub_js process to execute tasks */ +/* connect arn_js process to execute tasks */ exec_tasks($token); echo "tasks executed:\t\t".$ntask_total."\n"; @@ -314,25 +314,25 @@ function exec_tasks($token) function build_env() { - global $cubrid_env, $cubrid_database_env; + global $arniadb_env, $arniadb_database_env; @system("rm -rf ".TEST_RESULT_DIR); //remove old result dir system("mkdir ".TEST_RESULT_DIR); //create an empty result dir - system("mkdir ".$cubrid_database_env."/copylogdb"); //create an empty dir for copylogdb - system("mkdir ".$cubrid_database_env."/applylogdb"); //create an empty dir for applylogdb - system("mkdir ".$cubrid_database_env."/destinationdb1"); //create an empty dir for destinationdb1 - system("cp ".TEST_CONFIG_DIR."tmp_file_for_test/* ".$cubrid_env."/tmp/"); //create an empty dir for applylogdb - system("echo task:class > ".$cubrid_env."/tmp/DBMT_comm_test.req"); - system("echo dbname:testclass >> ".$cubrid_env."/tmp/DBMT_comm_test.req"); + system("mkdir ".$arniadb_database_env."/copylogdb"); //create an empty dir for copylogdb + system("mkdir ".$arniadb_database_env."/applylogdb"); //create an empty dir for applylogdb + system("mkdir ".$arniadb_database_env."/destinationdb1"); //create an empty dir for destinationdb1 + system("cp ".TEST_CONFIG_DIR."tmp_file_for_test/* ".$arniadb_env."/tmp/"); //create an empty dir for applylogdb + system("echo task:class > ".$arniadb_env."/tmp/DBMT_comm_test.req"); + system("echo dbname:testclass >> ".$arniadb_env."/tmp/DBMT_comm_test.req"); } function clean_env() { - global $cubrid_database_env; - @system("rm -rf ".$cubrid_database_env."/copylogdb"); //remove copylogdb dir - @system("rm -rf ".$cubrid_database_env."/applylogdb"); //remove applylogdb dir - system("rm -rf ".$cubrid_database_env."/destinationdb1"); //remove an empty dir for destinationdb1 - system("rm -rf ".$cubrid_database_env."/destinationdb"); //remove an empty dir for destinationdb1 - system("rm -rf ".$cubrid_database_env."/copydb"); //remove an empty dir for destinationdb1 + global $arniadb_database_env; + @system("rm -rf ".$arniadb_database_env."/copylogdb"); //remove copylogdb dir + @system("rm -rf ".$arniadb_database_env."/applylogdb"); //remove applylogdb dir + system("rm -rf ".$arniadb_database_env."/destinationdb1"); //remove an empty dir for destinationdb1 + system("rm -rf ".$arniadb_database_env."/destinationdb"); //remove an empty dir for destinationdb1 + system("rm -rf ".$arniadb_database_env."/copydb"); //remove an empty dir for destinationdb1 } function exec_task($req_file, $token, $test_result) @@ -359,7 +359,7 @@ function exec_task($req_file, $token, $test_result) } $contents = file_get_contents(TEST_CASE_DIR . $req_file); - $contents = replace_env_vars($contents); /* replace cubrid relate env var to actual path */ + $contents = replace_env_vars($contents); /* replace arniadb relate env var to actual path */ #$kv_arr = string_to_kv_arr($contents); #$kv_arr["token"] = $token; $contents = setval_with_key($contents,"token", $token); @@ -474,9 +474,9 @@ function setval_with_key($string, $key_in, $val_in, $line_delim="\n", $kv_delim= return $out_str; } -function replace_env_vars($contents) /* replace cubrid relate env var to actual path */ +function replace_env_vars($contents) /* replace arniadb relate env var to actual path */ { - global $cubrid_env, $cubrid_database_env; + global $arniadb_env, $arniadb_database_env; $tmp_time = get_time_next_miniute("Y-m-d:Hi"); $time_elem = explode (":", $tmp_time); @@ -487,8 +487,8 @@ function replace_env_vars($contents) /* replace cubrid relate env var to act echo $query_time; $contents = str_replace('$AUTO_QUERY_TIME', $query_time, $contents); - $contents = str_replace('$CUBRID_DATABASES', $cubrid_database_env, $contents); - $contents = str_replace('$CUBRID', $cubrid_env, $contents); + $contents = str_replace('$ARNIADB_DATABASES', $arniadb_database_env, $contents); + $contents = str_replace('$ARNIADB', $arniadb_env, $contents); return $contents; } diff --git a/server/test/test_tasks.py b/server/test/test_tasks.py index 3272836..8336532 100644 --- a/server/test/test_tasks.py +++ b/server/test/test_tasks.py @@ -5,12 +5,12 @@ import os, sys def findport(): - cubrid = os.environ.get("CUBRID") - conf = cubrid + "/conf/cm_httpd.conf" + arniadb = os.environ.get("ARNIADB") + conf = arniadb + "/conf/cm_httpd.conf" cwm_find = False; cf = open(conf, "r") for line in cf: - idx = line.find("cwm.cubrid.org") + idx = line.find("cwm.arniadb.org") if idx > 0: cwm_find = True if cwm_find: @@ -29,8 +29,8 @@ def findport(): testdir="task_test_case_json/" token="" -CUBRID="" -CUBRID_DATABASES="" +ARNIADB="" +ARNIADB_DATABASES="" def exec_task(ip, port, url, body): conn = httplib.HTTPConnection(ip, port) @@ -42,8 +42,8 @@ def exec_task(ip, port, url, body): def load_task(taskfile): task=open(taskfile, "r") filebuf=task.read() - filebuf=filebuf.replace("$CUBRID_DATABASES", str(CUBRID_DATABASES)) - filebuf=filebuf.replace("$CUBRID", str(CUBRID)) + filebuf=filebuf.replace("$ARNIADB_DATABASES", str(ARNIADB_DATABASES)) + filebuf=filebuf.replace("$ARNIADB", str(ARNIADB)) data = json.loads(filebuf) return data @@ -99,12 +99,12 @@ def init_env(): response = data token = response["token"] response = do_one_job(testdir+"/getenv.txt", token) - bindir = response["CUBRID"] - datadir = response["CUBRID_DATABASES"] + bindir = response["ARNIADB"] + datadir = response["ARNIADB_DATABASES"] return token, bindir, datadir -token, CUBRID, CUBRID_DATABASES = init_env() -#print (token, CUBRID, CUBRID_DATABASES) +token, ARNIADB, ARNIADB_DATABASES = init_env() +#print (token, ARNIADB, ARNIADB_DATABASES) #do_one_job("task_json/renamedb.txt", token) do_all_jobs(token) diff --git a/server/win/cub_manager/cub_manager.vcproj b/server/win/arn_manager/arn_manager.vcproj similarity index 87% rename from server/win/cub_manager/cub_manager.vcproj rename to server/win/arn_manager/arn_manager.vcproj index 89b3abc..a7fe77f 100644 --- a/server/win/cub_manager/cub_manager.vcproj +++ b/server/win/arn_manager/arn_manager.vcproj @@ -2,9 +2,9 @@ @@ -44,7 +44,7 @@ @@ -118,7 +118,7 @@ @@ -193,7 +193,7 @@ Name="VCCLCompilerTool" Optimization="2" EnableIntrinsicFunctions="true" - AdditionalIncludeDirectories="..\..\win;..\..\src;$(cubrid_includedir);$(libevent_include)" + AdditionalIncludeDirectories="..\..\win;..\..\src;$(arniadb_includedir);$(libevent_include)" PreprocessorDefinitions="WIN;WINDOWS;WIN32;NDEBUG;_CRT_SECURE_NO_WARNINGS;DIAG_DEVEL;_USE_32BIT_TIME_T" RuntimeLibrary="0" EnableFunctionLevelLinking="true" @@ -213,7 +213,7 @@ Date: Sat, 16 Oct 2021 17:10:38 +0300 Subject: [PATCH 02/12] add ams --- README.md | 16 +- docs/api/README.md | 18 +- docs/api/getcmsenv.md | 20 - docs/api/monitorprocess.md | 2 +- server/Makefile.am | 2 +- server/build_cms_env.sh | 70 - server/build_server.bat | 4 +- server/cmserver/Makefile.am | 62 - server/cmserver/conf/Makefile.am | 23 - server/cmserver/conf/autoaddvoldb.conf | 0 server/cmserver/conf/autobackupdb.conf | 0 server/cmserver/conf/autoexecquery.conf | 0 server/cmserver/conf/autohistory.conf | 0 server/cmserver/conf/cm.conf | 67 - server/cmserver/conf/cm.pass | 1 - server/cmserver/conf/cm_ssl_cert.crt | 14 - server/cmserver/conf/cm_ssl_cert.key | 15 - server/cmserver/conf/cmdb.pass | 4 - .../cmserver/conf/diagactivitytemplate.conf | 0 server/cmserver/conf/diagstatustemplate.conf | 9 - server/configure.ac | 12 +- server/external/README | 4 +- .../openssl/aix_64/include/openssl/asn1.h | 2 +- .../openssl/aix_64/include/openssl/err.h | 4 +- .../openssl/aix_64/include/openssl/obj_mac.h | 18 +- .../aix_64/include/openssl/opensslconf.h | 8 +- .../openssl/aix_64/include/openssl/pem.h | 2 +- .../aix_64/include/openssl/safestack.h | 174 +- .../openssl/aix_64/include/openssl/symhacks.h | 32 +- .../openssl/linux_32/include/openssl/asn1.h | 2 +- .../openssl/linux_32/include/openssl/cms.h | 501 - .../openssl/linux_32/include/openssl/err.h | 4 +- .../openssl/linux_32/include/openssl/evp.h | 10 +- .../linux_32/include/openssl/obj_mac.h | 18 +- .../openssl/linux_32/include/openssl/pem.h | 2 +- .../linux_32/include/openssl/safestack.h | 174 +- .../linux_32/include/openssl/symhacks.h | 32 +- .../openssl/linux_64/include/openssl/asn1.h | 2 +- .../openssl/linux_64/include/openssl/cms.h | 339 - .../openssl/linux_64/include/openssl/cmserr.h | 202 - .../openssl/linux_64/include/openssl/dh.h | 4 +- .../openssl/linux_64/include/openssl/dherr.h | 6 +- .../openssl/linux_64/include/openssl/ecerr.h | 4 +- .../openssl/linux_64/include/openssl/err.h | 4 +- .../openssl/linux_64/include/openssl/evp.h | 12 +- .../linux_64/include/openssl/obj_mac.h | 18 +- .../openssl/linux_64/include/openssl/pem.h | 2 +- .../openssl/linux_64/include/openssl/rsaerr.h | 4 +- .../linux_64/include/openssl/symhacks.h | 6 +- .../openssl/win_32/include/openssl/asn1.h | 2 +- .../openssl/win_32/include/openssl/cms.h | 501 - .../openssl/win_32/include/openssl/err.h | 4 +- .../openssl/win_32/include/openssl/evp.h | 10 +- .../openssl/win_32/include/openssl/obj_mac.h | 18 +- .../openssl/win_32/include/openssl/pem.h | 2 +- .../win_32/include/openssl/safestack.h | 174 +- .../openssl/win_32/include/openssl/symhacks.h | 32 +- .../openssl/win_64/include/openssl/asn1.h | 2 +- .../openssl/win_64/include/openssl/cms.h | 501 - .../openssl/win_64/include/openssl/err.h | 4 +- .../openssl/win_64/include/openssl/evp.h | 10 +- .../openssl/win_64/include/openssl/obj_mac.h | 18 +- .../openssl/win_64/include/openssl/pem.h | 2 +- .../win_64/include/openssl/safestack.h | 174 +- .../openssl/win_64/include/openssl/symhacks.h | 32 +- server/src/cm_auto_task.cpp | 218 - server/src/cm_auto_task.h | 47 - server/src/cm_autojob.cpp | 1701 -- server/src/cm_autojob.h | 82 - server/src/cm_cci_interface.cpp | 1655 -- server/src/cm_cci_interface.h | 53 - server/src/cm_cmd.cpp | 83 - server/src/cm_cmd_exec.cpp | 1406 -- server/src/cm_cmd_exec.h | 279 - server/src/cm_cmd_task.cpp | 1490 -- server/src/cm_cmd_task.h | 61 - server/src/cm_cmd_util.cpp | 282 - server/src/cm_cmd_util.h | 123 - server/src/cm_compress.h | 6747 ------- server/src/cm_config.cpp | 809 - server/src/cm_config.h | 629 - server/src/cm_connect_info.cpp | 547 - server/src/cm_connect_info.h | 62 - server/src/cm_http_server.cpp | 664 - server/src/cm_http_server.h | 112 - server/src/cm_httpd.cpp | 921 - server/src/cm_job_task.cpp | 16143 ---------------- server/src/cm_job_task.h | 439 - server/src/cm_log.h | 515 - server/src/cm_mailer.h | 1913 -- server/src/cm_mon_stat.cpp | 1943 -- server/src/cm_mon_stat.h | 114 - server/src/cm_porting.h | 339 - server/src/cm_server_autoupdate.cpp | 386 - server/src/cm_server_autoupdate.h | 24 - server/src/cm_server_extend_interface.cpp | 2707 --- server/src/cm_server_extend_interface.h | 101 - server/src/cm_server_interface.cpp | 757 - server/src/cm_server_interface.h | 33 - server/src/cm_server_stat.c | 463 - server/src/cm_server_stat.h | 99 - server/src/cm_server_util.cpp | 3790 ---- server/src/cm_server_util.h | 219 - server/src/cm_text_encryption.c | 291 - server/src/cm_text_encryption.h | 38 - server/src/cm_user.cpp | 711 - server/src/cm_user.h | 113 - server/src/cm_win_wsa.c | 75 - server/src/cm_win_wsa.h | 63 - server/test/Makefile | 4 +- server/test/cm_mon_data/dump_data.py | 113 - server/test/hudsonbuild.sh | 10 +- server/test/task_list.txt | 2 +- server/test/task_test_case_json/getcmsenv.txt | 2 - .../cm_conf/arniadb_broker.conf | 50 - .../cm_conf/autoaddvoldb.conf | 4 - .../cm_conf/autobackupdb.conf | 14 - .../cm_conf/autoexecquery.conf | 11 - .../task_test_config/cm_conf/autohistory.conf | 2 - server/test/task_test_config/cm_conf/cm.conf | 48 - server/test/task_test_config/cm_conf/cm.pass | 1 - server/test/test_cci.py | 4 +- server/test/test_tasks.php | 2 +- server/test/test_tasks.py | 12 +- server/win/arn_manager/arn_manager.vcproj | 8 +- server/win/cm_admin/cm_admin.vcproj | 411 - server/win/cm_admin/resource.h | 32 - server/win/cm_admin/version.rc | 103 - server/win/cmserver.sln | 63 - server/win/install/install.bat | 8 +- server/win/install/install.vcproj | 22 +- 131 files changed, 579 insertions(+), 53009 deletions(-) delete mode 100644 docs/api/getcmsenv.md delete mode 100644 server/build_cms_env.sh delete mode 100644 server/cmserver/Makefile.am delete mode 100644 server/cmserver/conf/Makefile.am delete mode 100644 server/cmserver/conf/autoaddvoldb.conf delete mode 100644 server/cmserver/conf/autobackupdb.conf delete mode 100644 server/cmserver/conf/autoexecquery.conf delete mode 100644 server/cmserver/conf/autohistory.conf delete mode 100644 server/cmserver/conf/cm.conf delete mode 100644 server/cmserver/conf/cm.pass delete mode 100644 server/cmserver/conf/cm_ssl_cert.crt delete mode 100644 server/cmserver/conf/cm_ssl_cert.key delete mode 100644 server/cmserver/conf/cmdb.pass delete mode 100644 server/cmserver/conf/diagactivitytemplate.conf delete mode 100644 server/cmserver/conf/diagstatustemplate.conf delete mode 100644 server/external/openssl/linux_32/include/openssl/cms.h delete mode 100644 server/external/openssl/linux_64/include/openssl/cms.h delete mode 100644 server/external/openssl/linux_64/include/openssl/cmserr.h delete mode 100644 server/external/openssl/win_32/include/openssl/cms.h delete mode 100644 server/external/openssl/win_64/include/openssl/cms.h delete mode 100644 server/src/cm_auto_task.cpp delete mode 100644 server/src/cm_auto_task.h delete mode 100644 server/src/cm_autojob.cpp delete mode 100644 server/src/cm_autojob.h delete mode 100644 server/src/cm_cci_interface.cpp delete mode 100644 server/src/cm_cci_interface.h delete mode 100644 server/src/cm_cmd.cpp delete mode 100644 server/src/cm_cmd_exec.cpp delete mode 100644 server/src/cm_cmd_exec.h delete mode 100644 server/src/cm_cmd_task.cpp delete mode 100644 server/src/cm_cmd_task.h delete mode 100644 server/src/cm_cmd_util.cpp delete mode 100644 server/src/cm_cmd_util.h delete mode 100644 server/src/cm_compress.h delete mode 100644 server/src/cm_config.cpp delete mode 100644 server/src/cm_config.h delete mode 100644 server/src/cm_connect_info.cpp delete mode 100644 server/src/cm_connect_info.h delete mode 100644 server/src/cm_http_server.cpp delete mode 100644 server/src/cm_http_server.h delete mode 100644 server/src/cm_httpd.cpp delete mode 100644 server/src/cm_job_task.cpp delete mode 100644 server/src/cm_job_task.h delete mode 100644 server/src/cm_log.h delete mode 100644 server/src/cm_mailer.h delete mode 100644 server/src/cm_mon_stat.cpp delete mode 100644 server/src/cm_mon_stat.h delete mode 100644 server/src/cm_porting.h delete mode 100644 server/src/cm_server_autoupdate.cpp delete mode 100644 server/src/cm_server_autoupdate.h delete mode 100644 server/src/cm_server_extend_interface.cpp delete mode 100644 server/src/cm_server_extend_interface.h delete mode 100644 server/src/cm_server_interface.cpp delete mode 100644 server/src/cm_server_interface.h delete mode 100644 server/src/cm_server_stat.c delete mode 100644 server/src/cm_server_stat.h delete mode 100644 server/src/cm_server_util.cpp delete mode 100644 server/src/cm_server_util.h delete mode 100644 server/src/cm_text_encryption.c delete mode 100644 server/src/cm_text_encryption.h delete mode 100644 server/src/cm_user.cpp delete mode 100644 server/src/cm_user.h delete mode 100644 server/src/cm_win_wsa.c delete mode 100644 server/src/cm_win_wsa.h delete mode 100644 server/test/cm_mon_data/dump_data.py delete mode 100644 server/test/task_test_case_json/getcmsenv.txt delete mode 100644 server/test/task_test_config/cm_conf/arniadb_broker.conf delete mode 100644 server/test/task_test_config/cm_conf/autoaddvoldb.conf delete mode 100644 server/test/task_test_config/cm_conf/autobackupdb.conf delete mode 100644 server/test/task_test_config/cm_conf/autoexecquery.conf delete mode 100644 server/test/task_test_config/cm_conf/autohistory.conf delete mode 100644 server/test/task_test_config/cm_conf/cm.conf delete mode 100644 server/test/task_test_config/cm_conf/cm.pass delete mode 100644 server/win/cm_admin/cm_admin.vcproj delete mode 100644 server/win/cm_admin/resource.h delete mode 100644 server/win/cm_admin/version.rc delete mode 100644 server/win/cmserver.sln diff --git a/README.md b/README.md index b871473..c530929 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ # ARNIADB Manager Server System -ARNIADB Manager Server(CMS) is a part of ARNIADB Tools. +ARNIADB Manager Server(AMS) is a part of ARNIADB Tools. -CMS provides both HTTP or Socket interfaces for ARNIADB Manager +AMS provides both HTTP or Socket interfaces for ARNIADB Manager to managing ARNIADB system, and also provides monitoring information about ARNIADB system. ## MAJOR REFERENCES @@ -10,16 +10,16 @@ to managing ARNIADB system, and also provides monitoring information about ARNIA - ARNIADB Official Site: http://www.arniadb.org and http://www.arniadb.com ## DOWNLOADS and FILE REPOSITORIES -CMS is distributed within ARNIADB distribution which can be found here: +AMS is distributed within ARNIADB distribution which can be found here: - http://www.arniadb.org/downloads - http://ftp.arniadb.org -## HOW TO BUILD/INSTALL CMS +## HOW TO BUILD/INSTALL AMS ### build and install on Linux -Unzip the package of ARNIADB and you can find the source code of CMS here: arniadb-{version}/arniadbmanager/server. +Unzip the package of ARNIADB and you can find the source code of AMS here: arniadb-{version}/arniadbmanager/server. 1. Move to the directory where the source is stored. @@ -57,7 +57,7 @@ Unzip the package of ARNIADB and you can find the source code of CMS here: arnia ### build and install on windows -If you want to build CMS on windows, VS2008 must be installed. +If you want to build AMS on windows, VS2008 must be installed. 1. Open a commander "cmd.exe" and Move to the directory where the source is stored. @@ -78,7 +78,7 @@ If you want to build CMS on windows, VS2008 must be installed. ## PROGRAMMING APIs -- [CMS APIs](docs/api/README.md) +- [AMS APIs](docs/api/README.md) ## GETTING HELP @@ -88,4 +88,4 @@ questions, or find bugs, or have some suggestions, we kindly ask you to post your thoughts on our subreddit at https://www.reddit.com/r/ARNIADB/. Sincerely, -Your CMS Development Team. +Your AMS Development Team. diff --git a/docs/api/README.md b/docs/api/README.md index 692eefb..7b38248 100644 --- a/docs/api/README.md +++ b/docs/api/README.md @@ -2,20 +2,20 @@ ## Overview -The ARNIADB Manager Server (CMS) HTTP Interface is an interface that exists between the ARNIADB manager server and the application client, through which a web-based application client can access the ARNIADB manager server. The ARNIADB manager server delivers the request received from an application client to the ARNIADB, and transfers the execution result to the client. +The ARNIADB Manager Server (AMS) HTTP Interface is an interface that exists between the ARNIADB manager server and the application client, through which a web-based application client can access the ARNIADB manager server. The ARNIADB manager server delivers the request received from an application client to the ARNIADB, and transfers the execution result to the client. ## System Architecture -CMS is a manager tools for ARNIADB including database configure, monitor, SQL query. As the component of the ARNIADB Database Management System, CMS provides a web-based tool that allows users to remotely manage the database and the Broker. +AMS is a manager tools for ARNIADB including database configure, monitor, SQL query. As the component of the ARNIADB Database Management System, AMS provides a web-based tool that allows users to remotely manage the database and the Broker. -![CMS Architecture](images/architecture.png?raw=true "CMS Architecture") -CMS Architecture +![AMS Architecture](images/architecture.png?raw=true "AMS Architecture") +AMS Architecture ## Writing HTTP Application Program -CMS http interface is REST-like interface, client can POST JSON-format request to url `http://cms_ip:cms_port/cm_api`, and receive the execution result. +AMS http interface is REST-like interface, client can POST JSON-format request to url `http://ams_ip:ams_port/cm_api`, and receive the execution result. -The basic steps used for writing programs are as follows. First client must log in CMS with DBMT user name and password. If client login success, CMS will return a token which will be used in following request. The steps are implemented in example codes. +The basic steps used for writing programs are as follows. First client must log in AMS with DBMT user name and password. If client login success, AMS will return a token which will be used in following request. The steps are implemented in example codes. Example in Python Request: @@ -60,9 +60,9 @@ There are seven permissions. These permissions can indicate which authorities ar | ADMIN | Indicate the authority of admin | | ALL_AUTHORITY | This value is equal to "DBC | DBO | BRK | MON | JOB | VAR" | -## CMS Interfaces +## AMS Interfaces -CMs Interfaces are conposed by Json and is used for communication between CMS and Arniadb Manager. +AMS Interfaces are conposed by Json and is used for communication between AMS and Arniadb Manager. ### Broker @@ -226,6 +226,6 @@ CMs Interfaces are conposed by Json and is used for communication between CMS an | [getstandbyserverstat](getstandbyserverstat.md) | socket, http | ALL_AUTHORITY | | [login](login.md) | socket, http | ALL_AUTHORITY | | [logout](logout.md) | socket, http | ALL_AUTHORITY | -| [getcmsenv](getcmsenv.md) | socket, http | ALL_AUTHORITY | +| [getamsenv](getamsenv.md) | socket, http | ALL_AUTHORITY | | [shard_start](shard_start.md) | socket, http | DBC, DBO, BRK | | [shard_stop](shard_stop.md) | socket, http | DBC, DBO, BRK | diff --git a/docs/api/getcmsenv.md b/docs/api/getcmsenv.md deleted file mode 100644 index 103c84f..0000000 --- a/docs/api/getcmsenv.md +++ /dev/null @@ -1,20 +0,0 @@ -# getcmsenv - -Get databases' information in arniadb. - -## Request Json Syntax - -| **Key** | **Description** | -| --- | --- | -| task | task name | -| token | token string encrypted. | - - -## Request Sample - -``` -{ - "task":"getcmsenv", - "token":"4504b930fc1be99bf5dfd31fc5799faaa3f117fb903f397de087cd3544165d857926f07dd201b6aa" - } -``` diff --git a/docs/api/monitorprocess.md b/docs/api/monitorprocess.md index 21c3ed0..d383ec8 100644 --- a/docs/api/monitorprocess.md +++ b/docs/api/monitorprocess.md @@ -1,6 +1,6 @@ # monitorprocess -Monitor CMS process status. +Monitor AMS process status. ## Request Json Syntax diff --git a/server/Makefile.am b/server/Makefile.am index e4514c6..6d04705 100644 --- a/server/Makefile.am +++ b/server/Makefile.am @@ -18,6 +18,6 @@ # AUTOMAKE_OPTIONS = foreign -SUBDIRS = cmserver external +SUBDIRS = amserver external EXTRA_DIST = BUILD_NUMBER autogen.sh build_internal.bat build.bat build_server.bat build_external.sh test win src diff --git a/server/build_cms_env.sh b/server/build_cms_env.sh deleted file mode 100644 index 4196b42..0000000 --- a/server/build_cms_env.sh +++ /dev/null @@ -1,70 +0,0 @@ -#!/bin/bash - -if [ -z $JAVA_HOME ] -then - echo "WE NEED JAVA_HOME";exit 1; -fi - -yum install ant - -#build libevent -wget http://cloud.github.com/downloads/libevent/libevent/libevent-2.0.18-stable.tar.gz -tar zxvf libevent-2.0.18-stable.tar.gz -cd libevent-2.0.18-stable -./configure;make;make install - -cd .. - -#build jsoncpp -wget http://nchc.dl.sourceforge.net/project/jsoncpp/jsoncpp/0.5.0/jsoncpp-src-0.5.0.tar.gz -tar zxvf jsoncpp-src-0.5.0.tar.gz -cd jsoncpp-src-0.5.0 -g++ -o src/lib_json/json_reader.o -c -Wall -Iinclude src/lib_json/json_reader.cpp -g++ -o src/lib_json/json_value.o -c -Wall -Iinclude src/lib_json/json_value.cpp -g++ -o src/lib_json/json_writer.o -c -Wall -Iinclude src/lib_json/json_writer.cpp -ar rc src/lib_json/libjson.a src/lib_json/json_reader.o src/lib_json/json_value.o src/lib_json/json_writer.o -ranlib src/lib_json/libjson.a -cp -r include/json /usr/local/include -cp src/lib_json/libjson.a /usr/local/lib - -cd .. - -#build arniadb -wget ftp://ftp.arniadb.org/ARNIADB_Engine/8.4.1/Linux/ARNIADB-8.4.1.2032.src.tar.gz -tar xzvf ARNIADB-8.4.1.2032.src.tar.gz - -cd arniadb-8.4.1.2032 -./configure --enable-64bit --enable-debug -make -make install - -#configure arniadb env - -cat >> .arniadb.sh << EOF -#!/bin/bash -ARNIADB=/root/arniadb -ARNIADB_DATABASES=/root/arniadb/databases -ARNIADB_LANG=en_US -ld_lib_path=`printenv LD_LIBRARY_PATH` -if [ "$ld_lib_path" = "" ] -then -LD_LIBRARY_PATH=$ARNIADB/lib -else -LD_LIBRARY_PATH=$ARNIADB/lib:$LD_LIBRARY_PATH -fi -SHLIB_PATH=$LD_LIBRARY_PATH -LIBPATH=$LD_LIBRARY_PATH -PATH=$ARNIADB/bin:$ARNIADB/arniadbmanager:$PATH -export ARNIADB -export ARNIADB_DATABASES -export ARNIADB_LANG -export LD_LIBRARY_PATH -export SHLIB_PATH -export LIBPATH -export PATH -EOF -chmod +x .arniadb.sh -./.arniadb.sh - -mkdir $ARNIADB_DATABASES - diff --git a/server/build_server.bat b/server/build_server.bat index ea806a2..2d12219 100644 --- a/server/build_server.bat +++ b/server/build_server.bat @@ -10,13 +10,13 @@ cd win set arniadb_libdir=%arniadb_libdir% set arniadb_includedir=%arniadb_includedir% -cmd /c devenv cmserver.sln /project install /rebuild "%mode%|%platform%" +cmd /c devenv amserver.sln /project install /rebuild "%mode%|%platform%" set exitcode=%errorlevel% cd .. if not "%exitcode%" == "0" exit /b %exitcode% cd win/install -cd CMServer_%mode%_%platform% +cd AMServer_%mode%_%platform% robocopy . %prefix%\ /e if errorlevel 1 ( diff --git a/server/cmserver/Makefile.am b/server/cmserver/Makefile.am deleted file mode 100644 index 28f5f95..0000000 --- a/server/cmserver/Makefile.am +++ /dev/null @@ -1,62 +0,0 @@ - -# -# Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. -# -# 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 Street, Fifth Floor, Boston, MA 02110-1301 USA -# - - -SUBDIRS = conf - -SRC = $(top_srcdir)/src -DBMT_DIR = $(SRC) - -INCLUDES = @SRC_INC@ -DEFS += @SYS_DEFS@ @VERSION_DEFS@ @COMMON_DEFS@ -LIBS += @SYS_LIBS@ - -bin_PROGRAMS = cm_admin arn_manager - -cm_admin_SOURCES = \ - $(DBMT_DIR)/cm_text_encryption.c \ - $(DBMT_DIR)/cm_config.cpp \ - $(DBMT_DIR)/cm_server_util.cpp \ - $(DBMT_DIR)/cm_user.cpp \ - $(DBMT_DIR)/cm_cmd.cpp \ - $(DBMT_DIR)/cm_cmd_util.cpp \ - $(DBMT_DIR)/cm_connect_info.cpp \ - $(DBMT_DIR)/cm_cmd_task.cpp -cm_admin_CFLAGS = -D_FILE_OFFSET_BITS=64 -cm_admin_LDFLAGS = @CMDEP_LIB@ -D_FILE_OFFSET_BITS=64 - -arn_manager_SOURCES = \ - $(DBMT_DIR)/cm_server_util.cpp \ - $(DBMT_DIR)/cm_autojob.cpp \ - $(DBMT_DIR)/cm_text_encryption.c \ - $(DBMT_DIR)/cm_config.cpp \ - $(DBMT_DIR)/cm_job_task.cpp \ - $(DBMT_DIR)/cm_cmd_exec.cpp \ - $(DBMT_DIR)/cm_connect_info.cpp \ - $(DBMT_DIR)/cm_auto_task.cpp \ - $(DBMT_DIR)/cm_httpd.cpp \ - $(DBMT_DIR)/cm_mon_stat.cpp \ - $(DBMT_DIR)/cm_user.cpp \ - $(DBMT_DIR)/cm_http_server.cpp \ - $(DBMT_DIR)/cm_server_extend_interface.cpp \ - $(DBMT_DIR)/cm_server_interface.cpp \ - $(DBMT_DIR)/cm_cci_interface.cpp \ - $(DBMT_DIR)/cm_server_autoupdate.cpp -arn_manager_CPPFLAGS = $(AM_CFLAGS) -DFSERVER_SLAVE -DJSON_SUPPORT -DEVENT__HAVE_OPENSSL -D_FILE_OFFSET_BITS=64 @EXTERNAL_INC@ -arn_manager_LDFLAGS = -larniadbcs @CMSTAT_LIB@ @CMDEP_LIB@ @EXTERNAL_LIB@ -lrt -lcascci diff --git a/server/cmserver/conf/Makefile.am b/server/cmserver/conf/Makefile.am deleted file mode 100644 index cb61221..0000000 --- a/server/cmserver/conf/Makefile.am +++ /dev/null @@ -1,23 +0,0 @@ - -# -# Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. -# -# 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; version 2 of the License. -# -# 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 Street, Fifth Floor, Boston, MA 02110-1301, USA -# - - -confdir = ${prefix}/conf -dist_conf_DATA = autohistory.conf cmdb.pass autoaddvoldb.conf diagactivitytemplate.conf autobackupdb.conf cm.conf diagstatustemplate.conf autoexecquery.conf cm.pass \ - cm_ssl_cert.crt cm_ssl_cert.key - diff --git a/server/cmserver/conf/autoaddvoldb.conf b/server/cmserver/conf/autoaddvoldb.conf deleted file mode 100644 index e69de29..0000000 diff --git a/server/cmserver/conf/autobackupdb.conf b/server/cmserver/conf/autobackupdb.conf deleted file mode 100644 index e69de29..0000000 diff --git a/server/cmserver/conf/autoexecquery.conf b/server/cmserver/conf/autoexecquery.conf deleted file mode 100644 index e69de29..0000000 diff --git a/server/cmserver/conf/autohistory.conf b/server/cmserver/conf/autohistory.conf deleted file mode 100644 index e69de29..0000000 diff --git a/server/cmserver/conf/cm.conf b/server/cmserver/conf/cm.conf deleted file mode 100644 index 9db30d1..0000000 --- a/server/cmserver/conf/cm.conf +++ /dev/null @@ -1,67 +0,0 @@ -# cm.conf -# -- ARNIADB database management tool server configuration file -# -# -# When server starts, it looks for the environment variable -# 'ARNIADB_MANAGER' and use it to locate this file. It is assumed that -# 'ARNIADB_MANAGER' is the root directory of all ARNIADB Manager related files. -# -# Manager server section - a section for 'arniadb service' command -# Common section - properties for ARNIADB Manager Server -# This section will be applied before starting manager server. -[cm] -# -# Port number designation -# A port for the connection between ARNIADB Manager server and Client. -# ARNIADB Manager server uses the value cm_port. -# The default value is 8001. -# -cm_port=8001 - -# -# CMS Process Monitoring interval setting -# -cm_process_monitor_interval=5 - -# -# Allowing Multiple connection with one ARNIADB Manager user. -# -allow_user_multi_connection=YES - -############################### -# diagnostics parameter -############################### -# -# turn ON/OFF diag -# -#execute_diag=ON - -# -# server long query time (sec) -# -server_long_query_time=10 - -# -# Auto jobs execution timeout (sec) -# Default value: 43200 (12 hours) -# Minimum value: 60 -auto_job_timeout=43200 - -# -# Define token active time(session timeout), default value is 7200. -# -#token_active_time=7200 - -# -# support monitoring statistic (YES/NO), default NO -# If you want to use the advanced monitoring feature on ARNIADB Manager, -# you should set this value to YES. -# -support_mon_statistic=NO - -# -# max log file number: default 10 -# When the log files is more than max_log_files, -# The oldest log will be removed. -# -max_log_files=10 diff --git a/server/cmserver/conf/cm.pass b/server/cmserver/conf/cm.pass deleted file mode 100644 index 58ecec1..0000000 --- a/server/cmserver/conf/cm.pass +++ /dev/null @@ -1 +0,0 @@ -admin:6e85f0f80f030451dc9e98851098dfb2 diff --git a/server/cmserver/conf/cm_ssl_cert.crt b/server/cmserver/conf/cm_ssl_cert.crt deleted file mode 100644 index a72d8d3..0000000 --- a/server/cmserver/conf/cm_ssl_cert.crt +++ /dev/null @@ -1,14 +0,0 @@ ------BEGIN CERTIFICATE----- -MIICDzCCAXgCCQDO8wrRT6KVNzANBgkqhkiG9w0BAQUFADBMMQswCQYDVQQGEwJD -TjESMBAGA1UECBMJQmVya3NoaXJlMRAwDgYDVQQHEwdOZXdidXJ5MRcwFQYDVQQK -Ew5NeSBDb21wYW55IEx0ZDAeFw0xMjAzMDcwNzIwMDdaFw0xMzAzMDcwNzIwMDda -MEwxCzAJBgNVBAYTAkNOMRIwEAYDVQQIEwlCZXJrc2hpcmUxEDAOBgNVBAcTB05l -d2J1cnkxFzAVBgNVBAoTDk15IENvbXBhbnkgTHRkMIGfMA0GCSqGSIb3DQEBAQUA -A4GNADCBiQKBgQDyhIO7i4Xitj43+7VOyhez8FOQGafRfAlIzIoGKTF3WbmQB2ir -LTfs1vCPb28G40t49yFAxb/4XbKRlRhmVfHDqIrcZoPVDJ/01hfYPEzzOy02XEBH -x0jUqfbVkuS1Wr59afcqzciY2oQ1GrBAFvwwJiagDWfE8D9F+bSPyTF7jQIDAQAB -MA0GCSqGSIb3DQEBBQUAA4GBAIUq4xzJ8FS+ArVPYP+8Rf0OciSpdOYngeT4xWox -2AQdgTRs+1DS0M3jePqztPYc88acPGQrpkLeZqu2ICK5FMdEHBA8kPVCpJne7Oqh -Tqdc6j0MIYUVBN8cxQKO1XhTrh6qz26nDF4erXzt2txiPRhKqR4Tw0ekSkUeUHqb -DnWR ------END CERTIFICATE----- diff --git a/server/cmserver/conf/cm_ssl_cert.key b/server/cmserver/conf/cm_ssl_cert.key deleted file mode 100644 index 62fec17..0000000 --- a/server/cmserver/conf/cm_ssl_cert.key +++ /dev/null @@ -1,15 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIICXQIBAAKBgQDyhIO7i4Xitj43+7VOyhez8FOQGafRfAlIzIoGKTF3WbmQB2ir -LTfs1vCPb28G40t49yFAxb/4XbKRlRhmVfHDqIrcZoPVDJ/01hfYPEzzOy02XEBH -x0jUqfbVkuS1Wr59afcqzciY2oQ1GrBAFvwwJiagDWfE8D9F+bSPyTF7jQIDAQAB -AoGBALPC6epgNzOfJmtU1kW6ousr3qTXf39V04P0qPJ8IkB3b4aFF16au/OANvv6 -+289l7noZOugKPWubihfPaDNX8/YgWDT35tbwnu8ObL46oOGdChhTkoe0wqYmkXq -U2WVIpjip+f60AZYxDL5EDFrUvnBeG1QX9kRahiGbi8vTbZ5AkEA+T2fW47Bovnu -pTNP4uzKahjEt0Xu4sr4lvZ/r+24p23OgPtIU5Rajt7LUoNoRDW898Ht1v4iSFjP -FbeEP4NMSwJBAPkYN2skC4WRtMnsHWuMgiWD9evP4rcJwb9wBcKfNmnPXELk9RY2 -o+pkmwxyDhhV4TQNXsPe/Oat7fSTBGe0wIcCQQCsakyK8b5SF8NW1KA2wsdjja7H -ecE/cll1VSAPe8t5RyTLZQkriDz9CHJuqii+xs3qNmVpjHP6yDS5OTJrHVDxAkAp -lq96BfSegmtK408uK7F3Dgc7LeROZySgD9YGXoq5M9PVn2CEKu9HLTDt7QUJbx1A -kZLm5Q4YfaWjFgDAR991AkBysGv1IfMuTXJ+zEHfFzykwKB/f7q+JfmkrxalWbuL -pQkRp+3VqXPtHm8LR2yeOhk6c3mEi8EJBlFH8J0cixoz ------END RSA PRIVATE KEY----- diff --git a/server/cmserver/conf/cmdb.pass b/server/cmserver/conf/cmdb.pass deleted file mode 100644 index 3cf35aa..0000000 --- a/server/cmserver/conf/cmdb.pass +++ /dev/null @@ -1,4 +0,0 @@ -<<<:admin -unicas:admin -dbcreate:admin ->>>:admin diff --git a/server/cmserver/conf/diagactivitytemplate.conf b/server/cmserver/conf/diagactivitytemplate.conf deleted file mode 100644 index e69de29..0000000 diff --git a/server/cmserver/conf/diagstatustemplate.conf b/server/cmserver/conf/diagstatustemplate.conf deleted file mode 100644 index af78492..0000000 --- a/server/cmserver/conf/diagstatustemplate.conf +++ /dev/null @@ -1,9 +0,0 @@ -<<< -broker_template -status monitor template of broker - -1 -cas_st_request 1 0.1 -cas_st_transaction 7 0.1 -cas_st_active_session 3 0.1 ->>> diff --git a/server/configure.ac b/server/configure.ac index 3ab88d2..50d0176 100644 --- a/server/configure.ac +++ b/server/configure.ac @@ -52,7 +52,7 @@ export SYSTEM_TYPE MACHINE_TYPE case $SYSTEM_TYPE in *linux*) SYS_DEFS="-DGCC -DLINUX -D_GNU_SOURCE -DI386" SYS_LIBS="" - CMSTAT_LIB="" + AMSTAT_LIB="" if test "$bit_model" = "yes" then BIT_MODEL="-m64" @@ -65,7 +65,7 @@ case $SYSTEM_TYPE in *aix*) SYS_DEFS="-DGCC -DAIX -D_GNU_SOURCE -DPPC -fsigned-char -D_THREAD_SAFE" SYS_LIBS="-Wl,-bmaxdata:0x800000000 -Wl,-bnoipath" - CMSTAT_LIB="-lperfstat" + AMSTAT_LIB="-lperfstat" CC="$CC -pthread" CXX="$CXX -pthread" if test "$enable_64bit" = "yes" @@ -248,7 +248,7 @@ else fi ARNCS_LIB="-larniadbcs" CMDEP_LIB="-L$ARNIADB_LIBDIR -lcmdep $ARNCS_LIB" - CMSTAT_LIB="-L$ARNIADB_LIBDIR -lcmstat $CMSTAT_LIB" + AMSTAT_LIB="-L$ARNIADB_LIBDIR -lamstat $AMSTAT_LIB" SRC_INC="-I$ARNIADB_INCLUDEDIR" fi @@ -303,7 +303,7 @@ AC_SUBST([SYS_LIBS]) AC_SUBST([COMMON_DEFS]) AC_SUBST([VERSION_DEFS]) AC_SUBST([SRC_INC]) -AC_SUBST([CMSTAT_LIB]) +AC_SUBST([AMSTAT_LIB]) AC_SUBST([CMDEP_LIB]) AC_SUBST([EXTERNAL_LIB]) AC_SUBST([EXTERNAL_INC]) @@ -323,6 +323,6 @@ AH_BOTTOM([ AC_CONFIG_FILES([Makefile external/Makefile - cmserver/Makefile - cmserver/conf/Makefile]) + amserver/Makefile + amserver/conf/Makefile]) AC_OUTPUT diff --git a/server/external/README b/server/external/README index a3ddbcb..518ecdf 100644 --- a/server/external/README +++ b/server/external/README @@ -1,6 +1,6 @@ ARNIADB Manager Server System ============================= -ARNIADB Manager Server(CMS) use some 3rd software, like openssl, libevent and json. +ARNIADB Manager Server(AMS) use some 3rd software, like openssl, libevent and json. The following is steps to compile them by yourself. ============== @@ -74,4 +74,4 @@ nmake OPENSSL_DIR=F:\openssl /f Makefile.nmake Sincerely, -Your CMS Development Team. +Your AMS Development Team. diff --git a/server/external/openssl/aix_64/include/openssl/asn1.h b/server/external/openssl/aix_64/include/openssl/asn1.h index 7a5ae68..ca91ead 100644 --- a/server/external/openssl/aix_64/include/openssl/asn1.h +++ b/server/external/openssl/aix_64/include/openssl/asn1.h @@ -240,7 +240,7 @@ typedef struct asn1_object_st */ #define ASN1_STRING_FLAG_NDEF 0x010 -/* This flag is used by the CMS code to indicate that a string is not +/* This flag is used by the AMS code to indicate that a string is not * complete and is a place holder for content when it had all been * accessed. The flag will be reset when content has been written to it. */ diff --git a/server/external/openssl/aix_64/include/openssl/err.h b/server/external/openssl/aix_64/include/openssl/err.h index e5422df..ed841ba 100644 --- a/server/external/openssl/aix_64/include/openssl/err.h +++ b/server/external/openssl/aix_64/include/openssl/err.h @@ -157,7 +157,7 @@ typedef struct err_state_st #define ERR_LIB_ECDH 43 #define ERR_LIB_STORE 44 #define ERR_LIB_FIPS 45 -#define ERR_LIB_CMS 46 +#define ERR_LIB_AMS 46 #define ERR_LIB_JPAKE 47 #define ERR_LIB_USER 128 @@ -191,7 +191,7 @@ typedef struct err_state_st #define ECDHerr(f,r) ERR_PUT_error(ERR_LIB_ECDH,(f),(r),__FILE__,__LINE__) #define STOREerr(f,r) ERR_PUT_error(ERR_LIB_STORE,(f),(r),__FILE__,__LINE__) #define FIPSerr(f,r) ERR_PUT_error(ERR_LIB_FIPS,(f),(r),__FILE__,__LINE__) -#define CMSerr(f,r) ERR_PUT_error(ERR_LIB_CMS,(f),(r),__FILE__,__LINE__) +#define AMSerr(f,r) ERR_PUT_error(ERR_LIB_AMS,(f),(r),__FILE__,__LINE__) #define JPAKEerr(f,r) ERR_PUT_error(ERR_LIB_JPAKE,(f),(r),__FILE__,__LINE__) /* Borland C seems too stupid to be able to shift and do longs in diff --git a/server/external/openssl/aix_64/include/openssl/obj_mac.h b/server/external/openssl/aix_64/include/openssl/obj_mac.h index e85417a..c9d18dc 100644 --- a/server/external/openssl/aix_64/include/openssl/obj_mac.h +++ b/server/external/openssl/aix_64/include/openssl/obj_mac.h @@ -781,9 +781,9 @@ #define NID_id_smime_cti 195 #define OBJ_id_smime_cti OBJ_SMIME,6L -#define SN_id_smime_mod_cms "id-smime-mod-cms" -#define NID_id_smime_mod_cms 196 -#define OBJ_id_smime_mod_cms OBJ_id_smime_mod,1L +#define SN_id_smime_mod_ams "id-smime-mod-ams" +#define NID_id_smime_mod_ams 196 +#define OBJ_id_smime_mod_ams OBJ_id_smime_mod,1L #define SN_id_smime_mod_ess "id-smime-mod-ess" #define NID_id_smime_mod_ess 197 @@ -989,13 +989,13 @@ #define NID_id_smime_alg_ESDH 245 #define OBJ_id_smime_alg_ESDH OBJ_id_smime_alg,5L -#define SN_id_smime_alg_CMS3DESwrap "id-smime-alg-CMS3DESwrap" -#define NID_id_smime_alg_CMS3DESwrap 246 -#define OBJ_id_smime_alg_CMS3DESwrap OBJ_id_smime_alg,6L +#define SN_id_smime_alg_AMS3DESwrap "id-smime-alg-AMS3DESwrap" +#define NID_id_smime_alg_AMS3DESwrap 246 +#define OBJ_id_smime_alg_AMS3DESwrap OBJ_id_smime_alg,6L -#define SN_id_smime_alg_CMSRC2wrap "id-smime-alg-CMSRC2wrap" -#define NID_id_smime_alg_CMSRC2wrap 247 -#define OBJ_id_smime_alg_CMSRC2wrap OBJ_id_smime_alg,7L +#define SN_id_smime_alg_AMSRC2wrap "id-smime-alg-AMSRC2wrap" +#define NID_id_smime_alg_AMSRC2wrap 247 +#define OBJ_id_smime_alg_AMSRC2wrap OBJ_id_smime_alg,7L #define SN_id_smime_cd_ldap "id-smime-cd-ldap" #define NID_id_smime_cd_ldap 248 diff --git a/server/external/openssl/aix_64/include/openssl/opensslconf.h b/server/external/openssl/aix_64/include/openssl/opensslconf.h index b3b1c8d..d083e89 100644 --- a/server/external/openssl/aix_64/include/openssl/opensslconf.h +++ b/server/external/openssl/aix_64/include/openssl/opensslconf.h @@ -30,8 +30,8 @@ #ifndef OPENSSL_NO_CAPIENG # define OPENSSL_NO_CAPIENG #endif -#ifndef OPENSSL_NO_CMS -# define OPENSSL_NO_CMS +#ifndef OPENSSL_NO_AMS +# define OPENSSL_NO_AMS #endif #ifndef OPENSSL_NO_EC # define OPENSSL_NO_EC @@ -87,8 +87,8 @@ # if defined(OPENSSL_NO_CAPIENG) && !defined(NO_CAPIENG) # define NO_CAPIENG # endif -# if defined(OPENSSL_NO_CMS) && !defined(NO_CMS) -# define NO_CMS +# if defined(OPENSSL_NO_AMS) && !defined(NO_AMS) +# define NO_AMS # endif # if defined(OPENSSL_NO_EC) && !defined(NO_EC) # define NO_EC diff --git a/server/external/openssl/aix_64/include/openssl/pem.h b/server/external/openssl/aix_64/include/openssl/pem.h index f42ecaa..6195e44 100644 --- a/server/external/openssl/aix_64/include/openssl/pem.h +++ b/server/external/openssl/aix_64/include/openssl/pem.h @@ -150,7 +150,7 @@ extern "C" { #define PEM_STRING_ECDSA_PUBLIC "ECDSA PUBLIC KEY" #define PEM_STRING_ECPARAMETERS "EC PARAMETERS" #define PEM_STRING_ECPRIVATEKEY "EC PRIVATE KEY" -#define PEM_STRING_CMS "CMS" +#define PEM_STRING_AMS "AMS" /* Note that this structure is initialised by PEM_SealInit and cleaned up by PEM_SealFinal (at least for now) */ diff --git a/server/external/openssl/aix_64/include/openssl/safestack.h b/server/external/openssl/aix_64/include/openssl/safestack.h index 53440d9..a340a98 100644 --- a/server/external/openssl/aix_64/include/openssl/safestack.h +++ b/server/external/openssl/aix_64/include/openssl/safestack.h @@ -430,93 +430,93 @@ STACK_OF(type) \ #define sk_BIO_sort(st) SKM_sk_sort(BIO, (st)) #define sk_BIO_is_sorted(st) SKM_sk_is_sorted(BIO, (st)) -#define sk_CMS_CertificateChoices_new(st) SKM_sk_new(CMS_CertificateChoices, (st)) -#define sk_CMS_CertificateChoices_new_null() SKM_sk_new_null(CMS_CertificateChoices) -#define sk_CMS_CertificateChoices_free(st) SKM_sk_free(CMS_CertificateChoices, (st)) -#define sk_CMS_CertificateChoices_num(st) SKM_sk_num(CMS_CertificateChoices, (st)) -#define sk_CMS_CertificateChoices_value(st, i) SKM_sk_value(CMS_CertificateChoices, (st), (i)) -#define sk_CMS_CertificateChoices_set(st, i, val) SKM_sk_set(CMS_CertificateChoices, (st), (i), (val)) -#define sk_CMS_CertificateChoices_zero(st) SKM_sk_zero(CMS_CertificateChoices, (st)) -#define sk_CMS_CertificateChoices_push(st, val) SKM_sk_push(CMS_CertificateChoices, (st), (val)) -#define sk_CMS_CertificateChoices_unshift(st, val) SKM_sk_unshift(CMS_CertificateChoices, (st), (val)) -#define sk_CMS_CertificateChoices_find(st, val) SKM_sk_find(CMS_CertificateChoices, (st), (val)) -#define sk_CMS_CertificateChoices_find_ex(st, val) SKM_sk_find_ex(CMS_CertificateChoices, (st), (val)) -#define sk_CMS_CertificateChoices_delete(st, i) SKM_sk_delete(CMS_CertificateChoices, (st), (i)) -#define sk_CMS_CertificateChoices_delete_ptr(st, ptr) SKM_sk_delete_ptr(CMS_CertificateChoices, (st), (ptr)) -#define sk_CMS_CertificateChoices_insert(st, val, i) SKM_sk_insert(CMS_CertificateChoices, (st), (val), (i)) -#define sk_CMS_CertificateChoices_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(CMS_CertificateChoices, (st), (cmp)) -#define sk_CMS_CertificateChoices_dup(st) SKM_sk_dup(CMS_CertificateChoices, st) -#define sk_CMS_CertificateChoices_pop_free(st, free_func) SKM_sk_pop_free(CMS_CertificateChoices, (st), (free_func)) -#define sk_CMS_CertificateChoices_shift(st) SKM_sk_shift(CMS_CertificateChoices, (st)) -#define sk_CMS_CertificateChoices_pop(st) SKM_sk_pop(CMS_CertificateChoices, (st)) -#define sk_CMS_CertificateChoices_sort(st) SKM_sk_sort(CMS_CertificateChoices, (st)) -#define sk_CMS_CertificateChoices_is_sorted(st) SKM_sk_is_sorted(CMS_CertificateChoices, (st)) - -#define sk_CMS_RecipientInfo_new(st) SKM_sk_new(CMS_RecipientInfo, (st)) -#define sk_CMS_RecipientInfo_new_null() SKM_sk_new_null(CMS_RecipientInfo) -#define sk_CMS_RecipientInfo_free(st) SKM_sk_free(CMS_RecipientInfo, (st)) -#define sk_CMS_RecipientInfo_num(st) SKM_sk_num(CMS_RecipientInfo, (st)) -#define sk_CMS_RecipientInfo_value(st, i) SKM_sk_value(CMS_RecipientInfo, (st), (i)) -#define sk_CMS_RecipientInfo_set(st, i, val) SKM_sk_set(CMS_RecipientInfo, (st), (i), (val)) -#define sk_CMS_RecipientInfo_zero(st) SKM_sk_zero(CMS_RecipientInfo, (st)) -#define sk_CMS_RecipientInfo_push(st, val) SKM_sk_push(CMS_RecipientInfo, (st), (val)) -#define sk_CMS_RecipientInfo_unshift(st, val) SKM_sk_unshift(CMS_RecipientInfo, (st), (val)) -#define sk_CMS_RecipientInfo_find(st, val) SKM_sk_find(CMS_RecipientInfo, (st), (val)) -#define sk_CMS_RecipientInfo_find_ex(st, val) SKM_sk_find_ex(CMS_RecipientInfo, (st), (val)) -#define sk_CMS_RecipientInfo_delete(st, i) SKM_sk_delete(CMS_RecipientInfo, (st), (i)) -#define sk_CMS_RecipientInfo_delete_ptr(st, ptr) SKM_sk_delete_ptr(CMS_RecipientInfo, (st), (ptr)) -#define sk_CMS_RecipientInfo_insert(st, val, i) SKM_sk_insert(CMS_RecipientInfo, (st), (val), (i)) -#define sk_CMS_RecipientInfo_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(CMS_RecipientInfo, (st), (cmp)) -#define sk_CMS_RecipientInfo_dup(st) SKM_sk_dup(CMS_RecipientInfo, st) -#define sk_CMS_RecipientInfo_pop_free(st, free_func) SKM_sk_pop_free(CMS_RecipientInfo, (st), (free_func)) -#define sk_CMS_RecipientInfo_shift(st) SKM_sk_shift(CMS_RecipientInfo, (st)) -#define sk_CMS_RecipientInfo_pop(st) SKM_sk_pop(CMS_RecipientInfo, (st)) -#define sk_CMS_RecipientInfo_sort(st) SKM_sk_sort(CMS_RecipientInfo, (st)) -#define sk_CMS_RecipientInfo_is_sorted(st) SKM_sk_is_sorted(CMS_RecipientInfo, (st)) - -#define sk_CMS_RevocationInfoChoice_new(st) SKM_sk_new(CMS_RevocationInfoChoice, (st)) -#define sk_CMS_RevocationInfoChoice_new_null() SKM_sk_new_null(CMS_RevocationInfoChoice) -#define sk_CMS_RevocationInfoChoice_free(st) SKM_sk_free(CMS_RevocationInfoChoice, (st)) -#define sk_CMS_RevocationInfoChoice_num(st) SKM_sk_num(CMS_RevocationInfoChoice, (st)) -#define sk_CMS_RevocationInfoChoice_value(st, i) SKM_sk_value(CMS_RevocationInfoChoice, (st), (i)) -#define sk_CMS_RevocationInfoChoice_set(st, i, val) SKM_sk_set(CMS_RevocationInfoChoice, (st), (i), (val)) -#define sk_CMS_RevocationInfoChoice_zero(st) SKM_sk_zero(CMS_RevocationInfoChoice, (st)) -#define sk_CMS_RevocationInfoChoice_push(st, val) SKM_sk_push(CMS_RevocationInfoChoice, (st), (val)) -#define sk_CMS_RevocationInfoChoice_unshift(st, val) SKM_sk_unshift(CMS_RevocationInfoChoice, (st), (val)) -#define sk_CMS_RevocationInfoChoice_find(st, val) SKM_sk_find(CMS_RevocationInfoChoice, (st), (val)) -#define sk_CMS_RevocationInfoChoice_find_ex(st, val) SKM_sk_find_ex(CMS_RevocationInfoChoice, (st), (val)) -#define sk_CMS_RevocationInfoChoice_delete(st, i) SKM_sk_delete(CMS_RevocationInfoChoice, (st), (i)) -#define sk_CMS_RevocationInfoChoice_delete_ptr(st, ptr) SKM_sk_delete_ptr(CMS_RevocationInfoChoice, (st), (ptr)) -#define sk_CMS_RevocationInfoChoice_insert(st, val, i) SKM_sk_insert(CMS_RevocationInfoChoice, (st), (val), (i)) -#define sk_CMS_RevocationInfoChoice_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(CMS_RevocationInfoChoice, (st), (cmp)) -#define sk_CMS_RevocationInfoChoice_dup(st) SKM_sk_dup(CMS_RevocationInfoChoice, st) -#define sk_CMS_RevocationInfoChoice_pop_free(st, free_func) SKM_sk_pop_free(CMS_RevocationInfoChoice, (st), (free_func)) -#define sk_CMS_RevocationInfoChoice_shift(st) SKM_sk_shift(CMS_RevocationInfoChoice, (st)) -#define sk_CMS_RevocationInfoChoice_pop(st) SKM_sk_pop(CMS_RevocationInfoChoice, (st)) -#define sk_CMS_RevocationInfoChoice_sort(st) SKM_sk_sort(CMS_RevocationInfoChoice, (st)) -#define sk_CMS_RevocationInfoChoice_is_sorted(st) SKM_sk_is_sorted(CMS_RevocationInfoChoice, (st)) - -#define sk_CMS_SignerInfo_new(st) SKM_sk_new(CMS_SignerInfo, (st)) -#define sk_CMS_SignerInfo_new_null() SKM_sk_new_null(CMS_SignerInfo) -#define sk_CMS_SignerInfo_free(st) SKM_sk_free(CMS_SignerInfo, (st)) -#define sk_CMS_SignerInfo_num(st) SKM_sk_num(CMS_SignerInfo, (st)) -#define sk_CMS_SignerInfo_value(st, i) SKM_sk_value(CMS_SignerInfo, (st), (i)) -#define sk_CMS_SignerInfo_set(st, i, val) SKM_sk_set(CMS_SignerInfo, (st), (i), (val)) -#define sk_CMS_SignerInfo_zero(st) SKM_sk_zero(CMS_SignerInfo, (st)) -#define sk_CMS_SignerInfo_push(st, val) SKM_sk_push(CMS_SignerInfo, (st), (val)) -#define sk_CMS_SignerInfo_unshift(st, val) SKM_sk_unshift(CMS_SignerInfo, (st), (val)) -#define sk_CMS_SignerInfo_find(st, val) SKM_sk_find(CMS_SignerInfo, (st), (val)) -#define sk_CMS_SignerInfo_find_ex(st, val) SKM_sk_find_ex(CMS_SignerInfo, (st), (val)) -#define sk_CMS_SignerInfo_delete(st, i) SKM_sk_delete(CMS_SignerInfo, (st), (i)) -#define sk_CMS_SignerInfo_delete_ptr(st, ptr) SKM_sk_delete_ptr(CMS_SignerInfo, (st), (ptr)) -#define sk_CMS_SignerInfo_insert(st, val, i) SKM_sk_insert(CMS_SignerInfo, (st), (val), (i)) -#define sk_CMS_SignerInfo_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(CMS_SignerInfo, (st), (cmp)) -#define sk_CMS_SignerInfo_dup(st) SKM_sk_dup(CMS_SignerInfo, st) -#define sk_CMS_SignerInfo_pop_free(st, free_func) SKM_sk_pop_free(CMS_SignerInfo, (st), (free_func)) -#define sk_CMS_SignerInfo_shift(st) SKM_sk_shift(CMS_SignerInfo, (st)) -#define sk_CMS_SignerInfo_pop(st) SKM_sk_pop(CMS_SignerInfo, (st)) -#define sk_CMS_SignerInfo_sort(st) SKM_sk_sort(CMS_SignerInfo, (st)) -#define sk_CMS_SignerInfo_is_sorted(st) SKM_sk_is_sorted(CMS_SignerInfo, (st)) +#define sk_AMS_CertificateChoices_new(st) SKM_sk_new(AMS_CertificateChoices, (st)) +#define sk_AMS_CertificateChoices_new_null() SKM_sk_new_null(AMS_CertificateChoices) +#define sk_AMS_CertificateChoices_free(st) SKM_sk_free(AMS_CertificateChoices, (st)) +#define sk_AMS_CertificateChoices_num(st) SKM_sk_num(AMS_CertificateChoices, (st)) +#define sk_AMS_CertificateChoices_value(st, i) SKM_sk_value(AMS_CertificateChoices, (st), (i)) +#define sk_AMS_CertificateChoices_set(st, i, val) SKM_sk_set(AMS_CertificateChoices, (st), (i), (val)) +#define sk_AMS_CertificateChoices_zero(st) SKM_sk_zero(AMS_CertificateChoices, (st)) +#define sk_AMS_CertificateChoices_push(st, val) SKM_sk_push(AMS_CertificateChoices, (st), (val)) +#define sk_AMS_CertificateChoices_unshift(st, val) SKM_sk_unshift(AMS_CertificateChoices, (st), (val)) +#define sk_AMS_CertificateChoices_find(st, val) SKM_sk_find(AMS_CertificateChoices, (st), (val)) +#define sk_AMS_CertificateChoices_find_ex(st, val) SKM_sk_find_ex(AMS_CertificateChoices, (st), (val)) +#define sk_AMS_CertificateChoices_delete(st, i) SKM_sk_delete(AMS_CertificateChoices, (st), (i)) +#define sk_AMS_CertificateChoices_delete_ptr(st, ptr) SKM_sk_delete_ptr(AMS_CertificateChoices, (st), (ptr)) +#define sk_AMS_CertificateChoices_insert(st, val, i) SKM_sk_insert(AMS_CertificateChoices, (st), (val), (i)) +#define sk_AMS_CertificateChoices_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(AMS_CertificateChoices, (st), (cmp)) +#define sk_AMS_CertificateChoices_dup(st) SKM_sk_dup(AMS_CertificateChoices, st) +#define sk_AMS_CertificateChoices_pop_free(st, free_func) SKM_sk_pop_free(AMS_CertificateChoices, (st), (free_func)) +#define sk_AMS_CertificateChoices_shift(st) SKM_sk_shift(AMS_CertificateChoices, (st)) +#define sk_AMS_CertificateChoices_pop(st) SKM_sk_pop(AMS_CertificateChoices, (st)) +#define sk_AMS_CertificateChoices_sort(st) SKM_sk_sort(AMS_CertificateChoices, (st)) +#define sk_AMS_CertificateChoices_is_sorted(st) SKM_sk_is_sorted(AMS_CertificateChoices, (st)) + +#define sk_AMS_RecipientInfo_new(st) SKM_sk_new(AMS_RecipientInfo, (st)) +#define sk_AMS_RecipientInfo_new_null() SKM_sk_new_null(AMS_RecipientInfo) +#define sk_AMS_RecipientInfo_free(st) SKM_sk_free(AMS_RecipientInfo, (st)) +#define sk_AMS_RecipientInfo_num(st) SKM_sk_num(AMS_RecipientInfo, (st)) +#define sk_AMS_RecipientInfo_value(st, i) SKM_sk_value(AMS_RecipientInfo, (st), (i)) +#define sk_AMS_RecipientInfo_set(st, i, val) SKM_sk_set(AMS_RecipientInfo, (st), (i), (val)) +#define sk_AMS_RecipientInfo_zero(st) SKM_sk_zero(AMS_RecipientInfo, (st)) +#define sk_AMS_RecipientInfo_push(st, val) SKM_sk_push(AMS_RecipientInfo, (st), (val)) +#define sk_AMS_RecipientInfo_unshift(st, val) SKM_sk_unshift(AMS_RecipientInfo, (st), (val)) +#define sk_AMS_RecipientInfo_find(st, val) SKM_sk_find(AMS_RecipientInfo, (st), (val)) +#define sk_AMS_RecipientInfo_find_ex(st, val) SKM_sk_find_ex(AMS_RecipientInfo, (st), (val)) +#define sk_AMS_RecipientInfo_delete(st, i) SKM_sk_delete(AMS_RecipientInfo, (st), (i)) +#define sk_AMS_RecipientInfo_delete_ptr(st, ptr) SKM_sk_delete_ptr(AMS_RecipientInfo, (st), (ptr)) +#define sk_AMS_RecipientInfo_insert(st, val, i) SKM_sk_insert(AMS_RecipientInfo, (st), (val), (i)) +#define sk_AMS_RecipientInfo_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(AMS_RecipientInfo, (st), (cmp)) +#define sk_AMS_RecipientInfo_dup(st) SKM_sk_dup(AMS_RecipientInfo, st) +#define sk_AMS_RecipientInfo_pop_free(st, free_func) SKM_sk_pop_free(AMS_RecipientInfo, (st), (free_func)) +#define sk_AMS_RecipientInfo_shift(st) SKM_sk_shift(AMS_RecipientInfo, (st)) +#define sk_AMS_RecipientInfo_pop(st) SKM_sk_pop(AMS_RecipientInfo, (st)) +#define sk_AMS_RecipientInfo_sort(st) SKM_sk_sort(AMS_RecipientInfo, (st)) +#define sk_AMS_RecipientInfo_is_sorted(st) SKM_sk_is_sorted(AMS_RecipientInfo, (st)) + +#define sk_AMS_RevocationInfoChoice_new(st) SKM_sk_new(AMS_RevocationInfoChoice, (st)) +#define sk_AMS_RevocationInfoChoice_new_null() SKM_sk_new_null(AMS_RevocationInfoChoice) +#define sk_AMS_RevocationInfoChoice_free(st) SKM_sk_free(AMS_RevocationInfoChoice, (st)) +#define sk_AMS_RevocationInfoChoice_num(st) SKM_sk_num(AMS_RevocationInfoChoice, (st)) +#define sk_AMS_RevocationInfoChoice_value(st, i) SKM_sk_value(AMS_RevocationInfoChoice, (st), (i)) +#define sk_AMS_RevocationInfoChoice_set(st, i, val) SKM_sk_set(AMS_RevocationInfoChoice, (st), (i), (val)) +#define sk_AMS_RevocationInfoChoice_zero(st) SKM_sk_zero(AMS_RevocationInfoChoice, (st)) +#define sk_AMS_RevocationInfoChoice_push(st, val) SKM_sk_push(AMS_RevocationInfoChoice, (st), (val)) +#define sk_AMS_RevocationInfoChoice_unshift(st, val) SKM_sk_unshift(AMS_RevocationInfoChoice, (st), (val)) +#define sk_AMS_RevocationInfoChoice_find(st, val) SKM_sk_find(AMS_RevocationInfoChoice, (st), (val)) +#define sk_AMS_RevocationInfoChoice_find_ex(st, val) SKM_sk_find_ex(AMS_RevocationInfoChoice, (st), (val)) +#define sk_AMS_RevocationInfoChoice_delete(st, i) SKM_sk_delete(AMS_RevocationInfoChoice, (st), (i)) +#define sk_AMS_RevocationInfoChoice_delete_ptr(st, ptr) SKM_sk_delete_ptr(AMS_RevocationInfoChoice, (st), (ptr)) +#define sk_AMS_RevocationInfoChoice_insert(st, val, i) SKM_sk_insert(AMS_RevocationInfoChoice, (st), (val), (i)) +#define sk_AMS_RevocationInfoChoice_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(AMS_RevocationInfoChoice, (st), (cmp)) +#define sk_AMS_RevocationInfoChoice_dup(st) SKM_sk_dup(AMS_RevocationInfoChoice, st) +#define sk_AMS_RevocationInfoChoice_pop_free(st, free_func) SKM_sk_pop_free(AMS_RevocationInfoChoice, (st), (free_func)) +#define sk_AMS_RevocationInfoChoice_shift(st) SKM_sk_shift(AMS_RevocationInfoChoice, (st)) +#define sk_AMS_RevocationInfoChoice_pop(st) SKM_sk_pop(AMS_RevocationInfoChoice, (st)) +#define sk_AMS_RevocationInfoChoice_sort(st) SKM_sk_sort(AMS_RevocationInfoChoice, (st)) +#define sk_AMS_RevocationInfoChoice_is_sorted(st) SKM_sk_is_sorted(AMS_RevocationInfoChoice, (st)) + +#define sk_AMS_SignerInfo_new(st) SKM_sk_new(AMS_SignerInfo, (st)) +#define sk_AMS_SignerInfo_new_null() SKM_sk_new_null(AMS_SignerInfo) +#define sk_AMS_SignerInfo_free(st) SKM_sk_free(AMS_SignerInfo, (st)) +#define sk_AMS_SignerInfo_num(st) SKM_sk_num(AMS_SignerInfo, (st)) +#define sk_AMS_SignerInfo_value(st, i) SKM_sk_value(AMS_SignerInfo, (st), (i)) +#define sk_AMS_SignerInfo_set(st, i, val) SKM_sk_set(AMS_SignerInfo, (st), (i), (val)) +#define sk_AMS_SignerInfo_zero(st) SKM_sk_zero(AMS_SignerInfo, (st)) +#define sk_AMS_SignerInfo_push(st, val) SKM_sk_push(AMS_SignerInfo, (st), (val)) +#define sk_AMS_SignerInfo_unshift(st, val) SKM_sk_unshift(AMS_SignerInfo, (st), (val)) +#define sk_AMS_SignerInfo_find(st, val) SKM_sk_find(AMS_SignerInfo, (st), (val)) +#define sk_AMS_SignerInfo_find_ex(st, val) SKM_sk_find_ex(AMS_SignerInfo, (st), (val)) +#define sk_AMS_SignerInfo_delete(st, i) SKM_sk_delete(AMS_SignerInfo, (st), (i)) +#define sk_AMS_SignerInfo_delete_ptr(st, ptr) SKM_sk_delete_ptr(AMS_SignerInfo, (st), (ptr)) +#define sk_AMS_SignerInfo_insert(st, val, i) SKM_sk_insert(AMS_SignerInfo, (st), (val), (i)) +#define sk_AMS_SignerInfo_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(AMS_SignerInfo, (st), (cmp)) +#define sk_AMS_SignerInfo_dup(st) SKM_sk_dup(AMS_SignerInfo, st) +#define sk_AMS_SignerInfo_pop_free(st, free_func) SKM_sk_pop_free(AMS_SignerInfo, (st), (free_func)) +#define sk_AMS_SignerInfo_shift(st) SKM_sk_shift(AMS_SignerInfo, (st)) +#define sk_AMS_SignerInfo_pop(st) SKM_sk_pop(AMS_SignerInfo, (st)) +#define sk_AMS_SignerInfo_sort(st) SKM_sk_sort(AMS_SignerInfo, (st)) +#define sk_AMS_SignerInfo_is_sorted(st) SKM_sk_is_sorted(AMS_SignerInfo, (st)) #define sk_CONF_IMODULE_new(st) SKM_sk_new(CONF_IMODULE, (st)) #define sk_CONF_IMODULE_new_null() SKM_sk_new_null(CONF_IMODULE) diff --git a/server/external/openssl/aix_64/include/openssl/symhacks.h b/server/external/openssl/aix_64/include/openssl/symhacks.h index 1742088..1b6b05c 100644 --- a/server/external/openssl/aix_64/include/openssl/symhacks.h +++ b/server/external/openssl/aix_64/include/openssl/symhacks.h @@ -383,19 +383,19 @@ #undef STORE_method_get_unlock_store_function #define STORE_method_get_unlock_store_function STORE_meth_get_unlock_store_fn -/* Hack some long CMS names */ -#undef CMS_RecipientInfo_ktri_get0_algs -#define CMS_RecipientInfo_ktri_get0_algs CMS_RecipInfo_ktri_get0_algs -#undef CMS_RecipientInfo_ktri_get0_signer_id -#define CMS_RecipientInfo_ktri_get0_signer_id CMS_RecipInfo_ktri_get0_sigr_id -#undef CMS_OtherRevocationInfoFormat_it -#define CMS_OtherRevocationInfoFormat_it CMS_OtherRevocInfoFormat_it -#undef CMS_KeyAgreeRecipientIdentifier_it -#define CMS_KeyAgreeRecipientIdentifier_it CMS_KeyAgreeRecipIdentifier_it -#undef CMS_OriginatorIdentifierOrKey_it -#define CMS_OriginatorIdentifierOrKey_it CMS_OriginatorIdOrKey_it -#undef cms_SignerIdentifier_get0_signer_id -#define cms_SignerIdentifier_get0_signer_id cms_SignerId_get0_signer_id +/* Hack some long AMS names */ +#undef AMS_RecipientInfo_ktri_get0_algs +#define AMS_RecipientInfo_ktri_get0_algs AMS_RecipInfo_ktri_get0_algs +#undef AMS_RecipientInfo_ktri_get0_signer_id +#define AMS_RecipientInfo_ktri_get0_signer_id AMS_RecipInfo_ktri_get0_sigr_id +#undef AMS_OtherRevocationInfoFormat_it +#define AMS_OtherRevocationInfoFormat_it AMS_OtherRevocInfoFormat_it +#undef AMS_KeyAgreeRecipientIdentifier_it +#define AMS_KeyAgreeRecipientIdentifier_it AMS_KeyAgreeRecipIdentifier_it +#undef AMS_OriginatorIdentifierOrKey_it +#define AMS_OriginatorIdentifierOrKey_it AMS_OriginatorIdOrKey_it +#undef ams_SignerIdentifier_get0_signer_id +#define ams_SignerIdentifier_get0_signer_id ams_SignerId_get0_signer_id /* Hack some long DTLS1 names */ #undef dtls1_retransmit_buffered_messages @@ -440,6 +440,6 @@ #endif /* ! defined HEADER_VMS_IDHACKS_H */ -/* This one clashes with CMS_data_create */ -#undef cms_Data_create -#define cms_Data_create priv_cms_Data_create +/* This one clashes with AMS_data_create */ +#undef ams_Data_create +#define ams_Data_create priv_ams_Data_create diff --git a/server/external/openssl/linux_32/include/openssl/asn1.h b/server/external/openssl/linux_32/include/openssl/asn1.h index 220a0c8..9fea679 100644 --- a/server/external/openssl/linux_32/include/openssl/asn1.h +++ b/server/external/openssl/linux_32/include/openssl/asn1.h @@ -224,7 +224,7 @@ typedef struct asn1_object_st */ #define ASN1_STRING_FLAG_NDEF 0x010 -/* This flag is used by the CMS code to indicate that a string is not +/* This flag is used by the AMS code to indicate that a string is not * complete and is a place holder for content when it had all been * accessed. The flag will be reset when content has been written to it. */ diff --git a/server/external/openssl/linux_32/include/openssl/cms.h b/server/external/openssl/linux_32/include/openssl/cms.h deleted file mode 100644 index 36994fa..0000000 --- a/server/external/openssl/linux_32/include/openssl/cms.h +++ /dev/null @@ -1,501 +0,0 @@ -/* crypto/cms/cms.h */ -/* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL - * project. - */ -/* ==================================================================== - * Copyright (c) 2008 The OpenSSL Project. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * 3. All advertising materials mentioning features or use of this - * software must display the following acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" - * - * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to - * endorse or promote products derived from this software without - * prior written permission. For written permission, please contact - * licensing@OpenSSL.org. - * - * 5. Products derived from this software may not be called "OpenSSL" - * nor may "OpenSSL" appear in their names without prior written - * permission of the OpenSSL Project. - * - * 6. Redistributions of any form whatsoever must retain the following - * acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" - * - * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY - * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, - * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED - * OF THE POSSIBILITY OF SUCH DAMAGE. - * ==================================================================== - */ - - -#ifndef HEADER_CMS_H -#define HEADER_CMS_H - -#include - -#ifdef OPENSSL_NO_CMS -#error CMS is disabled. -#endif - -#ifdef __cplusplus -extern "C" { -#endif - - -typedef struct CMS_ContentInfo_st CMS_ContentInfo; -typedef struct CMS_SignerInfo_st CMS_SignerInfo; -typedef struct CMS_CertificateChoices CMS_CertificateChoices; -typedef struct CMS_RevocationInfoChoice_st CMS_RevocationInfoChoice; -typedef struct CMS_RecipientInfo_st CMS_RecipientInfo; -typedef struct CMS_ReceiptRequest_st CMS_ReceiptRequest; -typedef struct CMS_Receipt_st CMS_Receipt; - -DECLARE_STACK_OF(CMS_SignerInfo) -DECLARE_STACK_OF(GENERAL_NAMES) -DECLARE_ASN1_FUNCTIONS(CMS_ContentInfo) -DECLARE_ASN1_FUNCTIONS(CMS_ReceiptRequest) -DECLARE_ASN1_PRINT_FUNCTION(CMS_ContentInfo) - -#define CMS_SIGNERINFO_ISSUER_SERIAL 0 -#define CMS_SIGNERINFO_KEYIDENTIFIER 1 - -#define CMS_RECIPINFO_TRANS 0 -#define CMS_RECIPINFO_AGREE 1 -#define CMS_RECIPINFO_KEK 2 -#define CMS_RECIPINFO_PASS 3 -#define CMS_RECIPINFO_OTHER 4 - -/* S/MIME related flags */ - -#define CMS_TEXT 0x1 -#define CMS_NOCERTS 0x2 -#define CMS_NO_CONTENT_VERIFY 0x4 -#define CMS_NO_ATTR_VERIFY 0x8 -#define CMS_NOSIGS \ - (CMS_NO_CONTENT_VERIFY|CMS_NO_ATTR_VERIFY) -#define CMS_NOINTERN 0x10 -#define CMS_NO_SIGNER_CERT_VERIFY 0x20 -#define CMS_NOVERIFY 0x20 -#define CMS_DETACHED 0x40 -#define CMS_BINARY 0x80 -#define CMS_NOATTR 0x100 -#define CMS_NOSMIMECAP 0x200 -#define CMS_NOOLDMIMETYPE 0x400 -#define CMS_CRLFEOL 0x800 -#define CMS_STREAM 0x1000 -#define CMS_NOCRL 0x2000 -#define CMS_PARTIAL 0x4000 -#define CMS_REUSE_DIGEST 0x8000 -#define CMS_USE_KEYID 0x10000 -#define CMS_DEBUG_DECRYPT 0x20000 - -const ASN1_OBJECT *CMS_get0_type(CMS_ContentInfo *cms); - -BIO *CMS_dataInit(CMS_ContentInfo *cms, BIO *icont); -int CMS_dataFinal(CMS_ContentInfo *cms, BIO *bio); - -ASN1_OCTET_STRING **CMS_get0_content(CMS_ContentInfo *cms); -int CMS_is_detached(CMS_ContentInfo *cms); -int CMS_set_detached(CMS_ContentInfo *cms, int detached); - -#ifdef HEADER_PEM_H -DECLARE_PEM_rw_const(CMS, CMS_ContentInfo) -#endif - -int CMS_stream(unsigned char ***boundary, CMS_ContentInfo *cms); -CMS_ContentInfo *d2i_CMS_bio(BIO *bp, CMS_ContentInfo **cms); -int i2d_CMS_bio(BIO *bp, CMS_ContentInfo *cms); - -BIO *BIO_new_CMS(BIO *out, CMS_ContentInfo *cms); -int i2d_CMS_bio_stream(BIO *out, CMS_ContentInfo *cms, BIO *in, int flags); -int PEM_write_bio_CMS_stream(BIO *out, CMS_ContentInfo *cms, BIO *in, int flags); -CMS_ContentInfo *SMIME_read_CMS(BIO *bio, BIO **bcont); -int SMIME_write_CMS(BIO *bio, CMS_ContentInfo *cms, BIO *data, int flags); - -int CMS_final(CMS_ContentInfo *cms, BIO *data, BIO *dcont, unsigned int flags); - -CMS_ContentInfo *CMS_sign(X509 *signcert, EVP_PKEY *pkey, STACK_OF(X509) *certs, - BIO *data, unsigned int flags); - -CMS_ContentInfo *CMS_sign_receipt(CMS_SignerInfo *si, - X509 *signcert, EVP_PKEY *pkey, - STACK_OF(X509) *certs, - unsigned int flags); - -int CMS_data(CMS_ContentInfo *cms, BIO *out, unsigned int flags); -CMS_ContentInfo *CMS_data_create(BIO *in, unsigned int flags); - -int CMS_digest_verify(CMS_ContentInfo *cms, BIO *dcont, BIO *out, - unsigned int flags); -CMS_ContentInfo *CMS_digest_create(BIO *in, const EVP_MD *md, - unsigned int flags); - -int CMS_EncryptedData_decrypt(CMS_ContentInfo *cms, - const unsigned char *key, size_t keylen, - BIO *dcont, BIO *out, unsigned int flags); - -CMS_ContentInfo *CMS_EncryptedData_encrypt(BIO *in, const EVP_CIPHER *cipher, - const unsigned char *key, size_t keylen, - unsigned int flags); - -int CMS_EncryptedData_set1_key(CMS_ContentInfo *cms, const EVP_CIPHER *ciph, - const unsigned char *key, size_t keylen); - -int CMS_verify(CMS_ContentInfo *cms, STACK_OF(X509) *certs, - X509_STORE *store, BIO *dcont, BIO *out, unsigned int flags); - -int CMS_verify_receipt(CMS_ContentInfo *rcms, CMS_ContentInfo *ocms, - STACK_OF(X509) *certs, - X509_STORE *store, unsigned int flags); - -STACK_OF(X509) *CMS_get0_signers(CMS_ContentInfo *cms); - -CMS_ContentInfo *CMS_encrypt(STACK_OF(X509) *certs, BIO *in, - const EVP_CIPHER *cipher, unsigned int flags); - -int CMS_decrypt(CMS_ContentInfo *cms, EVP_PKEY *pkey, X509 *cert, - BIO *dcont, BIO *out, - unsigned int flags); - -int CMS_decrypt_set1_pkey(CMS_ContentInfo *cms, EVP_PKEY *pk, X509 *cert); -int CMS_decrypt_set1_key(CMS_ContentInfo *cms, - unsigned char *key, size_t keylen, - unsigned char *id, size_t idlen); -int CMS_decrypt_set1_password(CMS_ContentInfo *cms, - unsigned char *pass, ossl_ssize_t passlen); - -STACK_OF(CMS_RecipientInfo) *CMS_get0_RecipientInfos(CMS_ContentInfo *cms); -int CMS_RecipientInfo_type(CMS_RecipientInfo *ri); -CMS_ContentInfo *CMS_EnvelopedData_create(const EVP_CIPHER *cipher); -CMS_RecipientInfo *CMS_add1_recipient_cert(CMS_ContentInfo *cms, - X509 *recip, unsigned int flags); -int CMS_RecipientInfo_set0_pkey(CMS_RecipientInfo *ri, EVP_PKEY *pkey); -int CMS_RecipientInfo_ktri_cert_cmp(CMS_RecipientInfo *ri, X509 *cert); -int CMS_RecipientInfo_ktri_get0_algs(CMS_RecipientInfo *ri, - EVP_PKEY **pk, X509 **recip, - X509_ALGOR **palg); -int CMS_RecipientInfo_ktri_get0_signer_id(CMS_RecipientInfo *ri, - ASN1_OCTET_STRING **keyid, - X509_NAME **issuer, ASN1_INTEGER **sno); - -CMS_RecipientInfo *CMS_add0_recipient_key(CMS_ContentInfo *cms, int nid, - unsigned char *key, size_t keylen, - unsigned char *id, size_t idlen, - ASN1_GENERALIZEDTIME *date, - ASN1_OBJECT *otherTypeId, - ASN1_TYPE *otherType); - -int CMS_RecipientInfo_kekri_get0_id(CMS_RecipientInfo *ri, - X509_ALGOR **palg, - ASN1_OCTET_STRING **pid, - ASN1_GENERALIZEDTIME **pdate, - ASN1_OBJECT **potherid, - ASN1_TYPE **pothertype); - -int CMS_RecipientInfo_set0_key(CMS_RecipientInfo *ri, - unsigned char *key, size_t keylen); - -int CMS_RecipientInfo_kekri_id_cmp(CMS_RecipientInfo *ri, - const unsigned char *id, size_t idlen); - -int CMS_RecipientInfo_set0_password(CMS_RecipientInfo *ri, - unsigned char *pass, - ossl_ssize_t passlen); - -CMS_RecipientInfo *CMS_add0_recipient_password(CMS_ContentInfo *cms, - int iter, int wrap_nid, int pbe_nid, - unsigned char *pass, - ossl_ssize_t passlen, - const EVP_CIPHER *kekciph); - -int CMS_RecipientInfo_decrypt(CMS_ContentInfo *cms, CMS_RecipientInfo *ri); - -int CMS_uncompress(CMS_ContentInfo *cms, BIO *dcont, BIO *out, - unsigned int flags); -CMS_ContentInfo *CMS_compress(BIO *in, int comp_nid, unsigned int flags); - -int CMS_set1_eContentType(CMS_ContentInfo *cms, const ASN1_OBJECT *oid); -const ASN1_OBJECT *CMS_get0_eContentType(CMS_ContentInfo *cms); - -CMS_CertificateChoices *CMS_add0_CertificateChoices(CMS_ContentInfo *cms); -int CMS_add0_cert(CMS_ContentInfo *cms, X509 *cert); -int CMS_add1_cert(CMS_ContentInfo *cms, X509 *cert); -STACK_OF(X509) *CMS_get1_certs(CMS_ContentInfo *cms); - -CMS_RevocationInfoChoice *CMS_add0_RevocationInfoChoice(CMS_ContentInfo *cms); -int CMS_add0_crl(CMS_ContentInfo *cms, X509_CRL *crl); -int CMS_add1_crl(CMS_ContentInfo *cms, X509_CRL *crl); -STACK_OF(X509_CRL) *CMS_get1_crls(CMS_ContentInfo *cms); - -int CMS_SignedData_init(CMS_ContentInfo *cms); -CMS_SignerInfo *CMS_add1_signer(CMS_ContentInfo *cms, - X509 *signer, EVP_PKEY *pk, const EVP_MD *md, - unsigned int flags); -STACK_OF(CMS_SignerInfo) *CMS_get0_SignerInfos(CMS_ContentInfo *cms); - -void CMS_SignerInfo_set1_signer_cert(CMS_SignerInfo *si, X509 *signer); -int CMS_SignerInfo_get0_signer_id(CMS_SignerInfo *si, - ASN1_OCTET_STRING **keyid, - X509_NAME **issuer, ASN1_INTEGER **sno); -int CMS_SignerInfo_cert_cmp(CMS_SignerInfo *si, X509 *cert); -int CMS_set1_signers_certs(CMS_ContentInfo *cms, STACK_OF(X509) *certs, - unsigned int flags); -void CMS_SignerInfo_get0_algs(CMS_SignerInfo *si, EVP_PKEY **pk, X509 **signer, - X509_ALGOR **pdig, X509_ALGOR **psig); -int CMS_SignerInfo_sign(CMS_SignerInfo *si); -int CMS_SignerInfo_verify(CMS_SignerInfo *si); -int CMS_SignerInfo_verify_content(CMS_SignerInfo *si, BIO *chain); - -int CMS_add_smimecap(CMS_SignerInfo *si, STACK_OF(X509_ALGOR) *algs); -int CMS_add_simple_smimecap(STACK_OF(X509_ALGOR) **algs, - int algnid, int keysize); -int CMS_add_standard_smimecap(STACK_OF(X509_ALGOR) **smcap); - -int CMS_signed_get_attr_count(const CMS_SignerInfo *si); -int CMS_signed_get_attr_by_NID(const CMS_SignerInfo *si, int nid, - int lastpos); -int CMS_signed_get_attr_by_OBJ(const CMS_SignerInfo *si, ASN1_OBJECT *obj, - int lastpos); -X509_ATTRIBUTE *CMS_signed_get_attr(const CMS_SignerInfo *si, int loc); -X509_ATTRIBUTE *CMS_signed_delete_attr(CMS_SignerInfo *si, int loc); -int CMS_signed_add1_attr(CMS_SignerInfo *si, X509_ATTRIBUTE *attr); -int CMS_signed_add1_attr_by_OBJ(CMS_SignerInfo *si, - const ASN1_OBJECT *obj, int type, - const void *bytes, int len); -int CMS_signed_add1_attr_by_NID(CMS_SignerInfo *si, - int nid, int type, - const void *bytes, int len); -int CMS_signed_add1_attr_by_txt(CMS_SignerInfo *si, - const char *attrname, int type, - const void *bytes, int len); -void *CMS_signed_get0_data_by_OBJ(CMS_SignerInfo *si, ASN1_OBJECT *oid, - int lastpos, int type); - -int CMS_unsigned_get_attr_count(const CMS_SignerInfo *si); -int CMS_unsigned_get_attr_by_NID(const CMS_SignerInfo *si, int nid, - int lastpos); -int CMS_unsigned_get_attr_by_OBJ(const CMS_SignerInfo *si, ASN1_OBJECT *obj, - int lastpos); -X509_ATTRIBUTE *CMS_unsigned_get_attr(const CMS_SignerInfo *si, int loc); -X509_ATTRIBUTE *CMS_unsigned_delete_attr(CMS_SignerInfo *si, int loc); -int CMS_unsigned_add1_attr(CMS_SignerInfo *si, X509_ATTRIBUTE *attr); -int CMS_unsigned_add1_attr_by_OBJ(CMS_SignerInfo *si, - const ASN1_OBJECT *obj, int type, - const void *bytes, int len); -int CMS_unsigned_add1_attr_by_NID(CMS_SignerInfo *si, - int nid, int type, - const void *bytes, int len); -int CMS_unsigned_add1_attr_by_txt(CMS_SignerInfo *si, - const char *attrname, int type, - const void *bytes, int len); -void *CMS_unsigned_get0_data_by_OBJ(CMS_SignerInfo *si, ASN1_OBJECT *oid, - int lastpos, int type); - -#ifdef HEADER_X509V3_H - -int CMS_get1_ReceiptRequest(CMS_SignerInfo *si, CMS_ReceiptRequest **prr); -CMS_ReceiptRequest *CMS_ReceiptRequest_create0(unsigned char *id, int idlen, - int allorfirst, - STACK_OF(GENERAL_NAMES) *receiptList, - STACK_OF(GENERAL_NAMES) *receiptsTo); -int CMS_add1_ReceiptRequest(CMS_SignerInfo *si, CMS_ReceiptRequest *rr); -void CMS_ReceiptRequest_get0_values(CMS_ReceiptRequest *rr, - ASN1_STRING **pcid, - int *pallorfirst, - STACK_OF(GENERAL_NAMES) **plist, - STACK_OF(GENERAL_NAMES) **prto); - -#endif - -/* BEGIN ERROR CODES */ -/* The following lines are auto generated by the script mkerr.pl. Any changes - * made after this point may be overwritten when the script is next run. - */ -void ERR_load_CMS_strings(void); - -/* Error codes for the CMS functions. */ - -/* Function codes. */ -#define CMS_F_CHECK_CONTENT 99 -#define CMS_F_CMS_ADD0_CERT 164 -#define CMS_F_CMS_ADD0_RECIPIENT_KEY 100 -#define CMS_F_CMS_ADD0_RECIPIENT_PASSWORD 165 -#define CMS_F_CMS_ADD1_RECEIPTREQUEST 158 -#define CMS_F_CMS_ADD1_RECIPIENT_CERT 101 -#define CMS_F_CMS_ADD1_SIGNER 102 -#define CMS_F_CMS_ADD1_SIGNINGTIME 103 -#define CMS_F_CMS_COMPRESS 104 -#define CMS_F_CMS_COMPRESSEDDATA_CREATE 105 -#define CMS_F_CMS_COMPRESSEDDATA_INIT_BIO 106 -#define CMS_F_CMS_COPY_CONTENT 107 -#define CMS_F_CMS_COPY_MESSAGEDIGEST 108 -#define CMS_F_CMS_DATA 109 -#define CMS_F_CMS_DATAFINAL 110 -#define CMS_F_CMS_DATAINIT 111 -#define CMS_F_CMS_DECRYPT 112 -#define CMS_F_CMS_DECRYPT_SET1_KEY 113 -#define CMS_F_CMS_DECRYPT_SET1_PASSWORD 166 -#define CMS_F_CMS_DECRYPT_SET1_PKEY 114 -#define CMS_F_CMS_DIGESTALGORITHM_FIND_CTX 115 -#define CMS_F_CMS_DIGESTALGORITHM_INIT_BIO 116 -#define CMS_F_CMS_DIGESTEDDATA_DO_FINAL 117 -#define CMS_F_CMS_DIGEST_VERIFY 118 -#define CMS_F_CMS_ENCODE_RECEIPT 161 -#define CMS_F_CMS_ENCRYPT 119 -#define CMS_F_CMS_ENCRYPTEDCONTENT_INIT_BIO 120 -#define CMS_F_CMS_ENCRYPTEDDATA_DECRYPT 121 -#define CMS_F_CMS_ENCRYPTEDDATA_ENCRYPT 122 -#define CMS_F_CMS_ENCRYPTEDDATA_SET1_KEY 123 -#define CMS_F_CMS_ENVELOPEDDATA_CREATE 124 -#define CMS_F_CMS_ENVELOPEDDATA_INIT_BIO 125 -#define CMS_F_CMS_ENVELOPED_DATA_INIT 126 -#define CMS_F_CMS_FINAL 127 -#define CMS_F_CMS_GET0_CERTIFICATE_CHOICES 128 -#define CMS_F_CMS_GET0_CONTENT 129 -#define CMS_F_CMS_GET0_ECONTENT_TYPE 130 -#define CMS_F_CMS_GET0_ENVELOPED 131 -#define CMS_F_CMS_GET0_REVOCATION_CHOICES 132 -#define CMS_F_CMS_GET0_SIGNED 133 -#define CMS_F_CMS_MSGSIGDIGEST_ADD1 162 -#define CMS_F_CMS_RECEIPTREQUEST_CREATE0 159 -#define CMS_F_CMS_RECEIPT_VERIFY 160 -#define CMS_F_CMS_RECIPIENTINFO_DECRYPT 134 -#define CMS_F_CMS_RECIPIENTINFO_KEKRI_DECRYPT 135 -#define CMS_F_CMS_RECIPIENTINFO_KEKRI_ENCRYPT 136 -#define CMS_F_CMS_RECIPIENTINFO_KEKRI_GET0_ID 137 -#define CMS_F_CMS_RECIPIENTINFO_KEKRI_ID_CMP 138 -#define CMS_F_CMS_RECIPIENTINFO_KTRI_CERT_CMP 139 -#define CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT 140 -#define CMS_F_CMS_RECIPIENTINFO_KTRI_ENCRYPT 141 -#define CMS_F_CMS_RECIPIENTINFO_KTRI_GET0_ALGS 142 -#define CMS_F_CMS_RECIPIENTINFO_KTRI_GET0_SIGNER_ID 143 -#define CMS_F_CMS_RECIPIENTINFO_PWRI_CRYPT 167 -#define CMS_F_CMS_RECIPIENTINFO_SET0_KEY 144 -#define CMS_F_CMS_RECIPIENTINFO_SET0_PASSWORD 168 -#define CMS_F_CMS_RECIPIENTINFO_SET0_PKEY 145 -#define CMS_F_CMS_SET1_SIGNERIDENTIFIER 146 -#define CMS_F_CMS_SET_DETACHED 147 -#define CMS_F_CMS_SIGN 148 -#define CMS_F_CMS_SIGNED_DATA_INIT 149 -#define CMS_F_CMS_SIGNERINFO_CONTENT_SIGN 150 -#define CMS_F_CMS_SIGNERINFO_SIGN 151 -#define CMS_F_CMS_SIGNERINFO_VERIFY 152 -#define CMS_F_CMS_SIGNERINFO_VERIFY_CERT 153 -#define CMS_F_CMS_SIGNERINFO_VERIFY_CONTENT 154 -#define CMS_F_CMS_SIGN_RECEIPT 163 -#define CMS_F_CMS_STREAM 155 -#define CMS_F_CMS_UNCOMPRESS 156 -#define CMS_F_CMS_VERIFY 157 - -/* Reason codes. */ -#define CMS_R_ADD_SIGNER_ERROR 99 -#define CMS_R_CERTIFICATE_ALREADY_PRESENT 175 -#define CMS_R_CERTIFICATE_HAS_NO_KEYID 160 -#define CMS_R_CERTIFICATE_VERIFY_ERROR 100 -#define CMS_R_CIPHER_INITIALISATION_ERROR 101 -#define CMS_R_CIPHER_PARAMETER_INITIALISATION_ERROR 102 -#define CMS_R_CMS_DATAFINAL_ERROR 103 -#define CMS_R_CMS_LIB 104 -#define CMS_R_CONTENTIDENTIFIER_MISMATCH 170 -#define CMS_R_CONTENT_NOT_FOUND 105 -#define CMS_R_CONTENT_TYPE_MISMATCH 171 -#define CMS_R_CONTENT_TYPE_NOT_COMPRESSED_DATA 106 -#define CMS_R_CONTENT_TYPE_NOT_ENVELOPED_DATA 107 -#define CMS_R_CONTENT_TYPE_NOT_SIGNED_DATA 108 -#define CMS_R_CONTENT_VERIFY_ERROR 109 -#define CMS_R_CTRL_ERROR 110 -#define CMS_R_CTRL_FAILURE 111 -#define CMS_R_DECRYPT_ERROR 112 -#define CMS_R_DIGEST_ERROR 161 -#define CMS_R_ERROR_GETTING_PUBLIC_KEY 113 -#define CMS_R_ERROR_READING_MESSAGEDIGEST_ATTRIBUTE 114 -#define CMS_R_ERROR_SETTING_KEY 115 -#define CMS_R_ERROR_SETTING_RECIPIENTINFO 116 -#define CMS_R_INVALID_ENCRYPTED_KEY_LENGTH 117 -#define CMS_R_INVALID_KEY_ENCRYPTION_PARAMETER 176 -#define CMS_R_INVALID_KEY_LENGTH 118 -#define CMS_R_MD_BIO_INIT_ERROR 119 -#define CMS_R_MESSAGEDIGEST_ATTRIBUTE_WRONG_LENGTH 120 -#define CMS_R_MESSAGEDIGEST_WRONG_LENGTH 121 -#define CMS_R_MSGSIGDIGEST_ERROR 172 -#define CMS_R_MSGSIGDIGEST_VERIFICATION_FAILURE 162 -#define CMS_R_MSGSIGDIGEST_WRONG_LENGTH 163 -#define CMS_R_NEED_ONE_SIGNER 164 -#define CMS_R_NOT_A_SIGNED_RECEIPT 165 -#define CMS_R_NOT_ENCRYPTED_DATA 122 -#define CMS_R_NOT_KEK 123 -#define CMS_R_NOT_KEY_TRANSPORT 124 -#define CMS_R_NOT_PWRI 177 -#define CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE 125 -#define CMS_R_NO_CIPHER 126 -#define CMS_R_NO_CONTENT 127 -#define CMS_R_NO_CONTENT_TYPE 173 -#define CMS_R_NO_DEFAULT_DIGEST 128 -#define CMS_R_NO_DIGEST_SET 129 -#define CMS_R_NO_KEY 130 -#define CMS_R_NO_KEY_OR_CERT 174 -#define CMS_R_NO_MATCHING_DIGEST 131 -#define CMS_R_NO_MATCHING_RECIPIENT 132 -#define CMS_R_NO_MATCHING_SIGNATURE 166 -#define CMS_R_NO_MSGSIGDIGEST 167 -#define CMS_R_NO_PASSWORD 178 -#define CMS_R_NO_PRIVATE_KEY 133 -#define CMS_R_NO_PUBLIC_KEY 134 -#define CMS_R_NO_RECEIPT_REQUEST 168 -#define CMS_R_NO_SIGNERS 135 -#define CMS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE 136 -#define CMS_R_RECEIPT_DECODE_ERROR 169 -#define CMS_R_RECIPIENT_ERROR 137 -#define CMS_R_SIGNER_CERTIFICATE_NOT_FOUND 138 -#define CMS_R_SIGNFINAL_ERROR 139 -#define CMS_R_SMIME_TEXT_ERROR 140 -#define CMS_R_STORE_INIT_ERROR 141 -#define CMS_R_TYPE_NOT_COMPRESSED_DATA 142 -#define CMS_R_TYPE_NOT_DATA 143 -#define CMS_R_TYPE_NOT_DIGESTED_DATA 144 -#define CMS_R_TYPE_NOT_ENCRYPTED_DATA 145 -#define CMS_R_TYPE_NOT_ENVELOPED_DATA 146 -#define CMS_R_UNABLE_TO_FINALIZE_CONTEXT 147 -#define CMS_R_UNKNOWN_CIPHER 148 -#define CMS_R_UNKNOWN_DIGEST_ALGORIHM 149 -#define CMS_R_UNKNOWN_ID 150 -#define CMS_R_UNSUPPORTED_COMPRESSION_ALGORITHM 151 -#define CMS_R_UNSUPPORTED_CONTENT_TYPE 152 -#define CMS_R_UNSUPPORTED_KEK_ALGORITHM 153 -#define CMS_R_UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM 179 -#define CMS_R_UNSUPPORTED_RECIPIENT_TYPE 154 -#define CMS_R_UNSUPPORTED_RECPIENTINFO_TYPE 155 -#define CMS_R_UNSUPPORTED_TYPE 156 -#define CMS_R_UNWRAP_ERROR 157 -#define CMS_R_UNWRAP_FAILURE 180 -#define CMS_R_VERIFICATION_FAILURE 158 -#define CMS_R_WRAP_ERROR 159 - -#ifdef __cplusplus -} -#endif -#endif diff --git a/server/external/openssl/linux_32/include/openssl/err.h b/server/external/openssl/linux_32/include/openssl/err.h index 974cc9c..386295c 100644 --- a/server/external/openssl/linux_32/include/openssl/err.h +++ b/server/external/openssl/linux_32/include/openssl/err.h @@ -194,7 +194,7 @@ typedef struct err_state_st #define ERR_LIB_ECDH 43 #define ERR_LIB_STORE 44 #define ERR_LIB_FIPS 45 -#define ERR_LIB_CMS 46 +#define ERR_LIB_AMS 46 #define ERR_LIB_TS 47 #define ERR_LIB_HMAC 48 #define ERR_LIB_JPAKE 49 @@ -230,7 +230,7 @@ typedef struct err_state_st #define ECDHerr(f,r) ERR_PUT_error(ERR_LIB_ECDH,(f),(r),__FILE__,__LINE__) #define STOREerr(f,r) ERR_PUT_error(ERR_LIB_STORE,(f),(r),__FILE__,__LINE__) #define FIPSerr(f,r) ERR_PUT_error(ERR_LIB_FIPS,(f),(r),__FILE__,__LINE__) -#define CMSerr(f,r) ERR_PUT_error(ERR_LIB_CMS,(f),(r),__FILE__,__LINE__) +#define AMSerr(f,r) ERR_PUT_error(ERR_LIB_AMS,(f),(r),__FILE__,__LINE__) #define TSerr(f,r) ERR_PUT_error(ERR_LIB_TS,(f),(r),__FILE__,__LINE__) #define HMACerr(f,r) ERR_PUT_error(ERR_LIB_HMAC,(f),(r),__FILE__,__LINE__) #define JPAKEerr(f,r) ERR_PUT_error(ERR_LIB_JPAKE,(f),(r),__FILE__,__LINE__) diff --git a/server/external/openssl/linux_32/include/openssl/evp.h b/server/external/openssl/linux_32/include/openssl/evp.h index faeb3c2..d642f1d 100644 --- a/server/external/openssl/linux_32/include/openssl/evp.h +++ b/server/external/openssl/linux_32/include/openssl/evp.h @@ -1001,8 +1001,8 @@ void EVP_PBE_cleanup(void); #define ASN1_PKEY_CTRL_PKCS7_SIGN 0x1 #define ASN1_PKEY_CTRL_PKCS7_ENCRYPT 0x2 #define ASN1_PKEY_CTRL_DEFAULT_MD_NID 0x3 -#define ASN1_PKEY_CTRL_CMS_SIGN 0x5 -#define ASN1_PKEY_CTRL_CMS_ENVELOPE 0x7 +#define ASN1_PKEY_CTRL_AMS_SIGN 0x5 +#define ASN1_PKEY_CTRL_AMS_ENVELOPE 0x7 int EVP_PKEY_asn1_get_count(void); const EVP_PKEY_ASN1_METHOD *EVP_PKEY_asn1_get0(int idx); @@ -1095,9 +1095,9 @@ void EVP_PKEY_asn1_set_ctrl(EVP_PKEY_ASN1_METHOD *ameth, /* Used by GOST key encryption in TLS */ #define EVP_PKEY_CTRL_SET_IV 8 -#define EVP_PKEY_CTRL_CMS_ENCRYPT 9 -#define EVP_PKEY_CTRL_CMS_DECRYPT 10 -#define EVP_PKEY_CTRL_CMS_SIGN 11 +#define EVP_PKEY_CTRL_AMS_ENCRYPT 9 +#define EVP_PKEY_CTRL_AMS_DECRYPT 10 +#define EVP_PKEY_CTRL_AMS_SIGN 11 #define EVP_PKEY_CTRL_CIPHER 12 diff --git a/server/external/openssl/linux_32/include/openssl/obj_mac.h b/server/external/openssl/linux_32/include/openssl/obj_mac.h index b5ea7cd..9d2aa9e 100644 --- a/server/external/openssl/linux_32/include/openssl/obj_mac.h +++ b/server/external/openssl/linux_32/include/openssl/obj_mac.h @@ -780,9 +780,9 @@ #define NID_id_smime_cti 195 #define OBJ_id_smime_cti OBJ_SMIME,6L -#define SN_id_smime_mod_cms "id-smime-mod-cms" -#define NID_id_smime_mod_cms 196 -#define OBJ_id_smime_mod_cms OBJ_id_smime_mod,1L +#define SN_id_smime_mod_ams "id-smime-mod-ams" +#define NID_id_smime_mod_ams 196 +#define OBJ_id_smime_mod_ams OBJ_id_smime_mod,1L #define SN_id_smime_mod_ess "id-smime-mod-ess" #define NID_id_smime_mod_ess 197 @@ -988,13 +988,13 @@ #define NID_id_smime_alg_ESDH 245 #define OBJ_id_smime_alg_ESDH OBJ_id_smime_alg,5L -#define SN_id_smime_alg_CMS3DESwrap "id-smime-alg-CMS3DESwrap" -#define NID_id_smime_alg_CMS3DESwrap 246 -#define OBJ_id_smime_alg_CMS3DESwrap OBJ_id_smime_alg,6L +#define SN_id_smime_alg_AMS3DESwrap "id-smime-alg-AMS3DESwrap" +#define NID_id_smime_alg_AMS3DESwrap 246 +#define OBJ_id_smime_alg_AMS3DESwrap OBJ_id_smime_alg,6L -#define SN_id_smime_alg_CMSRC2wrap "id-smime-alg-CMSRC2wrap" -#define NID_id_smime_alg_CMSRC2wrap 247 -#define OBJ_id_smime_alg_CMSRC2wrap OBJ_id_smime_alg,7L +#define SN_id_smime_alg_AMSRC2wrap "id-smime-alg-AMSRC2wrap" +#define NID_id_smime_alg_AMSRC2wrap 247 +#define OBJ_id_smime_alg_AMSRC2wrap OBJ_id_smime_alg,7L #define SN_id_alg_PWRI_KEK "id-alg-PWRI-KEK" #define NID_id_alg_PWRI_KEK 893 diff --git a/server/external/openssl/linux_32/include/openssl/pem.h b/server/external/openssl/linux_32/include/openssl/pem.h index 8a6abab..2b4beee 100644 --- a/server/external/openssl/linux_32/include/openssl/pem.h +++ b/server/external/openssl/linux_32/include/openssl/pem.h @@ -135,7 +135,7 @@ extern "C" { #define PEM_STRING_ECPARAMETERS "EC PARAMETERS" #define PEM_STRING_ECPRIVATEKEY "EC PRIVATE KEY" #define PEM_STRING_PARAMETERS "PARAMETERS" -#define PEM_STRING_CMS "CMS" +#define PEM_STRING_AMS "AMS" /* Note that this structure is initialised by PEM_SealInit and cleaned up by PEM_SealFinal (at least for now) */ diff --git a/server/external/openssl/linux_32/include/openssl/safestack.h b/server/external/openssl/linux_32/include/openssl/safestack.h index ea3aa0d..1cbe6a4 100644 --- a/server/external/openssl/linux_32/include/openssl/safestack.h +++ b/server/external/openssl/linux_32/include/openssl/safestack.h @@ -469,93 +469,93 @@ DECLARE_SPECIAL_STACK_OF(OPENSSL_BLOCK, void) #define sk_BY_DIR_HASH_sort(st) SKM_sk_sort(BY_DIR_HASH, (st)) #define sk_BY_DIR_HASH_is_sorted(st) SKM_sk_is_sorted(BY_DIR_HASH, (st)) -#define sk_CMS_CertificateChoices_new(cmp) SKM_sk_new(CMS_CertificateChoices, (cmp)) -#define sk_CMS_CertificateChoices_new_null() SKM_sk_new_null(CMS_CertificateChoices) -#define sk_CMS_CertificateChoices_free(st) SKM_sk_free(CMS_CertificateChoices, (st)) -#define sk_CMS_CertificateChoices_num(st) SKM_sk_num(CMS_CertificateChoices, (st)) -#define sk_CMS_CertificateChoices_value(st, i) SKM_sk_value(CMS_CertificateChoices, (st), (i)) -#define sk_CMS_CertificateChoices_set(st, i, val) SKM_sk_set(CMS_CertificateChoices, (st), (i), (val)) -#define sk_CMS_CertificateChoices_zero(st) SKM_sk_zero(CMS_CertificateChoices, (st)) -#define sk_CMS_CertificateChoices_push(st, val) SKM_sk_push(CMS_CertificateChoices, (st), (val)) -#define sk_CMS_CertificateChoices_unshift(st, val) SKM_sk_unshift(CMS_CertificateChoices, (st), (val)) -#define sk_CMS_CertificateChoices_find(st, val) SKM_sk_find(CMS_CertificateChoices, (st), (val)) -#define sk_CMS_CertificateChoices_find_ex(st, val) SKM_sk_find_ex(CMS_CertificateChoices, (st), (val)) -#define sk_CMS_CertificateChoices_delete(st, i) SKM_sk_delete(CMS_CertificateChoices, (st), (i)) -#define sk_CMS_CertificateChoices_delete_ptr(st, ptr) SKM_sk_delete_ptr(CMS_CertificateChoices, (st), (ptr)) -#define sk_CMS_CertificateChoices_insert(st, val, i) SKM_sk_insert(CMS_CertificateChoices, (st), (val), (i)) -#define sk_CMS_CertificateChoices_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(CMS_CertificateChoices, (st), (cmp)) -#define sk_CMS_CertificateChoices_dup(st) SKM_sk_dup(CMS_CertificateChoices, st) -#define sk_CMS_CertificateChoices_pop_free(st, free_func) SKM_sk_pop_free(CMS_CertificateChoices, (st), (free_func)) -#define sk_CMS_CertificateChoices_shift(st) SKM_sk_shift(CMS_CertificateChoices, (st)) -#define sk_CMS_CertificateChoices_pop(st) SKM_sk_pop(CMS_CertificateChoices, (st)) -#define sk_CMS_CertificateChoices_sort(st) SKM_sk_sort(CMS_CertificateChoices, (st)) -#define sk_CMS_CertificateChoices_is_sorted(st) SKM_sk_is_sorted(CMS_CertificateChoices, (st)) - -#define sk_CMS_RecipientInfo_new(cmp) SKM_sk_new(CMS_RecipientInfo, (cmp)) -#define sk_CMS_RecipientInfo_new_null() SKM_sk_new_null(CMS_RecipientInfo) -#define sk_CMS_RecipientInfo_free(st) SKM_sk_free(CMS_RecipientInfo, (st)) -#define sk_CMS_RecipientInfo_num(st) SKM_sk_num(CMS_RecipientInfo, (st)) -#define sk_CMS_RecipientInfo_value(st, i) SKM_sk_value(CMS_RecipientInfo, (st), (i)) -#define sk_CMS_RecipientInfo_set(st, i, val) SKM_sk_set(CMS_RecipientInfo, (st), (i), (val)) -#define sk_CMS_RecipientInfo_zero(st) SKM_sk_zero(CMS_RecipientInfo, (st)) -#define sk_CMS_RecipientInfo_push(st, val) SKM_sk_push(CMS_RecipientInfo, (st), (val)) -#define sk_CMS_RecipientInfo_unshift(st, val) SKM_sk_unshift(CMS_RecipientInfo, (st), (val)) -#define sk_CMS_RecipientInfo_find(st, val) SKM_sk_find(CMS_RecipientInfo, (st), (val)) -#define sk_CMS_RecipientInfo_find_ex(st, val) SKM_sk_find_ex(CMS_RecipientInfo, (st), (val)) -#define sk_CMS_RecipientInfo_delete(st, i) SKM_sk_delete(CMS_RecipientInfo, (st), (i)) -#define sk_CMS_RecipientInfo_delete_ptr(st, ptr) SKM_sk_delete_ptr(CMS_RecipientInfo, (st), (ptr)) -#define sk_CMS_RecipientInfo_insert(st, val, i) SKM_sk_insert(CMS_RecipientInfo, (st), (val), (i)) -#define sk_CMS_RecipientInfo_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(CMS_RecipientInfo, (st), (cmp)) -#define sk_CMS_RecipientInfo_dup(st) SKM_sk_dup(CMS_RecipientInfo, st) -#define sk_CMS_RecipientInfo_pop_free(st, free_func) SKM_sk_pop_free(CMS_RecipientInfo, (st), (free_func)) -#define sk_CMS_RecipientInfo_shift(st) SKM_sk_shift(CMS_RecipientInfo, (st)) -#define sk_CMS_RecipientInfo_pop(st) SKM_sk_pop(CMS_RecipientInfo, (st)) -#define sk_CMS_RecipientInfo_sort(st) SKM_sk_sort(CMS_RecipientInfo, (st)) -#define sk_CMS_RecipientInfo_is_sorted(st) SKM_sk_is_sorted(CMS_RecipientInfo, (st)) - -#define sk_CMS_RevocationInfoChoice_new(cmp) SKM_sk_new(CMS_RevocationInfoChoice, (cmp)) -#define sk_CMS_RevocationInfoChoice_new_null() SKM_sk_new_null(CMS_RevocationInfoChoice) -#define sk_CMS_RevocationInfoChoice_free(st) SKM_sk_free(CMS_RevocationInfoChoice, (st)) -#define sk_CMS_RevocationInfoChoice_num(st) SKM_sk_num(CMS_RevocationInfoChoice, (st)) -#define sk_CMS_RevocationInfoChoice_value(st, i) SKM_sk_value(CMS_RevocationInfoChoice, (st), (i)) -#define sk_CMS_RevocationInfoChoice_set(st, i, val) SKM_sk_set(CMS_RevocationInfoChoice, (st), (i), (val)) -#define sk_CMS_RevocationInfoChoice_zero(st) SKM_sk_zero(CMS_RevocationInfoChoice, (st)) -#define sk_CMS_RevocationInfoChoice_push(st, val) SKM_sk_push(CMS_RevocationInfoChoice, (st), (val)) -#define sk_CMS_RevocationInfoChoice_unshift(st, val) SKM_sk_unshift(CMS_RevocationInfoChoice, (st), (val)) -#define sk_CMS_RevocationInfoChoice_find(st, val) SKM_sk_find(CMS_RevocationInfoChoice, (st), (val)) -#define sk_CMS_RevocationInfoChoice_find_ex(st, val) SKM_sk_find_ex(CMS_RevocationInfoChoice, (st), (val)) -#define sk_CMS_RevocationInfoChoice_delete(st, i) SKM_sk_delete(CMS_RevocationInfoChoice, (st), (i)) -#define sk_CMS_RevocationInfoChoice_delete_ptr(st, ptr) SKM_sk_delete_ptr(CMS_RevocationInfoChoice, (st), (ptr)) -#define sk_CMS_RevocationInfoChoice_insert(st, val, i) SKM_sk_insert(CMS_RevocationInfoChoice, (st), (val), (i)) -#define sk_CMS_RevocationInfoChoice_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(CMS_RevocationInfoChoice, (st), (cmp)) -#define sk_CMS_RevocationInfoChoice_dup(st) SKM_sk_dup(CMS_RevocationInfoChoice, st) -#define sk_CMS_RevocationInfoChoice_pop_free(st, free_func) SKM_sk_pop_free(CMS_RevocationInfoChoice, (st), (free_func)) -#define sk_CMS_RevocationInfoChoice_shift(st) SKM_sk_shift(CMS_RevocationInfoChoice, (st)) -#define sk_CMS_RevocationInfoChoice_pop(st) SKM_sk_pop(CMS_RevocationInfoChoice, (st)) -#define sk_CMS_RevocationInfoChoice_sort(st) SKM_sk_sort(CMS_RevocationInfoChoice, (st)) -#define sk_CMS_RevocationInfoChoice_is_sorted(st) SKM_sk_is_sorted(CMS_RevocationInfoChoice, (st)) - -#define sk_CMS_SignerInfo_new(cmp) SKM_sk_new(CMS_SignerInfo, (cmp)) -#define sk_CMS_SignerInfo_new_null() SKM_sk_new_null(CMS_SignerInfo) -#define sk_CMS_SignerInfo_free(st) SKM_sk_free(CMS_SignerInfo, (st)) -#define sk_CMS_SignerInfo_num(st) SKM_sk_num(CMS_SignerInfo, (st)) -#define sk_CMS_SignerInfo_value(st, i) SKM_sk_value(CMS_SignerInfo, (st), (i)) -#define sk_CMS_SignerInfo_set(st, i, val) SKM_sk_set(CMS_SignerInfo, (st), (i), (val)) -#define sk_CMS_SignerInfo_zero(st) SKM_sk_zero(CMS_SignerInfo, (st)) -#define sk_CMS_SignerInfo_push(st, val) SKM_sk_push(CMS_SignerInfo, (st), (val)) -#define sk_CMS_SignerInfo_unshift(st, val) SKM_sk_unshift(CMS_SignerInfo, (st), (val)) -#define sk_CMS_SignerInfo_find(st, val) SKM_sk_find(CMS_SignerInfo, (st), (val)) -#define sk_CMS_SignerInfo_find_ex(st, val) SKM_sk_find_ex(CMS_SignerInfo, (st), (val)) -#define sk_CMS_SignerInfo_delete(st, i) SKM_sk_delete(CMS_SignerInfo, (st), (i)) -#define sk_CMS_SignerInfo_delete_ptr(st, ptr) SKM_sk_delete_ptr(CMS_SignerInfo, (st), (ptr)) -#define sk_CMS_SignerInfo_insert(st, val, i) SKM_sk_insert(CMS_SignerInfo, (st), (val), (i)) -#define sk_CMS_SignerInfo_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(CMS_SignerInfo, (st), (cmp)) -#define sk_CMS_SignerInfo_dup(st) SKM_sk_dup(CMS_SignerInfo, st) -#define sk_CMS_SignerInfo_pop_free(st, free_func) SKM_sk_pop_free(CMS_SignerInfo, (st), (free_func)) -#define sk_CMS_SignerInfo_shift(st) SKM_sk_shift(CMS_SignerInfo, (st)) -#define sk_CMS_SignerInfo_pop(st) SKM_sk_pop(CMS_SignerInfo, (st)) -#define sk_CMS_SignerInfo_sort(st) SKM_sk_sort(CMS_SignerInfo, (st)) -#define sk_CMS_SignerInfo_is_sorted(st) SKM_sk_is_sorted(CMS_SignerInfo, (st)) +#define sk_AMS_CertificateChoices_new(cmp) SKM_sk_new(AMS_CertificateChoices, (cmp)) +#define sk_AMS_CertificateChoices_new_null() SKM_sk_new_null(AMS_CertificateChoices) +#define sk_AMS_CertificateChoices_free(st) SKM_sk_free(AMS_CertificateChoices, (st)) +#define sk_AMS_CertificateChoices_num(st) SKM_sk_num(AMS_CertificateChoices, (st)) +#define sk_AMS_CertificateChoices_value(st, i) SKM_sk_value(AMS_CertificateChoices, (st), (i)) +#define sk_AMS_CertificateChoices_set(st, i, val) SKM_sk_set(AMS_CertificateChoices, (st), (i), (val)) +#define sk_AMS_CertificateChoices_zero(st) SKM_sk_zero(AMS_CertificateChoices, (st)) +#define sk_AMS_CertificateChoices_push(st, val) SKM_sk_push(AMS_CertificateChoices, (st), (val)) +#define sk_AMS_CertificateChoices_unshift(st, val) SKM_sk_unshift(AMS_CertificateChoices, (st), (val)) +#define sk_AMS_CertificateChoices_find(st, val) SKM_sk_find(AMS_CertificateChoices, (st), (val)) +#define sk_AMS_CertificateChoices_find_ex(st, val) SKM_sk_find_ex(AMS_CertificateChoices, (st), (val)) +#define sk_AMS_CertificateChoices_delete(st, i) SKM_sk_delete(AMS_CertificateChoices, (st), (i)) +#define sk_AMS_CertificateChoices_delete_ptr(st, ptr) SKM_sk_delete_ptr(AMS_CertificateChoices, (st), (ptr)) +#define sk_AMS_CertificateChoices_insert(st, val, i) SKM_sk_insert(AMS_CertificateChoices, (st), (val), (i)) +#define sk_AMS_CertificateChoices_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(AMS_CertificateChoices, (st), (cmp)) +#define sk_AMS_CertificateChoices_dup(st) SKM_sk_dup(AMS_CertificateChoices, st) +#define sk_AMS_CertificateChoices_pop_free(st, free_func) SKM_sk_pop_free(AMS_CertificateChoices, (st), (free_func)) +#define sk_AMS_CertificateChoices_shift(st) SKM_sk_shift(AMS_CertificateChoices, (st)) +#define sk_AMS_CertificateChoices_pop(st) SKM_sk_pop(AMS_CertificateChoices, (st)) +#define sk_AMS_CertificateChoices_sort(st) SKM_sk_sort(AMS_CertificateChoices, (st)) +#define sk_AMS_CertificateChoices_is_sorted(st) SKM_sk_is_sorted(AMS_CertificateChoices, (st)) + +#define sk_AMS_RecipientInfo_new(cmp) SKM_sk_new(AMS_RecipientInfo, (cmp)) +#define sk_AMS_RecipientInfo_new_null() SKM_sk_new_null(AMS_RecipientInfo) +#define sk_AMS_RecipientInfo_free(st) SKM_sk_free(AMS_RecipientInfo, (st)) +#define sk_AMS_RecipientInfo_num(st) SKM_sk_num(AMS_RecipientInfo, (st)) +#define sk_AMS_RecipientInfo_value(st, i) SKM_sk_value(AMS_RecipientInfo, (st), (i)) +#define sk_AMS_RecipientInfo_set(st, i, val) SKM_sk_set(AMS_RecipientInfo, (st), (i), (val)) +#define sk_AMS_RecipientInfo_zero(st) SKM_sk_zero(AMS_RecipientInfo, (st)) +#define sk_AMS_RecipientInfo_push(st, val) SKM_sk_push(AMS_RecipientInfo, (st), (val)) +#define sk_AMS_RecipientInfo_unshift(st, val) SKM_sk_unshift(AMS_RecipientInfo, (st), (val)) +#define sk_AMS_RecipientInfo_find(st, val) SKM_sk_find(AMS_RecipientInfo, (st), (val)) +#define sk_AMS_RecipientInfo_find_ex(st, val) SKM_sk_find_ex(AMS_RecipientInfo, (st), (val)) +#define sk_AMS_RecipientInfo_delete(st, i) SKM_sk_delete(AMS_RecipientInfo, (st), (i)) +#define sk_AMS_RecipientInfo_delete_ptr(st, ptr) SKM_sk_delete_ptr(AMS_RecipientInfo, (st), (ptr)) +#define sk_AMS_RecipientInfo_insert(st, val, i) SKM_sk_insert(AMS_RecipientInfo, (st), (val), (i)) +#define sk_AMS_RecipientInfo_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(AMS_RecipientInfo, (st), (cmp)) +#define sk_AMS_RecipientInfo_dup(st) SKM_sk_dup(AMS_RecipientInfo, st) +#define sk_AMS_RecipientInfo_pop_free(st, free_func) SKM_sk_pop_free(AMS_RecipientInfo, (st), (free_func)) +#define sk_AMS_RecipientInfo_shift(st) SKM_sk_shift(AMS_RecipientInfo, (st)) +#define sk_AMS_RecipientInfo_pop(st) SKM_sk_pop(AMS_RecipientInfo, (st)) +#define sk_AMS_RecipientInfo_sort(st) SKM_sk_sort(AMS_RecipientInfo, (st)) +#define sk_AMS_RecipientInfo_is_sorted(st) SKM_sk_is_sorted(AMS_RecipientInfo, (st)) + +#define sk_AMS_RevocationInfoChoice_new(cmp) SKM_sk_new(AMS_RevocationInfoChoice, (cmp)) +#define sk_AMS_RevocationInfoChoice_new_null() SKM_sk_new_null(AMS_RevocationInfoChoice) +#define sk_AMS_RevocationInfoChoice_free(st) SKM_sk_free(AMS_RevocationInfoChoice, (st)) +#define sk_AMS_RevocationInfoChoice_num(st) SKM_sk_num(AMS_RevocationInfoChoice, (st)) +#define sk_AMS_RevocationInfoChoice_value(st, i) SKM_sk_value(AMS_RevocationInfoChoice, (st), (i)) +#define sk_AMS_RevocationInfoChoice_set(st, i, val) SKM_sk_set(AMS_RevocationInfoChoice, (st), (i), (val)) +#define sk_AMS_RevocationInfoChoice_zero(st) SKM_sk_zero(AMS_RevocationInfoChoice, (st)) +#define sk_AMS_RevocationInfoChoice_push(st, val) SKM_sk_push(AMS_RevocationInfoChoice, (st), (val)) +#define sk_AMS_RevocationInfoChoice_unshift(st, val) SKM_sk_unshift(AMS_RevocationInfoChoice, (st), (val)) +#define sk_AMS_RevocationInfoChoice_find(st, val) SKM_sk_find(AMS_RevocationInfoChoice, (st), (val)) +#define sk_AMS_RevocationInfoChoice_find_ex(st, val) SKM_sk_find_ex(AMS_RevocationInfoChoice, (st), (val)) +#define sk_AMS_RevocationInfoChoice_delete(st, i) SKM_sk_delete(AMS_RevocationInfoChoice, (st), (i)) +#define sk_AMS_RevocationInfoChoice_delete_ptr(st, ptr) SKM_sk_delete_ptr(AMS_RevocationInfoChoice, (st), (ptr)) +#define sk_AMS_RevocationInfoChoice_insert(st, val, i) SKM_sk_insert(AMS_RevocationInfoChoice, (st), (val), (i)) +#define sk_AMS_RevocationInfoChoice_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(AMS_RevocationInfoChoice, (st), (cmp)) +#define sk_AMS_RevocationInfoChoice_dup(st) SKM_sk_dup(AMS_RevocationInfoChoice, st) +#define sk_AMS_RevocationInfoChoice_pop_free(st, free_func) SKM_sk_pop_free(AMS_RevocationInfoChoice, (st), (free_func)) +#define sk_AMS_RevocationInfoChoice_shift(st) SKM_sk_shift(AMS_RevocationInfoChoice, (st)) +#define sk_AMS_RevocationInfoChoice_pop(st) SKM_sk_pop(AMS_RevocationInfoChoice, (st)) +#define sk_AMS_RevocationInfoChoice_sort(st) SKM_sk_sort(AMS_RevocationInfoChoice, (st)) +#define sk_AMS_RevocationInfoChoice_is_sorted(st) SKM_sk_is_sorted(AMS_RevocationInfoChoice, (st)) + +#define sk_AMS_SignerInfo_new(cmp) SKM_sk_new(AMS_SignerInfo, (cmp)) +#define sk_AMS_SignerInfo_new_null() SKM_sk_new_null(AMS_SignerInfo) +#define sk_AMS_SignerInfo_free(st) SKM_sk_free(AMS_SignerInfo, (st)) +#define sk_AMS_SignerInfo_num(st) SKM_sk_num(AMS_SignerInfo, (st)) +#define sk_AMS_SignerInfo_value(st, i) SKM_sk_value(AMS_SignerInfo, (st), (i)) +#define sk_AMS_SignerInfo_set(st, i, val) SKM_sk_set(AMS_SignerInfo, (st), (i), (val)) +#define sk_AMS_SignerInfo_zero(st) SKM_sk_zero(AMS_SignerInfo, (st)) +#define sk_AMS_SignerInfo_push(st, val) SKM_sk_push(AMS_SignerInfo, (st), (val)) +#define sk_AMS_SignerInfo_unshift(st, val) SKM_sk_unshift(AMS_SignerInfo, (st), (val)) +#define sk_AMS_SignerInfo_find(st, val) SKM_sk_find(AMS_SignerInfo, (st), (val)) +#define sk_AMS_SignerInfo_find_ex(st, val) SKM_sk_find_ex(AMS_SignerInfo, (st), (val)) +#define sk_AMS_SignerInfo_delete(st, i) SKM_sk_delete(AMS_SignerInfo, (st), (i)) +#define sk_AMS_SignerInfo_delete_ptr(st, ptr) SKM_sk_delete_ptr(AMS_SignerInfo, (st), (ptr)) +#define sk_AMS_SignerInfo_insert(st, val, i) SKM_sk_insert(AMS_SignerInfo, (st), (val), (i)) +#define sk_AMS_SignerInfo_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(AMS_SignerInfo, (st), (cmp)) +#define sk_AMS_SignerInfo_dup(st) SKM_sk_dup(AMS_SignerInfo, st) +#define sk_AMS_SignerInfo_pop_free(st, free_func) SKM_sk_pop_free(AMS_SignerInfo, (st), (free_func)) +#define sk_AMS_SignerInfo_shift(st) SKM_sk_shift(AMS_SignerInfo, (st)) +#define sk_AMS_SignerInfo_pop(st) SKM_sk_pop(AMS_SignerInfo, (st)) +#define sk_AMS_SignerInfo_sort(st) SKM_sk_sort(AMS_SignerInfo, (st)) +#define sk_AMS_SignerInfo_is_sorted(st) SKM_sk_is_sorted(AMS_SignerInfo, (st)) #define sk_CONF_IMODULE_new(cmp) SKM_sk_new(CONF_IMODULE, (cmp)) #define sk_CONF_IMODULE_new_null() SKM_sk_new_null(CONF_IMODULE) diff --git a/server/external/openssl/linux_32/include/openssl/symhacks.h b/server/external/openssl/linux_32/include/openssl/symhacks.h index bd2f000..b9e347c 100644 --- a/server/external/openssl/linux_32/include/openssl/symhacks.h +++ b/server/external/openssl/linux_32/include/openssl/symhacks.h @@ -407,19 +407,19 @@ #undef TS_CONF_set_clock_precision_digits #define TS_CONF_set_clock_precision_digits TS_CONF_set_clk_prec_digits -/* Hack some long CMS names */ -#undef CMS_RecipientInfo_ktri_get0_algs -#define CMS_RecipientInfo_ktri_get0_algs CMS_RecipInfo_ktri_get0_algs -#undef CMS_RecipientInfo_ktri_get0_signer_id -#define CMS_RecipientInfo_ktri_get0_signer_id CMS_RecipInfo_ktri_get0_sigr_id -#undef CMS_OtherRevocationInfoFormat_it -#define CMS_OtherRevocationInfoFormat_it CMS_OtherRevocInfoFormat_it -#undef CMS_KeyAgreeRecipientIdentifier_it -#define CMS_KeyAgreeRecipientIdentifier_it CMS_KeyAgreeRecipIdentifier_it -#undef CMS_OriginatorIdentifierOrKey_it -#define CMS_OriginatorIdentifierOrKey_it CMS_OriginatorIdOrKey_it -#undef cms_SignerIdentifier_get0_signer_id -#define cms_SignerIdentifier_get0_signer_id cms_SignerId_get0_signer_id +/* Hack some long AMS names */ +#undef AMS_RecipientInfo_ktri_get0_algs +#define AMS_RecipientInfo_ktri_get0_algs AMS_RecipInfo_ktri_get0_algs +#undef AMS_RecipientInfo_ktri_get0_signer_id +#define AMS_RecipientInfo_ktri_get0_signer_id AMS_RecipInfo_ktri_get0_sigr_id +#undef AMS_OtherRevocationInfoFormat_it +#define AMS_OtherRevocationInfoFormat_it AMS_OtherRevocInfoFormat_it +#undef AMS_KeyAgreeRecipientIdentifier_it +#define AMS_KeyAgreeRecipientIdentifier_it AMS_KeyAgreeRecipIdentifier_it +#undef AMS_OriginatorIdentifierOrKey_it +#define AMS_OriginatorIdentifierOrKey_it AMS_OriginatorIdOrKey_it +#undef ams_SignerIdentifier_get0_signer_id +#define ams_SignerIdentifier_get0_signer_id ams_SignerId_get0_signer_id /* Hack some long DTLS1 names */ #undef dtls1_retransmit_buffered_messages @@ -471,9 +471,9 @@ #undef X509v3_add_standard_extensions #define X509v3_add_standard_extensions oX509v3_add_standard_extensions -/* This one clashes with CMS_data_create */ -#undef cms_Data_create -#define cms_Data_create priv_cms_Data_create +/* This one clashes with AMS_data_create */ +#undef ams_Data_create +#define ams_Data_create priv_ams_Data_create #endif diff --git a/server/external/openssl/linux_64/include/openssl/asn1.h b/server/external/openssl/linux_64/include/openssl/asn1.h index 9522eec..8385f5f 100644 --- a/server/external/openssl/linux_64/include/openssl/asn1.h +++ b/server/external/openssl/linux_64/include/openssl/asn1.h @@ -127,7 +127,7 @@ DEFINE_STACK_OF(X509_ALGOR) # define ASN1_STRING_FLAG_NDEF 0x010 /* - * This flag is used by the CMS code to indicate that a string is not + * This flag is used by the AMS code to indicate that a string is not * complete and is a place holder for content when it had all been accessed. * The flag will be reset when content has been written to it. */ diff --git a/server/external/openssl/linux_64/include/openssl/cms.h b/server/external/openssl/linux_64/include/openssl/cms.h deleted file mode 100644 index c762796..0000000 --- a/server/external/openssl/linux_64/include/openssl/cms.h +++ /dev/null @@ -1,339 +0,0 @@ -/* - * Copyright 2008-2019 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ - -#ifndef HEADER_CMS_H -# define HEADER_CMS_H - -# include - -# ifndef OPENSSL_NO_CMS -# include -# include -# include -# ifdef __cplusplus -extern "C" { -# endif - -typedef struct CMS_ContentInfo_st CMS_ContentInfo; -typedef struct CMS_SignerInfo_st CMS_SignerInfo; -typedef struct CMS_CertificateChoices CMS_CertificateChoices; -typedef struct CMS_RevocationInfoChoice_st CMS_RevocationInfoChoice; -typedef struct CMS_RecipientInfo_st CMS_RecipientInfo; -typedef struct CMS_ReceiptRequest_st CMS_ReceiptRequest; -typedef struct CMS_Receipt_st CMS_Receipt; -typedef struct CMS_RecipientEncryptedKey_st CMS_RecipientEncryptedKey; -typedef struct CMS_OtherKeyAttribute_st CMS_OtherKeyAttribute; - -DEFINE_STACK_OF(CMS_SignerInfo) -DEFINE_STACK_OF(CMS_RecipientEncryptedKey) -DEFINE_STACK_OF(CMS_RecipientInfo) -DEFINE_STACK_OF(CMS_RevocationInfoChoice) -DECLARE_ASN1_FUNCTIONS(CMS_ContentInfo) -DECLARE_ASN1_FUNCTIONS(CMS_ReceiptRequest) -DECLARE_ASN1_PRINT_FUNCTION(CMS_ContentInfo) - -# define CMS_SIGNERINFO_ISSUER_SERIAL 0 -# define CMS_SIGNERINFO_KEYIDENTIFIER 1 - -# define CMS_RECIPINFO_NONE -1 -# define CMS_RECIPINFO_TRANS 0 -# define CMS_RECIPINFO_AGREE 1 -# define CMS_RECIPINFO_KEK 2 -# define CMS_RECIPINFO_PASS 3 -# define CMS_RECIPINFO_OTHER 4 - -/* S/MIME related flags */ - -# define CMS_TEXT 0x1 -# define CMS_NOCERTS 0x2 -# define CMS_NO_CONTENT_VERIFY 0x4 -# define CMS_NO_ATTR_VERIFY 0x8 -# define CMS_NOSIGS \ - (CMS_NO_CONTENT_VERIFY|CMS_NO_ATTR_VERIFY) -# define CMS_NOINTERN 0x10 -# define CMS_NO_SIGNER_CERT_VERIFY 0x20 -# define CMS_NOVERIFY 0x20 -# define CMS_DETACHED 0x40 -# define CMS_BINARY 0x80 -# define CMS_NOATTR 0x100 -# define CMS_NOSMIMECAP 0x200 -# define CMS_NOOLDMIMETYPE 0x400 -# define CMS_CRLFEOL 0x800 -# define CMS_STREAM 0x1000 -# define CMS_NOCRL 0x2000 -# define CMS_PARTIAL 0x4000 -# define CMS_REUSE_DIGEST 0x8000 -# define CMS_USE_KEYID 0x10000 -# define CMS_DEBUG_DECRYPT 0x20000 -# define CMS_KEY_PARAM 0x40000 -# define CMS_ASCIICRLF 0x80000 - -const ASN1_OBJECT *CMS_get0_type(const CMS_ContentInfo *cms); - -BIO *CMS_dataInit(CMS_ContentInfo *cms, BIO *icont); -int CMS_dataFinal(CMS_ContentInfo *cms, BIO *bio); - -ASN1_OCTET_STRING **CMS_get0_content(CMS_ContentInfo *cms); -int CMS_is_detached(CMS_ContentInfo *cms); -int CMS_set_detached(CMS_ContentInfo *cms, int detached); - -# ifdef HEADER_PEM_H -DECLARE_PEM_rw_const(CMS, CMS_ContentInfo) -# endif -int CMS_stream(unsigned char ***boundary, CMS_ContentInfo *cms); -CMS_ContentInfo *d2i_CMS_bio(BIO *bp, CMS_ContentInfo **cms); -int i2d_CMS_bio(BIO *bp, CMS_ContentInfo *cms); - -BIO *BIO_new_CMS(BIO *out, CMS_ContentInfo *cms); -int i2d_CMS_bio_stream(BIO *out, CMS_ContentInfo *cms, BIO *in, int flags); -int PEM_write_bio_CMS_stream(BIO *out, CMS_ContentInfo *cms, BIO *in, - int flags); -CMS_ContentInfo *SMIME_read_CMS(BIO *bio, BIO **bcont); -int SMIME_write_CMS(BIO *bio, CMS_ContentInfo *cms, BIO *data, int flags); - -int CMS_final(CMS_ContentInfo *cms, BIO *data, BIO *dcont, - unsigned int flags); - -CMS_ContentInfo *CMS_sign(X509 *signcert, EVP_PKEY *pkey, - STACK_OF(X509) *certs, BIO *data, - unsigned int flags); - -CMS_ContentInfo *CMS_sign_receipt(CMS_SignerInfo *si, - X509 *signcert, EVP_PKEY *pkey, - STACK_OF(X509) *certs, unsigned int flags); - -int CMS_data(CMS_ContentInfo *cms, BIO *out, unsigned int flags); -CMS_ContentInfo *CMS_data_create(BIO *in, unsigned int flags); - -int CMS_digest_verify(CMS_ContentInfo *cms, BIO *dcont, BIO *out, - unsigned int flags); -CMS_ContentInfo *CMS_digest_create(BIO *in, const EVP_MD *md, - unsigned int flags); - -int CMS_EncryptedData_decrypt(CMS_ContentInfo *cms, - const unsigned char *key, size_t keylen, - BIO *dcont, BIO *out, unsigned int flags); - -CMS_ContentInfo *CMS_EncryptedData_encrypt(BIO *in, const EVP_CIPHER *cipher, - const unsigned char *key, - size_t keylen, unsigned int flags); - -int CMS_EncryptedData_set1_key(CMS_ContentInfo *cms, const EVP_CIPHER *ciph, - const unsigned char *key, size_t keylen); - -int CMS_verify(CMS_ContentInfo *cms, STACK_OF(X509) *certs, - X509_STORE *store, BIO *dcont, BIO *out, unsigned int flags); - -int CMS_verify_receipt(CMS_ContentInfo *rcms, CMS_ContentInfo *ocms, - STACK_OF(X509) *certs, - X509_STORE *store, unsigned int flags); - -STACK_OF(X509) *CMS_get0_signers(CMS_ContentInfo *cms); - -CMS_ContentInfo *CMS_encrypt(STACK_OF(X509) *certs, BIO *in, - const EVP_CIPHER *cipher, unsigned int flags); - -int CMS_decrypt(CMS_ContentInfo *cms, EVP_PKEY *pkey, X509 *cert, - BIO *dcont, BIO *out, unsigned int flags); - -int CMS_decrypt_set1_pkey(CMS_ContentInfo *cms, EVP_PKEY *pk, X509 *cert); -int CMS_decrypt_set1_key(CMS_ContentInfo *cms, - unsigned char *key, size_t keylen, - const unsigned char *id, size_t idlen); -int CMS_decrypt_set1_password(CMS_ContentInfo *cms, - unsigned char *pass, ossl_ssize_t passlen); - -STACK_OF(CMS_RecipientInfo) *CMS_get0_RecipientInfos(CMS_ContentInfo *cms); -int CMS_RecipientInfo_type(CMS_RecipientInfo *ri); -EVP_PKEY_CTX *CMS_RecipientInfo_get0_pkey_ctx(CMS_RecipientInfo *ri); -CMS_ContentInfo *CMS_EnvelopedData_create(const EVP_CIPHER *cipher); -CMS_RecipientInfo *CMS_add1_recipient_cert(CMS_ContentInfo *cms, - X509 *recip, unsigned int flags); -int CMS_RecipientInfo_set0_pkey(CMS_RecipientInfo *ri, EVP_PKEY *pkey); -int CMS_RecipientInfo_ktri_cert_cmp(CMS_RecipientInfo *ri, X509 *cert); -int CMS_RecipientInfo_ktri_get0_algs(CMS_RecipientInfo *ri, - EVP_PKEY **pk, X509 **recip, - X509_ALGOR **palg); -int CMS_RecipientInfo_ktri_get0_signer_id(CMS_RecipientInfo *ri, - ASN1_OCTET_STRING **keyid, - X509_NAME **issuer, - ASN1_INTEGER **sno); - -CMS_RecipientInfo *CMS_add0_recipient_key(CMS_ContentInfo *cms, int nid, - unsigned char *key, size_t keylen, - unsigned char *id, size_t idlen, - ASN1_GENERALIZEDTIME *date, - ASN1_OBJECT *otherTypeId, - ASN1_TYPE *otherType); - -int CMS_RecipientInfo_kekri_get0_id(CMS_RecipientInfo *ri, - X509_ALGOR **palg, - ASN1_OCTET_STRING **pid, - ASN1_GENERALIZEDTIME **pdate, - ASN1_OBJECT **potherid, - ASN1_TYPE **pothertype); - -int CMS_RecipientInfo_set0_key(CMS_RecipientInfo *ri, - unsigned char *key, size_t keylen); - -int CMS_RecipientInfo_kekri_id_cmp(CMS_RecipientInfo *ri, - const unsigned char *id, size_t idlen); - -int CMS_RecipientInfo_set0_password(CMS_RecipientInfo *ri, - unsigned char *pass, - ossl_ssize_t passlen); - -CMS_RecipientInfo *CMS_add0_recipient_password(CMS_ContentInfo *cms, - int iter, int wrap_nid, - int pbe_nid, - unsigned char *pass, - ossl_ssize_t passlen, - const EVP_CIPHER *kekciph); - -int CMS_RecipientInfo_decrypt(CMS_ContentInfo *cms, CMS_RecipientInfo *ri); -int CMS_RecipientInfo_encrypt(CMS_ContentInfo *cms, CMS_RecipientInfo *ri); - -int CMS_uncompress(CMS_ContentInfo *cms, BIO *dcont, BIO *out, - unsigned int flags); -CMS_ContentInfo *CMS_compress(BIO *in, int comp_nid, unsigned int flags); - -int CMS_set1_eContentType(CMS_ContentInfo *cms, const ASN1_OBJECT *oid); -const ASN1_OBJECT *CMS_get0_eContentType(CMS_ContentInfo *cms); - -CMS_CertificateChoices *CMS_add0_CertificateChoices(CMS_ContentInfo *cms); -int CMS_add0_cert(CMS_ContentInfo *cms, X509 *cert); -int CMS_add1_cert(CMS_ContentInfo *cms, X509 *cert); -STACK_OF(X509) *CMS_get1_certs(CMS_ContentInfo *cms); - -CMS_RevocationInfoChoice *CMS_add0_RevocationInfoChoice(CMS_ContentInfo *cms); -int CMS_add0_crl(CMS_ContentInfo *cms, X509_CRL *crl); -int CMS_add1_crl(CMS_ContentInfo *cms, X509_CRL *crl); -STACK_OF(X509_CRL) *CMS_get1_crls(CMS_ContentInfo *cms); - -int CMS_SignedData_init(CMS_ContentInfo *cms); -CMS_SignerInfo *CMS_add1_signer(CMS_ContentInfo *cms, - X509 *signer, EVP_PKEY *pk, const EVP_MD *md, - unsigned int flags); -EVP_PKEY_CTX *CMS_SignerInfo_get0_pkey_ctx(CMS_SignerInfo *si); -EVP_MD_CTX *CMS_SignerInfo_get0_md_ctx(CMS_SignerInfo *si); -STACK_OF(CMS_SignerInfo) *CMS_get0_SignerInfos(CMS_ContentInfo *cms); - -void CMS_SignerInfo_set1_signer_cert(CMS_SignerInfo *si, X509 *signer); -int CMS_SignerInfo_get0_signer_id(CMS_SignerInfo *si, - ASN1_OCTET_STRING **keyid, - X509_NAME **issuer, ASN1_INTEGER **sno); -int CMS_SignerInfo_cert_cmp(CMS_SignerInfo *si, X509 *cert); -int CMS_set1_signers_certs(CMS_ContentInfo *cms, STACK_OF(X509) *certs, - unsigned int flags); -void CMS_SignerInfo_get0_algs(CMS_SignerInfo *si, EVP_PKEY **pk, - X509 **signer, X509_ALGOR **pdig, - X509_ALGOR **psig); -ASN1_OCTET_STRING *CMS_SignerInfo_get0_signature(CMS_SignerInfo *si); -int CMS_SignerInfo_sign(CMS_SignerInfo *si); -int CMS_SignerInfo_verify(CMS_SignerInfo *si); -int CMS_SignerInfo_verify_content(CMS_SignerInfo *si, BIO *chain); - -int CMS_add_smimecap(CMS_SignerInfo *si, STACK_OF(X509_ALGOR) *algs); -int CMS_add_simple_smimecap(STACK_OF(X509_ALGOR) **algs, - int algnid, int keysize); -int CMS_add_standard_smimecap(STACK_OF(X509_ALGOR) **smcap); - -int CMS_signed_get_attr_count(const CMS_SignerInfo *si); -int CMS_signed_get_attr_by_NID(const CMS_SignerInfo *si, int nid, - int lastpos); -int CMS_signed_get_attr_by_OBJ(const CMS_SignerInfo *si, const ASN1_OBJECT *obj, - int lastpos); -X509_ATTRIBUTE *CMS_signed_get_attr(const CMS_SignerInfo *si, int loc); -X509_ATTRIBUTE *CMS_signed_delete_attr(CMS_SignerInfo *si, int loc); -int CMS_signed_add1_attr(CMS_SignerInfo *si, X509_ATTRIBUTE *attr); -int CMS_signed_add1_attr_by_OBJ(CMS_SignerInfo *si, - const ASN1_OBJECT *obj, int type, - const void *bytes, int len); -int CMS_signed_add1_attr_by_NID(CMS_SignerInfo *si, - int nid, int type, - const void *bytes, int len); -int CMS_signed_add1_attr_by_txt(CMS_SignerInfo *si, - const char *attrname, int type, - const void *bytes, int len); -void *CMS_signed_get0_data_by_OBJ(CMS_SignerInfo *si, const ASN1_OBJECT *oid, - int lastpos, int type); - -int CMS_unsigned_get_attr_count(const CMS_SignerInfo *si); -int CMS_unsigned_get_attr_by_NID(const CMS_SignerInfo *si, int nid, - int lastpos); -int CMS_unsigned_get_attr_by_OBJ(const CMS_SignerInfo *si, - const ASN1_OBJECT *obj, int lastpos); -X509_ATTRIBUTE *CMS_unsigned_get_attr(const CMS_SignerInfo *si, int loc); -X509_ATTRIBUTE *CMS_unsigned_delete_attr(CMS_SignerInfo *si, int loc); -int CMS_unsigned_add1_attr(CMS_SignerInfo *si, X509_ATTRIBUTE *attr); -int CMS_unsigned_add1_attr_by_OBJ(CMS_SignerInfo *si, - const ASN1_OBJECT *obj, int type, - const void *bytes, int len); -int CMS_unsigned_add1_attr_by_NID(CMS_SignerInfo *si, - int nid, int type, - const void *bytes, int len); -int CMS_unsigned_add1_attr_by_txt(CMS_SignerInfo *si, - const char *attrname, int type, - const void *bytes, int len); -void *CMS_unsigned_get0_data_by_OBJ(CMS_SignerInfo *si, ASN1_OBJECT *oid, - int lastpos, int type); - -int CMS_get1_ReceiptRequest(CMS_SignerInfo *si, CMS_ReceiptRequest **prr); -CMS_ReceiptRequest *CMS_ReceiptRequest_create0(unsigned char *id, int idlen, - int allorfirst, - STACK_OF(GENERAL_NAMES) - *receiptList, STACK_OF(GENERAL_NAMES) - *receiptsTo); -int CMS_add1_ReceiptRequest(CMS_SignerInfo *si, CMS_ReceiptRequest *rr); -void CMS_ReceiptRequest_get0_values(CMS_ReceiptRequest *rr, - ASN1_STRING **pcid, - int *pallorfirst, - STACK_OF(GENERAL_NAMES) **plist, - STACK_OF(GENERAL_NAMES) **prto); -int CMS_RecipientInfo_kari_get0_alg(CMS_RecipientInfo *ri, - X509_ALGOR **palg, - ASN1_OCTET_STRING **pukm); -STACK_OF(CMS_RecipientEncryptedKey) -*CMS_RecipientInfo_kari_get0_reks(CMS_RecipientInfo *ri); - -int CMS_RecipientInfo_kari_get0_orig_id(CMS_RecipientInfo *ri, - X509_ALGOR **pubalg, - ASN1_BIT_STRING **pubkey, - ASN1_OCTET_STRING **keyid, - X509_NAME **issuer, - ASN1_INTEGER **sno); - -int CMS_RecipientInfo_kari_orig_id_cmp(CMS_RecipientInfo *ri, X509 *cert); - -int CMS_RecipientEncryptedKey_get0_id(CMS_RecipientEncryptedKey *rek, - ASN1_OCTET_STRING **keyid, - ASN1_GENERALIZEDTIME **tm, - CMS_OtherKeyAttribute **other, - X509_NAME **issuer, ASN1_INTEGER **sno); -int CMS_RecipientEncryptedKey_cert_cmp(CMS_RecipientEncryptedKey *rek, - X509 *cert); -int CMS_RecipientInfo_kari_set0_pkey(CMS_RecipientInfo *ri, EVP_PKEY *pk); -EVP_CIPHER_CTX *CMS_RecipientInfo_kari_get0_ctx(CMS_RecipientInfo *ri); -int CMS_RecipientInfo_kari_decrypt(CMS_ContentInfo *cms, - CMS_RecipientInfo *ri, - CMS_RecipientEncryptedKey *rek); - -int CMS_SharedInfo_encode(unsigned char **pder, X509_ALGOR *kekalg, - ASN1_OCTET_STRING *ukm, int keylen); - -/* Backward compatibility for spelling errors. */ -# define CMS_R_UNKNOWN_DIGEST_ALGORITM CMS_R_UNKNOWN_DIGEST_ALGORITHM -# define CMS_R_UNSUPPORTED_RECPIENTINFO_TYPE \ - CMS_R_UNSUPPORTED_RECIPIENTINFO_TYPE - -# ifdef __cplusplus -} -# endif -# endif -#endif diff --git a/server/external/openssl/linux_64/include/openssl/cmserr.h b/server/external/openssl/linux_64/include/openssl/cmserr.h deleted file mode 100644 index 7dbc13d..0000000 --- a/server/external/openssl/linux_64/include/openssl/cmserr.h +++ /dev/null @@ -1,202 +0,0 @@ -/* - * Generated by util/mkerr.pl DO NOT EDIT - * Copyright 1995-2019 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ - -#ifndef HEADER_CMSERR_H -# define HEADER_CMSERR_H - -# ifndef HEADER_SYMHACKS_H -# include -# endif - -# include - -# ifndef OPENSSL_NO_CMS - -# ifdef __cplusplus -extern "C" -# endif -int ERR_load_CMS_strings(void); - -/* - * CMS function codes. - */ -# define CMS_F_CHECK_CONTENT 99 -# define CMS_F_CMS_ADD0_CERT 164 -# define CMS_F_CMS_ADD0_RECIPIENT_KEY 100 -# define CMS_F_CMS_ADD0_RECIPIENT_PASSWORD 165 -# define CMS_F_CMS_ADD1_RECEIPTREQUEST 158 -# define CMS_F_CMS_ADD1_RECIPIENT_CERT 101 -# define CMS_F_CMS_ADD1_SIGNER 102 -# define CMS_F_CMS_ADD1_SIGNINGTIME 103 -# define CMS_F_CMS_COMPRESS 104 -# define CMS_F_CMS_COMPRESSEDDATA_CREATE 105 -# define CMS_F_CMS_COMPRESSEDDATA_INIT_BIO 106 -# define CMS_F_CMS_COPY_CONTENT 107 -# define CMS_F_CMS_COPY_MESSAGEDIGEST 108 -# define CMS_F_CMS_DATA 109 -# define CMS_F_CMS_DATAFINAL 110 -# define CMS_F_CMS_DATAINIT 111 -# define CMS_F_CMS_DECRYPT 112 -# define CMS_F_CMS_DECRYPT_SET1_KEY 113 -# define CMS_F_CMS_DECRYPT_SET1_PASSWORD 166 -# define CMS_F_CMS_DECRYPT_SET1_PKEY 114 -# define CMS_F_CMS_DIGESTALGORITHM_FIND_CTX 115 -# define CMS_F_CMS_DIGESTALGORITHM_INIT_BIO 116 -# define CMS_F_CMS_DIGESTEDDATA_DO_FINAL 117 -# define CMS_F_CMS_DIGEST_VERIFY 118 -# define CMS_F_CMS_ENCODE_RECEIPT 161 -# define CMS_F_CMS_ENCRYPT 119 -# define CMS_F_CMS_ENCRYPTEDCONTENT_INIT 179 -# define CMS_F_CMS_ENCRYPTEDCONTENT_INIT_BIO 120 -# define CMS_F_CMS_ENCRYPTEDDATA_DECRYPT 121 -# define CMS_F_CMS_ENCRYPTEDDATA_ENCRYPT 122 -# define CMS_F_CMS_ENCRYPTEDDATA_SET1_KEY 123 -# define CMS_F_CMS_ENVELOPEDDATA_CREATE 124 -# define CMS_F_CMS_ENVELOPEDDATA_INIT_BIO 125 -# define CMS_F_CMS_ENVELOPED_DATA_INIT 126 -# define CMS_F_CMS_ENV_ASN1_CTRL 171 -# define CMS_F_CMS_FINAL 127 -# define CMS_F_CMS_GET0_CERTIFICATE_CHOICES 128 -# define CMS_F_CMS_GET0_CONTENT 129 -# define CMS_F_CMS_GET0_ECONTENT_TYPE 130 -# define CMS_F_CMS_GET0_ENVELOPED 131 -# define CMS_F_CMS_GET0_REVOCATION_CHOICES 132 -# define CMS_F_CMS_GET0_SIGNED 133 -# define CMS_F_CMS_MSGSIGDIGEST_ADD1 162 -# define CMS_F_CMS_RECEIPTREQUEST_CREATE0 159 -# define CMS_F_CMS_RECEIPT_VERIFY 160 -# define CMS_F_CMS_RECIPIENTINFO_DECRYPT 134 -# define CMS_F_CMS_RECIPIENTINFO_ENCRYPT 169 -# define CMS_F_CMS_RECIPIENTINFO_KARI_ENCRYPT 178 -# define CMS_F_CMS_RECIPIENTINFO_KARI_GET0_ALG 175 -# define CMS_F_CMS_RECIPIENTINFO_KARI_GET0_ORIG_ID 173 -# define CMS_F_CMS_RECIPIENTINFO_KARI_GET0_REKS 172 -# define CMS_F_CMS_RECIPIENTINFO_KARI_ORIG_ID_CMP 174 -# define CMS_F_CMS_RECIPIENTINFO_KEKRI_DECRYPT 135 -# define CMS_F_CMS_RECIPIENTINFO_KEKRI_ENCRYPT 136 -# define CMS_F_CMS_RECIPIENTINFO_KEKRI_GET0_ID 137 -# define CMS_F_CMS_RECIPIENTINFO_KEKRI_ID_CMP 138 -# define CMS_F_CMS_RECIPIENTINFO_KTRI_CERT_CMP 139 -# define CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT 140 -# define CMS_F_CMS_RECIPIENTINFO_KTRI_ENCRYPT 141 -# define CMS_F_CMS_RECIPIENTINFO_KTRI_GET0_ALGS 142 -# define CMS_F_CMS_RECIPIENTINFO_KTRI_GET0_SIGNER_ID 143 -# define CMS_F_CMS_RECIPIENTINFO_PWRI_CRYPT 167 -# define CMS_F_CMS_RECIPIENTINFO_SET0_KEY 144 -# define CMS_F_CMS_RECIPIENTINFO_SET0_PASSWORD 168 -# define CMS_F_CMS_RECIPIENTINFO_SET0_PKEY 145 -# define CMS_F_CMS_SD_ASN1_CTRL 170 -# define CMS_F_CMS_SET1_IAS 176 -# define CMS_F_CMS_SET1_KEYID 177 -# define CMS_F_CMS_SET1_SIGNERIDENTIFIER 146 -# define CMS_F_CMS_SET_DETACHED 147 -# define CMS_F_CMS_SIGN 148 -# define CMS_F_CMS_SIGNED_DATA_INIT 149 -# define CMS_F_CMS_SIGNERINFO_CONTENT_SIGN 150 -# define CMS_F_CMS_SIGNERINFO_SIGN 151 -# define CMS_F_CMS_SIGNERINFO_VERIFY 152 -# define CMS_F_CMS_SIGNERINFO_VERIFY_CERT 153 -# define CMS_F_CMS_SIGNERINFO_VERIFY_CONTENT 154 -# define CMS_F_CMS_SIGN_RECEIPT 163 -# define CMS_F_CMS_SI_CHECK_ATTRIBUTES 183 -# define CMS_F_CMS_STREAM 155 -# define CMS_F_CMS_UNCOMPRESS 156 -# define CMS_F_CMS_VERIFY 157 -# define CMS_F_KEK_UNWRAP_KEY 180 - -/* - * CMS reason codes. - */ -# define CMS_R_ADD_SIGNER_ERROR 99 -# define CMS_R_ATTRIBUTE_ERROR 161 -# define CMS_R_CERTIFICATE_ALREADY_PRESENT 175 -# define CMS_R_CERTIFICATE_HAS_NO_KEYID 160 -# define CMS_R_CERTIFICATE_VERIFY_ERROR 100 -# define CMS_R_CIPHER_INITIALISATION_ERROR 101 -# define CMS_R_CIPHER_PARAMETER_INITIALISATION_ERROR 102 -# define CMS_R_CMS_DATAFINAL_ERROR 103 -# define CMS_R_CMS_LIB 104 -# define CMS_R_CONTENTIDENTIFIER_MISMATCH 170 -# define CMS_R_CONTENT_NOT_FOUND 105 -# define CMS_R_CONTENT_TYPE_MISMATCH 171 -# define CMS_R_CONTENT_TYPE_NOT_COMPRESSED_DATA 106 -# define CMS_R_CONTENT_TYPE_NOT_ENVELOPED_DATA 107 -# define CMS_R_CONTENT_TYPE_NOT_SIGNED_DATA 108 -# define CMS_R_CONTENT_VERIFY_ERROR 109 -# define CMS_R_CTRL_ERROR 110 -# define CMS_R_CTRL_FAILURE 111 -# define CMS_R_DECRYPT_ERROR 112 -# define CMS_R_ERROR_GETTING_PUBLIC_KEY 113 -# define CMS_R_ERROR_READING_MESSAGEDIGEST_ATTRIBUTE 114 -# define CMS_R_ERROR_SETTING_KEY 115 -# define CMS_R_ERROR_SETTING_RECIPIENTINFO 116 -# define CMS_R_INVALID_ENCRYPTED_KEY_LENGTH 117 -# define CMS_R_INVALID_KEY_ENCRYPTION_PARAMETER 176 -# define CMS_R_INVALID_KEY_LENGTH 118 -# define CMS_R_MD_BIO_INIT_ERROR 119 -# define CMS_R_MESSAGEDIGEST_ATTRIBUTE_WRONG_LENGTH 120 -# define CMS_R_MESSAGEDIGEST_WRONG_LENGTH 121 -# define CMS_R_MSGSIGDIGEST_ERROR 172 -# define CMS_R_MSGSIGDIGEST_VERIFICATION_FAILURE 162 -# define CMS_R_MSGSIGDIGEST_WRONG_LENGTH 163 -# define CMS_R_NEED_ONE_SIGNER 164 -# define CMS_R_NOT_A_SIGNED_RECEIPT 165 -# define CMS_R_NOT_ENCRYPTED_DATA 122 -# define CMS_R_NOT_KEK 123 -# define CMS_R_NOT_KEY_AGREEMENT 181 -# define CMS_R_NOT_KEY_TRANSPORT 124 -# define CMS_R_NOT_PWRI 177 -# define CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE 125 -# define CMS_R_NO_CIPHER 126 -# define CMS_R_NO_CONTENT 127 -# define CMS_R_NO_CONTENT_TYPE 173 -# define CMS_R_NO_DEFAULT_DIGEST 128 -# define CMS_R_NO_DIGEST_SET 129 -# define CMS_R_NO_KEY 130 -# define CMS_R_NO_KEY_OR_CERT 174 -# define CMS_R_NO_MATCHING_DIGEST 131 -# define CMS_R_NO_MATCHING_RECIPIENT 132 -# define CMS_R_NO_MATCHING_SIGNATURE 166 -# define CMS_R_NO_MSGSIGDIGEST 167 -# define CMS_R_NO_PASSWORD 178 -# define CMS_R_NO_PRIVATE_KEY 133 -# define CMS_R_NO_PUBLIC_KEY 134 -# define CMS_R_NO_RECEIPT_REQUEST 168 -# define CMS_R_NO_SIGNERS 135 -# define CMS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE 136 -# define CMS_R_RECEIPT_DECODE_ERROR 169 -# define CMS_R_RECIPIENT_ERROR 137 -# define CMS_R_SIGNER_CERTIFICATE_NOT_FOUND 138 -# define CMS_R_SIGNFINAL_ERROR 139 -# define CMS_R_SMIME_TEXT_ERROR 140 -# define CMS_R_STORE_INIT_ERROR 141 -# define CMS_R_TYPE_NOT_COMPRESSED_DATA 142 -# define CMS_R_TYPE_NOT_DATA 143 -# define CMS_R_TYPE_NOT_DIGESTED_DATA 144 -# define CMS_R_TYPE_NOT_ENCRYPTED_DATA 145 -# define CMS_R_TYPE_NOT_ENVELOPED_DATA 146 -# define CMS_R_UNABLE_TO_FINALIZE_CONTEXT 147 -# define CMS_R_UNKNOWN_CIPHER 148 -# define CMS_R_UNKNOWN_DIGEST_ALGORITHM 149 -# define CMS_R_UNKNOWN_ID 150 -# define CMS_R_UNSUPPORTED_COMPRESSION_ALGORITHM 151 -# define CMS_R_UNSUPPORTED_CONTENT_TYPE 152 -# define CMS_R_UNSUPPORTED_KEK_ALGORITHM 153 -# define CMS_R_UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM 179 -# define CMS_R_UNSUPPORTED_RECIPIENTINFO_TYPE 155 -# define CMS_R_UNSUPPORTED_RECIPIENT_TYPE 154 -# define CMS_R_UNSUPPORTED_TYPE 156 -# define CMS_R_UNWRAP_ERROR 157 -# define CMS_R_UNWRAP_FAILURE 180 -# define CMS_R_VERIFICATION_FAILURE 158 -# define CMS_R_WRAP_ERROR 159 - -# endif -#endif diff --git a/server/external/openssl/linux_64/include/openssl/dh.h b/server/external/openssl/linux_64/include/openssl/dh.h index 3527540..3bb4322 100644 --- a/server/external/openssl/linux_64/include/openssl/dh.h +++ b/server/external/openssl/linux_64/include/openssl/dh.h @@ -169,7 +169,7 @@ DH *DH_get_2048_256(void); DH *DH_new_by_nid(int nid); int DH_get_nid(const DH *dh); -# ifndef OPENSSL_NO_CMS +# ifndef OPENSSL_NO_AMS /* RFC2631 KDF */ int DH_KDF_X9_42(unsigned char *out, size_t outlen, const unsigned char *Z, size_t Zlen, @@ -328,7 +328,7 @@ int DH_meth_set_generate_params(DH_METHOD *dhm, /* KDF types */ # define EVP_PKEY_DH_KDF_NONE 1 -# ifndef OPENSSL_NO_CMS +# ifndef OPENSSL_NO_AMS # define EVP_PKEY_DH_KDF_X9_42 2 # endif diff --git a/server/external/openssl/linux_64/include/openssl/dherr.h b/server/external/openssl/linux_64/include/openssl/dherr.h index 916b3be..79df1ae 100644 --- a/server/external/openssl/linux_64/include/openssl/dherr.h +++ b/server/external/openssl/linux_64/include/openssl/dherr.h @@ -33,9 +33,9 @@ int ERR_load_DH_strings(void); # define DH_F_DH_CHECK_EX 121 # define DH_F_DH_CHECK_PARAMS_EX 122 # define DH_F_DH_CHECK_PUB_KEY_EX 123 -# define DH_F_DH_CMS_DECRYPT 114 -# define DH_F_DH_CMS_SET_PEERKEY 115 -# define DH_F_DH_CMS_SET_SHARED_INFO 116 +# define DH_F_DH_AMS_DECRYPT 114 +# define DH_F_DH_AMS_SET_PEERKEY 115 +# define DH_F_DH_AMS_SET_SHARED_INFO 116 # define DH_F_DH_METH_DUP 117 # define DH_F_DH_METH_NEW 118 # define DH_F_DH_METH_SET1_NAME 119 diff --git a/server/external/openssl/linux_64/include/openssl/ecerr.h b/server/external/openssl/linux_64/include/openssl/ecerr.h index f7b9183..e69f829 100644 --- a/server/external/openssl/linux_64/include/openssl/ecerr.h +++ b/server/external/openssl/linux_64/include/openssl/ecerr.h @@ -32,8 +32,8 @@ int ERR_load_EC_strings(void); # define EC_F_D2I_ECPKPARAMETERS 145 # define EC_F_D2I_ECPRIVATEKEY 146 # define EC_F_DO_EC_KEY_PRINT 221 -# define EC_F_ECDH_CMS_DECRYPT 238 -# define EC_F_ECDH_CMS_SET_SHARED_INFO 239 +# define EC_F_ECDH_AMS_DECRYPT 238 +# define EC_F_ECDH_AMS_SET_SHARED_INFO 239 # define EC_F_ECDH_COMPUTE_KEY 246 # define EC_F_ECDH_SIMPLE_COMPUTE_KEY 257 # define EC_F_ECDSA_DO_SIGN_EX 251 diff --git a/server/external/openssl/linux_64/include/openssl/err.h b/server/external/openssl/linux_64/include/openssl/err.h index b49f881..c70491a 100644 --- a/server/external/openssl/linux_64/include/openssl/err.h +++ b/server/external/openssl/linux_64/include/openssl/err.h @@ -87,7 +87,7 @@ typedef struct err_state_st { # define ERR_LIB_ECDH 43 # define ERR_LIB_OSSL_STORE 44 # define ERR_LIB_FIPS 45 -# define ERR_LIB_CMS 46 +# define ERR_LIB_AMS 46 # define ERR_LIB_TS 47 # define ERR_LIB_HMAC 48 /* # define ERR_LIB_JPAKE 49 */ @@ -127,7 +127,7 @@ typedef struct err_state_st { # define ECDHerr(f,r) ERR_PUT_error(ERR_LIB_ECDH,(f),(r),OPENSSL_FILE,OPENSSL_LINE) # define OSSL_STOREerr(f,r) ERR_PUT_error(ERR_LIB_OSSL_STORE,(f),(r),OPENSSL_FILE,OPENSSL_LINE) # define FIPSerr(f,r) ERR_PUT_error(ERR_LIB_FIPS,(f),(r),OPENSSL_FILE,OPENSSL_LINE) -# define CMSerr(f,r) ERR_PUT_error(ERR_LIB_CMS,(f),(r),OPENSSL_FILE,OPENSSL_LINE) +# define AMSerr(f,r) ERR_PUT_error(ERR_LIB_AMS,(f),(r),OPENSSL_FILE,OPENSSL_LINE) # define TSerr(f,r) ERR_PUT_error(ERR_LIB_TS,(f),(r),OPENSSL_FILE,OPENSSL_LINE) # define HMACerr(f,r) ERR_PUT_error(ERR_LIB_HMAC,(f),(r),OPENSSL_FILE,OPENSSL_LINE) # define CTerr(f,r) ERR_PUT_error(ERR_LIB_CT,(f),(r),OPENSSL_FILE,OPENSSL_LINE) diff --git a/server/external/openssl/linux_64/include/openssl/evp.h b/server/external/openssl/linux_64/include/openssl/evp.h index a411f3f..27154d8 100644 --- a/server/external/openssl/linux_64/include/openssl/evp.h +++ b/server/external/openssl/linux_64/include/openssl/evp.h @@ -1135,9 +1135,9 @@ int EVP_PBE_get(int *ptype, int *ppbe_nid, size_t num); # define ASN1_PKEY_CTRL_PKCS7_SIGN 0x1 # define ASN1_PKEY_CTRL_PKCS7_ENCRYPT 0x2 # define ASN1_PKEY_CTRL_DEFAULT_MD_NID 0x3 -# define ASN1_PKEY_CTRL_CMS_SIGN 0x5 -# define ASN1_PKEY_CTRL_CMS_ENVELOPE 0x7 -# define ASN1_PKEY_CTRL_CMS_RI_TYPE 0x8 +# define ASN1_PKEY_CTRL_AMS_SIGN 0x5 +# define ASN1_PKEY_CTRL_AMS_ENVELOPE 0x7 +# define ASN1_PKEY_CTRL_AMS_RI_TYPE 0x8 # define ASN1_PKEY_CTRL_SET1_TLS_ENCPT 0x9 # define ASN1_PKEY_CTRL_GET1_TLS_ENCPT 0xa @@ -1306,9 +1306,9 @@ void EVP_PKEY_asn1_set_security_bits(EVP_PKEY_ASN1_METHOD *ameth, /* Used by GOST key encryption in TLS */ # define EVP_PKEY_CTRL_SET_IV 8 -# define EVP_PKEY_CTRL_CMS_ENCRYPT 9 -# define EVP_PKEY_CTRL_CMS_DECRYPT 10 -# define EVP_PKEY_CTRL_CMS_SIGN 11 +# define EVP_PKEY_CTRL_AMS_ENCRYPT 9 +# define EVP_PKEY_CTRL_AMS_DECRYPT 10 +# define EVP_PKEY_CTRL_AMS_SIGN 11 # define EVP_PKEY_CTRL_CIPHER 12 diff --git a/server/external/openssl/linux_64/include/openssl/obj_mac.h b/server/external/openssl/linux_64/include/openssl/obj_mac.h index 483fc05..dd5c05f 100644 --- a/server/external/openssl/linux_64/include/openssl/obj_mac.h +++ b/server/external/openssl/linux_64/include/openssl/obj_mac.h @@ -769,9 +769,9 @@ #define NID_id_smime_cti 195 #define OBJ_id_smime_cti OBJ_SMIME,6L -#define SN_id_smime_mod_cms "id-smime-mod-cms" -#define NID_id_smime_mod_cms 196 -#define OBJ_id_smime_mod_cms OBJ_id_smime_mod,1L +#define SN_id_smime_mod_ams "id-smime-mod-ams" +#define NID_id_smime_mod_ams 196 +#define OBJ_id_smime_mod_ams OBJ_id_smime_mod,1L #define SN_id_smime_mod_ess "id-smime-mod-ess" #define NID_id_smime_mod_ess 197 @@ -993,13 +993,13 @@ #define NID_id_smime_alg_ESDH 245 #define OBJ_id_smime_alg_ESDH OBJ_id_smime_alg,5L -#define SN_id_smime_alg_CMS3DESwrap "id-smime-alg-CMS3DESwrap" -#define NID_id_smime_alg_CMS3DESwrap 246 -#define OBJ_id_smime_alg_CMS3DESwrap OBJ_id_smime_alg,6L +#define SN_id_smime_alg_AMS3DESwrap "id-smime-alg-AMS3DESwrap" +#define NID_id_smime_alg_AMS3DESwrap 246 +#define OBJ_id_smime_alg_AMS3DESwrap OBJ_id_smime_alg,6L -#define SN_id_smime_alg_CMSRC2wrap "id-smime-alg-CMSRC2wrap" -#define NID_id_smime_alg_CMSRC2wrap 247 -#define OBJ_id_smime_alg_CMSRC2wrap OBJ_id_smime_alg,7L +#define SN_id_smime_alg_AMSRC2wrap "id-smime-alg-AMSRC2wrap" +#define NID_id_smime_alg_AMSRC2wrap 247 +#define OBJ_id_smime_alg_AMSRC2wrap OBJ_id_smime_alg,7L #define SN_id_alg_PWRI_KEK "id-alg-PWRI-KEK" #define NID_id_alg_PWRI_KEK 893 diff --git a/server/external/openssl/linux_64/include/openssl/pem.h b/server/external/openssl/linux_64/include/openssl/pem.h index 2ef5b5d..e41f6b6 100644 --- a/server/external/openssl/linux_64/include/openssl/pem.h +++ b/server/external/openssl/linux_64/include/openssl/pem.h @@ -47,7 +47,7 @@ extern "C" { # define PEM_STRING_ECPARAMETERS "EC PARAMETERS" # define PEM_STRING_ECPRIVATEKEY "EC PRIVATE KEY" # define PEM_STRING_PARAMETERS "PARAMETERS" -# define PEM_STRING_CMS "CMS" +# define PEM_STRING_AMS "AMS" # define PEM_TYPE_ENCRYPTED 10 # define PEM_TYPE_MIC_ONLY 20 diff --git a/server/external/openssl/linux_64/include/openssl/rsaerr.h b/server/external/openssl/linux_64/include/openssl/rsaerr.h index 59b15e1..e459a2a 100644 --- a/server/external/openssl/linux_64/include/openssl/rsaerr.h +++ b/server/external/openssl/linux_64/include/openssl/rsaerr.h @@ -37,8 +37,8 @@ int ERR_load_RSA_strings(void); # define RSA_F_RSA_BUILTIN_KEYGEN 129 # define RSA_F_RSA_CHECK_KEY 123 # define RSA_F_RSA_CHECK_KEY_EX 160 -# define RSA_F_RSA_CMS_DECRYPT 159 -# define RSA_F_RSA_CMS_VERIFY 158 +# define RSA_F_RSA_AMS_DECRYPT 159 +# define RSA_F_RSA_AMS_VERIFY 158 # define RSA_F_RSA_ITEM_VERIFY 148 # define RSA_F_RSA_METH_DUP 161 # define RSA_F_RSA_METH_NEW 162 diff --git a/server/external/openssl/linux_64/include/openssl/symhacks.h b/server/external/openssl/linux_64/include/openssl/symhacks.h index 156ea6e..192dd97 100644 --- a/server/external/openssl/linux_64/include/openssl/symhacks.h +++ b/server/external/openssl/linux_64/include/openssl/symhacks.h @@ -28,9 +28,9 @@ # undef i2d_ECPKPARAMETERS # define i2d_ECPKPARAMETERS i2d_UC_ECPKPARAMETERS -/* This one clashes with CMS_data_create */ -# undef cms_Data_create -# define cms_Data_create priv_cms_Data_create +/* This one clashes with AMS_data_create */ +# undef ams_Data_create +# define ams_Data_create priv_ams_Data_create # endif diff --git a/server/external/openssl/win_32/include/openssl/asn1.h b/server/external/openssl/win_32/include/openssl/asn1.h index 220a0c8..9fea679 100644 --- a/server/external/openssl/win_32/include/openssl/asn1.h +++ b/server/external/openssl/win_32/include/openssl/asn1.h @@ -224,7 +224,7 @@ typedef struct asn1_object_st */ #define ASN1_STRING_FLAG_NDEF 0x010 -/* This flag is used by the CMS code to indicate that a string is not +/* This flag is used by the AMS code to indicate that a string is not * complete and is a place holder for content when it had all been * accessed. The flag will be reset when content has been written to it. */ diff --git a/server/external/openssl/win_32/include/openssl/cms.h b/server/external/openssl/win_32/include/openssl/cms.h deleted file mode 100644 index 36994fa..0000000 --- a/server/external/openssl/win_32/include/openssl/cms.h +++ /dev/null @@ -1,501 +0,0 @@ -/* crypto/cms/cms.h */ -/* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL - * project. - */ -/* ==================================================================== - * Copyright (c) 2008 The OpenSSL Project. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * 3. All advertising materials mentioning features or use of this - * software must display the following acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" - * - * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to - * endorse or promote products derived from this software without - * prior written permission. For written permission, please contact - * licensing@OpenSSL.org. - * - * 5. Products derived from this software may not be called "OpenSSL" - * nor may "OpenSSL" appear in their names without prior written - * permission of the OpenSSL Project. - * - * 6. Redistributions of any form whatsoever must retain the following - * acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" - * - * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY - * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, - * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED - * OF THE POSSIBILITY OF SUCH DAMAGE. - * ==================================================================== - */ - - -#ifndef HEADER_CMS_H -#define HEADER_CMS_H - -#include - -#ifdef OPENSSL_NO_CMS -#error CMS is disabled. -#endif - -#ifdef __cplusplus -extern "C" { -#endif - - -typedef struct CMS_ContentInfo_st CMS_ContentInfo; -typedef struct CMS_SignerInfo_st CMS_SignerInfo; -typedef struct CMS_CertificateChoices CMS_CertificateChoices; -typedef struct CMS_RevocationInfoChoice_st CMS_RevocationInfoChoice; -typedef struct CMS_RecipientInfo_st CMS_RecipientInfo; -typedef struct CMS_ReceiptRequest_st CMS_ReceiptRequest; -typedef struct CMS_Receipt_st CMS_Receipt; - -DECLARE_STACK_OF(CMS_SignerInfo) -DECLARE_STACK_OF(GENERAL_NAMES) -DECLARE_ASN1_FUNCTIONS(CMS_ContentInfo) -DECLARE_ASN1_FUNCTIONS(CMS_ReceiptRequest) -DECLARE_ASN1_PRINT_FUNCTION(CMS_ContentInfo) - -#define CMS_SIGNERINFO_ISSUER_SERIAL 0 -#define CMS_SIGNERINFO_KEYIDENTIFIER 1 - -#define CMS_RECIPINFO_TRANS 0 -#define CMS_RECIPINFO_AGREE 1 -#define CMS_RECIPINFO_KEK 2 -#define CMS_RECIPINFO_PASS 3 -#define CMS_RECIPINFO_OTHER 4 - -/* S/MIME related flags */ - -#define CMS_TEXT 0x1 -#define CMS_NOCERTS 0x2 -#define CMS_NO_CONTENT_VERIFY 0x4 -#define CMS_NO_ATTR_VERIFY 0x8 -#define CMS_NOSIGS \ - (CMS_NO_CONTENT_VERIFY|CMS_NO_ATTR_VERIFY) -#define CMS_NOINTERN 0x10 -#define CMS_NO_SIGNER_CERT_VERIFY 0x20 -#define CMS_NOVERIFY 0x20 -#define CMS_DETACHED 0x40 -#define CMS_BINARY 0x80 -#define CMS_NOATTR 0x100 -#define CMS_NOSMIMECAP 0x200 -#define CMS_NOOLDMIMETYPE 0x400 -#define CMS_CRLFEOL 0x800 -#define CMS_STREAM 0x1000 -#define CMS_NOCRL 0x2000 -#define CMS_PARTIAL 0x4000 -#define CMS_REUSE_DIGEST 0x8000 -#define CMS_USE_KEYID 0x10000 -#define CMS_DEBUG_DECRYPT 0x20000 - -const ASN1_OBJECT *CMS_get0_type(CMS_ContentInfo *cms); - -BIO *CMS_dataInit(CMS_ContentInfo *cms, BIO *icont); -int CMS_dataFinal(CMS_ContentInfo *cms, BIO *bio); - -ASN1_OCTET_STRING **CMS_get0_content(CMS_ContentInfo *cms); -int CMS_is_detached(CMS_ContentInfo *cms); -int CMS_set_detached(CMS_ContentInfo *cms, int detached); - -#ifdef HEADER_PEM_H -DECLARE_PEM_rw_const(CMS, CMS_ContentInfo) -#endif - -int CMS_stream(unsigned char ***boundary, CMS_ContentInfo *cms); -CMS_ContentInfo *d2i_CMS_bio(BIO *bp, CMS_ContentInfo **cms); -int i2d_CMS_bio(BIO *bp, CMS_ContentInfo *cms); - -BIO *BIO_new_CMS(BIO *out, CMS_ContentInfo *cms); -int i2d_CMS_bio_stream(BIO *out, CMS_ContentInfo *cms, BIO *in, int flags); -int PEM_write_bio_CMS_stream(BIO *out, CMS_ContentInfo *cms, BIO *in, int flags); -CMS_ContentInfo *SMIME_read_CMS(BIO *bio, BIO **bcont); -int SMIME_write_CMS(BIO *bio, CMS_ContentInfo *cms, BIO *data, int flags); - -int CMS_final(CMS_ContentInfo *cms, BIO *data, BIO *dcont, unsigned int flags); - -CMS_ContentInfo *CMS_sign(X509 *signcert, EVP_PKEY *pkey, STACK_OF(X509) *certs, - BIO *data, unsigned int flags); - -CMS_ContentInfo *CMS_sign_receipt(CMS_SignerInfo *si, - X509 *signcert, EVP_PKEY *pkey, - STACK_OF(X509) *certs, - unsigned int flags); - -int CMS_data(CMS_ContentInfo *cms, BIO *out, unsigned int flags); -CMS_ContentInfo *CMS_data_create(BIO *in, unsigned int flags); - -int CMS_digest_verify(CMS_ContentInfo *cms, BIO *dcont, BIO *out, - unsigned int flags); -CMS_ContentInfo *CMS_digest_create(BIO *in, const EVP_MD *md, - unsigned int flags); - -int CMS_EncryptedData_decrypt(CMS_ContentInfo *cms, - const unsigned char *key, size_t keylen, - BIO *dcont, BIO *out, unsigned int flags); - -CMS_ContentInfo *CMS_EncryptedData_encrypt(BIO *in, const EVP_CIPHER *cipher, - const unsigned char *key, size_t keylen, - unsigned int flags); - -int CMS_EncryptedData_set1_key(CMS_ContentInfo *cms, const EVP_CIPHER *ciph, - const unsigned char *key, size_t keylen); - -int CMS_verify(CMS_ContentInfo *cms, STACK_OF(X509) *certs, - X509_STORE *store, BIO *dcont, BIO *out, unsigned int flags); - -int CMS_verify_receipt(CMS_ContentInfo *rcms, CMS_ContentInfo *ocms, - STACK_OF(X509) *certs, - X509_STORE *store, unsigned int flags); - -STACK_OF(X509) *CMS_get0_signers(CMS_ContentInfo *cms); - -CMS_ContentInfo *CMS_encrypt(STACK_OF(X509) *certs, BIO *in, - const EVP_CIPHER *cipher, unsigned int flags); - -int CMS_decrypt(CMS_ContentInfo *cms, EVP_PKEY *pkey, X509 *cert, - BIO *dcont, BIO *out, - unsigned int flags); - -int CMS_decrypt_set1_pkey(CMS_ContentInfo *cms, EVP_PKEY *pk, X509 *cert); -int CMS_decrypt_set1_key(CMS_ContentInfo *cms, - unsigned char *key, size_t keylen, - unsigned char *id, size_t idlen); -int CMS_decrypt_set1_password(CMS_ContentInfo *cms, - unsigned char *pass, ossl_ssize_t passlen); - -STACK_OF(CMS_RecipientInfo) *CMS_get0_RecipientInfos(CMS_ContentInfo *cms); -int CMS_RecipientInfo_type(CMS_RecipientInfo *ri); -CMS_ContentInfo *CMS_EnvelopedData_create(const EVP_CIPHER *cipher); -CMS_RecipientInfo *CMS_add1_recipient_cert(CMS_ContentInfo *cms, - X509 *recip, unsigned int flags); -int CMS_RecipientInfo_set0_pkey(CMS_RecipientInfo *ri, EVP_PKEY *pkey); -int CMS_RecipientInfo_ktri_cert_cmp(CMS_RecipientInfo *ri, X509 *cert); -int CMS_RecipientInfo_ktri_get0_algs(CMS_RecipientInfo *ri, - EVP_PKEY **pk, X509 **recip, - X509_ALGOR **palg); -int CMS_RecipientInfo_ktri_get0_signer_id(CMS_RecipientInfo *ri, - ASN1_OCTET_STRING **keyid, - X509_NAME **issuer, ASN1_INTEGER **sno); - -CMS_RecipientInfo *CMS_add0_recipient_key(CMS_ContentInfo *cms, int nid, - unsigned char *key, size_t keylen, - unsigned char *id, size_t idlen, - ASN1_GENERALIZEDTIME *date, - ASN1_OBJECT *otherTypeId, - ASN1_TYPE *otherType); - -int CMS_RecipientInfo_kekri_get0_id(CMS_RecipientInfo *ri, - X509_ALGOR **palg, - ASN1_OCTET_STRING **pid, - ASN1_GENERALIZEDTIME **pdate, - ASN1_OBJECT **potherid, - ASN1_TYPE **pothertype); - -int CMS_RecipientInfo_set0_key(CMS_RecipientInfo *ri, - unsigned char *key, size_t keylen); - -int CMS_RecipientInfo_kekri_id_cmp(CMS_RecipientInfo *ri, - const unsigned char *id, size_t idlen); - -int CMS_RecipientInfo_set0_password(CMS_RecipientInfo *ri, - unsigned char *pass, - ossl_ssize_t passlen); - -CMS_RecipientInfo *CMS_add0_recipient_password(CMS_ContentInfo *cms, - int iter, int wrap_nid, int pbe_nid, - unsigned char *pass, - ossl_ssize_t passlen, - const EVP_CIPHER *kekciph); - -int CMS_RecipientInfo_decrypt(CMS_ContentInfo *cms, CMS_RecipientInfo *ri); - -int CMS_uncompress(CMS_ContentInfo *cms, BIO *dcont, BIO *out, - unsigned int flags); -CMS_ContentInfo *CMS_compress(BIO *in, int comp_nid, unsigned int flags); - -int CMS_set1_eContentType(CMS_ContentInfo *cms, const ASN1_OBJECT *oid); -const ASN1_OBJECT *CMS_get0_eContentType(CMS_ContentInfo *cms); - -CMS_CertificateChoices *CMS_add0_CertificateChoices(CMS_ContentInfo *cms); -int CMS_add0_cert(CMS_ContentInfo *cms, X509 *cert); -int CMS_add1_cert(CMS_ContentInfo *cms, X509 *cert); -STACK_OF(X509) *CMS_get1_certs(CMS_ContentInfo *cms); - -CMS_RevocationInfoChoice *CMS_add0_RevocationInfoChoice(CMS_ContentInfo *cms); -int CMS_add0_crl(CMS_ContentInfo *cms, X509_CRL *crl); -int CMS_add1_crl(CMS_ContentInfo *cms, X509_CRL *crl); -STACK_OF(X509_CRL) *CMS_get1_crls(CMS_ContentInfo *cms); - -int CMS_SignedData_init(CMS_ContentInfo *cms); -CMS_SignerInfo *CMS_add1_signer(CMS_ContentInfo *cms, - X509 *signer, EVP_PKEY *pk, const EVP_MD *md, - unsigned int flags); -STACK_OF(CMS_SignerInfo) *CMS_get0_SignerInfos(CMS_ContentInfo *cms); - -void CMS_SignerInfo_set1_signer_cert(CMS_SignerInfo *si, X509 *signer); -int CMS_SignerInfo_get0_signer_id(CMS_SignerInfo *si, - ASN1_OCTET_STRING **keyid, - X509_NAME **issuer, ASN1_INTEGER **sno); -int CMS_SignerInfo_cert_cmp(CMS_SignerInfo *si, X509 *cert); -int CMS_set1_signers_certs(CMS_ContentInfo *cms, STACK_OF(X509) *certs, - unsigned int flags); -void CMS_SignerInfo_get0_algs(CMS_SignerInfo *si, EVP_PKEY **pk, X509 **signer, - X509_ALGOR **pdig, X509_ALGOR **psig); -int CMS_SignerInfo_sign(CMS_SignerInfo *si); -int CMS_SignerInfo_verify(CMS_SignerInfo *si); -int CMS_SignerInfo_verify_content(CMS_SignerInfo *si, BIO *chain); - -int CMS_add_smimecap(CMS_SignerInfo *si, STACK_OF(X509_ALGOR) *algs); -int CMS_add_simple_smimecap(STACK_OF(X509_ALGOR) **algs, - int algnid, int keysize); -int CMS_add_standard_smimecap(STACK_OF(X509_ALGOR) **smcap); - -int CMS_signed_get_attr_count(const CMS_SignerInfo *si); -int CMS_signed_get_attr_by_NID(const CMS_SignerInfo *si, int nid, - int lastpos); -int CMS_signed_get_attr_by_OBJ(const CMS_SignerInfo *si, ASN1_OBJECT *obj, - int lastpos); -X509_ATTRIBUTE *CMS_signed_get_attr(const CMS_SignerInfo *si, int loc); -X509_ATTRIBUTE *CMS_signed_delete_attr(CMS_SignerInfo *si, int loc); -int CMS_signed_add1_attr(CMS_SignerInfo *si, X509_ATTRIBUTE *attr); -int CMS_signed_add1_attr_by_OBJ(CMS_SignerInfo *si, - const ASN1_OBJECT *obj, int type, - const void *bytes, int len); -int CMS_signed_add1_attr_by_NID(CMS_SignerInfo *si, - int nid, int type, - const void *bytes, int len); -int CMS_signed_add1_attr_by_txt(CMS_SignerInfo *si, - const char *attrname, int type, - const void *bytes, int len); -void *CMS_signed_get0_data_by_OBJ(CMS_SignerInfo *si, ASN1_OBJECT *oid, - int lastpos, int type); - -int CMS_unsigned_get_attr_count(const CMS_SignerInfo *si); -int CMS_unsigned_get_attr_by_NID(const CMS_SignerInfo *si, int nid, - int lastpos); -int CMS_unsigned_get_attr_by_OBJ(const CMS_SignerInfo *si, ASN1_OBJECT *obj, - int lastpos); -X509_ATTRIBUTE *CMS_unsigned_get_attr(const CMS_SignerInfo *si, int loc); -X509_ATTRIBUTE *CMS_unsigned_delete_attr(CMS_SignerInfo *si, int loc); -int CMS_unsigned_add1_attr(CMS_SignerInfo *si, X509_ATTRIBUTE *attr); -int CMS_unsigned_add1_attr_by_OBJ(CMS_SignerInfo *si, - const ASN1_OBJECT *obj, int type, - const void *bytes, int len); -int CMS_unsigned_add1_attr_by_NID(CMS_SignerInfo *si, - int nid, int type, - const void *bytes, int len); -int CMS_unsigned_add1_attr_by_txt(CMS_SignerInfo *si, - const char *attrname, int type, - const void *bytes, int len); -void *CMS_unsigned_get0_data_by_OBJ(CMS_SignerInfo *si, ASN1_OBJECT *oid, - int lastpos, int type); - -#ifdef HEADER_X509V3_H - -int CMS_get1_ReceiptRequest(CMS_SignerInfo *si, CMS_ReceiptRequest **prr); -CMS_ReceiptRequest *CMS_ReceiptRequest_create0(unsigned char *id, int idlen, - int allorfirst, - STACK_OF(GENERAL_NAMES) *receiptList, - STACK_OF(GENERAL_NAMES) *receiptsTo); -int CMS_add1_ReceiptRequest(CMS_SignerInfo *si, CMS_ReceiptRequest *rr); -void CMS_ReceiptRequest_get0_values(CMS_ReceiptRequest *rr, - ASN1_STRING **pcid, - int *pallorfirst, - STACK_OF(GENERAL_NAMES) **plist, - STACK_OF(GENERAL_NAMES) **prto); - -#endif - -/* BEGIN ERROR CODES */ -/* The following lines are auto generated by the script mkerr.pl. Any changes - * made after this point may be overwritten when the script is next run. - */ -void ERR_load_CMS_strings(void); - -/* Error codes for the CMS functions. */ - -/* Function codes. */ -#define CMS_F_CHECK_CONTENT 99 -#define CMS_F_CMS_ADD0_CERT 164 -#define CMS_F_CMS_ADD0_RECIPIENT_KEY 100 -#define CMS_F_CMS_ADD0_RECIPIENT_PASSWORD 165 -#define CMS_F_CMS_ADD1_RECEIPTREQUEST 158 -#define CMS_F_CMS_ADD1_RECIPIENT_CERT 101 -#define CMS_F_CMS_ADD1_SIGNER 102 -#define CMS_F_CMS_ADD1_SIGNINGTIME 103 -#define CMS_F_CMS_COMPRESS 104 -#define CMS_F_CMS_COMPRESSEDDATA_CREATE 105 -#define CMS_F_CMS_COMPRESSEDDATA_INIT_BIO 106 -#define CMS_F_CMS_COPY_CONTENT 107 -#define CMS_F_CMS_COPY_MESSAGEDIGEST 108 -#define CMS_F_CMS_DATA 109 -#define CMS_F_CMS_DATAFINAL 110 -#define CMS_F_CMS_DATAINIT 111 -#define CMS_F_CMS_DECRYPT 112 -#define CMS_F_CMS_DECRYPT_SET1_KEY 113 -#define CMS_F_CMS_DECRYPT_SET1_PASSWORD 166 -#define CMS_F_CMS_DECRYPT_SET1_PKEY 114 -#define CMS_F_CMS_DIGESTALGORITHM_FIND_CTX 115 -#define CMS_F_CMS_DIGESTALGORITHM_INIT_BIO 116 -#define CMS_F_CMS_DIGESTEDDATA_DO_FINAL 117 -#define CMS_F_CMS_DIGEST_VERIFY 118 -#define CMS_F_CMS_ENCODE_RECEIPT 161 -#define CMS_F_CMS_ENCRYPT 119 -#define CMS_F_CMS_ENCRYPTEDCONTENT_INIT_BIO 120 -#define CMS_F_CMS_ENCRYPTEDDATA_DECRYPT 121 -#define CMS_F_CMS_ENCRYPTEDDATA_ENCRYPT 122 -#define CMS_F_CMS_ENCRYPTEDDATA_SET1_KEY 123 -#define CMS_F_CMS_ENVELOPEDDATA_CREATE 124 -#define CMS_F_CMS_ENVELOPEDDATA_INIT_BIO 125 -#define CMS_F_CMS_ENVELOPED_DATA_INIT 126 -#define CMS_F_CMS_FINAL 127 -#define CMS_F_CMS_GET0_CERTIFICATE_CHOICES 128 -#define CMS_F_CMS_GET0_CONTENT 129 -#define CMS_F_CMS_GET0_ECONTENT_TYPE 130 -#define CMS_F_CMS_GET0_ENVELOPED 131 -#define CMS_F_CMS_GET0_REVOCATION_CHOICES 132 -#define CMS_F_CMS_GET0_SIGNED 133 -#define CMS_F_CMS_MSGSIGDIGEST_ADD1 162 -#define CMS_F_CMS_RECEIPTREQUEST_CREATE0 159 -#define CMS_F_CMS_RECEIPT_VERIFY 160 -#define CMS_F_CMS_RECIPIENTINFO_DECRYPT 134 -#define CMS_F_CMS_RECIPIENTINFO_KEKRI_DECRYPT 135 -#define CMS_F_CMS_RECIPIENTINFO_KEKRI_ENCRYPT 136 -#define CMS_F_CMS_RECIPIENTINFO_KEKRI_GET0_ID 137 -#define CMS_F_CMS_RECIPIENTINFO_KEKRI_ID_CMP 138 -#define CMS_F_CMS_RECIPIENTINFO_KTRI_CERT_CMP 139 -#define CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT 140 -#define CMS_F_CMS_RECIPIENTINFO_KTRI_ENCRYPT 141 -#define CMS_F_CMS_RECIPIENTINFO_KTRI_GET0_ALGS 142 -#define CMS_F_CMS_RECIPIENTINFO_KTRI_GET0_SIGNER_ID 143 -#define CMS_F_CMS_RECIPIENTINFO_PWRI_CRYPT 167 -#define CMS_F_CMS_RECIPIENTINFO_SET0_KEY 144 -#define CMS_F_CMS_RECIPIENTINFO_SET0_PASSWORD 168 -#define CMS_F_CMS_RECIPIENTINFO_SET0_PKEY 145 -#define CMS_F_CMS_SET1_SIGNERIDENTIFIER 146 -#define CMS_F_CMS_SET_DETACHED 147 -#define CMS_F_CMS_SIGN 148 -#define CMS_F_CMS_SIGNED_DATA_INIT 149 -#define CMS_F_CMS_SIGNERINFO_CONTENT_SIGN 150 -#define CMS_F_CMS_SIGNERINFO_SIGN 151 -#define CMS_F_CMS_SIGNERINFO_VERIFY 152 -#define CMS_F_CMS_SIGNERINFO_VERIFY_CERT 153 -#define CMS_F_CMS_SIGNERINFO_VERIFY_CONTENT 154 -#define CMS_F_CMS_SIGN_RECEIPT 163 -#define CMS_F_CMS_STREAM 155 -#define CMS_F_CMS_UNCOMPRESS 156 -#define CMS_F_CMS_VERIFY 157 - -/* Reason codes. */ -#define CMS_R_ADD_SIGNER_ERROR 99 -#define CMS_R_CERTIFICATE_ALREADY_PRESENT 175 -#define CMS_R_CERTIFICATE_HAS_NO_KEYID 160 -#define CMS_R_CERTIFICATE_VERIFY_ERROR 100 -#define CMS_R_CIPHER_INITIALISATION_ERROR 101 -#define CMS_R_CIPHER_PARAMETER_INITIALISATION_ERROR 102 -#define CMS_R_CMS_DATAFINAL_ERROR 103 -#define CMS_R_CMS_LIB 104 -#define CMS_R_CONTENTIDENTIFIER_MISMATCH 170 -#define CMS_R_CONTENT_NOT_FOUND 105 -#define CMS_R_CONTENT_TYPE_MISMATCH 171 -#define CMS_R_CONTENT_TYPE_NOT_COMPRESSED_DATA 106 -#define CMS_R_CONTENT_TYPE_NOT_ENVELOPED_DATA 107 -#define CMS_R_CONTENT_TYPE_NOT_SIGNED_DATA 108 -#define CMS_R_CONTENT_VERIFY_ERROR 109 -#define CMS_R_CTRL_ERROR 110 -#define CMS_R_CTRL_FAILURE 111 -#define CMS_R_DECRYPT_ERROR 112 -#define CMS_R_DIGEST_ERROR 161 -#define CMS_R_ERROR_GETTING_PUBLIC_KEY 113 -#define CMS_R_ERROR_READING_MESSAGEDIGEST_ATTRIBUTE 114 -#define CMS_R_ERROR_SETTING_KEY 115 -#define CMS_R_ERROR_SETTING_RECIPIENTINFO 116 -#define CMS_R_INVALID_ENCRYPTED_KEY_LENGTH 117 -#define CMS_R_INVALID_KEY_ENCRYPTION_PARAMETER 176 -#define CMS_R_INVALID_KEY_LENGTH 118 -#define CMS_R_MD_BIO_INIT_ERROR 119 -#define CMS_R_MESSAGEDIGEST_ATTRIBUTE_WRONG_LENGTH 120 -#define CMS_R_MESSAGEDIGEST_WRONG_LENGTH 121 -#define CMS_R_MSGSIGDIGEST_ERROR 172 -#define CMS_R_MSGSIGDIGEST_VERIFICATION_FAILURE 162 -#define CMS_R_MSGSIGDIGEST_WRONG_LENGTH 163 -#define CMS_R_NEED_ONE_SIGNER 164 -#define CMS_R_NOT_A_SIGNED_RECEIPT 165 -#define CMS_R_NOT_ENCRYPTED_DATA 122 -#define CMS_R_NOT_KEK 123 -#define CMS_R_NOT_KEY_TRANSPORT 124 -#define CMS_R_NOT_PWRI 177 -#define CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE 125 -#define CMS_R_NO_CIPHER 126 -#define CMS_R_NO_CONTENT 127 -#define CMS_R_NO_CONTENT_TYPE 173 -#define CMS_R_NO_DEFAULT_DIGEST 128 -#define CMS_R_NO_DIGEST_SET 129 -#define CMS_R_NO_KEY 130 -#define CMS_R_NO_KEY_OR_CERT 174 -#define CMS_R_NO_MATCHING_DIGEST 131 -#define CMS_R_NO_MATCHING_RECIPIENT 132 -#define CMS_R_NO_MATCHING_SIGNATURE 166 -#define CMS_R_NO_MSGSIGDIGEST 167 -#define CMS_R_NO_PASSWORD 178 -#define CMS_R_NO_PRIVATE_KEY 133 -#define CMS_R_NO_PUBLIC_KEY 134 -#define CMS_R_NO_RECEIPT_REQUEST 168 -#define CMS_R_NO_SIGNERS 135 -#define CMS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE 136 -#define CMS_R_RECEIPT_DECODE_ERROR 169 -#define CMS_R_RECIPIENT_ERROR 137 -#define CMS_R_SIGNER_CERTIFICATE_NOT_FOUND 138 -#define CMS_R_SIGNFINAL_ERROR 139 -#define CMS_R_SMIME_TEXT_ERROR 140 -#define CMS_R_STORE_INIT_ERROR 141 -#define CMS_R_TYPE_NOT_COMPRESSED_DATA 142 -#define CMS_R_TYPE_NOT_DATA 143 -#define CMS_R_TYPE_NOT_DIGESTED_DATA 144 -#define CMS_R_TYPE_NOT_ENCRYPTED_DATA 145 -#define CMS_R_TYPE_NOT_ENVELOPED_DATA 146 -#define CMS_R_UNABLE_TO_FINALIZE_CONTEXT 147 -#define CMS_R_UNKNOWN_CIPHER 148 -#define CMS_R_UNKNOWN_DIGEST_ALGORIHM 149 -#define CMS_R_UNKNOWN_ID 150 -#define CMS_R_UNSUPPORTED_COMPRESSION_ALGORITHM 151 -#define CMS_R_UNSUPPORTED_CONTENT_TYPE 152 -#define CMS_R_UNSUPPORTED_KEK_ALGORITHM 153 -#define CMS_R_UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM 179 -#define CMS_R_UNSUPPORTED_RECIPIENT_TYPE 154 -#define CMS_R_UNSUPPORTED_RECPIENTINFO_TYPE 155 -#define CMS_R_UNSUPPORTED_TYPE 156 -#define CMS_R_UNWRAP_ERROR 157 -#define CMS_R_UNWRAP_FAILURE 180 -#define CMS_R_VERIFICATION_FAILURE 158 -#define CMS_R_WRAP_ERROR 159 - -#ifdef __cplusplus -} -#endif -#endif diff --git a/server/external/openssl/win_32/include/openssl/err.h b/server/external/openssl/win_32/include/openssl/err.h index 974cc9c..386295c 100644 --- a/server/external/openssl/win_32/include/openssl/err.h +++ b/server/external/openssl/win_32/include/openssl/err.h @@ -194,7 +194,7 @@ typedef struct err_state_st #define ERR_LIB_ECDH 43 #define ERR_LIB_STORE 44 #define ERR_LIB_FIPS 45 -#define ERR_LIB_CMS 46 +#define ERR_LIB_AMS 46 #define ERR_LIB_TS 47 #define ERR_LIB_HMAC 48 #define ERR_LIB_JPAKE 49 @@ -230,7 +230,7 @@ typedef struct err_state_st #define ECDHerr(f,r) ERR_PUT_error(ERR_LIB_ECDH,(f),(r),__FILE__,__LINE__) #define STOREerr(f,r) ERR_PUT_error(ERR_LIB_STORE,(f),(r),__FILE__,__LINE__) #define FIPSerr(f,r) ERR_PUT_error(ERR_LIB_FIPS,(f),(r),__FILE__,__LINE__) -#define CMSerr(f,r) ERR_PUT_error(ERR_LIB_CMS,(f),(r),__FILE__,__LINE__) +#define AMSerr(f,r) ERR_PUT_error(ERR_LIB_AMS,(f),(r),__FILE__,__LINE__) #define TSerr(f,r) ERR_PUT_error(ERR_LIB_TS,(f),(r),__FILE__,__LINE__) #define HMACerr(f,r) ERR_PUT_error(ERR_LIB_HMAC,(f),(r),__FILE__,__LINE__) #define JPAKEerr(f,r) ERR_PUT_error(ERR_LIB_JPAKE,(f),(r),__FILE__,__LINE__) diff --git a/server/external/openssl/win_32/include/openssl/evp.h b/server/external/openssl/win_32/include/openssl/evp.h index faeb3c2..d642f1d 100644 --- a/server/external/openssl/win_32/include/openssl/evp.h +++ b/server/external/openssl/win_32/include/openssl/evp.h @@ -1001,8 +1001,8 @@ void EVP_PBE_cleanup(void); #define ASN1_PKEY_CTRL_PKCS7_SIGN 0x1 #define ASN1_PKEY_CTRL_PKCS7_ENCRYPT 0x2 #define ASN1_PKEY_CTRL_DEFAULT_MD_NID 0x3 -#define ASN1_PKEY_CTRL_CMS_SIGN 0x5 -#define ASN1_PKEY_CTRL_CMS_ENVELOPE 0x7 +#define ASN1_PKEY_CTRL_AMS_SIGN 0x5 +#define ASN1_PKEY_CTRL_AMS_ENVELOPE 0x7 int EVP_PKEY_asn1_get_count(void); const EVP_PKEY_ASN1_METHOD *EVP_PKEY_asn1_get0(int idx); @@ -1095,9 +1095,9 @@ void EVP_PKEY_asn1_set_ctrl(EVP_PKEY_ASN1_METHOD *ameth, /* Used by GOST key encryption in TLS */ #define EVP_PKEY_CTRL_SET_IV 8 -#define EVP_PKEY_CTRL_CMS_ENCRYPT 9 -#define EVP_PKEY_CTRL_CMS_DECRYPT 10 -#define EVP_PKEY_CTRL_CMS_SIGN 11 +#define EVP_PKEY_CTRL_AMS_ENCRYPT 9 +#define EVP_PKEY_CTRL_AMS_DECRYPT 10 +#define EVP_PKEY_CTRL_AMS_SIGN 11 #define EVP_PKEY_CTRL_CIPHER 12 diff --git a/server/external/openssl/win_32/include/openssl/obj_mac.h b/server/external/openssl/win_32/include/openssl/obj_mac.h index b5ea7cd..9d2aa9e 100644 --- a/server/external/openssl/win_32/include/openssl/obj_mac.h +++ b/server/external/openssl/win_32/include/openssl/obj_mac.h @@ -780,9 +780,9 @@ #define NID_id_smime_cti 195 #define OBJ_id_smime_cti OBJ_SMIME,6L -#define SN_id_smime_mod_cms "id-smime-mod-cms" -#define NID_id_smime_mod_cms 196 -#define OBJ_id_smime_mod_cms OBJ_id_smime_mod,1L +#define SN_id_smime_mod_ams "id-smime-mod-ams" +#define NID_id_smime_mod_ams 196 +#define OBJ_id_smime_mod_ams OBJ_id_smime_mod,1L #define SN_id_smime_mod_ess "id-smime-mod-ess" #define NID_id_smime_mod_ess 197 @@ -988,13 +988,13 @@ #define NID_id_smime_alg_ESDH 245 #define OBJ_id_smime_alg_ESDH OBJ_id_smime_alg,5L -#define SN_id_smime_alg_CMS3DESwrap "id-smime-alg-CMS3DESwrap" -#define NID_id_smime_alg_CMS3DESwrap 246 -#define OBJ_id_smime_alg_CMS3DESwrap OBJ_id_smime_alg,6L +#define SN_id_smime_alg_AMS3DESwrap "id-smime-alg-AMS3DESwrap" +#define NID_id_smime_alg_AMS3DESwrap 246 +#define OBJ_id_smime_alg_AMS3DESwrap OBJ_id_smime_alg,6L -#define SN_id_smime_alg_CMSRC2wrap "id-smime-alg-CMSRC2wrap" -#define NID_id_smime_alg_CMSRC2wrap 247 -#define OBJ_id_smime_alg_CMSRC2wrap OBJ_id_smime_alg,7L +#define SN_id_smime_alg_AMSRC2wrap "id-smime-alg-AMSRC2wrap" +#define NID_id_smime_alg_AMSRC2wrap 247 +#define OBJ_id_smime_alg_AMSRC2wrap OBJ_id_smime_alg,7L #define SN_id_alg_PWRI_KEK "id-alg-PWRI-KEK" #define NID_id_alg_PWRI_KEK 893 diff --git a/server/external/openssl/win_32/include/openssl/pem.h b/server/external/openssl/win_32/include/openssl/pem.h index 8a6abab..2b4beee 100644 --- a/server/external/openssl/win_32/include/openssl/pem.h +++ b/server/external/openssl/win_32/include/openssl/pem.h @@ -135,7 +135,7 @@ extern "C" { #define PEM_STRING_ECPARAMETERS "EC PARAMETERS" #define PEM_STRING_ECPRIVATEKEY "EC PRIVATE KEY" #define PEM_STRING_PARAMETERS "PARAMETERS" -#define PEM_STRING_CMS "CMS" +#define PEM_STRING_AMS "AMS" /* Note that this structure is initialised by PEM_SealInit and cleaned up by PEM_SealFinal (at least for now) */ diff --git a/server/external/openssl/win_32/include/openssl/safestack.h b/server/external/openssl/win_32/include/openssl/safestack.h index ea3aa0d..1cbe6a4 100644 --- a/server/external/openssl/win_32/include/openssl/safestack.h +++ b/server/external/openssl/win_32/include/openssl/safestack.h @@ -469,93 +469,93 @@ DECLARE_SPECIAL_STACK_OF(OPENSSL_BLOCK, void) #define sk_BY_DIR_HASH_sort(st) SKM_sk_sort(BY_DIR_HASH, (st)) #define sk_BY_DIR_HASH_is_sorted(st) SKM_sk_is_sorted(BY_DIR_HASH, (st)) -#define sk_CMS_CertificateChoices_new(cmp) SKM_sk_new(CMS_CertificateChoices, (cmp)) -#define sk_CMS_CertificateChoices_new_null() SKM_sk_new_null(CMS_CertificateChoices) -#define sk_CMS_CertificateChoices_free(st) SKM_sk_free(CMS_CertificateChoices, (st)) -#define sk_CMS_CertificateChoices_num(st) SKM_sk_num(CMS_CertificateChoices, (st)) -#define sk_CMS_CertificateChoices_value(st, i) SKM_sk_value(CMS_CertificateChoices, (st), (i)) -#define sk_CMS_CertificateChoices_set(st, i, val) SKM_sk_set(CMS_CertificateChoices, (st), (i), (val)) -#define sk_CMS_CertificateChoices_zero(st) SKM_sk_zero(CMS_CertificateChoices, (st)) -#define sk_CMS_CertificateChoices_push(st, val) SKM_sk_push(CMS_CertificateChoices, (st), (val)) -#define sk_CMS_CertificateChoices_unshift(st, val) SKM_sk_unshift(CMS_CertificateChoices, (st), (val)) -#define sk_CMS_CertificateChoices_find(st, val) SKM_sk_find(CMS_CertificateChoices, (st), (val)) -#define sk_CMS_CertificateChoices_find_ex(st, val) SKM_sk_find_ex(CMS_CertificateChoices, (st), (val)) -#define sk_CMS_CertificateChoices_delete(st, i) SKM_sk_delete(CMS_CertificateChoices, (st), (i)) -#define sk_CMS_CertificateChoices_delete_ptr(st, ptr) SKM_sk_delete_ptr(CMS_CertificateChoices, (st), (ptr)) -#define sk_CMS_CertificateChoices_insert(st, val, i) SKM_sk_insert(CMS_CertificateChoices, (st), (val), (i)) -#define sk_CMS_CertificateChoices_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(CMS_CertificateChoices, (st), (cmp)) -#define sk_CMS_CertificateChoices_dup(st) SKM_sk_dup(CMS_CertificateChoices, st) -#define sk_CMS_CertificateChoices_pop_free(st, free_func) SKM_sk_pop_free(CMS_CertificateChoices, (st), (free_func)) -#define sk_CMS_CertificateChoices_shift(st) SKM_sk_shift(CMS_CertificateChoices, (st)) -#define sk_CMS_CertificateChoices_pop(st) SKM_sk_pop(CMS_CertificateChoices, (st)) -#define sk_CMS_CertificateChoices_sort(st) SKM_sk_sort(CMS_CertificateChoices, (st)) -#define sk_CMS_CertificateChoices_is_sorted(st) SKM_sk_is_sorted(CMS_CertificateChoices, (st)) - -#define sk_CMS_RecipientInfo_new(cmp) SKM_sk_new(CMS_RecipientInfo, (cmp)) -#define sk_CMS_RecipientInfo_new_null() SKM_sk_new_null(CMS_RecipientInfo) -#define sk_CMS_RecipientInfo_free(st) SKM_sk_free(CMS_RecipientInfo, (st)) -#define sk_CMS_RecipientInfo_num(st) SKM_sk_num(CMS_RecipientInfo, (st)) -#define sk_CMS_RecipientInfo_value(st, i) SKM_sk_value(CMS_RecipientInfo, (st), (i)) -#define sk_CMS_RecipientInfo_set(st, i, val) SKM_sk_set(CMS_RecipientInfo, (st), (i), (val)) -#define sk_CMS_RecipientInfo_zero(st) SKM_sk_zero(CMS_RecipientInfo, (st)) -#define sk_CMS_RecipientInfo_push(st, val) SKM_sk_push(CMS_RecipientInfo, (st), (val)) -#define sk_CMS_RecipientInfo_unshift(st, val) SKM_sk_unshift(CMS_RecipientInfo, (st), (val)) -#define sk_CMS_RecipientInfo_find(st, val) SKM_sk_find(CMS_RecipientInfo, (st), (val)) -#define sk_CMS_RecipientInfo_find_ex(st, val) SKM_sk_find_ex(CMS_RecipientInfo, (st), (val)) -#define sk_CMS_RecipientInfo_delete(st, i) SKM_sk_delete(CMS_RecipientInfo, (st), (i)) -#define sk_CMS_RecipientInfo_delete_ptr(st, ptr) SKM_sk_delete_ptr(CMS_RecipientInfo, (st), (ptr)) -#define sk_CMS_RecipientInfo_insert(st, val, i) SKM_sk_insert(CMS_RecipientInfo, (st), (val), (i)) -#define sk_CMS_RecipientInfo_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(CMS_RecipientInfo, (st), (cmp)) -#define sk_CMS_RecipientInfo_dup(st) SKM_sk_dup(CMS_RecipientInfo, st) -#define sk_CMS_RecipientInfo_pop_free(st, free_func) SKM_sk_pop_free(CMS_RecipientInfo, (st), (free_func)) -#define sk_CMS_RecipientInfo_shift(st) SKM_sk_shift(CMS_RecipientInfo, (st)) -#define sk_CMS_RecipientInfo_pop(st) SKM_sk_pop(CMS_RecipientInfo, (st)) -#define sk_CMS_RecipientInfo_sort(st) SKM_sk_sort(CMS_RecipientInfo, (st)) -#define sk_CMS_RecipientInfo_is_sorted(st) SKM_sk_is_sorted(CMS_RecipientInfo, (st)) - -#define sk_CMS_RevocationInfoChoice_new(cmp) SKM_sk_new(CMS_RevocationInfoChoice, (cmp)) -#define sk_CMS_RevocationInfoChoice_new_null() SKM_sk_new_null(CMS_RevocationInfoChoice) -#define sk_CMS_RevocationInfoChoice_free(st) SKM_sk_free(CMS_RevocationInfoChoice, (st)) -#define sk_CMS_RevocationInfoChoice_num(st) SKM_sk_num(CMS_RevocationInfoChoice, (st)) -#define sk_CMS_RevocationInfoChoice_value(st, i) SKM_sk_value(CMS_RevocationInfoChoice, (st), (i)) -#define sk_CMS_RevocationInfoChoice_set(st, i, val) SKM_sk_set(CMS_RevocationInfoChoice, (st), (i), (val)) -#define sk_CMS_RevocationInfoChoice_zero(st) SKM_sk_zero(CMS_RevocationInfoChoice, (st)) -#define sk_CMS_RevocationInfoChoice_push(st, val) SKM_sk_push(CMS_RevocationInfoChoice, (st), (val)) -#define sk_CMS_RevocationInfoChoice_unshift(st, val) SKM_sk_unshift(CMS_RevocationInfoChoice, (st), (val)) -#define sk_CMS_RevocationInfoChoice_find(st, val) SKM_sk_find(CMS_RevocationInfoChoice, (st), (val)) -#define sk_CMS_RevocationInfoChoice_find_ex(st, val) SKM_sk_find_ex(CMS_RevocationInfoChoice, (st), (val)) -#define sk_CMS_RevocationInfoChoice_delete(st, i) SKM_sk_delete(CMS_RevocationInfoChoice, (st), (i)) -#define sk_CMS_RevocationInfoChoice_delete_ptr(st, ptr) SKM_sk_delete_ptr(CMS_RevocationInfoChoice, (st), (ptr)) -#define sk_CMS_RevocationInfoChoice_insert(st, val, i) SKM_sk_insert(CMS_RevocationInfoChoice, (st), (val), (i)) -#define sk_CMS_RevocationInfoChoice_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(CMS_RevocationInfoChoice, (st), (cmp)) -#define sk_CMS_RevocationInfoChoice_dup(st) SKM_sk_dup(CMS_RevocationInfoChoice, st) -#define sk_CMS_RevocationInfoChoice_pop_free(st, free_func) SKM_sk_pop_free(CMS_RevocationInfoChoice, (st), (free_func)) -#define sk_CMS_RevocationInfoChoice_shift(st) SKM_sk_shift(CMS_RevocationInfoChoice, (st)) -#define sk_CMS_RevocationInfoChoice_pop(st) SKM_sk_pop(CMS_RevocationInfoChoice, (st)) -#define sk_CMS_RevocationInfoChoice_sort(st) SKM_sk_sort(CMS_RevocationInfoChoice, (st)) -#define sk_CMS_RevocationInfoChoice_is_sorted(st) SKM_sk_is_sorted(CMS_RevocationInfoChoice, (st)) - -#define sk_CMS_SignerInfo_new(cmp) SKM_sk_new(CMS_SignerInfo, (cmp)) -#define sk_CMS_SignerInfo_new_null() SKM_sk_new_null(CMS_SignerInfo) -#define sk_CMS_SignerInfo_free(st) SKM_sk_free(CMS_SignerInfo, (st)) -#define sk_CMS_SignerInfo_num(st) SKM_sk_num(CMS_SignerInfo, (st)) -#define sk_CMS_SignerInfo_value(st, i) SKM_sk_value(CMS_SignerInfo, (st), (i)) -#define sk_CMS_SignerInfo_set(st, i, val) SKM_sk_set(CMS_SignerInfo, (st), (i), (val)) -#define sk_CMS_SignerInfo_zero(st) SKM_sk_zero(CMS_SignerInfo, (st)) -#define sk_CMS_SignerInfo_push(st, val) SKM_sk_push(CMS_SignerInfo, (st), (val)) -#define sk_CMS_SignerInfo_unshift(st, val) SKM_sk_unshift(CMS_SignerInfo, (st), (val)) -#define sk_CMS_SignerInfo_find(st, val) SKM_sk_find(CMS_SignerInfo, (st), (val)) -#define sk_CMS_SignerInfo_find_ex(st, val) SKM_sk_find_ex(CMS_SignerInfo, (st), (val)) -#define sk_CMS_SignerInfo_delete(st, i) SKM_sk_delete(CMS_SignerInfo, (st), (i)) -#define sk_CMS_SignerInfo_delete_ptr(st, ptr) SKM_sk_delete_ptr(CMS_SignerInfo, (st), (ptr)) -#define sk_CMS_SignerInfo_insert(st, val, i) SKM_sk_insert(CMS_SignerInfo, (st), (val), (i)) -#define sk_CMS_SignerInfo_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(CMS_SignerInfo, (st), (cmp)) -#define sk_CMS_SignerInfo_dup(st) SKM_sk_dup(CMS_SignerInfo, st) -#define sk_CMS_SignerInfo_pop_free(st, free_func) SKM_sk_pop_free(CMS_SignerInfo, (st), (free_func)) -#define sk_CMS_SignerInfo_shift(st) SKM_sk_shift(CMS_SignerInfo, (st)) -#define sk_CMS_SignerInfo_pop(st) SKM_sk_pop(CMS_SignerInfo, (st)) -#define sk_CMS_SignerInfo_sort(st) SKM_sk_sort(CMS_SignerInfo, (st)) -#define sk_CMS_SignerInfo_is_sorted(st) SKM_sk_is_sorted(CMS_SignerInfo, (st)) +#define sk_AMS_CertificateChoices_new(cmp) SKM_sk_new(AMS_CertificateChoices, (cmp)) +#define sk_AMS_CertificateChoices_new_null() SKM_sk_new_null(AMS_CertificateChoices) +#define sk_AMS_CertificateChoices_free(st) SKM_sk_free(AMS_CertificateChoices, (st)) +#define sk_AMS_CertificateChoices_num(st) SKM_sk_num(AMS_CertificateChoices, (st)) +#define sk_AMS_CertificateChoices_value(st, i) SKM_sk_value(AMS_CertificateChoices, (st), (i)) +#define sk_AMS_CertificateChoices_set(st, i, val) SKM_sk_set(AMS_CertificateChoices, (st), (i), (val)) +#define sk_AMS_CertificateChoices_zero(st) SKM_sk_zero(AMS_CertificateChoices, (st)) +#define sk_AMS_CertificateChoices_push(st, val) SKM_sk_push(AMS_CertificateChoices, (st), (val)) +#define sk_AMS_CertificateChoices_unshift(st, val) SKM_sk_unshift(AMS_CertificateChoices, (st), (val)) +#define sk_AMS_CertificateChoices_find(st, val) SKM_sk_find(AMS_CertificateChoices, (st), (val)) +#define sk_AMS_CertificateChoices_find_ex(st, val) SKM_sk_find_ex(AMS_CertificateChoices, (st), (val)) +#define sk_AMS_CertificateChoices_delete(st, i) SKM_sk_delete(AMS_CertificateChoices, (st), (i)) +#define sk_AMS_CertificateChoices_delete_ptr(st, ptr) SKM_sk_delete_ptr(AMS_CertificateChoices, (st), (ptr)) +#define sk_AMS_CertificateChoices_insert(st, val, i) SKM_sk_insert(AMS_CertificateChoices, (st), (val), (i)) +#define sk_AMS_CertificateChoices_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(AMS_CertificateChoices, (st), (cmp)) +#define sk_AMS_CertificateChoices_dup(st) SKM_sk_dup(AMS_CertificateChoices, st) +#define sk_AMS_CertificateChoices_pop_free(st, free_func) SKM_sk_pop_free(AMS_CertificateChoices, (st), (free_func)) +#define sk_AMS_CertificateChoices_shift(st) SKM_sk_shift(AMS_CertificateChoices, (st)) +#define sk_AMS_CertificateChoices_pop(st) SKM_sk_pop(AMS_CertificateChoices, (st)) +#define sk_AMS_CertificateChoices_sort(st) SKM_sk_sort(AMS_CertificateChoices, (st)) +#define sk_AMS_CertificateChoices_is_sorted(st) SKM_sk_is_sorted(AMS_CertificateChoices, (st)) + +#define sk_AMS_RecipientInfo_new(cmp) SKM_sk_new(AMS_RecipientInfo, (cmp)) +#define sk_AMS_RecipientInfo_new_null() SKM_sk_new_null(AMS_RecipientInfo) +#define sk_AMS_RecipientInfo_free(st) SKM_sk_free(AMS_RecipientInfo, (st)) +#define sk_AMS_RecipientInfo_num(st) SKM_sk_num(AMS_RecipientInfo, (st)) +#define sk_AMS_RecipientInfo_value(st, i) SKM_sk_value(AMS_RecipientInfo, (st), (i)) +#define sk_AMS_RecipientInfo_set(st, i, val) SKM_sk_set(AMS_RecipientInfo, (st), (i), (val)) +#define sk_AMS_RecipientInfo_zero(st) SKM_sk_zero(AMS_RecipientInfo, (st)) +#define sk_AMS_RecipientInfo_push(st, val) SKM_sk_push(AMS_RecipientInfo, (st), (val)) +#define sk_AMS_RecipientInfo_unshift(st, val) SKM_sk_unshift(AMS_RecipientInfo, (st), (val)) +#define sk_AMS_RecipientInfo_find(st, val) SKM_sk_find(AMS_RecipientInfo, (st), (val)) +#define sk_AMS_RecipientInfo_find_ex(st, val) SKM_sk_find_ex(AMS_RecipientInfo, (st), (val)) +#define sk_AMS_RecipientInfo_delete(st, i) SKM_sk_delete(AMS_RecipientInfo, (st), (i)) +#define sk_AMS_RecipientInfo_delete_ptr(st, ptr) SKM_sk_delete_ptr(AMS_RecipientInfo, (st), (ptr)) +#define sk_AMS_RecipientInfo_insert(st, val, i) SKM_sk_insert(AMS_RecipientInfo, (st), (val), (i)) +#define sk_AMS_RecipientInfo_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(AMS_RecipientInfo, (st), (cmp)) +#define sk_AMS_RecipientInfo_dup(st) SKM_sk_dup(AMS_RecipientInfo, st) +#define sk_AMS_RecipientInfo_pop_free(st, free_func) SKM_sk_pop_free(AMS_RecipientInfo, (st), (free_func)) +#define sk_AMS_RecipientInfo_shift(st) SKM_sk_shift(AMS_RecipientInfo, (st)) +#define sk_AMS_RecipientInfo_pop(st) SKM_sk_pop(AMS_RecipientInfo, (st)) +#define sk_AMS_RecipientInfo_sort(st) SKM_sk_sort(AMS_RecipientInfo, (st)) +#define sk_AMS_RecipientInfo_is_sorted(st) SKM_sk_is_sorted(AMS_RecipientInfo, (st)) + +#define sk_AMS_RevocationInfoChoice_new(cmp) SKM_sk_new(AMS_RevocationInfoChoice, (cmp)) +#define sk_AMS_RevocationInfoChoice_new_null() SKM_sk_new_null(AMS_RevocationInfoChoice) +#define sk_AMS_RevocationInfoChoice_free(st) SKM_sk_free(AMS_RevocationInfoChoice, (st)) +#define sk_AMS_RevocationInfoChoice_num(st) SKM_sk_num(AMS_RevocationInfoChoice, (st)) +#define sk_AMS_RevocationInfoChoice_value(st, i) SKM_sk_value(AMS_RevocationInfoChoice, (st), (i)) +#define sk_AMS_RevocationInfoChoice_set(st, i, val) SKM_sk_set(AMS_RevocationInfoChoice, (st), (i), (val)) +#define sk_AMS_RevocationInfoChoice_zero(st) SKM_sk_zero(AMS_RevocationInfoChoice, (st)) +#define sk_AMS_RevocationInfoChoice_push(st, val) SKM_sk_push(AMS_RevocationInfoChoice, (st), (val)) +#define sk_AMS_RevocationInfoChoice_unshift(st, val) SKM_sk_unshift(AMS_RevocationInfoChoice, (st), (val)) +#define sk_AMS_RevocationInfoChoice_find(st, val) SKM_sk_find(AMS_RevocationInfoChoice, (st), (val)) +#define sk_AMS_RevocationInfoChoice_find_ex(st, val) SKM_sk_find_ex(AMS_RevocationInfoChoice, (st), (val)) +#define sk_AMS_RevocationInfoChoice_delete(st, i) SKM_sk_delete(AMS_RevocationInfoChoice, (st), (i)) +#define sk_AMS_RevocationInfoChoice_delete_ptr(st, ptr) SKM_sk_delete_ptr(AMS_RevocationInfoChoice, (st), (ptr)) +#define sk_AMS_RevocationInfoChoice_insert(st, val, i) SKM_sk_insert(AMS_RevocationInfoChoice, (st), (val), (i)) +#define sk_AMS_RevocationInfoChoice_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(AMS_RevocationInfoChoice, (st), (cmp)) +#define sk_AMS_RevocationInfoChoice_dup(st) SKM_sk_dup(AMS_RevocationInfoChoice, st) +#define sk_AMS_RevocationInfoChoice_pop_free(st, free_func) SKM_sk_pop_free(AMS_RevocationInfoChoice, (st), (free_func)) +#define sk_AMS_RevocationInfoChoice_shift(st) SKM_sk_shift(AMS_RevocationInfoChoice, (st)) +#define sk_AMS_RevocationInfoChoice_pop(st) SKM_sk_pop(AMS_RevocationInfoChoice, (st)) +#define sk_AMS_RevocationInfoChoice_sort(st) SKM_sk_sort(AMS_RevocationInfoChoice, (st)) +#define sk_AMS_RevocationInfoChoice_is_sorted(st) SKM_sk_is_sorted(AMS_RevocationInfoChoice, (st)) + +#define sk_AMS_SignerInfo_new(cmp) SKM_sk_new(AMS_SignerInfo, (cmp)) +#define sk_AMS_SignerInfo_new_null() SKM_sk_new_null(AMS_SignerInfo) +#define sk_AMS_SignerInfo_free(st) SKM_sk_free(AMS_SignerInfo, (st)) +#define sk_AMS_SignerInfo_num(st) SKM_sk_num(AMS_SignerInfo, (st)) +#define sk_AMS_SignerInfo_value(st, i) SKM_sk_value(AMS_SignerInfo, (st), (i)) +#define sk_AMS_SignerInfo_set(st, i, val) SKM_sk_set(AMS_SignerInfo, (st), (i), (val)) +#define sk_AMS_SignerInfo_zero(st) SKM_sk_zero(AMS_SignerInfo, (st)) +#define sk_AMS_SignerInfo_push(st, val) SKM_sk_push(AMS_SignerInfo, (st), (val)) +#define sk_AMS_SignerInfo_unshift(st, val) SKM_sk_unshift(AMS_SignerInfo, (st), (val)) +#define sk_AMS_SignerInfo_find(st, val) SKM_sk_find(AMS_SignerInfo, (st), (val)) +#define sk_AMS_SignerInfo_find_ex(st, val) SKM_sk_find_ex(AMS_SignerInfo, (st), (val)) +#define sk_AMS_SignerInfo_delete(st, i) SKM_sk_delete(AMS_SignerInfo, (st), (i)) +#define sk_AMS_SignerInfo_delete_ptr(st, ptr) SKM_sk_delete_ptr(AMS_SignerInfo, (st), (ptr)) +#define sk_AMS_SignerInfo_insert(st, val, i) SKM_sk_insert(AMS_SignerInfo, (st), (val), (i)) +#define sk_AMS_SignerInfo_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(AMS_SignerInfo, (st), (cmp)) +#define sk_AMS_SignerInfo_dup(st) SKM_sk_dup(AMS_SignerInfo, st) +#define sk_AMS_SignerInfo_pop_free(st, free_func) SKM_sk_pop_free(AMS_SignerInfo, (st), (free_func)) +#define sk_AMS_SignerInfo_shift(st) SKM_sk_shift(AMS_SignerInfo, (st)) +#define sk_AMS_SignerInfo_pop(st) SKM_sk_pop(AMS_SignerInfo, (st)) +#define sk_AMS_SignerInfo_sort(st) SKM_sk_sort(AMS_SignerInfo, (st)) +#define sk_AMS_SignerInfo_is_sorted(st) SKM_sk_is_sorted(AMS_SignerInfo, (st)) #define sk_CONF_IMODULE_new(cmp) SKM_sk_new(CONF_IMODULE, (cmp)) #define sk_CONF_IMODULE_new_null() SKM_sk_new_null(CONF_IMODULE) diff --git a/server/external/openssl/win_32/include/openssl/symhacks.h b/server/external/openssl/win_32/include/openssl/symhacks.h index bd2f000..b9e347c 100644 --- a/server/external/openssl/win_32/include/openssl/symhacks.h +++ b/server/external/openssl/win_32/include/openssl/symhacks.h @@ -407,19 +407,19 @@ #undef TS_CONF_set_clock_precision_digits #define TS_CONF_set_clock_precision_digits TS_CONF_set_clk_prec_digits -/* Hack some long CMS names */ -#undef CMS_RecipientInfo_ktri_get0_algs -#define CMS_RecipientInfo_ktri_get0_algs CMS_RecipInfo_ktri_get0_algs -#undef CMS_RecipientInfo_ktri_get0_signer_id -#define CMS_RecipientInfo_ktri_get0_signer_id CMS_RecipInfo_ktri_get0_sigr_id -#undef CMS_OtherRevocationInfoFormat_it -#define CMS_OtherRevocationInfoFormat_it CMS_OtherRevocInfoFormat_it -#undef CMS_KeyAgreeRecipientIdentifier_it -#define CMS_KeyAgreeRecipientIdentifier_it CMS_KeyAgreeRecipIdentifier_it -#undef CMS_OriginatorIdentifierOrKey_it -#define CMS_OriginatorIdentifierOrKey_it CMS_OriginatorIdOrKey_it -#undef cms_SignerIdentifier_get0_signer_id -#define cms_SignerIdentifier_get0_signer_id cms_SignerId_get0_signer_id +/* Hack some long AMS names */ +#undef AMS_RecipientInfo_ktri_get0_algs +#define AMS_RecipientInfo_ktri_get0_algs AMS_RecipInfo_ktri_get0_algs +#undef AMS_RecipientInfo_ktri_get0_signer_id +#define AMS_RecipientInfo_ktri_get0_signer_id AMS_RecipInfo_ktri_get0_sigr_id +#undef AMS_OtherRevocationInfoFormat_it +#define AMS_OtherRevocationInfoFormat_it AMS_OtherRevocInfoFormat_it +#undef AMS_KeyAgreeRecipientIdentifier_it +#define AMS_KeyAgreeRecipientIdentifier_it AMS_KeyAgreeRecipIdentifier_it +#undef AMS_OriginatorIdentifierOrKey_it +#define AMS_OriginatorIdentifierOrKey_it AMS_OriginatorIdOrKey_it +#undef ams_SignerIdentifier_get0_signer_id +#define ams_SignerIdentifier_get0_signer_id ams_SignerId_get0_signer_id /* Hack some long DTLS1 names */ #undef dtls1_retransmit_buffered_messages @@ -471,9 +471,9 @@ #undef X509v3_add_standard_extensions #define X509v3_add_standard_extensions oX509v3_add_standard_extensions -/* This one clashes with CMS_data_create */ -#undef cms_Data_create -#define cms_Data_create priv_cms_Data_create +/* This one clashes with AMS_data_create */ +#undef ams_Data_create +#define ams_Data_create priv_ams_Data_create #endif diff --git a/server/external/openssl/win_64/include/openssl/asn1.h b/server/external/openssl/win_64/include/openssl/asn1.h index 220a0c8..9fea679 100644 --- a/server/external/openssl/win_64/include/openssl/asn1.h +++ b/server/external/openssl/win_64/include/openssl/asn1.h @@ -224,7 +224,7 @@ typedef struct asn1_object_st */ #define ASN1_STRING_FLAG_NDEF 0x010 -/* This flag is used by the CMS code to indicate that a string is not +/* This flag is used by the AMS code to indicate that a string is not * complete and is a place holder for content when it had all been * accessed. The flag will be reset when content has been written to it. */ diff --git a/server/external/openssl/win_64/include/openssl/cms.h b/server/external/openssl/win_64/include/openssl/cms.h deleted file mode 100644 index 36994fa..0000000 --- a/server/external/openssl/win_64/include/openssl/cms.h +++ /dev/null @@ -1,501 +0,0 @@ -/* crypto/cms/cms.h */ -/* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL - * project. - */ -/* ==================================================================== - * Copyright (c) 2008 The OpenSSL Project. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * 3. All advertising materials mentioning features or use of this - * software must display the following acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" - * - * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to - * endorse or promote products derived from this software without - * prior written permission. For written permission, please contact - * licensing@OpenSSL.org. - * - * 5. Products derived from this software may not be called "OpenSSL" - * nor may "OpenSSL" appear in their names without prior written - * permission of the OpenSSL Project. - * - * 6. Redistributions of any form whatsoever must retain the following - * acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" - * - * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY - * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, - * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED - * OF THE POSSIBILITY OF SUCH DAMAGE. - * ==================================================================== - */ - - -#ifndef HEADER_CMS_H -#define HEADER_CMS_H - -#include - -#ifdef OPENSSL_NO_CMS -#error CMS is disabled. -#endif - -#ifdef __cplusplus -extern "C" { -#endif - - -typedef struct CMS_ContentInfo_st CMS_ContentInfo; -typedef struct CMS_SignerInfo_st CMS_SignerInfo; -typedef struct CMS_CertificateChoices CMS_CertificateChoices; -typedef struct CMS_RevocationInfoChoice_st CMS_RevocationInfoChoice; -typedef struct CMS_RecipientInfo_st CMS_RecipientInfo; -typedef struct CMS_ReceiptRequest_st CMS_ReceiptRequest; -typedef struct CMS_Receipt_st CMS_Receipt; - -DECLARE_STACK_OF(CMS_SignerInfo) -DECLARE_STACK_OF(GENERAL_NAMES) -DECLARE_ASN1_FUNCTIONS(CMS_ContentInfo) -DECLARE_ASN1_FUNCTIONS(CMS_ReceiptRequest) -DECLARE_ASN1_PRINT_FUNCTION(CMS_ContentInfo) - -#define CMS_SIGNERINFO_ISSUER_SERIAL 0 -#define CMS_SIGNERINFO_KEYIDENTIFIER 1 - -#define CMS_RECIPINFO_TRANS 0 -#define CMS_RECIPINFO_AGREE 1 -#define CMS_RECIPINFO_KEK 2 -#define CMS_RECIPINFO_PASS 3 -#define CMS_RECIPINFO_OTHER 4 - -/* S/MIME related flags */ - -#define CMS_TEXT 0x1 -#define CMS_NOCERTS 0x2 -#define CMS_NO_CONTENT_VERIFY 0x4 -#define CMS_NO_ATTR_VERIFY 0x8 -#define CMS_NOSIGS \ - (CMS_NO_CONTENT_VERIFY|CMS_NO_ATTR_VERIFY) -#define CMS_NOINTERN 0x10 -#define CMS_NO_SIGNER_CERT_VERIFY 0x20 -#define CMS_NOVERIFY 0x20 -#define CMS_DETACHED 0x40 -#define CMS_BINARY 0x80 -#define CMS_NOATTR 0x100 -#define CMS_NOSMIMECAP 0x200 -#define CMS_NOOLDMIMETYPE 0x400 -#define CMS_CRLFEOL 0x800 -#define CMS_STREAM 0x1000 -#define CMS_NOCRL 0x2000 -#define CMS_PARTIAL 0x4000 -#define CMS_REUSE_DIGEST 0x8000 -#define CMS_USE_KEYID 0x10000 -#define CMS_DEBUG_DECRYPT 0x20000 - -const ASN1_OBJECT *CMS_get0_type(CMS_ContentInfo *cms); - -BIO *CMS_dataInit(CMS_ContentInfo *cms, BIO *icont); -int CMS_dataFinal(CMS_ContentInfo *cms, BIO *bio); - -ASN1_OCTET_STRING **CMS_get0_content(CMS_ContentInfo *cms); -int CMS_is_detached(CMS_ContentInfo *cms); -int CMS_set_detached(CMS_ContentInfo *cms, int detached); - -#ifdef HEADER_PEM_H -DECLARE_PEM_rw_const(CMS, CMS_ContentInfo) -#endif - -int CMS_stream(unsigned char ***boundary, CMS_ContentInfo *cms); -CMS_ContentInfo *d2i_CMS_bio(BIO *bp, CMS_ContentInfo **cms); -int i2d_CMS_bio(BIO *bp, CMS_ContentInfo *cms); - -BIO *BIO_new_CMS(BIO *out, CMS_ContentInfo *cms); -int i2d_CMS_bio_stream(BIO *out, CMS_ContentInfo *cms, BIO *in, int flags); -int PEM_write_bio_CMS_stream(BIO *out, CMS_ContentInfo *cms, BIO *in, int flags); -CMS_ContentInfo *SMIME_read_CMS(BIO *bio, BIO **bcont); -int SMIME_write_CMS(BIO *bio, CMS_ContentInfo *cms, BIO *data, int flags); - -int CMS_final(CMS_ContentInfo *cms, BIO *data, BIO *dcont, unsigned int flags); - -CMS_ContentInfo *CMS_sign(X509 *signcert, EVP_PKEY *pkey, STACK_OF(X509) *certs, - BIO *data, unsigned int flags); - -CMS_ContentInfo *CMS_sign_receipt(CMS_SignerInfo *si, - X509 *signcert, EVP_PKEY *pkey, - STACK_OF(X509) *certs, - unsigned int flags); - -int CMS_data(CMS_ContentInfo *cms, BIO *out, unsigned int flags); -CMS_ContentInfo *CMS_data_create(BIO *in, unsigned int flags); - -int CMS_digest_verify(CMS_ContentInfo *cms, BIO *dcont, BIO *out, - unsigned int flags); -CMS_ContentInfo *CMS_digest_create(BIO *in, const EVP_MD *md, - unsigned int flags); - -int CMS_EncryptedData_decrypt(CMS_ContentInfo *cms, - const unsigned char *key, size_t keylen, - BIO *dcont, BIO *out, unsigned int flags); - -CMS_ContentInfo *CMS_EncryptedData_encrypt(BIO *in, const EVP_CIPHER *cipher, - const unsigned char *key, size_t keylen, - unsigned int flags); - -int CMS_EncryptedData_set1_key(CMS_ContentInfo *cms, const EVP_CIPHER *ciph, - const unsigned char *key, size_t keylen); - -int CMS_verify(CMS_ContentInfo *cms, STACK_OF(X509) *certs, - X509_STORE *store, BIO *dcont, BIO *out, unsigned int flags); - -int CMS_verify_receipt(CMS_ContentInfo *rcms, CMS_ContentInfo *ocms, - STACK_OF(X509) *certs, - X509_STORE *store, unsigned int flags); - -STACK_OF(X509) *CMS_get0_signers(CMS_ContentInfo *cms); - -CMS_ContentInfo *CMS_encrypt(STACK_OF(X509) *certs, BIO *in, - const EVP_CIPHER *cipher, unsigned int flags); - -int CMS_decrypt(CMS_ContentInfo *cms, EVP_PKEY *pkey, X509 *cert, - BIO *dcont, BIO *out, - unsigned int flags); - -int CMS_decrypt_set1_pkey(CMS_ContentInfo *cms, EVP_PKEY *pk, X509 *cert); -int CMS_decrypt_set1_key(CMS_ContentInfo *cms, - unsigned char *key, size_t keylen, - unsigned char *id, size_t idlen); -int CMS_decrypt_set1_password(CMS_ContentInfo *cms, - unsigned char *pass, ossl_ssize_t passlen); - -STACK_OF(CMS_RecipientInfo) *CMS_get0_RecipientInfos(CMS_ContentInfo *cms); -int CMS_RecipientInfo_type(CMS_RecipientInfo *ri); -CMS_ContentInfo *CMS_EnvelopedData_create(const EVP_CIPHER *cipher); -CMS_RecipientInfo *CMS_add1_recipient_cert(CMS_ContentInfo *cms, - X509 *recip, unsigned int flags); -int CMS_RecipientInfo_set0_pkey(CMS_RecipientInfo *ri, EVP_PKEY *pkey); -int CMS_RecipientInfo_ktri_cert_cmp(CMS_RecipientInfo *ri, X509 *cert); -int CMS_RecipientInfo_ktri_get0_algs(CMS_RecipientInfo *ri, - EVP_PKEY **pk, X509 **recip, - X509_ALGOR **palg); -int CMS_RecipientInfo_ktri_get0_signer_id(CMS_RecipientInfo *ri, - ASN1_OCTET_STRING **keyid, - X509_NAME **issuer, ASN1_INTEGER **sno); - -CMS_RecipientInfo *CMS_add0_recipient_key(CMS_ContentInfo *cms, int nid, - unsigned char *key, size_t keylen, - unsigned char *id, size_t idlen, - ASN1_GENERALIZEDTIME *date, - ASN1_OBJECT *otherTypeId, - ASN1_TYPE *otherType); - -int CMS_RecipientInfo_kekri_get0_id(CMS_RecipientInfo *ri, - X509_ALGOR **palg, - ASN1_OCTET_STRING **pid, - ASN1_GENERALIZEDTIME **pdate, - ASN1_OBJECT **potherid, - ASN1_TYPE **pothertype); - -int CMS_RecipientInfo_set0_key(CMS_RecipientInfo *ri, - unsigned char *key, size_t keylen); - -int CMS_RecipientInfo_kekri_id_cmp(CMS_RecipientInfo *ri, - const unsigned char *id, size_t idlen); - -int CMS_RecipientInfo_set0_password(CMS_RecipientInfo *ri, - unsigned char *pass, - ossl_ssize_t passlen); - -CMS_RecipientInfo *CMS_add0_recipient_password(CMS_ContentInfo *cms, - int iter, int wrap_nid, int pbe_nid, - unsigned char *pass, - ossl_ssize_t passlen, - const EVP_CIPHER *kekciph); - -int CMS_RecipientInfo_decrypt(CMS_ContentInfo *cms, CMS_RecipientInfo *ri); - -int CMS_uncompress(CMS_ContentInfo *cms, BIO *dcont, BIO *out, - unsigned int flags); -CMS_ContentInfo *CMS_compress(BIO *in, int comp_nid, unsigned int flags); - -int CMS_set1_eContentType(CMS_ContentInfo *cms, const ASN1_OBJECT *oid); -const ASN1_OBJECT *CMS_get0_eContentType(CMS_ContentInfo *cms); - -CMS_CertificateChoices *CMS_add0_CertificateChoices(CMS_ContentInfo *cms); -int CMS_add0_cert(CMS_ContentInfo *cms, X509 *cert); -int CMS_add1_cert(CMS_ContentInfo *cms, X509 *cert); -STACK_OF(X509) *CMS_get1_certs(CMS_ContentInfo *cms); - -CMS_RevocationInfoChoice *CMS_add0_RevocationInfoChoice(CMS_ContentInfo *cms); -int CMS_add0_crl(CMS_ContentInfo *cms, X509_CRL *crl); -int CMS_add1_crl(CMS_ContentInfo *cms, X509_CRL *crl); -STACK_OF(X509_CRL) *CMS_get1_crls(CMS_ContentInfo *cms); - -int CMS_SignedData_init(CMS_ContentInfo *cms); -CMS_SignerInfo *CMS_add1_signer(CMS_ContentInfo *cms, - X509 *signer, EVP_PKEY *pk, const EVP_MD *md, - unsigned int flags); -STACK_OF(CMS_SignerInfo) *CMS_get0_SignerInfos(CMS_ContentInfo *cms); - -void CMS_SignerInfo_set1_signer_cert(CMS_SignerInfo *si, X509 *signer); -int CMS_SignerInfo_get0_signer_id(CMS_SignerInfo *si, - ASN1_OCTET_STRING **keyid, - X509_NAME **issuer, ASN1_INTEGER **sno); -int CMS_SignerInfo_cert_cmp(CMS_SignerInfo *si, X509 *cert); -int CMS_set1_signers_certs(CMS_ContentInfo *cms, STACK_OF(X509) *certs, - unsigned int flags); -void CMS_SignerInfo_get0_algs(CMS_SignerInfo *si, EVP_PKEY **pk, X509 **signer, - X509_ALGOR **pdig, X509_ALGOR **psig); -int CMS_SignerInfo_sign(CMS_SignerInfo *si); -int CMS_SignerInfo_verify(CMS_SignerInfo *si); -int CMS_SignerInfo_verify_content(CMS_SignerInfo *si, BIO *chain); - -int CMS_add_smimecap(CMS_SignerInfo *si, STACK_OF(X509_ALGOR) *algs); -int CMS_add_simple_smimecap(STACK_OF(X509_ALGOR) **algs, - int algnid, int keysize); -int CMS_add_standard_smimecap(STACK_OF(X509_ALGOR) **smcap); - -int CMS_signed_get_attr_count(const CMS_SignerInfo *si); -int CMS_signed_get_attr_by_NID(const CMS_SignerInfo *si, int nid, - int lastpos); -int CMS_signed_get_attr_by_OBJ(const CMS_SignerInfo *si, ASN1_OBJECT *obj, - int lastpos); -X509_ATTRIBUTE *CMS_signed_get_attr(const CMS_SignerInfo *si, int loc); -X509_ATTRIBUTE *CMS_signed_delete_attr(CMS_SignerInfo *si, int loc); -int CMS_signed_add1_attr(CMS_SignerInfo *si, X509_ATTRIBUTE *attr); -int CMS_signed_add1_attr_by_OBJ(CMS_SignerInfo *si, - const ASN1_OBJECT *obj, int type, - const void *bytes, int len); -int CMS_signed_add1_attr_by_NID(CMS_SignerInfo *si, - int nid, int type, - const void *bytes, int len); -int CMS_signed_add1_attr_by_txt(CMS_SignerInfo *si, - const char *attrname, int type, - const void *bytes, int len); -void *CMS_signed_get0_data_by_OBJ(CMS_SignerInfo *si, ASN1_OBJECT *oid, - int lastpos, int type); - -int CMS_unsigned_get_attr_count(const CMS_SignerInfo *si); -int CMS_unsigned_get_attr_by_NID(const CMS_SignerInfo *si, int nid, - int lastpos); -int CMS_unsigned_get_attr_by_OBJ(const CMS_SignerInfo *si, ASN1_OBJECT *obj, - int lastpos); -X509_ATTRIBUTE *CMS_unsigned_get_attr(const CMS_SignerInfo *si, int loc); -X509_ATTRIBUTE *CMS_unsigned_delete_attr(CMS_SignerInfo *si, int loc); -int CMS_unsigned_add1_attr(CMS_SignerInfo *si, X509_ATTRIBUTE *attr); -int CMS_unsigned_add1_attr_by_OBJ(CMS_SignerInfo *si, - const ASN1_OBJECT *obj, int type, - const void *bytes, int len); -int CMS_unsigned_add1_attr_by_NID(CMS_SignerInfo *si, - int nid, int type, - const void *bytes, int len); -int CMS_unsigned_add1_attr_by_txt(CMS_SignerInfo *si, - const char *attrname, int type, - const void *bytes, int len); -void *CMS_unsigned_get0_data_by_OBJ(CMS_SignerInfo *si, ASN1_OBJECT *oid, - int lastpos, int type); - -#ifdef HEADER_X509V3_H - -int CMS_get1_ReceiptRequest(CMS_SignerInfo *si, CMS_ReceiptRequest **prr); -CMS_ReceiptRequest *CMS_ReceiptRequest_create0(unsigned char *id, int idlen, - int allorfirst, - STACK_OF(GENERAL_NAMES) *receiptList, - STACK_OF(GENERAL_NAMES) *receiptsTo); -int CMS_add1_ReceiptRequest(CMS_SignerInfo *si, CMS_ReceiptRequest *rr); -void CMS_ReceiptRequest_get0_values(CMS_ReceiptRequest *rr, - ASN1_STRING **pcid, - int *pallorfirst, - STACK_OF(GENERAL_NAMES) **plist, - STACK_OF(GENERAL_NAMES) **prto); - -#endif - -/* BEGIN ERROR CODES */ -/* The following lines are auto generated by the script mkerr.pl. Any changes - * made after this point may be overwritten when the script is next run. - */ -void ERR_load_CMS_strings(void); - -/* Error codes for the CMS functions. */ - -/* Function codes. */ -#define CMS_F_CHECK_CONTENT 99 -#define CMS_F_CMS_ADD0_CERT 164 -#define CMS_F_CMS_ADD0_RECIPIENT_KEY 100 -#define CMS_F_CMS_ADD0_RECIPIENT_PASSWORD 165 -#define CMS_F_CMS_ADD1_RECEIPTREQUEST 158 -#define CMS_F_CMS_ADD1_RECIPIENT_CERT 101 -#define CMS_F_CMS_ADD1_SIGNER 102 -#define CMS_F_CMS_ADD1_SIGNINGTIME 103 -#define CMS_F_CMS_COMPRESS 104 -#define CMS_F_CMS_COMPRESSEDDATA_CREATE 105 -#define CMS_F_CMS_COMPRESSEDDATA_INIT_BIO 106 -#define CMS_F_CMS_COPY_CONTENT 107 -#define CMS_F_CMS_COPY_MESSAGEDIGEST 108 -#define CMS_F_CMS_DATA 109 -#define CMS_F_CMS_DATAFINAL 110 -#define CMS_F_CMS_DATAINIT 111 -#define CMS_F_CMS_DECRYPT 112 -#define CMS_F_CMS_DECRYPT_SET1_KEY 113 -#define CMS_F_CMS_DECRYPT_SET1_PASSWORD 166 -#define CMS_F_CMS_DECRYPT_SET1_PKEY 114 -#define CMS_F_CMS_DIGESTALGORITHM_FIND_CTX 115 -#define CMS_F_CMS_DIGESTALGORITHM_INIT_BIO 116 -#define CMS_F_CMS_DIGESTEDDATA_DO_FINAL 117 -#define CMS_F_CMS_DIGEST_VERIFY 118 -#define CMS_F_CMS_ENCODE_RECEIPT 161 -#define CMS_F_CMS_ENCRYPT 119 -#define CMS_F_CMS_ENCRYPTEDCONTENT_INIT_BIO 120 -#define CMS_F_CMS_ENCRYPTEDDATA_DECRYPT 121 -#define CMS_F_CMS_ENCRYPTEDDATA_ENCRYPT 122 -#define CMS_F_CMS_ENCRYPTEDDATA_SET1_KEY 123 -#define CMS_F_CMS_ENVELOPEDDATA_CREATE 124 -#define CMS_F_CMS_ENVELOPEDDATA_INIT_BIO 125 -#define CMS_F_CMS_ENVELOPED_DATA_INIT 126 -#define CMS_F_CMS_FINAL 127 -#define CMS_F_CMS_GET0_CERTIFICATE_CHOICES 128 -#define CMS_F_CMS_GET0_CONTENT 129 -#define CMS_F_CMS_GET0_ECONTENT_TYPE 130 -#define CMS_F_CMS_GET0_ENVELOPED 131 -#define CMS_F_CMS_GET0_REVOCATION_CHOICES 132 -#define CMS_F_CMS_GET0_SIGNED 133 -#define CMS_F_CMS_MSGSIGDIGEST_ADD1 162 -#define CMS_F_CMS_RECEIPTREQUEST_CREATE0 159 -#define CMS_F_CMS_RECEIPT_VERIFY 160 -#define CMS_F_CMS_RECIPIENTINFO_DECRYPT 134 -#define CMS_F_CMS_RECIPIENTINFO_KEKRI_DECRYPT 135 -#define CMS_F_CMS_RECIPIENTINFO_KEKRI_ENCRYPT 136 -#define CMS_F_CMS_RECIPIENTINFO_KEKRI_GET0_ID 137 -#define CMS_F_CMS_RECIPIENTINFO_KEKRI_ID_CMP 138 -#define CMS_F_CMS_RECIPIENTINFO_KTRI_CERT_CMP 139 -#define CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT 140 -#define CMS_F_CMS_RECIPIENTINFO_KTRI_ENCRYPT 141 -#define CMS_F_CMS_RECIPIENTINFO_KTRI_GET0_ALGS 142 -#define CMS_F_CMS_RECIPIENTINFO_KTRI_GET0_SIGNER_ID 143 -#define CMS_F_CMS_RECIPIENTINFO_PWRI_CRYPT 167 -#define CMS_F_CMS_RECIPIENTINFO_SET0_KEY 144 -#define CMS_F_CMS_RECIPIENTINFO_SET0_PASSWORD 168 -#define CMS_F_CMS_RECIPIENTINFO_SET0_PKEY 145 -#define CMS_F_CMS_SET1_SIGNERIDENTIFIER 146 -#define CMS_F_CMS_SET_DETACHED 147 -#define CMS_F_CMS_SIGN 148 -#define CMS_F_CMS_SIGNED_DATA_INIT 149 -#define CMS_F_CMS_SIGNERINFO_CONTENT_SIGN 150 -#define CMS_F_CMS_SIGNERINFO_SIGN 151 -#define CMS_F_CMS_SIGNERINFO_VERIFY 152 -#define CMS_F_CMS_SIGNERINFO_VERIFY_CERT 153 -#define CMS_F_CMS_SIGNERINFO_VERIFY_CONTENT 154 -#define CMS_F_CMS_SIGN_RECEIPT 163 -#define CMS_F_CMS_STREAM 155 -#define CMS_F_CMS_UNCOMPRESS 156 -#define CMS_F_CMS_VERIFY 157 - -/* Reason codes. */ -#define CMS_R_ADD_SIGNER_ERROR 99 -#define CMS_R_CERTIFICATE_ALREADY_PRESENT 175 -#define CMS_R_CERTIFICATE_HAS_NO_KEYID 160 -#define CMS_R_CERTIFICATE_VERIFY_ERROR 100 -#define CMS_R_CIPHER_INITIALISATION_ERROR 101 -#define CMS_R_CIPHER_PARAMETER_INITIALISATION_ERROR 102 -#define CMS_R_CMS_DATAFINAL_ERROR 103 -#define CMS_R_CMS_LIB 104 -#define CMS_R_CONTENTIDENTIFIER_MISMATCH 170 -#define CMS_R_CONTENT_NOT_FOUND 105 -#define CMS_R_CONTENT_TYPE_MISMATCH 171 -#define CMS_R_CONTENT_TYPE_NOT_COMPRESSED_DATA 106 -#define CMS_R_CONTENT_TYPE_NOT_ENVELOPED_DATA 107 -#define CMS_R_CONTENT_TYPE_NOT_SIGNED_DATA 108 -#define CMS_R_CONTENT_VERIFY_ERROR 109 -#define CMS_R_CTRL_ERROR 110 -#define CMS_R_CTRL_FAILURE 111 -#define CMS_R_DECRYPT_ERROR 112 -#define CMS_R_DIGEST_ERROR 161 -#define CMS_R_ERROR_GETTING_PUBLIC_KEY 113 -#define CMS_R_ERROR_READING_MESSAGEDIGEST_ATTRIBUTE 114 -#define CMS_R_ERROR_SETTING_KEY 115 -#define CMS_R_ERROR_SETTING_RECIPIENTINFO 116 -#define CMS_R_INVALID_ENCRYPTED_KEY_LENGTH 117 -#define CMS_R_INVALID_KEY_ENCRYPTION_PARAMETER 176 -#define CMS_R_INVALID_KEY_LENGTH 118 -#define CMS_R_MD_BIO_INIT_ERROR 119 -#define CMS_R_MESSAGEDIGEST_ATTRIBUTE_WRONG_LENGTH 120 -#define CMS_R_MESSAGEDIGEST_WRONG_LENGTH 121 -#define CMS_R_MSGSIGDIGEST_ERROR 172 -#define CMS_R_MSGSIGDIGEST_VERIFICATION_FAILURE 162 -#define CMS_R_MSGSIGDIGEST_WRONG_LENGTH 163 -#define CMS_R_NEED_ONE_SIGNER 164 -#define CMS_R_NOT_A_SIGNED_RECEIPT 165 -#define CMS_R_NOT_ENCRYPTED_DATA 122 -#define CMS_R_NOT_KEK 123 -#define CMS_R_NOT_KEY_TRANSPORT 124 -#define CMS_R_NOT_PWRI 177 -#define CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE 125 -#define CMS_R_NO_CIPHER 126 -#define CMS_R_NO_CONTENT 127 -#define CMS_R_NO_CONTENT_TYPE 173 -#define CMS_R_NO_DEFAULT_DIGEST 128 -#define CMS_R_NO_DIGEST_SET 129 -#define CMS_R_NO_KEY 130 -#define CMS_R_NO_KEY_OR_CERT 174 -#define CMS_R_NO_MATCHING_DIGEST 131 -#define CMS_R_NO_MATCHING_RECIPIENT 132 -#define CMS_R_NO_MATCHING_SIGNATURE 166 -#define CMS_R_NO_MSGSIGDIGEST 167 -#define CMS_R_NO_PASSWORD 178 -#define CMS_R_NO_PRIVATE_KEY 133 -#define CMS_R_NO_PUBLIC_KEY 134 -#define CMS_R_NO_RECEIPT_REQUEST 168 -#define CMS_R_NO_SIGNERS 135 -#define CMS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE 136 -#define CMS_R_RECEIPT_DECODE_ERROR 169 -#define CMS_R_RECIPIENT_ERROR 137 -#define CMS_R_SIGNER_CERTIFICATE_NOT_FOUND 138 -#define CMS_R_SIGNFINAL_ERROR 139 -#define CMS_R_SMIME_TEXT_ERROR 140 -#define CMS_R_STORE_INIT_ERROR 141 -#define CMS_R_TYPE_NOT_COMPRESSED_DATA 142 -#define CMS_R_TYPE_NOT_DATA 143 -#define CMS_R_TYPE_NOT_DIGESTED_DATA 144 -#define CMS_R_TYPE_NOT_ENCRYPTED_DATA 145 -#define CMS_R_TYPE_NOT_ENVELOPED_DATA 146 -#define CMS_R_UNABLE_TO_FINALIZE_CONTEXT 147 -#define CMS_R_UNKNOWN_CIPHER 148 -#define CMS_R_UNKNOWN_DIGEST_ALGORIHM 149 -#define CMS_R_UNKNOWN_ID 150 -#define CMS_R_UNSUPPORTED_COMPRESSION_ALGORITHM 151 -#define CMS_R_UNSUPPORTED_CONTENT_TYPE 152 -#define CMS_R_UNSUPPORTED_KEK_ALGORITHM 153 -#define CMS_R_UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM 179 -#define CMS_R_UNSUPPORTED_RECIPIENT_TYPE 154 -#define CMS_R_UNSUPPORTED_RECPIENTINFO_TYPE 155 -#define CMS_R_UNSUPPORTED_TYPE 156 -#define CMS_R_UNWRAP_ERROR 157 -#define CMS_R_UNWRAP_FAILURE 180 -#define CMS_R_VERIFICATION_FAILURE 158 -#define CMS_R_WRAP_ERROR 159 - -#ifdef __cplusplus -} -#endif -#endif diff --git a/server/external/openssl/win_64/include/openssl/err.h b/server/external/openssl/win_64/include/openssl/err.h index 974cc9c..386295c 100644 --- a/server/external/openssl/win_64/include/openssl/err.h +++ b/server/external/openssl/win_64/include/openssl/err.h @@ -194,7 +194,7 @@ typedef struct err_state_st #define ERR_LIB_ECDH 43 #define ERR_LIB_STORE 44 #define ERR_LIB_FIPS 45 -#define ERR_LIB_CMS 46 +#define ERR_LIB_AMS 46 #define ERR_LIB_TS 47 #define ERR_LIB_HMAC 48 #define ERR_LIB_JPAKE 49 @@ -230,7 +230,7 @@ typedef struct err_state_st #define ECDHerr(f,r) ERR_PUT_error(ERR_LIB_ECDH,(f),(r),__FILE__,__LINE__) #define STOREerr(f,r) ERR_PUT_error(ERR_LIB_STORE,(f),(r),__FILE__,__LINE__) #define FIPSerr(f,r) ERR_PUT_error(ERR_LIB_FIPS,(f),(r),__FILE__,__LINE__) -#define CMSerr(f,r) ERR_PUT_error(ERR_LIB_CMS,(f),(r),__FILE__,__LINE__) +#define AMSerr(f,r) ERR_PUT_error(ERR_LIB_AMS,(f),(r),__FILE__,__LINE__) #define TSerr(f,r) ERR_PUT_error(ERR_LIB_TS,(f),(r),__FILE__,__LINE__) #define HMACerr(f,r) ERR_PUT_error(ERR_LIB_HMAC,(f),(r),__FILE__,__LINE__) #define JPAKEerr(f,r) ERR_PUT_error(ERR_LIB_JPAKE,(f),(r),__FILE__,__LINE__) diff --git a/server/external/openssl/win_64/include/openssl/evp.h b/server/external/openssl/win_64/include/openssl/evp.h index faeb3c2..d642f1d 100644 --- a/server/external/openssl/win_64/include/openssl/evp.h +++ b/server/external/openssl/win_64/include/openssl/evp.h @@ -1001,8 +1001,8 @@ void EVP_PBE_cleanup(void); #define ASN1_PKEY_CTRL_PKCS7_SIGN 0x1 #define ASN1_PKEY_CTRL_PKCS7_ENCRYPT 0x2 #define ASN1_PKEY_CTRL_DEFAULT_MD_NID 0x3 -#define ASN1_PKEY_CTRL_CMS_SIGN 0x5 -#define ASN1_PKEY_CTRL_CMS_ENVELOPE 0x7 +#define ASN1_PKEY_CTRL_AMS_SIGN 0x5 +#define ASN1_PKEY_CTRL_AMS_ENVELOPE 0x7 int EVP_PKEY_asn1_get_count(void); const EVP_PKEY_ASN1_METHOD *EVP_PKEY_asn1_get0(int idx); @@ -1095,9 +1095,9 @@ void EVP_PKEY_asn1_set_ctrl(EVP_PKEY_ASN1_METHOD *ameth, /* Used by GOST key encryption in TLS */ #define EVP_PKEY_CTRL_SET_IV 8 -#define EVP_PKEY_CTRL_CMS_ENCRYPT 9 -#define EVP_PKEY_CTRL_CMS_DECRYPT 10 -#define EVP_PKEY_CTRL_CMS_SIGN 11 +#define EVP_PKEY_CTRL_AMS_ENCRYPT 9 +#define EVP_PKEY_CTRL_AMS_DECRYPT 10 +#define EVP_PKEY_CTRL_AMS_SIGN 11 #define EVP_PKEY_CTRL_CIPHER 12 diff --git a/server/external/openssl/win_64/include/openssl/obj_mac.h b/server/external/openssl/win_64/include/openssl/obj_mac.h index b5ea7cd..9d2aa9e 100644 --- a/server/external/openssl/win_64/include/openssl/obj_mac.h +++ b/server/external/openssl/win_64/include/openssl/obj_mac.h @@ -780,9 +780,9 @@ #define NID_id_smime_cti 195 #define OBJ_id_smime_cti OBJ_SMIME,6L -#define SN_id_smime_mod_cms "id-smime-mod-cms" -#define NID_id_smime_mod_cms 196 -#define OBJ_id_smime_mod_cms OBJ_id_smime_mod,1L +#define SN_id_smime_mod_ams "id-smime-mod-ams" +#define NID_id_smime_mod_ams 196 +#define OBJ_id_smime_mod_ams OBJ_id_smime_mod,1L #define SN_id_smime_mod_ess "id-smime-mod-ess" #define NID_id_smime_mod_ess 197 @@ -988,13 +988,13 @@ #define NID_id_smime_alg_ESDH 245 #define OBJ_id_smime_alg_ESDH OBJ_id_smime_alg,5L -#define SN_id_smime_alg_CMS3DESwrap "id-smime-alg-CMS3DESwrap" -#define NID_id_smime_alg_CMS3DESwrap 246 -#define OBJ_id_smime_alg_CMS3DESwrap OBJ_id_smime_alg,6L +#define SN_id_smime_alg_AMS3DESwrap "id-smime-alg-AMS3DESwrap" +#define NID_id_smime_alg_AMS3DESwrap 246 +#define OBJ_id_smime_alg_AMS3DESwrap OBJ_id_smime_alg,6L -#define SN_id_smime_alg_CMSRC2wrap "id-smime-alg-CMSRC2wrap" -#define NID_id_smime_alg_CMSRC2wrap 247 -#define OBJ_id_smime_alg_CMSRC2wrap OBJ_id_smime_alg,7L +#define SN_id_smime_alg_AMSRC2wrap "id-smime-alg-AMSRC2wrap" +#define NID_id_smime_alg_AMSRC2wrap 247 +#define OBJ_id_smime_alg_AMSRC2wrap OBJ_id_smime_alg,7L #define SN_id_alg_PWRI_KEK "id-alg-PWRI-KEK" #define NID_id_alg_PWRI_KEK 893 diff --git a/server/external/openssl/win_64/include/openssl/pem.h b/server/external/openssl/win_64/include/openssl/pem.h index 8a6abab..2b4beee 100644 --- a/server/external/openssl/win_64/include/openssl/pem.h +++ b/server/external/openssl/win_64/include/openssl/pem.h @@ -135,7 +135,7 @@ extern "C" { #define PEM_STRING_ECPARAMETERS "EC PARAMETERS" #define PEM_STRING_ECPRIVATEKEY "EC PRIVATE KEY" #define PEM_STRING_PARAMETERS "PARAMETERS" -#define PEM_STRING_CMS "CMS" +#define PEM_STRING_AMS "AMS" /* Note that this structure is initialised by PEM_SealInit and cleaned up by PEM_SealFinal (at least for now) */ diff --git a/server/external/openssl/win_64/include/openssl/safestack.h b/server/external/openssl/win_64/include/openssl/safestack.h index ea3aa0d..1cbe6a4 100644 --- a/server/external/openssl/win_64/include/openssl/safestack.h +++ b/server/external/openssl/win_64/include/openssl/safestack.h @@ -469,93 +469,93 @@ DECLARE_SPECIAL_STACK_OF(OPENSSL_BLOCK, void) #define sk_BY_DIR_HASH_sort(st) SKM_sk_sort(BY_DIR_HASH, (st)) #define sk_BY_DIR_HASH_is_sorted(st) SKM_sk_is_sorted(BY_DIR_HASH, (st)) -#define sk_CMS_CertificateChoices_new(cmp) SKM_sk_new(CMS_CertificateChoices, (cmp)) -#define sk_CMS_CertificateChoices_new_null() SKM_sk_new_null(CMS_CertificateChoices) -#define sk_CMS_CertificateChoices_free(st) SKM_sk_free(CMS_CertificateChoices, (st)) -#define sk_CMS_CertificateChoices_num(st) SKM_sk_num(CMS_CertificateChoices, (st)) -#define sk_CMS_CertificateChoices_value(st, i) SKM_sk_value(CMS_CertificateChoices, (st), (i)) -#define sk_CMS_CertificateChoices_set(st, i, val) SKM_sk_set(CMS_CertificateChoices, (st), (i), (val)) -#define sk_CMS_CertificateChoices_zero(st) SKM_sk_zero(CMS_CertificateChoices, (st)) -#define sk_CMS_CertificateChoices_push(st, val) SKM_sk_push(CMS_CertificateChoices, (st), (val)) -#define sk_CMS_CertificateChoices_unshift(st, val) SKM_sk_unshift(CMS_CertificateChoices, (st), (val)) -#define sk_CMS_CertificateChoices_find(st, val) SKM_sk_find(CMS_CertificateChoices, (st), (val)) -#define sk_CMS_CertificateChoices_find_ex(st, val) SKM_sk_find_ex(CMS_CertificateChoices, (st), (val)) -#define sk_CMS_CertificateChoices_delete(st, i) SKM_sk_delete(CMS_CertificateChoices, (st), (i)) -#define sk_CMS_CertificateChoices_delete_ptr(st, ptr) SKM_sk_delete_ptr(CMS_CertificateChoices, (st), (ptr)) -#define sk_CMS_CertificateChoices_insert(st, val, i) SKM_sk_insert(CMS_CertificateChoices, (st), (val), (i)) -#define sk_CMS_CertificateChoices_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(CMS_CertificateChoices, (st), (cmp)) -#define sk_CMS_CertificateChoices_dup(st) SKM_sk_dup(CMS_CertificateChoices, st) -#define sk_CMS_CertificateChoices_pop_free(st, free_func) SKM_sk_pop_free(CMS_CertificateChoices, (st), (free_func)) -#define sk_CMS_CertificateChoices_shift(st) SKM_sk_shift(CMS_CertificateChoices, (st)) -#define sk_CMS_CertificateChoices_pop(st) SKM_sk_pop(CMS_CertificateChoices, (st)) -#define sk_CMS_CertificateChoices_sort(st) SKM_sk_sort(CMS_CertificateChoices, (st)) -#define sk_CMS_CertificateChoices_is_sorted(st) SKM_sk_is_sorted(CMS_CertificateChoices, (st)) - -#define sk_CMS_RecipientInfo_new(cmp) SKM_sk_new(CMS_RecipientInfo, (cmp)) -#define sk_CMS_RecipientInfo_new_null() SKM_sk_new_null(CMS_RecipientInfo) -#define sk_CMS_RecipientInfo_free(st) SKM_sk_free(CMS_RecipientInfo, (st)) -#define sk_CMS_RecipientInfo_num(st) SKM_sk_num(CMS_RecipientInfo, (st)) -#define sk_CMS_RecipientInfo_value(st, i) SKM_sk_value(CMS_RecipientInfo, (st), (i)) -#define sk_CMS_RecipientInfo_set(st, i, val) SKM_sk_set(CMS_RecipientInfo, (st), (i), (val)) -#define sk_CMS_RecipientInfo_zero(st) SKM_sk_zero(CMS_RecipientInfo, (st)) -#define sk_CMS_RecipientInfo_push(st, val) SKM_sk_push(CMS_RecipientInfo, (st), (val)) -#define sk_CMS_RecipientInfo_unshift(st, val) SKM_sk_unshift(CMS_RecipientInfo, (st), (val)) -#define sk_CMS_RecipientInfo_find(st, val) SKM_sk_find(CMS_RecipientInfo, (st), (val)) -#define sk_CMS_RecipientInfo_find_ex(st, val) SKM_sk_find_ex(CMS_RecipientInfo, (st), (val)) -#define sk_CMS_RecipientInfo_delete(st, i) SKM_sk_delete(CMS_RecipientInfo, (st), (i)) -#define sk_CMS_RecipientInfo_delete_ptr(st, ptr) SKM_sk_delete_ptr(CMS_RecipientInfo, (st), (ptr)) -#define sk_CMS_RecipientInfo_insert(st, val, i) SKM_sk_insert(CMS_RecipientInfo, (st), (val), (i)) -#define sk_CMS_RecipientInfo_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(CMS_RecipientInfo, (st), (cmp)) -#define sk_CMS_RecipientInfo_dup(st) SKM_sk_dup(CMS_RecipientInfo, st) -#define sk_CMS_RecipientInfo_pop_free(st, free_func) SKM_sk_pop_free(CMS_RecipientInfo, (st), (free_func)) -#define sk_CMS_RecipientInfo_shift(st) SKM_sk_shift(CMS_RecipientInfo, (st)) -#define sk_CMS_RecipientInfo_pop(st) SKM_sk_pop(CMS_RecipientInfo, (st)) -#define sk_CMS_RecipientInfo_sort(st) SKM_sk_sort(CMS_RecipientInfo, (st)) -#define sk_CMS_RecipientInfo_is_sorted(st) SKM_sk_is_sorted(CMS_RecipientInfo, (st)) - -#define sk_CMS_RevocationInfoChoice_new(cmp) SKM_sk_new(CMS_RevocationInfoChoice, (cmp)) -#define sk_CMS_RevocationInfoChoice_new_null() SKM_sk_new_null(CMS_RevocationInfoChoice) -#define sk_CMS_RevocationInfoChoice_free(st) SKM_sk_free(CMS_RevocationInfoChoice, (st)) -#define sk_CMS_RevocationInfoChoice_num(st) SKM_sk_num(CMS_RevocationInfoChoice, (st)) -#define sk_CMS_RevocationInfoChoice_value(st, i) SKM_sk_value(CMS_RevocationInfoChoice, (st), (i)) -#define sk_CMS_RevocationInfoChoice_set(st, i, val) SKM_sk_set(CMS_RevocationInfoChoice, (st), (i), (val)) -#define sk_CMS_RevocationInfoChoice_zero(st) SKM_sk_zero(CMS_RevocationInfoChoice, (st)) -#define sk_CMS_RevocationInfoChoice_push(st, val) SKM_sk_push(CMS_RevocationInfoChoice, (st), (val)) -#define sk_CMS_RevocationInfoChoice_unshift(st, val) SKM_sk_unshift(CMS_RevocationInfoChoice, (st), (val)) -#define sk_CMS_RevocationInfoChoice_find(st, val) SKM_sk_find(CMS_RevocationInfoChoice, (st), (val)) -#define sk_CMS_RevocationInfoChoice_find_ex(st, val) SKM_sk_find_ex(CMS_RevocationInfoChoice, (st), (val)) -#define sk_CMS_RevocationInfoChoice_delete(st, i) SKM_sk_delete(CMS_RevocationInfoChoice, (st), (i)) -#define sk_CMS_RevocationInfoChoice_delete_ptr(st, ptr) SKM_sk_delete_ptr(CMS_RevocationInfoChoice, (st), (ptr)) -#define sk_CMS_RevocationInfoChoice_insert(st, val, i) SKM_sk_insert(CMS_RevocationInfoChoice, (st), (val), (i)) -#define sk_CMS_RevocationInfoChoice_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(CMS_RevocationInfoChoice, (st), (cmp)) -#define sk_CMS_RevocationInfoChoice_dup(st) SKM_sk_dup(CMS_RevocationInfoChoice, st) -#define sk_CMS_RevocationInfoChoice_pop_free(st, free_func) SKM_sk_pop_free(CMS_RevocationInfoChoice, (st), (free_func)) -#define sk_CMS_RevocationInfoChoice_shift(st) SKM_sk_shift(CMS_RevocationInfoChoice, (st)) -#define sk_CMS_RevocationInfoChoice_pop(st) SKM_sk_pop(CMS_RevocationInfoChoice, (st)) -#define sk_CMS_RevocationInfoChoice_sort(st) SKM_sk_sort(CMS_RevocationInfoChoice, (st)) -#define sk_CMS_RevocationInfoChoice_is_sorted(st) SKM_sk_is_sorted(CMS_RevocationInfoChoice, (st)) - -#define sk_CMS_SignerInfo_new(cmp) SKM_sk_new(CMS_SignerInfo, (cmp)) -#define sk_CMS_SignerInfo_new_null() SKM_sk_new_null(CMS_SignerInfo) -#define sk_CMS_SignerInfo_free(st) SKM_sk_free(CMS_SignerInfo, (st)) -#define sk_CMS_SignerInfo_num(st) SKM_sk_num(CMS_SignerInfo, (st)) -#define sk_CMS_SignerInfo_value(st, i) SKM_sk_value(CMS_SignerInfo, (st), (i)) -#define sk_CMS_SignerInfo_set(st, i, val) SKM_sk_set(CMS_SignerInfo, (st), (i), (val)) -#define sk_CMS_SignerInfo_zero(st) SKM_sk_zero(CMS_SignerInfo, (st)) -#define sk_CMS_SignerInfo_push(st, val) SKM_sk_push(CMS_SignerInfo, (st), (val)) -#define sk_CMS_SignerInfo_unshift(st, val) SKM_sk_unshift(CMS_SignerInfo, (st), (val)) -#define sk_CMS_SignerInfo_find(st, val) SKM_sk_find(CMS_SignerInfo, (st), (val)) -#define sk_CMS_SignerInfo_find_ex(st, val) SKM_sk_find_ex(CMS_SignerInfo, (st), (val)) -#define sk_CMS_SignerInfo_delete(st, i) SKM_sk_delete(CMS_SignerInfo, (st), (i)) -#define sk_CMS_SignerInfo_delete_ptr(st, ptr) SKM_sk_delete_ptr(CMS_SignerInfo, (st), (ptr)) -#define sk_CMS_SignerInfo_insert(st, val, i) SKM_sk_insert(CMS_SignerInfo, (st), (val), (i)) -#define sk_CMS_SignerInfo_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(CMS_SignerInfo, (st), (cmp)) -#define sk_CMS_SignerInfo_dup(st) SKM_sk_dup(CMS_SignerInfo, st) -#define sk_CMS_SignerInfo_pop_free(st, free_func) SKM_sk_pop_free(CMS_SignerInfo, (st), (free_func)) -#define sk_CMS_SignerInfo_shift(st) SKM_sk_shift(CMS_SignerInfo, (st)) -#define sk_CMS_SignerInfo_pop(st) SKM_sk_pop(CMS_SignerInfo, (st)) -#define sk_CMS_SignerInfo_sort(st) SKM_sk_sort(CMS_SignerInfo, (st)) -#define sk_CMS_SignerInfo_is_sorted(st) SKM_sk_is_sorted(CMS_SignerInfo, (st)) +#define sk_AMS_CertificateChoices_new(cmp) SKM_sk_new(AMS_CertificateChoices, (cmp)) +#define sk_AMS_CertificateChoices_new_null() SKM_sk_new_null(AMS_CertificateChoices) +#define sk_AMS_CertificateChoices_free(st) SKM_sk_free(AMS_CertificateChoices, (st)) +#define sk_AMS_CertificateChoices_num(st) SKM_sk_num(AMS_CertificateChoices, (st)) +#define sk_AMS_CertificateChoices_value(st, i) SKM_sk_value(AMS_CertificateChoices, (st), (i)) +#define sk_AMS_CertificateChoices_set(st, i, val) SKM_sk_set(AMS_CertificateChoices, (st), (i), (val)) +#define sk_AMS_CertificateChoices_zero(st) SKM_sk_zero(AMS_CertificateChoices, (st)) +#define sk_AMS_CertificateChoices_push(st, val) SKM_sk_push(AMS_CertificateChoices, (st), (val)) +#define sk_AMS_CertificateChoices_unshift(st, val) SKM_sk_unshift(AMS_CertificateChoices, (st), (val)) +#define sk_AMS_CertificateChoices_find(st, val) SKM_sk_find(AMS_CertificateChoices, (st), (val)) +#define sk_AMS_CertificateChoices_find_ex(st, val) SKM_sk_find_ex(AMS_CertificateChoices, (st), (val)) +#define sk_AMS_CertificateChoices_delete(st, i) SKM_sk_delete(AMS_CertificateChoices, (st), (i)) +#define sk_AMS_CertificateChoices_delete_ptr(st, ptr) SKM_sk_delete_ptr(AMS_CertificateChoices, (st), (ptr)) +#define sk_AMS_CertificateChoices_insert(st, val, i) SKM_sk_insert(AMS_CertificateChoices, (st), (val), (i)) +#define sk_AMS_CertificateChoices_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(AMS_CertificateChoices, (st), (cmp)) +#define sk_AMS_CertificateChoices_dup(st) SKM_sk_dup(AMS_CertificateChoices, st) +#define sk_AMS_CertificateChoices_pop_free(st, free_func) SKM_sk_pop_free(AMS_CertificateChoices, (st), (free_func)) +#define sk_AMS_CertificateChoices_shift(st) SKM_sk_shift(AMS_CertificateChoices, (st)) +#define sk_AMS_CertificateChoices_pop(st) SKM_sk_pop(AMS_CertificateChoices, (st)) +#define sk_AMS_CertificateChoices_sort(st) SKM_sk_sort(AMS_CertificateChoices, (st)) +#define sk_AMS_CertificateChoices_is_sorted(st) SKM_sk_is_sorted(AMS_CertificateChoices, (st)) + +#define sk_AMS_RecipientInfo_new(cmp) SKM_sk_new(AMS_RecipientInfo, (cmp)) +#define sk_AMS_RecipientInfo_new_null() SKM_sk_new_null(AMS_RecipientInfo) +#define sk_AMS_RecipientInfo_free(st) SKM_sk_free(AMS_RecipientInfo, (st)) +#define sk_AMS_RecipientInfo_num(st) SKM_sk_num(AMS_RecipientInfo, (st)) +#define sk_AMS_RecipientInfo_value(st, i) SKM_sk_value(AMS_RecipientInfo, (st), (i)) +#define sk_AMS_RecipientInfo_set(st, i, val) SKM_sk_set(AMS_RecipientInfo, (st), (i), (val)) +#define sk_AMS_RecipientInfo_zero(st) SKM_sk_zero(AMS_RecipientInfo, (st)) +#define sk_AMS_RecipientInfo_push(st, val) SKM_sk_push(AMS_RecipientInfo, (st), (val)) +#define sk_AMS_RecipientInfo_unshift(st, val) SKM_sk_unshift(AMS_RecipientInfo, (st), (val)) +#define sk_AMS_RecipientInfo_find(st, val) SKM_sk_find(AMS_RecipientInfo, (st), (val)) +#define sk_AMS_RecipientInfo_find_ex(st, val) SKM_sk_find_ex(AMS_RecipientInfo, (st), (val)) +#define sk_AMS_RecipientInfo_delete(st, i) SKM_sk_delete(AMS_RecipientInfo, (st), (i)) +#define sk_AMS_RecipientInfo_delete_ptr(st, ptr) SKM_sk_delete_ptr(AMS_RecipientInfo, (st), (ptr)) +#define sk_AMS_RecipientInfo_insert(st, val, i) SKM_sk_insert(AMS_RecipientInfo, (st), (val), (i)) +#define sk_AMS_RecipientInfo_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(AMS_RecipientInfo, (st), (cmp)) +#define sk_AMS_RecipientInfo_dup(st) SKM_sk_dup(AMS_RecipientInfo, st) +#define sk_AMS_RecipientInfo_pop_free(st, free_func) SKM_sk_pop_free(AMS_RecipientInfo, (st), (free_func)) +#define sk_AMS_RecipientInfo_shift(st) SKM_sk_shift(AMS_RecipientInfo, (st)) +#define sk_AMS_RecipientInfo_pop(st) SKM_sk_pop(AMS_RecipientInfo, (st)) +#define sk_AMS_RecipientInfo_sort(st) SKM_sk_sort(AMS_RecipientInfo, (st)) +#define sk_AMS_RecipientInfo_is_sorted(st) SKM_sk_is_sorted(AMS_RecipientInfo, (st)) + +#define sk_AMS_RevocationInfoChoice_new(cmp) SKM_sk_new(AMS_RevocationInfoChoice, (cmp)) +#define sk_AMS_RevocationInfoChoice_new_null() SKM_sk_new_null(AMS_RevocationInfoChoice) +#define sk_AMS_RevocationInfoChoice_free(st) SKM_sk_free(AMS_RevocationInfoChoice, (st)) +#define sk_AMS_RevocationInfoChoice_num(st) SKM_sk_num(AMS_RevocationInfoChoice, (st)) +#define sk_AMS_RevocationInfoChoice_value(st, i) SKM_sk_value(AMS_RevocationInfoChoice, (st), (i)) +#define sk_AMS_RevocationInfoChoice_set(st, i, val) SKM_sk_set(AMS_RevocationInfoChoice, (st), (i), (val)) +#define sk_AMS_RevocationInfoChoice_zero(st) SKM_sk_zero(AMS_RevocationInfoChoice, (st)) +#define sk_AMS_RevocationInfoChoice_push(st, val) SKM_sk_push(AMS_RevocationInfoChoice, (st), (val)) +#define sk_AMS_RevocationInfoChoice_unshift(st, val) SKM_sk_unshift(AMS_RevocationInfoChoice, (st), (val)) +#define sk_AMS_RevocationInfoChoice_find(st, val) SKM_sk_find(AMS_RevocationInfoChoice, (st), (val)) +#define sk_AMS_RevocationInfoChoice_find_ex(st, val) SKM_sk_find_ex(AMS_RevocationInfoChoice, (st), (val)) +#define sk_AMS_RevocationInfoChoice_delete(st, i) SKM_sk_delete(AMS_RevocationInfoChoice, (st), (i)) +#define sk_AMS_RevocationInfoChoice_delete_ptr(st, ptr) SKM_sk_delete_ptr(AMS_RevocationInfoChoice, (st), (ptr)) +#define sk_AMS_RevocationInfoChoice_insert(st, val, i) SKM_sk_insert(AMS_RevocationInfoChoice, (st), (val), (i)) +#define sk_AMS_RevocationInfoChoice_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(AMS_RevocationInfoChoice, (st), (cmp)) +#define sk_AMS_RevocationInfoChoice_dup(st) SKM_sk_dup(AMS_RevocationInfoChoice, st) +#define sk_AMS_RevocationInfoChoice_pop_free(st, free_func) SKM_sk_pop_free(AMS_RevocationInfoChoice, (st), (free_func)) +#define sk_AMS_RevocationInfoChoice_shift(st) SKM_sk_shift(AMS_RevocationInfoChoice, (st)) +#define sk_AMS_RevocationInfoChoice_pop(st) SKM_sk_pop(AMS_RevocationInfoChoice, (st)) +#define sk_AMS_RevocationInfoChoice_sort(st) SKM_sk_sort(AMS_RevocationInfoChoice, (st)) +#define sk_AMS_RevocationInfoChoice_is_sorted(st) SKM_sk_is_sorted(AMS_RevocationInfoChoice, (st)) + +#define sk_AMS_SignerInfo_new(cmp) SKM_sk_new(AMS_SignerInfo, (cmp)) +#define sk_AMS_SignerInfo_new_null() SKM_sk_new_null(AMS_SignerInfo) +#define sk_AMS_SignerInfo_free(st) SKM_sk_free(AMS_SignerInfo, (st)) +#define sk_AMS_SignerInfo_num(st) SKM_sk_num(AMS_SignerInfo, (st)) +#define sk_AMS_SignerInfo_value(st, i) SKM_sk_value(AMS_SignerInfo, (st), (i)) +#define sk_AMS_SignerInfo_set(st, i, val) SKM_sk_set(AMS_SignerInfo, (st), (i), (val)) +#define sk_AMS_SignerInfo_zero(st) SKM_sk_zero(AMS_SignerInfo, (st)) +#define sk_AMS_SignerInfo_push(st, val) SKM_sk_push(AMS_SignerInfo, (st), (val)) +#define sk_AMS_SignerInfo_unshift(st, val) SKM_sk_unshift(AMS_SignerInfo, (st), (val)) +#define sk_AMS_SignerInfo_find(st, val) SKM_sk_find(AMS_SignerInfo, (st), (val)) +#define sk_AMS_SignerInfo_find_ex(st, val) SKM_sk_find_ex(AMS_SignerInfo, (st), (val)) +#define sk_AMS_SignerInfo_delete(st, i) SKM_sk_delete(AMS_SignerInfo, (st), (i)) +#define sk_AMS_SignerInfo_delete_ptr(st, ptr) SKM_sk_delete_ptr(AMS_SignerInfo, (st), (ptr)) +#define sk_AMS_SignerInfo_insert(st, val, i) SKM_sk_insert(AMS_SignerInfo, (st), (val), (i)) +#define sk_AMS_SignerInfo_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(AMS_SignerInfo, (st), (cmp)) +#define sk_AMS_SignerInfo_dup(st) SKM_sk_dup(AMS_SignerInfo, st) +#define sk_AMS_SignerInfo_pop_free(st, free_func) SKM_sk_pop_free(AMS_SignerInfo, (st), (free_func)) +#define sk_AMS_SignerInfo_shift(st) SKM_sk_shift(AMS_SignerInfo, (st)) +#define sk_AMS_SignerInfo_pop(st) SKM_sk_pop(AMS_SignerInfo, (st)) +#define sk_AMS_SignerInfo_sort(st) SKM_sk_sort(AMS_SignerInfo, (st)) +#define sk_AMS_SignerInfo_is_sorted(st) SKM_sk_is_sorted(AMS_SignerInfo, (st)) #define sk_CONF_IMODULE_new(cmp) SKM_sk_new(CONF_IMODULE, (cmp)) #define sk_CONF_IMODULE_new_null() SKM_sk_new_null(CONF_IMODULE) diff --git a/server/external/openssl/win_64/include/openssl/symhacks.h b/server/external/openssl/win_64/include/openssl/symhacks.h index bd2f000..b9e347c 100644 --- a/server/external/openssl/win_64/include/openssl/symhacks.h +++ b/server/external/openssl/win_64/include/openssl/symhacks.h @@ -407,19 +407,19 @@ #undef TS_CONF_set_clock_precision_digits #define TS_CONF_set_clock_precision_digits TS_CONF_set_clk_prec_digits -/* Hack some long CMS names */ -#undef CMS_RecipientInfo_ktri_get0_algs -#define CMS_RecipientInfo_ktri_get0_algs CMS_RecipInfo_ktri_get0_algs -#undef CMS_RecipientInfo_ktri_get0_signer_id -#define CMS_RecipientInfo_ktri_get0_signer_id CMS_RecipInfo_ktri_get0_sigr_id -#undef CMS_OtherRevocationInfoFormat_it -#define CMS_OtherRevocationInfoFormat_it CMS_OtherRevocInfoFormat_it -#undef CMS_KeyAgreeRecipientIdentifier_it -#define CMS_KeyAgreeRecipientIdentifier_it CMS_KeyAgreeRecipIdentifier_it -#undef CMS_OriginatorIdentifierOrKey_it -#define CMS_OriginatorIdentifierOrKey_it CMS_OriginatorIdOrKey_it -#undef cms_SignerIdentifier_get0_signer_id -#define cms_SignerIdentifier_get0_signer_id cms_SignerId_get0_signer_id +/* Hack some long AMS names */ +#undef AMS_RecipientInfo_ktri_get0_algs +#define AMS_RecipientInfo_ktri_get0_algs AMS_RecipInfo_ktri_get0_algs +#undef AMS_RecipientInfo_ktri_get0_signer_id +#define AMS_RecipientInfo_ktri_get0_signer_id AMS_RecipInfo_ktri_get0_sigr_id +#undef AMS_OtherRevocationInfoFormat_it +#define AMS_OtherRevocationInfoFormat_it AMS_OtherRevocInfoFormat_it +#undef AMS_KeyAgreeRecipientIdentifier_it +#define AMS_KeyAgreeRecipientIdentifier_it AMS_KeyAgreeRecipIdentifier_it +#undef AMS_OriginatorIdentifierOrKey_it +#define AMS_OriginatorIdentifierOrKey_it AMS_OriginatorIdOrKey_it +#undef ams_SignerIdentifier_get0_signer_id +#define ams_SignerIdentifier_get0_signer_id ams_SignerId_get0_signer_id /* Hack some long DTLS1 names */ #undef dtls1_retransmit_buffered_messages @@ -471,9 +471,9 @@ #undef X509v3_add_standard_extensions #define X509v3_add_standard_extensions oX509v3_add_standard_extensions -/* This one clashes with CMS_data_create */ -#undef cms_Data_create -#define cms_Data_create priv_cms_Data_create +/* This one clashes with AMS_data_create */ +#undef ams_Data_create +#define ams_Data_create priv_ams_Data_create #endif diff --git a/server/src/cm_auto_task.cpp b/server/src/cm_auto_task.cpp deleted file mode 100644 index 3b679c7..0000000 --- a/server/src/cm_auto_task.cpp +++ /dev/null @@ -1,218 +0,0 @@ -/* - * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. - * - * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/* - * cm_auto_task.cpp - - */ - -#include -#include - -#include "cm_auto_task.h" -#include "cm_porting.h" -#include "cm_dep.h" -#include "cm_server_util.h" -#include "cm_config.h" -#include "cm_user.h" -#include "cm_text_encryption.h" -#include "string.h" -#include "stdlib.h" - -#if defined(WINDOWS) -#include -#else -#include -#endif - -#ifdef _DEBUG_ -#include "deb.h" -#endif - -int -ts_validate_user (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char *id, *passwd; - char strbuf[1024]; - int retval, i; - T_DBMT_USER dbmt_user; - - id = nv_get_val (req, "id"); - passwd = nv_get_val (req, "password"); - - nv_update_val (res, "task", "authenticate"); - /* id, passwd checking */ - if (id == NULL) - { - sprintf (_dbmt_error, "%s", "parameter(id) is missing in request."); - ut_error_log (req, "ID not specified in the request"); - return ERR_PARAM_MISSING; - } - - if (passwd == NULL) - { - sprintf (_dbmt_error, "%s", - "parameter(password) is missing in request."); - ut_error_log (req, "password not specified in the request."); - return ERR_PARAM_MISSING; - } - - if (dbmt_user_read (&dbmt_user, strbuf) != ERR_NO_ERROR) - { - sprintf (_dbmt_error, "%s", "password file open error"); - ut_error_log (req, "Failed to read user info"); - return ERR_WITH_MSG; - } - - retval = -1; - for (i = 0; i < dbmt_user.num_dbmt_user; i++) - { - if (strcmp (dbmt_user.user_info[i].user_name, id) == 0) - { - char decrypted[PASSWD_LENGTH + 1]; - - uDecrypt (PASSWD_LENGTH, dbmt_user.user_info[i].user_passwd, - decrypted); - if (uStringEqual (passwd, decrypted)) - { - nv_update_val (res, "status", "success"); - retval = ERR_NO_ERROR; - } - else - { - ut_error_log (req, "Incorrect password"); - sprintf (_dbmt_error, "Incorrect password"); - retval = ERR_WITH_MSG; - } - break; - } - } - dbmt_user_free (&dbmt_user); - - if (retval < 0) - { - sprintf (_dbmt_error, "%s", "user not found."); - ut_error_log (req, "User not found."); - return ERR_WITH_MSG; - } - - return retval; -} - -int -ts_check_client_version (nvplist *req, nvplist *res) -{ - char *p; - int major_ver, minor_ver; - T_EMGR_VERSION clt_ver; - - major_ver = minor_ver = 0; - p = nv_get_val (req, "clientver"); - if (p != NULL) - { - major_ver = atoi (p); - p = strchr (p, '.'); - if (p != NULL) - { - minor_ver = atoi (p + 1); - } - } - clt_ver = EMGR_MAKE_VER (major_ver, minor_ver); - - if (clt_ver < EMGR_MAKE_VER (1, 0)) - { - nv_update_val (res, "status", "failure"); - nv_update_val (res, "note", - "Can not connect to the server due to version mismatch."); - return 0; - } - - return 1; -} - -int -ts_check_already_connected (nvplist *cli_response, int max_index, - int current_index, T_CLIENT_INFO *client_info) -{ - int index = 0; - for (index = 0; index <= max_index; index++) - { - if (IS_INVALID_SOCKET (client_info[index].sock_fd) - || (index == current_index)) - { - continue; - } - - if (!strcmp (client_info[current_index].user_id, client_info[index].user_id)) - { - char message[1024]; - sprintf (message, - "User %s was already connected from another client(%s)", - client_info[index].user_id, client_info[index].ip_address); - - nv_update_val (cli_response, "status", "failure"); - nv_update_val (cli_response, "note", message); - return index; - } - } - - return -1; -} - -int -ts_get_server_version (nvplist *req, nvplist *res) -{ - char tmpfile[PATH_MAX]; - char strbuf[1024]; - FILE *infile; - char cmd_name[ARNIADB_CMD_NAME_LEN]; - const char *argv[5]; - - nv_update_val (res, "task", "getversion"); - snprintf (tmpfile, PATH_MAX - 1, "%s/DBMT_task_015", sco.dbmt_tmp_dir); - - cmd_name[0] = '\0'; - snprintf (cmd_name, sizeof (cmd_name) - 1, "%s/%s%s", sco.szArniadb, - ARNIADB_DIR_BIN, UTIL_ARNIADB_REL_NAME); - - argv[0] = cmd_name; - argv[1] = NULL; - - run_child (argv, 1, NULL, tmpfile, NULL, NULL); /* arniadb_rel */ - - if ((infile = fopen (tmpfile, "r")) != NULL) - { - fgets (strbuf, sizeof (strbuf), infile); - fgets (strbuf, sizeof (strbuf), infile); - uRemoveCRLF (strbuf); - fclose (infile); - unlink (tmpfile); - nv_add_nvp (res, "ARNIADBVER", strbuf); - nv_update_val (res, "status", "success"); - } - else - { - nv_add_nvp (res, "ARNIADBVER", "none"); - nv_update_val (res, "status", "failure"); - nv_update_val (res, "note", "version information not available"); - return 0; - } - - return 1; -} diff --git a/server/src/cm_auto_task.h b/server/src/cm_auto_task.h deleted file mode 100644 index c4b232c..0000000 --- a/server/src/cm_auto_task.h +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. - * - * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/* - * cm_auto_task.h - - */ - -#ifndef _CM_AUTO_TASK_H_ -#define _CM_AUTO_TASK_H_ - -#include "cm_porting.h" -#include "cm_dep.h" - -typedef struct -{ - SOCKET sock_fd; - int state; - char *user_id; - char *ip_address; - short port; -} T_CLIENT_INFO; - -int ts_validate_user (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_get_server_version (nvplist *req, nvplist *res); -int ts_check_client_version (nvplist *req, nvplist *res); -int ts_check_already_connected (nvplist *cli_response, int max_index, - int current_index, - T_CLIENT_INFO *client_info); - -#endif /* _CM_AUTO_TASK_H_ */ diff --git a/server/src/cm_autojob.cpp b/server/src/cm_autojob.cpp deleted file mode 100644 index b855884..0000000 --- a/server/src/cm_autojob.cpp +++ /dev/null @@ -1,1701 +0,0 @@ -/* - * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. - * - * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/* - * cm_autojob.cpp - - */ - -#include -#include -#include -#include -#include -#include - -#if defined(WINDOWS) -#include -#include -#include -#else -#include -#include -#include -#include -#endif - -#include "cm_porting.h" -#include "cm_server_util.h" -#include "cm_autojob.h" -#include "cm_dep.h" -#include "cm_server_stat.h" -#include "cm_config.h" -#include "cm_cmd_exec.h" -#include "cm_text_encryption.h" -#include "cm_stat.h" - -#ifdef _DEBUG_ -#include "deb.h" -#include -#endif - -#define MIN_AUTOBACKUPDB_DELAY 600 -#define MAX_AUTOADD_FREE_SPACE_RATE 0.5 - - -typedef struct backup_period_details_t -{ - int date; - struct backup_period_details_t *next; -} backup_period_details; - -typedef struct autobackupdb_node_t -{ - char *dbname; - char *backup_id; - char *path; - int period_type; - //int period_date; - backup_period_details *period_date; - int time; - int level; - int archivedel; - int updatestatus; - int storeold; - int onoff; - int zip; - int check; - int mt; - int bk_num; - time_t lbt; - struct autobackupdb_node_t *next; - int is_interval; // 0 for specific time, 1 for interval -} autobackupdb_node; - -typedef struct unicasm_node_t -{ - char *bname; - short cpumonitor; - short busymonitor; - short logcpu; - short logbusy; - short cpurestart; - short busyrestart; - short cpulimit; - int busylimit; - time_t lrt; - struct unicasm_node_t *next; -} unicasm_node; - -/* This struct is for auto addvolume */ - -typedef enum -{ - AEQT_ONE, - AEQT_DAY, - AEQT_WEEK, - AEQT_MONTH -} T_EXECQUERY_PERIOD_TYPE; - -#define DETAIL_LEN 32 - -typedef struct query_period_details_t -{ - char detail[DETAIL_LEN]; - struct query_period_details_t *next; - -} query_period_details; - -typedef struct autoexecquery_t -{ - char dbname[64]; - char dbmt_uid[64]; - char query_id[64]; - char db_uid[64]; - char db_passwd[PASSWD_ENC_LENGTH]; - T_EXECQUERY_PERIOD_TYPE period; - query_period_details *detail1; - char detail2[16]; - char query_string[MAX_AUTOQUERY_SCRIPT_SIZE]; - int db_mode; - struct autoexecquery_t *next; -} autoexecquery_node; - -#ifdef HOST_MONITOR_PROC -/* This struct is for auto history logging */ -typedef struct autohistory_t -{ - time_t start_time; - time_t end_time; - float memory_limit; - float cpu_limit; - char **dbname; - int dbcount; - FILE *hfile; - void *mondata; -} autohistory_node; -#endif - -typedef enum -{ - ABPT_MONTHLY, - ABPT_WEEKLY, - ABPT_DAILY, - ABPT_HOURLY, - ABPT_SPECIAL -} T_AUTOBACKUP_PERIOD_TYPE; - -static void aj_load_execquery_conf (ajob *p_aj); -static void aj_execquery_handler (void *hd, time_t prev_check_time, - time_t cur_time); -static void aj_execquery_get_exec_time (autoexecquery_node *c, - query_period_details *d, - struct tm *exec_tm, - time_t prev_check_time); - -static void aj_execquery (autoexecquery_node *c); -static void _aj_autoexecquery_error_log (autoexecquery_node *node, - int err_code, const char *errmsg); -static void aj_load_autobackupdb_conf (ajob *ajp); -static void aj_load_autoaddvoldb_config (ajob *ajp); -static void aj_load_autohistory_conf (ajob *ajp); - -static void aj_autobackupdb_handler (void *ajp, time_t prev_check_time, - time_t cur_time); -static void aj_autoaddvoldb_handler (void *hd, time_t prev_check_time, - time_t cur_time); -static void aj_autohistory_handler (void *ajp, time_t prev_check_time, - time_t cur_time); - -static void aj_backupdb (autobackupdb_node *n); -static void _aj_autobackupdb_error_log (autobackupdb_node *n, char *errmsg); - -void -aj_initialize (ajob *ajlist, void *ud) -{ - struct stat statbuf; - - sprintf (ajlist[0].name, "autoaddvoldb"); - conf_get_dbmt_file (FID_AUTO_ADDVOLDB_CONF, ajlist[0].config_file); - stat (ajlist[0].config_file, &statbuf); - ajlist[0].last_modi = statbuf.st_mtime; - ajlist[0].is_on = 0; /* initially off */ - ajlist[0].ajob_handler = aj_autoaddvoldb_handler; - ajlist[0].ajob_loader = aj_load_autoaddvoldb_config; - ajlist[0].hd = NULL; - ajlist[0].mondata = ud; - - sprintf (ajlist[1].name, "autohistory"); - conf_get_dbmt_file (FID_AUTO_HISTORY_CONF, ajlist[1].config_file); - stat (ajlist[1].config_file, &statbuf); - ajlist[1].last_modi = statbuf.st_mtime; - ajlist[1].is_on = 0; - ajlist[1].ajob_handler = aj_autohistory_handler; - ajlist[1].ajob_loader = aj_load_autohistory_conf; - ajlist[1].hd = NULL; - ajlist[1].mondata = ud; - - sprintf (ajlist[2].name, "autobackupdb"); - conf_get_dbmt_file (FID_AUTO_BACKUPDB_CONF, ajlist[2].config_file); - stat (ajlist[2].config_file, &statbuf); - ajlist[2].last_modi = statbuf.st_mtime; - ajlist[2].is_on = 0; - ajlist[2].ajob_handler = aj_autobackupdb_handler; - ajlist[2].ajob_loader = aj_load_autobackupdb_conf; - ajlist[2].hd = NULL; - ajlist[2].mondata = ud; - - sprintf (ajlist[3].name, "autoexecquery"); - conf_get_dbmt_file (FID_AUTO_EXECQUERY_CONF, ajlist[3].config_file); - stat (ajlist[3].config_file, &statbuf); - ajlist[3].last_modi = statbuf.st_mtime; - ajlist[3].is_on = 0; - ajlist[3].ajob_handler = aj_execquery_handler; - ajlist[3].ajob_loader = aj_load_execquery_conf; - ajlist[3].hd = NULL; - ajlist[3].mondata = ud; -} - -/* This function calculates the free space fraction of given type */ -double -ajFreeSpace (GeneralSpacedbResult *cmd_res, const char *type) -{ - double total_page, free_page; - - total_page = free_page = 0.0; - cmd_res->get_total_and_free_page (type, free_page, total_page); - if (total_page > 0.0) - { - return (free_page / total_page); - } - - return 1.0; -} - -/* This function adds volume and write to file for fserver */ -void -aj_add_volume (char *dbname, const char *type, int increase, - int pagesize) -{ - char dbloca[512]; - char strbuf[1024]; - char volname[512] = { '\0' }; - FILE *outfile; - time_t mytime; - int retval; - char log_file_name[512]; - char cmd_name[ARNIADB_CMD_NAME_LEN]; - char inc_str[128]; - const char *argv[16]; - int argc = 0; - GeneralSpacedbResult *all_volumes; - char *pos = NULL; - char tmp_dbname[DB_NAME_LEN + MAXHOSTNAMELEN]; - - tmp_dbname[0] = '\0'; - pos = strchr (dbname, '@'); - if (pos != NULL) - { - strncpy (tmp_dbname, dbname, pos - dbname); - tmp_dbname[pos - dbname] = '\0'; - } - else - { - strncpy (tmp_dbname, dbname, strlen (dbname) + 1); - } - - if (uRetrieveDBDirectory (tmp_dbname, dbloca) != ERR_NO_ERROR) - { - return; - } - - if (access (dbloca, W_OK | X_OK | R_OK) < 0) - { - return; - } - -#if defined(WINDOWS) - nt_style_path (dbloca, dbloca); -#endif - - arniadb_cmd_name (cmd_name); - argv[argc++] = cmd_name; - argv[argc++] = UTIL_OPTION_ADDVOLDB; - argv[argc++] = "--" ADDVOL_FILE_PATH_L; - argv[argc++] = dbloca; - argv[argc++] = "--" ADDVOL_PURPOSE_L; - argv[argc++] = type; - argv[argc++] = "--" ADDVOL_DB_VOLUMN_SIZE_L; - sprintf (inc_str, "%lldB", (long long) pagesize * increase); - argv[argc++] = inc_str; - argv[argc++] = dbname; - argv[argc++] = NULL; - retval = run_child (argv, 1, NULL, NULL, NULL, NULL); /* addvoldb */ - - mytime = time (NULL); - conf_get_dbmt_file (FID_AUTO_ADDVOLDB_LOG, log_file_name); - if ((outfile = fopen (log_file_name, "a")) != NULL) - { - fprintf (outfile, "%s ", dbname); - fprintf (outfile, "%s ", type); - fprintf (outfile, "%d ", increase); - time_to_str (mytime, "%d-%d-%d,%d:%d:%d", strbuf, - TIME_STR_FMT_DATE_TIME); - fprintf (outfile, "%s ", strbuf); - fprintf (outfile, "start\n"); - fclose (outfile); - } - - mytime = 0; - - all_volumes = cmd_spacedb (dbname, ARNIADB_MODE_CS); - if (all_volumes == NULL) - { - return; - } - - mytime = all_volumes->get_my_time (dbloca); - mytime = time (&mytime); - if ((outfile = fopen (log_file_name, "a")) != NULL) - { - fprintf (outfile, "%s ", dbname); - if (retval == 0) - { - fprintf (outfile, "%s ", volname); - } - else - { - fprintf (outfile, "none "); - } - fprintf (outfile, "%s ", type); - fprintf (outfile, "%d ", increase); - time_to_str (mytime, "%d-%d-%d,%d:%d:%d", strbuf, - TIME_STR_FMT_DATE_TIME); - fprintf (outfile, "%s ", strbuf); - if (retval == 0) - { - fprintf (outfile, "success\n"); - } - else - { - fprintf (outfile, "failure\n"); - } - fclose (outfile); - } -} - -static void -aj_autohistory_handler (void *ajp, time_t prev_check_time, time_t cur_time) -{ -#ifdef HOST_MONITOR_PROC - time_t mytime, current_time; - float current_cpu, current_mem; - char strbuf[1024]; - autohistory_node *hsp; - userdata *mondata; - char timestr[64]; - - hsp = (autohistory_node *) ajp; - mondata = (userdata *) (hsp->mondata); - - current_time = time (¤t_time); - if ((current_time < hsp->start_time) || (current_time > hsp->end_time)) - { - if (hsp->hfile != NULL) - { - fclose (hsp->hfile); - } - hsp->hfile = NULL; - return; - } - - /* auto histoy feature */ - current_cpu = (float) (1000 - mondata->ssbuf.cpu_states[0]); - current_mem = - (float) (mondata->ssbuf.memory_stats[1]) / - (float) (mondata->ssbuf.memory_stats[0]) * 100.0; - - if ((current_cpu > hsp->cpu_limit) || (current_mem > hsp->memory_limit)) - { - mytime = time (&mytime); - - if (hsp->hfile == NULL) - { - time_to_str (mytime, "%04d%02d%02d.%02d%02d%02d", timestr, - TIME_STR_FMT_DATE_TIME); -#if !defined (DO_NOT_USE_ARNIADBENV) - sprintf (strbuf, "%s/logs/_dbmt_history.%s", sco.szArniadb, timestr); -#else - sprintf (strbuf, "%s/_dbmt_history.%s", ARNIADB_LOGDIR, timestr); -#endif - hsp->hfile = fopen (strbuf, "w"); - } - /* record system information */ - if (hsp->hfile != NULL) - { - time_to_str (mytime, "[%04d/%02d/%02d-%02d:%02d:%02d]", timestr, - TIME_STR_FMT_DATE_TIME); - fprintf (hsp->hfile, "%s", timestr); - fprintf (hsp->hfile, "load average 1min:%d 5min:%d 15min:%d\n", - mondata->ssbuf.load_avg[0], - mondata->ssbuf.load_avg[1], mondata->ssbuf.load_avg[2]); - fprintf (hsp->hfile, - "cpu time idle:%d user:%d kernel%d iowait:%d swap:%d\n", - mondata->ssbuf.cpu_states[0], - mondata->ssbuf.cpu_states[1], - mondata->ssbuf.cpu_states[2], - mondata->ssbuf.cpu_states[3], - mondata->ssbuf.cpu_states[4]); - fprintf (hsp->hfile, - "memory real:%dK active:%dK free:%dK swap:%dK swapfree:%dK\n", - mondata->ssbuf.memory_stats[0], - mondata->ssbuf.memory_stats[1], - mondata->ssbuf.memory_stats[2], - mondata->ssbuf.memory_stats[3], - mondata->ssbuf.memory_stats[4]); - fflush (hsp->hfile); - } - /* record db information */ - - if (hsp->hfile != NULL) - { - FILE *infile; - int i; - infile = - fopen (conf_get_dbmt_file (FID_AUTO_HISTORY_CONF, strbuf), "r"); - if (infile != NULL) - { - while (fgets (strbuf, sizeof (strbuf), infile)) - { - ut_trim (strbuf); - for (i = 0; i < MAX_INSTALLED_DB; ++i) - { - if ((mondata->dbvect[i] == 1) && - (uStringEqual (strbuf, mondata->dbbuf[i].db_name))) - { - fprintf (hsp->hfile, "database name:%s ", - mondata->dbbuf[i].db_name); - fprintf (hsp->hfile, "pid:%d ", - mondata->dbbuf[i].db_pid); - fprintf (hsp->hfile, "size:%ld ", - mondata->dbbuf[i].db_size); - fprintf (hsp->hfile, "status:%c ", - mondata->dbbuf[i].proc_stat[0]); - mytime = mondata->dbbuf[i].db_start_time; - time_to_str (mytime, - "%04d/%02d/%02d-%02d:%02d:%02d", - timestr, TIME_STR_FMT_DATE_TIME); - fprintf (hsp->hfile, "start_time:%s ", timestr); - fprintf (hsp->hfile, "cpu_usage:%f%% ", - mondata->dbbuf[i].db_cpu_usage); - fprintf (hsp->hfile, "mem_usage:%f%%\n\n", - mondata->dbbuf[i].db_mem_usage); - fflush (hsp->hfile); - } - } - } - fclose (infile); - } - fclose (hsp->hfile); - } - } -#endif -} - -static void -aj_autoaddvoldb_handler (void *hd, time_t prev_check_time, time_t cur_time) -{ - char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; - autoaddvoldb_node *curr; - GeneralSpacedbResult *spacedb_res; - T_SERVER_STATUS_RESULT *server_status_res; - int db_mode = 0; - - server_status_res = cmd_server_status (); - if (server_status_res == NULL) - { - return; - } - - for (curr = (autoaddvoldb_node *) hd; curr != NULL; curr = curr->next) - { - if (curr->dbname == NULL) - { - continue; - } - - if ((db_mode = - uIsDatabaseActive2 (server_status_res, curr->dbname)) == 0) - { - continue; - } - - /* if the HA mode is on, the db_mode equals 2. */ - if (db_mode == HA_MODE) - { - append_host_to_dbname (dbname_at_hostname, curr->dbname, - sizeof (dbname_at_hostname)); - spacedb_res = cmd_spacedb (dbname_at_hostname, ARNIADB_MODE_CS); - } - else - { - spacedb_res = cmd_spacedb (curr->dbname, ARNIADB_MODE_CS); - } - - if (spacedb_res == NULL) - { - continue; - } - - spacedb_res->auto_add_volume (curr, db_mode, dbname_at_hostname); - delete spacedb_res; - } - cmd_servstat_result_free (server_status_res); -} - -static void -aj_load_autoaddvoldb_config (ajob *ajp) -{ - FILE *infile = NULL; - char strbuf[1024]; - char *conf_item[AUTOADDVOL_CONF_ENTRY_NUM]; - autoaddvoldb_node *next, *curr; - - /* turn off autoaddvoldb feature */ - ajp->is_on = 0; - - /* free existing structure */ - curr = (autoaddvoldb_node *) (ajp->hd); - while (curr) - { - /* clear the linked list */ - next = curr->next; - FREE_MEM (curr); - curr = next; - } - ajp->hd = curr = NULL; - - infile = fopen (ajp->config_file, "r"); - if (infile == NULL) - { - return; - } - - while (fgets (strbuf, sizeof (strbuf), infile)) - { - ut_trim (strbuf); - if (strbuf[0] == '#' || strbuf[0] == '\0') - { - continue; - } - - if (string_tokenize (strbuf, conf_item, AUTOADDVOL_CONF_ENTRY_NUM) < 0) - { - continue; - } - - if (curr == NULL) - { - curr = (autoaddvoldb_node *) malloc (sizeof (autoaddvoldb_node)); - ajp->hd = curr; - } - else - { - curr->next = - (autoaddvoldb_node *) malloc (sizeof (autoaddvoldb_node)); - curr = curr->next; - } - if (curr == NULL) - { - break; - } - - memset (curr, 0, sizeof (autoaddvoldb_node)); - strcpy (curr->dbname, conf_item[0]); - - if (strcmp (conf_item[1], "ON") == 0) - { - curr->data_vol = 1; - ajp->is_on = 1; - } - - curr->data_warn_outofspace = atof (conf_item[2]); - if (curr->data_warn_outofspace > MAX_AUTOADD_FREE_SPACE_RATE) - { - curr->data_warn_outofspace = MAX_AUTOADD_FREE_SPACE_RATE; - } - - curr->data_ext_page = atoi (conf_item[3]); - - if (strcmp (conf_item[4], "ON") == 0) - { - curr->index_vol = 1; - ajp->is_on = 1; - } - - curr->index_warn_outofspace = atof (conf_item[5]); - if (curr->index_warn_outofspace > MAX_AUTOADD_FREE_SPACE_RATE) - { - curr->index_warn_outofspace = MAX_AUTOADD_FREE_SPACE_RATE; - } - - curr->index_ext_page = atoi (conf_item[6]); - curr->next = NULL; - } - fclose (infile); -} - -/* parameter ud : autojob structure for autohistory */ -/* parameter ud2 : data from collect_start() */ -static void -aj_load_autohistory_conf (ajob *ajp) -{ -#ifdef HOST_MONITOR_PROC - int i; - FILE *infile; - struct tm timeptr; - autohistory_node *ahist; - char strbuf[1024]; - char *conf_item[AUTOHISTORY_CONF_ENTRY_NUM]; - - ajp->is_on = 0; - - ahist = (autohistory_node *) (ajp->hd); - /* free existing structure */ - if (ahist) - { - for (i = 0; i < ahist->dbcount; ++i) - { - FREE_MEM (ahist->dbname[i]); - } - FREE_MEM (ahist->dbname); - FREE_MEM (ahist); - } - - /* create new struct and initialize */ - ajp->hd = (void *) malloc (sizeof (autohistory_node)); - ahist = (autohistory_node *) (ajp->hd); - ahist->memory_limit = 100.0; - ahist->cpu_limit = 100.0; - ahist->dbname = NULL; - ahist->dbcount = 0; - ahist->hfile = NULL; - ahist->mondata = ajp->mondata; - - if ((infile = fopen (ajp->config_file, "r")) == NULL) - { - return; - } - - memset (strbuf, 0, sizeof (strbuf)); - while (fgets (strbuf, sizeof (strbuf), infile)) - { - ut_trim (strbuf); - if (strbuf[0] == '#' || strbuf[0] == '\0') - { - memset (strbuf, 0, sizeof (strbuf)); - continue; - } - break; - } - if (string_tokenize (strbuf, conf_item, AUTOHISTORY_CONF_ENTRY_NUM) < 0) - { - fclose (infile); - return; - } - - if (strcmp (conf_item[0], "ON") == 0) - { - ajp->is_on = 1; - } - else - { - ajp->is_on = 0; - } - - timeptr.tm_year = atoi (conf_item[1]) - 1900; - timeptr.tm_mon = atoi (conf_item[2]) - 1; - timeptr.tm_mday = atoi (conf_item[3]); - timeptr.tm_hour = atoi (conf_item[4]); - timeptr.tm_min = atoi (conf_item[5]); - timeptr.tm_sec = atoi (conf_item[6]); - ahist->start_time = mktime (&timeptr); - - timeptr.tm_year = atoi (conf_item[7]) - 1900; - timeptr.tm_mon = atoi (conf_item[8]) - 1; - timeptr.tm_mday = atoi (conf_item[9]); - timeptr.tm_hour = atoi (conf_item[10]); - timeptr.tm_min = atoi (conf_item[11]); - timeptr.tm_sec = atoi (conf_item[12]); - ahist->end_time = mktime (&timeptr); - - ahist->memory_limit = atof (conf_item[13]); - ahist->cpu_limit = atof (conf_item[14]); - - while (fgets (strbuf, sizeof (strbuf), infile)) - { - ut_trim (strbuf); - ahist->dbcount++; - ahist->dbname = - REALLOC (ahist->dbname, sizeof (char *) * (ahist->dbcount)); - if (ahist->dbname == NULL) - { - break; - } - ahist->dbname[ahist->dbcount - 1] = strdup (strbuf); - } - - fclose (infile); -#endif -} - -static void -set_query_period_details (query_period_details **details, char *conf_item) -{ - char delim[] = " ,"; - char *token = NULL; - query_period_details *head = NULL; - - token = strtok (conf_item, delim); - while (token != NULL) - { - *details = (query_period_details *) malloc (sizeof (query_period_details)); - strncpy ((*details)->detail, token, DETAIL_LEN); - (*details)->next = head; - head = *details; - token = strtok (NULL, delim); - } -} - -static void -set_backup_period_details (backup_period_details **details, - int period_type, char *conf_item) -{ - char delim[] = " ,"; - char *token; - backup_period_details *head = NULL; - - token = strtok (conf_item, delim); - while (token != NULL) - { - *details = - (backup_period_details *) malloc (sizeof (backup_period_details)); - - switch (period_type) - { - case ABPT_MONTHLY: - case ABPT_HOURLY: - (*details)->date = atoi (token); - break; - - case ABPT_WEEKLY: - if (!strcmp (token, WEEK_SUNDAY_L)) - { - (*details)->date = 0; - } - else if (!strcmp (token, WEEK_MONDAY_L)) - { - (*details)->date = 1; - } - else if (!strcmp (token, WEEK_TUESDAY_L)) - { - (*details)->date = 2; - } - else if (!strcmp (token, WEEK_WEDNESDAY_L)) - { - (*details)->date = 3; - } - else if (!strcmp (token, WEEK_THURSDAY_L)) - { - (*details)->date = 4; - } - else if (!strcmp (token, WEEK_FRIDAY_L)) - { - (*details)->date = 5; - } - else if (!strcmp (token, WEEK_SATURDAY_L)) - { - (*details)->date = 6; - } - break; - - case ABPT_DAILY: - (*details)->date = -1; - break; - - case ABPT_SPECIAL: - (*details)->date = atoi (token) * 10000; - (*details)->date += atoi (token + 5) * 100; - (*details)->date += atoi (token + 8); - break; - - default: - break; - } - - (*details)->next = head; - head = *details; - token = strtok (NULL, delim); - } -} - -static void -aj_load_autobackupdb_conf (ajob *p_aj) -{ - char buf[1024]; - FILE *infile = NULL; - autobackupdb_node *c; - char *conf_item[AUTOBACKUP_CONF_ENTRY_NUM]; - int is_old_version_entry; - - p_aj->is_on = 0; - - c = (autobackupdb_node *) (p_aj->hd); - while (c != NULL) - { - autobackupdb_node *t; - backup_period_details *p; - - while (c->period_date != NULL) - { - p = c->period_date; - c->period_date = c->period_date->next; - FREE_MEM (p); - } - - t = c; - FREE_MEM (t->dbname); - FREE_MEM (t->backup_id); - FREE_MEM (t->path); - c = c->next; - FREE_MEM (t); - } - p_aj->hd = c = NULL; - - if ((infile = fopen (p_aj->config_file, "r")) == NULL) - { - return; - } - - while (fgets (buf, sizeof (buf), infile)) - { - is_old_version_entry = 0; - ut_trim (buf); - if (buf[0] == '#' || buf[0] == '\0') - { - continue; - } - - if (string_tokenize (buf, conf_item, AUTOBACKUP_CONF_ENTRY_NUM) < 0) - { - if (string_tokenize (buf, conf_item, AUTOBACKUP_CONF_ENTRY_NUM - 3) < 0) - { - continue; - } - else - { - is_old_version_entry = 1; - } - } - - if (c == NULL) - { - c = (autobackupdb_node *) malloc (sizeof (autobackupdb_node)); - p_aj->hd = c; - } - else - { - c->next = (autobackupdb_node *) malloc (sizeof (autobackupdb_node)); - c = c->next; - } - if (c == NULL) - { - break; - } - - c->lbt = -1; - c->dbname = strdup (conf_item[0]); - c->backup_id = strdup (conf_item[1]); - c->path = strdup (conf_item[2]); - - if (!strcmp (conf_item[3], "Monthly")) - { - c->period_type = ABPT_MONTHLY; - } - else if (!strcmp (conf_item[3], "Weekly")) - { - c->period_type = ABPT_WEEKLY; - } - else if (!strcmp (conf_item[3], "Daily")) - { - c->period_type = ABPT_DAILY; - } - else if (!strcmp (conf_item[3], "Hourly")) - { - c->period_type = ABPT_HOURLY; - } - else if (!strcmp (conf_item[3], "Special")) - { - c->period_type = ABPT_SPECIAL; - } - else - { - if (c != NULL) - { - FREE_MEM (c->dbname); - FREE_MEM (c->backup_id); - FREE_MEM (c->path); - FREE_MEM (c); - } - continue; - } - - set_backup_period_details (& (c->period_date), c->period_type, conf_item[4]); - - if ('i' == conf_item[5][0]) // interval time is set - { - c->is_interval = 1; - c->time = atoi (conf_item[5] + 1); - } - else // sepcific time is set - { - c->time = atoi (conf_item[5]); - c->is_interval = 0; - } - c->level = atoi (conf_item[6]); - c->archivedel = !strcmp (conf_item[7], "ON") ? 1 : 0; - c->updatestatus = !strcmp (conf_item[8], "ON") ? 1 : 0; - c->storeold = !strcmp (conf_item[9], "ON") ? 1 : 0; - c->onoff = !strcmp (conf_item[10], "ON") ? 1 : 0; - - if (is_old_version_entry) - { - c->zip = 0; - c->check = 0; - c->mt = 0; - c->bk_num = 1; - } - else - { - c->zip = !strcmp (conf_item[11], "y") ? 1 : 0; - c->check = !strcmp (conf_item[12], "y") ? 1 : 0; - c->mt = atoi (conf_item[13]); - c->bk_num = conf_item[14] ? atoi (conf_item[14]) : 1; - } - c->next = NULL; - } /* end of while */ - fclose (infile); - p_aj->is_on = 1; -} - -static void -aj_load_execquery_conf (ajob *p_aj) -{ - FILE *infile = NULL; - char *conf_item[AUTOEXECQUERY_CONF_ENTRY_NUM]; - char buf[MAX_JOB_CONFIG_FILE_LINE_LENGTH]; - autoexecquery_node *c; - - p_aj->is_on = 0; - - /* NODE reset */ - c = (autoexecquery_node *) (p_aj->hd); - while (c != NULL) - { - autoexecquery_node *t; - query_period_details *p; - - while (c->detail1 != NULL) - { - p = c->detail1; - c->detail1 = c->detail1->next; - FREE_MEM (p); - } - - t = c; - c = c->next; - FREE_MEM (t); - } - - p_aj->hd = c = NULL; - - /* read NODE information from file */ - if ((infile = fopen (p_aj->config_file, "r")) == NULL) - { - return; - } - - while (fgets (buf, sizeof (buf), infile)) - { - ut_trim (buf); - if (buf[0] == '#' || buf[0] == '\0') - { - continue; - } - - if (string_tokenize_accept_laststring_space - (buf, conf_item, AUTOEXECQUERY_CONF_ENTRY_NUM) < 0) - { - continue; - } - - if (c == NULL) - { - c = (autoexecquery_node *) malloc (sizeof (autoexecquery_node)); - p_aj->hd = c; - } - else - { - c->next = - (autoexecquery_node *) malloc (sizeof (autoexecquery_node)); - c = c->next; - } - if (c == NULL) - { - break; - } - - snprintf (c->dbname, sizeof (c->dbname) - 1, "%s", conf_item[0]); - snprintf (c->query_id, sizeof (c->query_id) - 1, "%s", conf_item[1]); - snprintf (c->db_uid, sizeof (c->db_uid) - 1, "%s", conf_item[2]); - snprintf (c->db_passwd, sizeof (c->db_passwd) - 1, "%s", conf_item[3]); - c->db_passwd[sizeof (c->db_passwd) - 1] = '\0'; - snprintf (c->dbmt_uid, sizeof (c->dbmt_uid) - 1, "%s", conf_item[4]); - - if (strcmp (conf_item[5], "ONE") == 0) - { - c->period = AEQT_ONE; - } - else if (strcmp (conf_item[5], "DAY") == 0) - { - c->period = AEQT_DAY; - } - else if (strcmp (conf_item[5], "WEEK") == 0) - { - c->period = AEQT_WEEK; - } - else if (strcmp (conf_item[5], "MONTH") == 0) - { - c->period = AEQT_MONTH; - } - - // snprintf (c->detail1, sizeof (c->detail1) - 1, "%s", conf_item[6]); - - //Tools-822, use a link list to store period_details. - set_query_period_details (& (c->detail1), conf_item[6]); - - snprintf (c->detail2, sizeof (c->detail2) - 1, "%s", conf_item[7]); - snprintf (c->query_string, sizeof (c->query_string) - 1, "%s", - conf_item[8]); - c->db_mode = 2; - c->next = NULL; - } /* end of while */ - fclose (infile); - p_aj->is_on = 1; - -} - -static void -aj_execquery_handler (void *hd, time_t prev_check_time, time_t cur_time) -{ - time_t execquery_time; - struct tm exec_tm, cur_tm, *tm_p; - autoexecquery_node *c; - query_period_details *detail1 = NULL; - int tm_wday = 0; - - tm_p = localtime (&cur_time); - if (tm_p == NULL) - { - return; - } - cur_tm = *tm_p; - - for (c = (autoexecquery_node *) (hd); c != NULL; c = c->next) - { - exec_tm = cur_tm; - detail1 = c->detail1; - - while (detail1 != NULL) - { - aj_execquery_get_exec_time (c, detail1, &exec_tm, prev_check_time); - - // backup tm_wday, since mktime can change tm_wday field. - tm_wday = exec_tm.tm_wday; - execquery_time = mktime (&exec_tm); - - if (execquery_time <= prev_check_time || execquery_time > cur_time) - { - detail1 = detail1->next; - continue; - } - - if ((c->period == AEQT_ONE) - || (c->period == AEQT_DAY) - || ((c->period == AEQT_WEEK) && cur_tm.tm_wday == tm_wday) - || ((c->period == AEQT_MONTH) - && cur_tm.tm_mday == exec_tm.tm_mday)) - { - aj_execquery (c); - } - detail1 = detail1->next; - } - } - - return; -} - -static void -aj_execquery_get_exec_time (autoexecquery_node *c, - query_period_details *d, - struct tm *exec_tm, time_t prev_check_time) -{ - switch (c->period) - { - case AEQT_ONE: - sscanf (d->detail, "%d/%d/%d", & (exec_tm->tm_year), & (exec_tm->tm_mon), - & (exec_tm->tm_mday)); - exec_tm->tm_year -= 1900; /* year : since 1900 */ - exec_tm->tm_mon -= 1; /* month : zero based month */ - break; - - case AEQT_DAY: - /* sscanf(c->detail2, "%d:%d", &(exec_tm->tm_hour), &(exec_tm->tm_min)); */ - break; - - case AEQT_WEEK: - if (strcmp (d->detail, WEEK_CAPITAL_SUNDAY_S) == 0) - { - exec_tm->tm_wday = 0; - } - else if (strcmp (d->detail, WEEK_CAPITAL_MONDAY_S) == 0) - { - exec_tm->tm_wday = 1; - } - else if (strcmp (d->detail, WEEK_CAPITAL_TUESDAY_S) == 0) - { - exec_tm->tm_wday = 2; - } - else if (strcmp (d->detail, WEEK_CAPITAL_WEDNESDAY_S) == 0) - { - exec_tm->tm_wday = 3; - } - else if (strcmp (d->detail, WEEK_CAPITAL_THURSDAY_S) == 0) - { - exec_tm->tm_wday = 4; - } - else if (strcmp (d->detail, WEEK_CAPITAL_FRIDAY_S) == 0) - { - exec_tm->tm_wday = 5; - } - else if (strcmp (d->detail, WEEK_CAPITAL_SATURDAY_S) == 0) - { - exec_tm->tm_wday = 6; - } - break; - - case AEQT_MONTH: - sscanf (d->detail, "%d", & (exec_tm->tm_mday)); - break; - } - - if ('i' == c->detail2[0]) // time interval for auto execute query - { - int interval; - time_t prev_day_sec = 0; - struct tm prev_tm, *tm_p; - - tm_p = localtime (&prev_check_time); - if (tm_p == NULL) - { - return; - } - prev_tm = *tm_p; - - sscanf (c->detail2, "i%d", &interval); - - prev_day_sec = - prev_tm.tm_hour * 3600 + prev_tm.tm_min * 60 + prev_tm.tm_sec; - if ((prev_day_sec + interval * 60) >= (24 * 3600)) // if across a day, start at 00:00 - { - exec_tm->tm_hour = 0; - exec_tm->tm_min = 0; - } - else // not across a day - { - time_t exec_sec = - (prev_day_sec / (interval * 60) + 1) * interval * 60; - exec_tm->tm_hour = (int) (exec_sec / 3600); - exec_tm->tm_min = (exec_sec % 3600) / 60; - } - } - else // specific time for auto execute query - { - sscanf (c->detail2, "%d:%d", & (exec_tm->tm_hour), & (exec_tm->tm_min)); - } - exec_tm->tm_sec = 0; -} - -static void -aj_execquery (autoexecquery_node *c) -{ - int retval; - int argc = 0; - const char *argv[11]; - char cmd_name[ARNIADB_CMD_NAME_LEN + 1]; - int ha_mode; - T_DB_SERVICE_MODE db_mode; - char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; - char dbpasswd[PASSWD_LENGTH + 1]; - int error_code; - char error_buffer[1024]; - char arniadb_err_file[PATH_MAX]; - char input_filename[256]; - FILE *input_file; - - arniadb_err_file[0] = '\0'; - - _aj_autoexecquery_error_log (c, 0, PRINT_CMD_START); - - memset (error_buffer, '\0', sizeof (error_buffer)); - - cmd_name[0] = '\0'; -#if !defined (DO_NOT_USE_ARNIADBENV) - sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ASQL_NAME); -#else - sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_ASQL_NAME); -#endif - argv[argc++] = cmd_name; - - db_mode = uDatabaseMode (c->dbname, &ha_mode); - if (ha_mode != 0) - { - append_host_to_dbname (dbname_at_hostname, c->dbname, - sizeof (dbname_at_hostname)); - argv[argc++] = dbname_at_hostname; - } - else - { - argv[argc++] = c->dbname; - } - - switch (db_mode) - { - case DB_SERVICE_MODE_SA: - sprintf (error_buffer, "Database(%s) is running in stand alone mode", - c->dbname); - _aj_autoexecquery_error_log (c, ERR_GENERAL_ERROR, error_buffer); - return; - case DB_SERVICE_MODE_CS: - argv[argc++] = "--" ASQL_CS_MODE_L; - break; - case DB_SERVICE_MODE_NONE: - argv[argc++] = "--" ASQL_SA_MODE_L; - break; - } - - sprintf (input_filename, "%s/dbmt_auto_execquery_%d", sco.dbmt_tmp_dir, - (int) getpid ()); - argv[argc++] = "--" ASQL_INPUT_FILE_L; - argv[argc++] = input_filename; - - argv[argc++] = "--" ASQL_USER_L; - argv[argc++] = c->db_uid; - - uDecrypt (PASSWD_LENGTH, c->db_passwd, dbpasswd); - argv[argc++] = "--" ASQL_PASSWORD_L; - argv[argc++] = dbpasswd; - - argv[argc++] = "--" ASQL_NO_AUTO_COMMIT_L; - - for (; argc < 11; argc++) - { - argv[argc] = NULL; - } - - input_file = fopen (input_filename, "w+"); - if (input_file != NULL) - { - fprintf (input_file, "%s\n", c->query_string); - fprintf (input_file, ";commit"); - fclose (input_file); - } - else - { - sprintf (error_buffer, "Can't create temp file"); - _aj_autoexecquery_error_log (c, ERR_FILE_CREATE_FAIL, error_buffer); - return; - } - - snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", - sco.dbmt_tmp_dir, "aj_execquery", getpid ()); - retval = run_child (argv, 1, NULL, NULL, arniadb_err_file, NULL); /* asql auto-execute */ - unlink (input_filename); - if (retval != 0) - { - sprintf (error_buffer, "Failed to execute Query with"); - _aj_autoexecquery_error_log (c, ERR_SYSTEM_CALL, error_buffer); - if (access (arniadb_err_file, F_OK) == 0) - { - unlink (arniadb_err_file); - } - return; - } - else - { - if (read_error_file2 (arniadb_err_file, error_buffer, DBMT_ERROR_MSG_SIZE, &error_code) < 0) - { - if (error_code == 0) - { - error_code = ERR_GENERAL_ERROR; - } - _aj_autoexecquery_error_log (c, error_code, error_buffer); - if (access (arniadb_err_file, F_OK) == 0) - { - unlink (arniadb_err_file); - } - return; - } - else - { - _aj_autoexecquery_error_log (c, 0, "success"); - if (access (arniadb_err_file, F_OK) == 0) - { - unlink (arniadb_err_file); - } - } - } -} - -static void -_aj_autoexecquery_error_log (autoexecquery_node *node, int error_code, - const char *errmsg) -{ - /* open error file and write errmsg */ - time_t tt; - FILE *outfile; - char logfile[256]; - char strbuf[128]; - - tt = time (&tt); -#if !defined (DO_NOT_USE_ARNIADBENV) - sprintf (logfile, "%s/log/manager/auto_execquery.log", sco.szArniadb); -#else - sprintf (logfile, "%s/manager/auto_execquery.log", ARNIADB_LOGDIR); -#endif - - outfile = fopen (logfile, "a"); - if (outfile == NULL) - { - return; - } - - time_to_str (tt, "DATE:%04d/%02d/%02d TIME:%02d:%02d:%02d", strbuf, - TIME_STR_FMT_DATE_TIME); - fprintf (outfile, "%s\n", strbuf); - fprintf (outfile, "DBNAME:%s EMGR-USERNAME:%s QUERY-ID:%s ERROR-CODE:%d\n", - node->dbname, node->dbmt_uid, node->query_id, error_code); - fprintf (outfile, "=> %s\n", errmsg); - fflush (outfile); - fclose (outfile); -} - -static void -aj_autobackupdb_handler (void *hd, time_t prev_check_time, time_t cur_time) -{ - time_t backup_time; - struct tm backup_tm, cur_tm, prev_tm, *tm_p; - autobackupdb_node *c; - - backup_period_details *period_date = NULL; - - tm_p = localtime (&cur_time); - if (tm_p == NULL) - { - return; - } - cur_tm = *tm_p; - - for (c = (autobackupdb_node *) (hd); c != NULL; c = c->next) - { - backup_tm = cur_tm; - period_date = c->period_date; - - while (period_date != NULL) - { - if (c->period_type == ABPT_SPECIAL) - { - backup_tm.tm_year = period_date->date / 10000 - 1900; - backup_tm.tm_mon = (period_date->date % 10000) / 100 - 1; - backup_tm.tm_mday = period_date->date % 100; - } - if (1 == c->is_interval) // interval time for auto backup - { - time_t prev_day_sec; - tm_p = localtime (&prev_check_time); - if (tm_p == NULL) - { - return; - } - prev_tm = *tm_p; - - prev_day_sec = - prev_tm.tm_hour * 3600 + prev_tm.tm_min * 60 + prev_tm.tm_sec; - if ((prev_day_sec + c->time * 60) >= 24 * 3600) // if across a day, start at 00:00 - { - backup_tm.tm_hour = 0; - backup_tm.tm_min = 0; - } - else // not across a day - { - time_t exec_sec = - (prev_day_sec / (c->time * 60) + 1) * c->time * 60; - backup_tm.tm_hour = (int) (exec_sec / 3600); - backup_tm.tm_min = (exec_sec % 3600) / 60; - } - } - else // specific time for auto backup - { - if (c->period_type != ABPT_HOURLY) - { - backup_tm.tm_hour = c->time / 100; - } - backup_tm.tm_min = c->time % 100; - } - backup_tm.tm_sec = 0; - - backup_time = mktime (&backup_tm); - if (backup_time <= prev_check_time || backup_time > cur_time) - { - period_date = period_date->next; - continue; - } - - if ((c->period_type == ABPT_MONTHLY - && cur_tm.tm_mday == period_date->date) - || (c->period_type == ABPT_WEEKLY - && cur_tm.tm_wday == period_date->date) - || (c->period_type == ABPT_DAILY) - || (c->period_type == ABPT_HOURLY) - || (c->period_type == ABPT_SPECIAL)) - { - aj_backupdb (c); - } - period_date = period_date->next; - } // while - } // for -} - -static void -_aj_autobackupdb_error_log (autobackupdb_node *n, char *errmsg) -{ - time_t tt; - FILE *outfile; - char logfile[256]; - char strbuf[128]; - - tt = time (&tt); -#if !defined (DO_NOT_USE_ARNIADBENV) - sprintf (logfile, "%s/log/manager/auto_backupdb.log", sco.szArniadb); -#else - sprintf (logfile, "%s/manager/auto_backupdb.log", ARNIADB_LOGDIR); -#endif - - outfile = fopen (logfile, "a"); - if (outfile == NULL) - { - return; - } - time_to_str (tt, "DATE:%04d/%02d/%02d TIME:%02d:%02d:%02d", strbuf, - TIME_STR_FMT_DATE_TIME); - fprintf (outfile, "%s\n", strbuf); - fprintf (outfile, "DBNAME:%s BACKUPID:%s\n", n->dbname, n->backup_id); - fprintf (outfile, "=> %s\n", errmsg); - fflush (outfile); - fclose (outfile); -} - -static void -aj_backupdb (autobackupdb_node *n) -{ - char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; - int ha_mode; - char bkpath[512]; - char inputfilepath[512]; - char buf[2048], dbdir[512]; - char backup_vol_name[128]; - const char *opt_mode; - char db_start_flag = 0; - char arniadb_err_file[PATH_MAX]; - int retval; - char cmd_name[ARNIADB_CMD_NAME_LEN]; - char level_str[32]; - char strtime[32]; - char thread_num_str[16]; - const char *argv[16]; - int argc = 0; - FILE *inputfile; - T_DB_SERVICE_MODE db_mode; - - arniadb_err_file[0] = '\0'; - - sprintf (buf, "backupdb(%s): auto job start", n->dbname); - _aj_autobackupdb_error_log (n, buf); - - n->lbt = time (NULL); - if (uRetrieveDBDirectory (n->dbname, dbdir) != ERR_NO_ERROR) - { - sprintf (buf, "DB directory not found"); - _aj_autobackupdb_error_log (n, buf); - return; - } - time_to_str (n->lbt, "%04d%02d%02d_%02d%02d%02d", strtime, - TIME_STR_FMT_DATE_TIME); - sprintf (backup_vol_name, "%s_auto_backup_lv%d", n->dbname, n->level); - sprintf (bkpath, "%s/%s_%s", n->path, strtime, backup_vol_name); - - db_mode = uDatabaseMode (n->dbname, &ha_mode); - if (db_mode == DB_SERVICE_MODE_SA) - { - sprintf (buf, "Failed to execute backupdb: %s is in standalone mode", n->dbname); - _aj_autobackupdb_error_log (n, buf); - return; - } - if (n->onoff == 1 && db_mode == DB_SERVICE_MODE_NONE) - { - sprintf (buf, "Failed to execute backupdb: %s is offline", n->dbname); - _aj_autobackupdb_error_log (n, buf); - return; - } - - if (access (n->path, F_OK) < 0) - { - if (uCreateDir (n->path) != ERR_NO_ERROR) - { - sprintf (buf, "Directory creation failed: %s", n->path); - _aj_autobackupdb_error_log (n, buf); - return; - } - } - - remove_extra_subdir (n->path, backup_vol_name, n->bk_num); - - if (access (bkpath, F_OK) < 0) - { - if (uCreateDir (bkpath) != ERR_NO_ERROR) - { - sprintf (buf, "Directory creation failed: %s", bkpath); - _aj_autobackupdb_error_log (n, buf); - return; - } - } - - /* if DB status is on then turn off */ - if (n->onoff == 0 && db_mode == DB_SERVICE_MODE_CS) - { - if (cmd_stop_server (n->dbname, NULL, 0) < 0) - { - sprintf (buf, "Failed to turn off DB"); - _aj_autobackupdb_error_log (n, buf); - return; - } - db_start_flag = 1; - } - - opt_mode = (n->onoff == 0) ? "--" ASQL_SA_MODE_L : "--" ASQL_CS_MODE_L; - - arniadb_cmd_name (cmd_name); - sprintf (thread_num_str, "%d", n->mt); - sprintf (level_str, "%d", n->level); - argc = 0; - argv[argc++] = cmd_name; - argv[argc++] = UTIL_OPTION_BACKUPDB; - argv[argc++] = opt_mode; - argv[argc++] = "--" BACKUP_LEVEL_L; - argv[argc++] = level_str; - argv[argc++] = "--" BACKUP_DESTINATION_PATH_L; - argv[argc++] = bkpath; - if (n->archivedel) - { - argv[argc++] = "--" BACKUP_REMOVE_ARCHIVE_L; - } - - if (n->mt > 0) - { - argv[argc++] = "--" BACKUP_THREAD_COUNT_L; - argv[argc++] = thread_num_str; - } - - if (n->zip) - { - argv[argc++] = "--" BACKUP_COMPRESS_L; - } - - if (!n->check) - { - argv[argc++] = "--" BACKUP_NO_CHECK_L; - } - - if (ha_mode != 0) - { - append_host_to_dbname (dbname_at_hostname, n->dbname, - sizeof (dbname_at_hostname)); - argv[argc++] = dbname_at_hostname; - } - else - { - argv[argc++] = n->dbname; - } - argv[argc++] = NULL; - - snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", - sco.dbmt_tmp_dir, "aj_backupdb", getpid ()); - - sprintf (inputfilepath, "%s/DBMT_task_%d.%d", sco.dbmt_tmp_dir, TS_BACKUPDB, - (int) getpid ()); - inputfile = fopen (inputfilepath, "w"); - if (inputfile) - { - fprintf (inputfile, "y"); - fclose (inputfile); - } - else - { - sprintf (buf, "Failed to write file: %s", inputfilepath); - _aj_autobackupdb_error_log (n, buf); - return; - } - - retval = run_child (argv, 1, inputfilepath, NULL, arniadb_err_file, NULL); /* backupdb */ - unlink (inputfilepath); - - if (read_error_file (arniadb_err_file, buf, sizeof (buf)) < 0) - { - _aj_autobackupdb_error_log (n, buf); - if (access (arniadb_err_file, F_OK) == 0) - { - unlink (arniadb_err_file); - } - return; - } - if (access (arniadb_err_file, F_OK) == 0) - { - unlink (arniadb_err_file); - } - if (retval < 0) - { - /* backupdb */ - sprintf (buf, "Failed to execute backupdb: %s", argv[0]); - _aj_autobackupdb_error_log (n, buf); - return; - } - - sprintf (buf, "backupdb(%s): success", n->dbname); - _aj_autobackupdb_error_log (n, buf); /* log success info to notify arniadb manager user */ - - /* update statistics */ - if (n->onoff == 0 && n->updatestatus) - { - arniadb_cmd_name (cmd_name); - argv[0] = cmd_name; - argv[1] = UTIL_OPTION_OPTIMIZEDB; - argv[2] = n->dbname; - argv[3] = NULL; - if (run_child (argv, 1, NULL, NULL, NULL, NULL) < 0) - { - /* optimizedb */ - sprintf (buf, "Failed to update statistics"); - _aj_autobackupdb_error_log (n, buf); - return; - } - } - - if (db_start_flag) - { - char err_buf[ERR_MSG_SIZE]; - if (cmd_start_server (n->dbname, err_buf, sizeof (err_buf)) < 0) - { - int buf_len; - memset (buf, 0, sizeof (buf)); - buf_len = sprintf (buf, "Failed to turn on DB : "); - snprintf (buf + buf_len, sizeof (buf) - buf_len - 1, "%s", err_buf); - _aj_autobackupdb_error_log (n, buf); - } - } -} diff --git a/server/src/cm_autojob.h b/server/src/cm_autojob.h deleted file mode 100644 index 24a178b..0000000 --- a/server/src/cm_autojob.h +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. - * - * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/* - * cm_autojob.h - - */ - -#ifndef _CM_AUTOJOB_H_ -#define _CM_AUTOJOB_H_ - -#include -#include "cm_cmd_exec.h" - -#define AUTOJOB_SIZE 4 -#define MIN_AUTO_ADDVOL_PAGE_SIZE 1000 -#define DBNAME_MAX_LEN 64 - -/* autobackupdb.conf */ -#define AJ_BACKUP_CONF_DBNAME "dbname" -#define AJ_BACKUP_CONF_BACKUPID "backupid" -#define AJ_BACKUP_CONF_PATH "path" -#define AJ_BACKUP_CONF_PERIOD_TYPE "period_type" -#define AJ_BACKUP_CONF_PERIOD_DATE "period_date" -#define AJ_BACKUP_CONF_TIME "time" -#define AJ_BACKUP_CONF_LEVEL "level" -#define AJ_BACKUP_CONF_ARCHIVEDEL "archivedel" -#define AJ_BACKUP_CONF_UPDATESTATUS "updatestatus" -#define AJ_BACKUP_CONF_STOREOLD "storeold" -#define AJ_BACKUP_CONF_ONOFF "onoff" - -class GeneralSpacedbResult; - -/* automatic job */ -typedef struct _ajob -{ - char name[64]; - char config_file[512]; /* config file name */ - time_t last_modi; /* last modified time of config file */ - int is_on; - void (*ajob_handler) (void *, time_t, time_t); - void (*ajob_loader) (struct _ajob *); - void *hd; /* handler specific data strudture */ - /* this pointer will be handed to ajob_handler as parameter */ - void *mondata; -} ajob; - -typedef struct autoaddvoldb_t -{ - char dbname[DBNAME_MAX_LEN]; - int data_vol; - double data_warn_outofspace; - int data_ext_page; - int index_vol; - double index_warn_outofspace; - int index_ext_page; - struct autoaddvoldb_t *next; -} autoaddvoldb_node; - -void aj_initialize (ajob *ajlist, void *ud); -void aj_add_volume (char *dbname, const char *type, - int increase, int pagesize); -double -ajFreeSpace (GeneralSpacedbResult *cmd_res, const char *type); - -#endif /* _CM_AUTOJOB_H_ */ diff --git a/server/src/cm_cci_interface.cpp b/server/src/cm_cci_interface.cpp deleted file mode 100644 index 16bc275..0000000 --- a/server/src/cm_cci_interface.cpp +++ /dev/null @@ -1,1655 +0,0 @@ -/* - * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. - * - * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - -/* -* cm_cci_interface.cpp -*/ - -#include -#include -#include -#include - -#if defined(WINDOWS) -#include -#else -#include -#endif - -#include -#include - -#include "cm_log.h" -#include "cm_cci_interface.h" -#include "cm_server_util.h" -#include "cm_cmd_exec.h" -#include "cm_config.h" - -#define SQL_FILE_SUFFIX ".sql" -#define CSV_FILE_SUFFIX ".csv" - -using namespace std; - -static T_HTTP_TASK_INFO http_task_info[] = -{ - {"exportdb", 0, http_arniadb_exportdb}, - {"importdb", 0, http_arniadb_importdb}, - {"sql", 0, http_arniadb_sql}, - {NULL, 0, NULL} -}; - -int -get_cci_task_info (const char *task, T_HTTP_TASK_FUNC *task_func) -{ - int i; - - for (i = 0; http_task_info[i].task_str != NULL; i++) - { - if (!strcmp (task, http_task_info[i].task_str)) - { - if (task_func) - { - *task_func = http_task_info[i].task_func; - } - return http_task_info[i].task_code; - } - } - - *task_func = NULL; - - return -1; -} - -int -build_common_header (Json::Value &response, int status, const char *note) -{ - response["status"] = status; - response["note"] = string (note); - - return status; -} - -int -_get_col_info (int req, T_CCI_SQLX_CMD &cmd_type, Json::Value &response) -{ - int i, col_count; - char *temp; - T_CCI_COL_INFO *res_col_info; - Json::Value attribute, col; - - res_col_info = cci_get_result_info (req, &cmd_type, &col_count); - if (cmd_type == ARNIADB_STMT_SELECT && !res_col_info) - { - return -1; - } - response["stmt_type"] = cmd_type; - - for (i = 1; i <= col_count; i++) - { - temp = CCI_GET_RESULT_INFO_NAME (res_col_info, i); - col["name"] = (temp == NULL) ? "" : temp; - temp = CCI_GET_RESULT_INFO_ATTR_NAME (res_col_info, i); - col["attr_name"] = (temp == NULL) ? "" : temp; - temp = CCI_GET_RESULT_INFO_CLASS_NAME (res_col_info, i); - col["class_name"] = (temp == NULL) ? "" : temp; - temp = CCI_GET_RESULT_INFO_DEFAULT_VALUE (res_col_info, i); - col["default"] = (temp == NULL) ? "" : temp; - - col["type"] = CCI_GET_RESULT_INFO_TYPE (res_col_info, i); - col["precision"] = CCI_GET_RESULT_INFO_PRECISION (res_col_info, i); - col["scale"] = CCI_GET_RESULT_INFO_SCALE (res_col_info, i); - col["is_not_null"] = CCI_GET_RESULT_INFO_IS_NON_NULL (res_col_info, i); - col["is_auto_inc"] = - CCI_GET_RESULT_INFO_IS_AUTO_INCREMENT (res_col_info, i); - col["is_unique_key"] = - CCI_GET_RESULT_INFO_IS_UNIQUE_KEY (res_col_info, i); - col["is_primary_key"] = - CCI_GET_RESULT_INFO_IS_PRIMARY_KEY (res_col_info, i); - col["is_foreign_key"] = - CCI_GET_RESULT_INFO_IS_FOREIGN_KEY (res_col_info, i); - col["is_reverse_index"] = - CCI_GET_RESULT_INFO_IS_REVERSE_INDEX (res_col_info, i); - col["is_reverse_unique"] = - CCI_GET_RESULT_INFO_IS_REVERSE_UNIQUE (res_col_info, i); - col["is_shared"] = CCI_GET_RESULT_INFO_IS_SHARED (res_col_info, i); - attribute.append (col); - } - response["attribute"] = attribute; - return col_count; -} - -typedef struct -{ - int con_id; - int fetch_size; - int fetch_offset; - int dump_plan; - const char *stmt; - Json::Value *response; -#ifndef WINDOWS - pthread_mutex_t *mutex; - pthread_cond_t *cond; -#endif -} async_stmt_st; - -int -_execute_async_stmt (int con_id, const char *stmt, int fetch_size, - int fetch_offset, int dump_plan, Json::Value &response) -{ - int req = 0, col_count = 0, res, ind, i, flag = 0; - char *buffer, oidbuf[1024], *plan = NULL; - Json::Value values, col, oid; - T_CCI_ERROR error; - int elapsed_msec = 0; - T_CCI_SQLX_CMD cmd_type; - struct timeval task_begin, task_end; - - response["stmt"] = stmt; - /* record the start time of running stmt */ - gettimeofday (&task_begin, NULL); - - if ((req = cci_prepare (con_id, (char *) stmt, CCI_PREPARE_INCLUDE_OID, &error)) < 0) - { - response["status"] = error.err_code; - response["note"] = error.err_msg; - res = req; - goto handle_error; - } - - if ((col_count = _get_col_info (req, cmd_type, response)) < 0) - { - response["status"] = -1; - response["note"] = "get col info error"; - res = col_count; - goto handle_error; - } - - if (dump_plan) - { - flag |= CCI_EXEC_QUERY_INFO; - } - if ((res = cci_execute (req, flag, 0, &error)) < 0) - { - response["status"] = error.err_code; - response["note"] = error.err_msg; - goto handle_error; - } - response["exec_retval"] = res; - - if (dump_plan && cmd_type == ARNIADB_STMT_SELECT) - { - if (cci_get_query_plan (req, &plan) >= 0) - { - response["query_plan"] = plan ? plan : ""; - cci_query_info_free (plan); - } - } - - if (fetch_size == 0) - { - fetch_size = res; - } - - while (fetch_size--) - { - res = cci_cursor (req, fetch_offset, CCI_CURSOR_CURRENT, &error); - if (res < 0) - { - break; - } - - fetch_offset = 1; - if ((res = cci_fetch (req, &error)) < 0) - { - break; - } - - col.clear (); - for (i = 1; i <= col_count; i++) - { - buffer = NULL; - if ((res = - cci_get_data (req, i, CCI_A_TYPE_STR, &buffer, &ind)) < 0) - { - break; - } - if (buffer == NULL) - { - col.append (Json::Value::null); - } - else - { - col.append (buffer); - } - } - values.append (col); - - if (!cci_get_cur_oid (req, oidbuf)) - { - oid.append (oidbuf); - } - else - { - oid.append (""); - } - } - response["values"] = values; - response["oid"] = oid; - - response["status"] = CCI_ER_NO_ERROR; - response["note"] = "note"; - res = CCI_ER_NO_ERROR; -handle_error: - if (req > 0) - { - cci_close_req_handle (req); - } - - gettimeofday (&task_end, NULL); - _ut_timeval_diff (&task_begin, &task_end, &elapsed_msec); - response["__EXEC_TIME"] = elapsed_msec; - return res; -} - -#ifdef WINDOWS -DWORD WINAPI -_async_stmt (LPVOID lpArg) -#else -void * -_async_stmt (void *lpArg) -#endif -{ - async_stmt_st *pstmt = (async_stmt_st *) lpArg; - _execute_async_stmt (pstmt->con_id, pstmt->stmt, pstmt->fetch_size, - pstmt->fetch_offset, pstmt->dump_plan, - * (pstmt->response)); - -#ifndef WINDOWS - pthread_mutex_lock (pstmt->mutex); - pthread_cond_broadcast (pstmt->cond); - pthread_mutex_unlock (pstmt->mutex); -#endif - return NULL; -} - -#ifdef WINDOWS -int -_execute_stmt (int con_id, const char *stmt, int fetch_size, int fetch_offset, - int dump_plan, Json::Value &response, unsigned long time_out = 120) -{ - HANDLE hHandles; - DWORD ThreadID; - DWORD dwCount = 0, dwWaitResult; - async_stmt_st *pstmt = (async_stmt_st *) malloc (sizeof (async_stmt_st)); - if (pstmt == NULL) - { - return CCI_ER_NO_MORE_MEMORY; - } - - pstmt->con_id = con_id; - pstmt->stmt = stmt; - pstmt->fetch_size = fetch_size; - pstmt->fetch_offset = fetch_offset; - pstmt->dump_plan = dump_plan; - pstmt->response = &response; - - hHandles = CreateThread (NULL, 0, _async_stmt, pstmt, 0, &ThreadID); - if (hHandles == NULL) - { - free (pstmt); - return build_common_header (response, CCI_ER_DBMS, - "failed to execute stmt"); - } - - dwWaitResult = WaitForSingleObject (hHandles, // handle to mutex - time_out * 1000); // no time-out interval - - if (dwWaitResult == WAIT_TIMEOUT) - { - TerminateThread (hHandles, 1); - CloseHandle (hHandles); - free (pstmt); - return build_common_header (response, CCI_ER_DBMS, - "execute stmt timeout"); - } - - CloseHandle (hHandles); - free (pstmt); - return CCI_ER_NO_ERROR; -} -#else -int -_execute_stmt (int con_id, const char *stmt, int fetch_size, int fetch_offset, - int dump_plan, Json::Value &response, unsigned long time_out = 120) -{ - int err = 0; - pthread_t async_thrd; -#if defined(AIX) - pthread_attr_t thread_attr; -#endif - pthread_cond_t cond; - pthread_mutex_t mutex; - timespec to; - async_stmt_st *pstmt = (async_stmt_st *) malloc (sizeof (async_stmt_st)); - if (pstmt == NULL) - { - return CCI_ER_NO_MORE_MEMORY; - } - - err = pthread_mutex_init (&mutex, NULL); - if (err != 0) - { - LOG_ERROR ("_execute_stmt : fail to set thread mutex."); - return build_common_header (response, CCI_ER_DBMS, - "failed to execute stmt"); - } - - err = pthread_cond_init (&cond, NULL); - if (err != 0) - { - LOG_ERROR ("_execute_stmt : fail to set thread condition."); - return build_common_header (response, CCI_ER_DBMS, - "failed to execute stmt"); - } - - pstmt->con_id = con_id; - pstmt->stmt = stmt; - pstmt->fetch_size = fetch_size; - pstmt->fetch_offset = fetch_offset; - pstmt->dump_plan = dump_plan; - pstmt->response = &response; - - pstmt->mutex = &mutex; - pstmt->cond = &cond; - -#if defined(AIX) - err = pthread_attr_init (&thread_attr); - if (err != 0) - { - LOG_ERROR ("_execute_stmt : fail to set thread attribute."); - return build_common_header (response, CCI_ER_DBMS, - "failed to execute stmt"); - } - - err = pthread_attr_setdetachstate (&thread_attr, PTHREAD_CREATE_DETACHED); - if (err != 0) - { - LOG_ERROR ("_execute_stmt : fail to set thread detach state."); - return build_common_header (response, CCI_ER_DBMS, - "failed to execute stmt"); - } - - /* AIX's pthread is slightly different from other systems. - Its performance highly depends on the pthread's scope and it's related - kernel parameters. */ - err = pthread_attr_setscope (&thread_attr, PTHREAD_SCOPE_PROCESS); - if (err != 0) - { - LOG_ERROR ("cm_execute_request_async : fail to set thread scope."); - return build_common_header (response, CCI_ER_DBMS, - "failed to execute stmt"); - } - - err = pthread_attr_setstacksize (&thread_attr, AIX_STACKSIZE_PER_THREAD); - if (err != 0) - { - LOG_ERROR ("cm_execute_request_async : fail to set thread stack size."); - return build_common_header (response, CCI_ER_DBMS, - "failed to execute stmt"); - } - - err = pthread_create (&async_thrd, &thread_attr, _async_stmt, pstmt); -#else /* except AIX */ - err = pthread_create (&async_thrd, NULL, _async_stmt, pstmt); -#endif - - if (err != 0) - { - free (pstmt); - pthread_mutex_destroy (&mutex); - pthread_cond_destroy (&cond); - return build_common_header (response, CCI_ER_DBMS, - "failed to execute stmt"); - } - pthread_mutex_lock (&mutex); - to.tv_sec = time (NULL) + time_out; - to.tv_nsec = 0; - err = pthread_cond_timedwait (&cond, &mutex, &to); - pthread_mutex_unlock (&mutex); - if (err == ETIMEDOUT) - { - pthread_cancel (async_thrd); - } - else - { - pthread_join (async_thrd, NULL); - } - - pthread_mutex_destroy (&mutex); - pthread_cond_destroy (&cond); - - free (pstmt); - - if (err == ETIMEDOUT) - return build_common_header (response, CCI_ER_QUERY_TIMEOUT, - "execute stmt timeout"); - - return CCI_ER_NO_ERROR; -} -#endif - -int -_saveto (string file_name, string info, string flag) -{ - FILE *fp = fopen (file_name.c_str (), flag.c_str ()); - if (fp == NULL) - { - return -1; - } - - fwrite (info.c_str (), 1, info.size (), fp); - fclose (fp); - return 0; -} - -string -_get_auto_increment () -{ - //" AUTO_INCREMENT(1,1)" - return ""; -} - -string -str_replace (const string &orign, const string &oldstr, - const string &newstr) -{ - size_t pos = 0; - string tempstr = orign; - string::size_type newlen = newstr.length (); - string::size_type oldlen = oldstr.length (); - while (true) - { - pos = tempstr.find (oldstr, pos); - if (pos == string::npos) - { - break; - } - - tempstr.replace (pos, oldlen, newstr); - pos += newlen; - } - - return tempstr; -} - - -string -_fix_cci_get_attr_type_str (const char *buf) -{ - int flag = 0; - const char *p = buf; - string fix_str = buf; - if (!strstr (buf, "float") && strstr (buf, "floa")) - { - fix_str = str_replace (fix_str, "floa", "float"); - } - if (!strstr (buf, "blob") && strstr (buf, "blo")) - { - fix_str = str_replace (fix_str, "blo", "blob"); - } - if (!strstr (buf, "clob") && strstr (buf, "clo")) - { - fix_str = str_replace (fix_str, "clo", "clob"); - } - if (!strstr (buf, "datetime") && strstr (buf, "datetim")) - { - fix_str = str_replace (fix_str, "datetim", "datetime"); - } - else if (!strstr (buf, "date") && strstr (buf, "dat")) - { - fix_str = str_replace (fix_str, "dat", "date"); - } - else if (!strstr (buf, "timestamp") && strstr (buf, "timestam")) - { - fix_str = str_replace (fix_str, "timestam", "timestamp"); - } - else if (!strstr (buf, "time") && strstr (buf, "tim")) - { - fix_str = str_replace (fix_str, "tim", "time"); - } - if (!strstr (buf, "monetary") && strstr (buf, "monetar")) - { - fix_str = str_replace (fix_str, "monetar", "monetary"); - } - if (!strstr (buf, "integer") && strstr (buf, "intege")) - { - fix_str = str_replace (fix_str, "intege", "integer"); - } - if (!strstr (buf, "double") && strstr (buf, "doubl")) - { - fix_str = str_replace (fix_str, "doubl", "double"); - } - if (!strstr (buf, "smallint") && strstr (buf, "smallin")) - { - fix_str = str_replace (fix_str, "smallin", "smallint"); - } - if (!strstr (buf, "string") && strstr (buf, "strin")) - { - fix_str = str_replace (fix_str, "strin", "string"); - } - if (!strstr (buf, "bigint") && strstr (buf, "bigin")) - { - fix_str = str_replace (fix_str, "bigin", "bigint"); - } - - while (*p != 0) - { - if (*p == '(') - { - flag++; - } - if (*p == ')') - { - flag--; - } - p++; - } - if (flag > 0) - { - fix_str.append (")"); - } - return fix_str; -} - -int -_get_attribute_type (int con_id, string db_name, string class_name, - Json::Value &attribute, list < string > &result_list) -{ - string schema; - char buf[256]; - T_CCI_ERROR err_buf; - string st_default = - attribute["default"].asString () == - "" ? "" : " DEFAULT '" + attribute["default"].asString () + "'"; - - schema += "\"" + attribute["name"].asString () + "\" "; - - /*cci_get_attr_type_str has bug, so before fix ,we use _fix_cci_get_attr_type_str */ - cci_get_attr_type_str (con_id, (char *) class_name.c_str (), - (char *) attribute["name"].asString ().c_str (), buf, - 256, &err_buf); - /* schema += buf; */ - schema += _fix_cci_get_attr_type_str (buf); - schema += st_default; - if (attribute["is_auto_inc"].asInt ()) - { - schema += _get_auto_increment (); - } - - if (attribute["is_not_null"].asInt ()) - { - schema += " NOT NULL"; - } - - if (!attribute["is_primary_key"].asInt ()) - { - if (attribute["is_unique_key"].asInt ()) - { - schema += " UNIQUE"; - } - } - attribute["type_str"] = buf; - - result_list.push_back (schema); - - return 0; -} - -int -_get_class_primary_key (string &pk, int has_pk, Json::Value &attribute) -{ - if (!attribute["is_primary_key"].asInt ()) - { - return 0; - } - - if (has_pk) - { - pk += ","; - } - pk += "\"" + attribute["name"].asString () + "\""; - return 1; -} - -int -_get_class_constraint (int con_id, string class_name, Json::Value &result) -{ - int cci_request = 0, cci_retval, cci_ind; - T_CCI_ERROR cci_error; - UNI_CCI_A_TYPE cci_value; - Json::Value constraint; - string index_name; - - if ((cci_request = cci_schema_info (con_id, CCI_SCH_CONSTRAINT, - (char *) class_name.c_str (), NULL, 0, - &cci_error)) < 0) - { - return -1; - } - - while (1) - { - cci_retval = cci_cursor (cci_request, 1, CCI_CURSOR_CURRENT, &cci_error); - if (cci_retval < 0) - { - break; - } - - if ((cci_retval = cci_fetch (cci_request, &cci_error)) < 0) - { - break; - } - - constraint.clear (); - /* type */ - if ((cci_retval = cci_get_data (cci_request, 1, CCI_A_TYPE_INT, &cci_value, &cci_ind)) < 0) - { - break; - } - constraint["type"] = cci_value.i; - - /* asc_or_desc */ - if ((cci_retval = cci_get_data (cci_request, 8, CCI_A_TYPE_STR, &cci_value, &cci_ind)) < 0) - { - break; - } - constraint["asc_or_desc"] = cci_value.str; - - /* index name */ - if ((cci_retval = cci_get_data (cci_request, 2, CCI_A_TYPE_STR, &cci_value, &cci_ind)) < 0) - { - break; - } - index_name = cci_value.str; - constraint["index_name"] = cci_value.str; - - /* column name */ - if ((cci_retval = cci_get_data (cci_request, 3, CCI_A_TYPE_STR, &cci_value, &cci_ind)) < 0) - { - break; - } - constraint["attr_name"] = cci_value.str; - - /* num pages */ - if ((cci_retval = cci_get_data (cci_request, 4, CCI_A_TYPE_INT, &cci_value, &cci_ind)) < 0) - { - break; - } - constraint["num_pages"] = cci_value.i; - - /* num keys */ - if ((cci_retval = cci_get_data (cci_request, 5, CCI_A_TYPE_INT, &cci_value, &cci_ind)) < 0) - { - break; - } - constraint["num_keys"] = cci_value.i; - - /* primary key */ - if ((cci_retval = cci_get_data (cci_request, 6, CCI_A_TYPE_INT, &cci_value, &cci_ind)) < 0) - { - break; - } - constraint["primary_key"] = cci_value.i; - - /* key order */ - if ((cci_retval = cci_get_data (cci_request, 7, CCI_A_TYPE_INT, &cci_value, &cci_ind)) < 0) - { - break; - } - constraint["key_order"] = cci_value.i; - - result[index_name].append (constraint); - } - cci_close_req_handle (cci_request); - return 0; -} - -int -_get_class_foreign_key (int con_id, string class_name, Json::Value &result) -{ - int cci_request = 0, cci_retval, cci_ind; - T_CCI_ERROR cci_error; - UNI_CCI_A_TYPE cci_value; - Json::Value constraint; - string fk_name; - if ((cci_request = - cci_schema_info (con_id, CCI_SCH_IMPORTED_KEYS, (char *) class_name.c_str (), NULL, 0, &cci_error)) < 0) - { - return -1; - } - - while (1) - { - cci_retval = cci_cursor (cci_request, 1, CCI_CURSOR_CURRENT, &cci_error); - if (cci_retval < 0) - { - break; - } - - if ((cci_retval = cci_fetch (cci_request, &cci_error)) < 0) - { - break; - } - - constraint.clear (); - - /* pk class name */ - if ((cci_retval = cci_get_data (cci_request, 1, CCI_A_TYPE_STR, &cci_value, &cci_ind)) < 0) - { - break; - } - constraint["pk_table_name"] = cci_value.str; - - /* pk column name */ - if ((cci_retval = cci_get_data (cci_request, 2, CCI_A_TYPE_STR, &cci_value, &cci_ind)) < 0) - { - break; - } - constraint["pk_column_name"] = cci_value.str; - - /* fk class name */ - if ((cci_retval = cci_get_data (cci_request, 3, CCI_A_TYPE_STR, &cci_value, &cci_ind)) < 0) - { - break; - } - constraint["fk_table_name"] = cci_value.str; - - /* fk column name */ - if ((cci_retval = cci_get_data (cci_request, 4, CCI_A_TYPE_STR, &cci_value, &cci_ind)) < 0) - { - break; - } - constraint["fk_column_name"] = cci_value.str; - - /* key sequence number */ - if ((cci_retval = cci_get_data (cci_request, 5, CCI_A_TYPE_INT, &cci_value, &cci_ind)) < 0) - { - break; - } - constraint["key_seq"] = cci_value.i; - - /* update rule */ - if ((cci_retval = cci_get_data (cci_request, 6, CCI_A_TYPE_INT, &cci_value, &cci_ind)) < 0) - { - break; - } - constraint["update_action"] = cci_value.i; - - /* delete rule */ - if ((cci_retval = cci_get_data (cci_request, 7, CCI_A_TYPE_INT, &cci_value, &cci_ind)) < 0) - { - break; - } - constraint["delete_action"] = cci_value.i; - - /* foreign key name */ - if ((cci_retval = cci_get_data (cci_request, 8, CCI_A_TYPE_STR, &cci_value, &cci_ind)) < 0) - { - break; - } - fk_name = cci_value.str; - constraint["fk_name"] = cci_value.str; - - /* primary key name */ - if ((cci_retval = cci_get_data (cci_request, 9, CCI_A_TYPE_STR, &cci_value, &cci_ind)) < 0) - { - break; - } - constraint["fk_name"] = cci_value.str; - - result[fk_name].append (constraint); - } - cci_close_req_handle (cci_request); - return 0; -} - -string -_get_action_type_str (int action) -{ - switch (action) - { - case 0: - return "CASCADE"; - case 1: - return "RESTRICT"; - case 2: - return "NO ACTION"; - case 3: - return "SET NULL"; - default: - break; - } - return ""; -} - -string -_get_index_type_str (int type) -{ - switch (type) - { - case 0: - return "UNIQUE INDEX"; - case 1: - return "INDEX"; - case 2: - return "REVERSE UNIQUE INDEX"; - case 3: - return "REVERSE INDEX"; - default: - break; - } - return ""; -} - -int -_build_foreign_key_str (Json::Value &f_key, list < string > &schema) -{ - int i = 0, size, on_delete = -1, on_update = -1; - string f_key_str = ""; - string fk_col_name, pk_col_name, pk_tab_name; - Json::Value::Members members (f_key.getMemberNames ()); - - for (Json::Value::Members::iterator it = members.begin (); - it != members.end (); ++it) - { - size = f_key[*it].size (); - fk_col_name = ""; - pk_col_name = ""; - for (i = 0; i < size; i++) - { - fk_col_name += - "\"" + f_key[*it][i]["fk_column_name"].asString () + "\""; - pk_col_name += - "\"" + f_key[*it][i]["pk_column_name"].asString () + "\""; - pk_tab_name = - "\"" + f_key[*it][i]["pk_table_name"].asString () + "\""; - on_delete = f_key[*it][i]["delete_action"].asInt (); - on_update = f_key[*it][i]["update_action"].asInt (); - if (i != (size - 1)) - { - fk_col_name += ","; - pk_col_name += ","; - } - } - f_key_str = "FOREIGN KEY (" + fk_col_name + ") REFERENCES " - + pk_tab_name + "(" + pk_col_name + ") ON DELETE " - + _get_action_type_str (on_delete) + " ON UPDATE " - + _get_action_type_str (on_update); - - schema.push_back (f_key_str); - } - return 0; -} - - -int -_build_index_str (Json::Value &index, string class_name, - list < string > &schema) -{ - int i = 0, size, type = 0; - string index_str = "", asc = ""; - string attr_name, pk_col_name, pk_tab_name; - Json::Value::Members members (index.getMemberNames ()); - - for (Json::Value::Members::iterator it = members.begin (); - it != members.end (); ++it) - { - size = index[*it].size (); - attr_name = ""; - for (i = 0; i < size; i++) - { - attr_name += "\"" + index[*it][i]["attr_name"].asString () + "\""; - asc = index[*it][i]["asc_or_desc"].asString (); - type = index[*it][i]["type"].asInt (); - - if (asc == "D") - { - attr_name += " DESC"; - } - - if (i != (size - 1)) - { - attr_name += ","; - } - } - - /* exclude ASC UNIQUE */ - if (type == 0 && asc == "A") - { - continue; - } - - index_str = - "CREATE " + _get_index_type_str (type) + " ON \"" + class_name + - "\"(" + attr_name + ");"; - - schema.push_back (index_str); - } - return 0; -} - -string -_dump_constraint_list (list < string > &schema_list, const string quote = ",") -{ - list < string >::iterator itor; - string schema = ""; - int flag = 0; - for (itor = schema_list.begin (); itor != schema_list.end (); - itor++, flag++) - { - if (flag) - { - schema += quote + "\n"; - } - schema += *itor; - } - schema += "\n"; - return schema; -} - -int -_export_class_schema (int con_id, string db_name, string class_name, - Json::Value &result, string export_path) -{ - int i, has_primary_key = 0; - int attr_size = result["attribute"].size (); - Json::Value fkey, index; - string schema = "CREATE TABLE \"" + class_name + "\" (\n"; - string pk = "CONSTRAINT PRIMARY KEY("; - list < string > schema_list, index_list; - - for (i = 0; i < attr_size; i++) - { - _get_attribute_type (con_id, db_name, class_name, result["attribute"][i], schema_list); - } - - for (i = 0; i < attr_size; i++) - { - has_primary_key += _get_class_primary_key (pk, has_primary_key, result["attribute"][i]); - } - - if (has_primary_key) - { - schema_list.push_back (pk + ")"); - } - - if (_get_class_foreign_key (con_id, class_name, fkey) == 0) - { - _build_foreign_key_str (fkey, schema_list); - } - - schema += _dump_constraint_list (schema_list) + ");\n"; - - if (_get_class_constraint (con_id, class_name, index) == 0) - { - _build_index_str (index, class_name, index_list); - } - - schema += _dump_constraint_list (index_list, "") + "\n"; - - return _saveto (export_path, schema, "a+"); -} - -string -_quota_mark (string &col) -{ - size_t it, size = col.size (); - string result; - for (it = 0; it != size; it++) - { - if (col[it] == '\'') - { - result.append (1, '\''); - } - - result.append (1, col[it]); - } - - return result; -} - -int -_export_class_object_sql (string class_name, Json::Value &result, - string export_path) -{ - unsigned int i, j; - string header = "insert into \"" + class_name + "\" "; - string values, col, type_str, prefix; - header = header + " values "; - for (i = 0; i < result["values"].size (); i++) - { - values = "("; - for (j = 0; j < result["values"][i].size (); j++) - { - type_str = result["attribute"][j]["type_str"].asString (); - if (type_str == "date") - { - prefix = "DATE"; - } - else - { - prefix = ""; - } - - col = result["values"][i][j].asString (); - - values += prefix + "'" + _quota_mark (col) + "'"; - if (j != (result["values"][i].size () - 1)) - { - values += ", "; - } - } - values += ");\n"; - _saveto (export_path, header + values, "a+"); - } - return 0; -} - -int -_export_class_object_csv (string class_name, Json::Value &result, - string export_path) -{ - unsigned int i, j; - string values, col; - - for (i = 0; i < result["values"].size (); i++) - { - values = ""; - for (j = 0; j < result["values"][i].size (); j++) - { - col = result["values"][i][j].asString (); - values += "\"" + _quota_mark (col) + "\""; - if (j != (result["values"][i].size () - 1)) - { - values += ","; - } - } - values += "\n"; - _saveto (export_path, values, "a+"); - } - return 0; -} - -typedef enum -{ - DUMP_TYPE_SQL = 0, - DUMP_TYPE_CSV -} E_DUMP_TYPE; - -typedef enum -{ - DUMP_FLAG_DATA = 1, - DUMP_FLAG_SCHEMA = 2, - DUMP_FLAG_DATA_SCHEMA = 3 -} E_DUMP_FLAG; - -void -_export_class (int con_id, string db_name, string class_name, - string export_path, int export_type, int export_flag, - Json::Value &result) -{ - switch (export_type) - { - case DUMP_TYPE_SQL: - if (export_flag & DUMP_FLAG_SCHEMA) - { - _export_class_schema (con_id, db_name, class_name, result, export_path); - } - if (export_flag & DUMP_FLAG_DATA) - { - _export_class_object_sql (class_name, result, export_path); - } - break; - case DUMP_TYPE_CSV: - _export_class_object_csv (class_name, result, export_path); - break; - default: - break; - } -} - -static bool -_get_export_path (string &export_path, string &export_filename, - int export_type, const string &db_name) -{ - time_t time_now; - struct tm *tm_now = NULL; - char file_name_dt[PATH_MAX]; - - file_name_dt[0] = '\0'; - - export_filename = ""; - export_path = string (sco.szCWMPath) + "/files/"; - if (access ((char *) export_path.c_str (), F_OK | R_OK | W_OK | X_OK) < 0) - { - return false; - } - - time_now = time (NULL); - if (time_now == -1) - { - return false; - } - -#ifndef WINDOWS - tm_now = new struct tm (); - if (localtime_r (&time_now, tm_now) == NULL) - { - delete tm_now; - tm_now = NULL; - return false; - } -#else - tm_now = localtime (&time_now); - if (tm_now == NULL) - { - return false; - } -#endif - - if (strftime (file_name_dt, PATH_MAX, "_%Y%m%d_%H%M%S", tm_now) == 0) - { -#ifndef WINDOWS - delete tm_now; -#endif - tm_now = NULL; - return false; - } - - bool success = true; - switch (export_type) - { - case DUMP_TYPE_SQL: - export_filename = db_name + file_name_dt + SQL_FILE_SUFFIX; - break; - - case DUMP_TYPE_CSV: - export_filename = db_name + file_name_dt + CSV_FILE_SUFFIX; - break; - - default: - export_filename = ""; - export_path = ""; - success = false; - break; - } - -#ifndef WINDOWS - delete tm_now; -#endif - tm_now = NULL; - - if (success) - { - export_path += export_filename; - } - return success; -} - -int -http_arniadb_exportdb (Json::Value &request, Json::Value &response) -{ - int con_handle, port, export_size, export_type, export_flag, res; - unsigned int i; - int time_out; - string ip, db_name, db_user, dbpasswd; - string export_path, export_filename, stmt, classname; - Json::Value result; - T_CCI_ERROR error; - - ip = request.get ("bip", "localhost").asString (); - port = request.get ("bport", sco.iCMS_port).asInt (); - export_size = request.get ("export_size", 0).asInt (); - export_type = request.get ("export_type", DUMP_TYPE_SQL).asInt (); - export_flag = request.get ("export_flag", DUMP_FLAG_DATA_SCHEMA).asInt (); - time_out = request.get ("time_out", 120).asInt (); - - JSON_FIND_V (request, "dbname", - build_common_header (response, ERR_PARAM_MISSING, "dbname")); - db_name = request["dbname"].asString (); - - JSON_FIND_V (request, "dbid", - build_common_header (response, ERR_PARAM_MISSING, "dbid")); - db_user = request["dbid"].asString (); - - JSON_FIND_V (request, "dbpasswd", - build_common_header (response, ERR_PARAM_MISSING, "dbpasswd")); - dbpasswd = request["dbpasswd"].asString (); - - if (!_get_export_path (export_path, export_filename, export_type, db_name)) - { - return build_common_header (response, ERR_WITH_MSG, "Can not generate the export file name."); - } - - con_handle = - cci_connect ((char *) ip.c_str (), port, (char *) db_name.c_str (), - (char *) db_user.c_str (), (char *) dbpasswd.c_str ()); - if (con_handle < 0) - { - cci_get_err_msg (con_handle, error.err_msg, 1024); - return build_common_header (response, con_handle, error.err_msg); - } - - if (Json::Value::null != request["charset"]) - { - cci_set_charset (con_handle, (char *) request["charset"].asString ().c_str ()); - } - - _saveto (export_path, "", "w"); - JSON_FIND_V (request, "class", - build_common_header (response, ERR_PARAM_MISSING, "stmt")); - for (i = 0; i < request["class"].size (); i++) - { - result.clear (); - classname = request["class"][i].asString (); - stmt = "select * from \"" + classname + "\""; - res = _execute_stmt (con_handle, stmt.c_str (), export_size, 1, 0, result, time_out); - if (res < 0) - { - result["class"] = classname; - response["result"].append (result); - continue; - } - _export_class (con_handle, db_name, request["class"][i].asString (), - export_path, export_type, export_flag, result); - } - - cci_disconnect (con_handle, &error); - build_common_header (response, ERR_NO_ERROR, "none"); - response["export_filename"] = export_filename; - - return ERR_NO_ERROR; -} - -int -_import_class_sql (Json::Value &request, Json::Value &response) -{ - string ip, db_name, db_user, dbpasswd; - string import_filename; - string import_path; - string error_continue_option = "y"; - T_ASQL_RESULT *asql_result; - T_ARNIADB_MODE mode; - - JSON_FIND_V (request, "dbname", - build_common_header (response, ERR_PARAM_MISSING, "dbname")); - db_name = request["dbname"].asString (); - - JSON_FIND_V (request, "dbid", - build_common_header (response, ERR_PARAM_MISSING, "dbid")); - db_user = request["dbid"].asString (); - - JSON_FIND_V (request, "dbpasswd", - build_common_header (response, ERR_PARAM_MISSING, "dbpasswd")); - dbpasswd = request["dbpasswd"].asString (); - - JSON_FIND_V (request, "import_filename", - build_common_header (response, ERR_PARAM_MISSING, - "Parameter(import_filename) missing in the request.")); - - import_filename = request["import_filename"].asString (); - import_path = string (sco.dbmt_tmp_dir) + "/" + import_filename; - - mode = (uDatabaseMode ((char *) db_name.c_str (), NULL) == - DB_SERVICE_MODE_NONE ? ARNIADB_MODE_SA : ARNIADB_MODE_CS); - asql_result = - cmd_asql ((char *) db_name.c_str (), (char *) db_user.c_str (), - (char *) dbpasswd.c_str (), mode, (char *) import_path.c_str (), - NULL, (char *) error_continue_option.c_str ()); - if (asql_result == NULL) - { - return build_common_header (response, ERR_WITH_MSG, - "Error occur when execurating asql."); - } - else if (strlen (asql_result->err_msg) != 0) - { - build_common_header (response, ERR_WITH_MSG, asql_result->err_msg); - free (asql_result); - return ERR_WITH_MSG; - } - free (asql_result); - return build_common_header (response, ERR_NO_ERROR, "none"); -} - -char * -_char_replace (char *str, char src, char dst) -{ - char *p = str; - while (*p != 0) - { - if (*p == src) - { - *p = dst; - } - p++; - } - - return str; -} - -string -_build_with_double_quotes (char *str, const char delimiter) -{ - char *pos = str; - char *begin = NULL, *end = NULL; - int quotes = 0; - string value; - while (*pos != 0) - { - if (*pos == '"') - { - if (quotes++) - { - end = pos; - } - else - { - begin = pos; - } - } - if (*pos == delimiter && 0 == (quotes % 2)) - { - if (begin) - { - *begin = '\''; - } - if (end) - { - *end = '\''; - } - *pos = 0; - value += begin; - value += ","; - quotes = 0; - } - pos++; - } - if (begin) - { - *begin = '\''; - } - if (end) - { - *end = '\''; - } - value += begin; - return value; -} - -string -_build_without_quotes (char *str, const char delimiter) -{ - char *pos = str; - char *begin = str; - string value; - while ((pos = strchr (begin, delimiter)) != NULL) - { - *pos = 0; - value += "'"; - value += begin; - value += "',"; - begin = pos + 1; - } - value += "'"; - value += begin; - value += "'"; - return value; -} - -string -_build_quotes (char *str, const char delimiter) -{ - if (str == NULL) - { - return ""; - } - if (*str == '"') - { - return _build_with_double_quotes (str, delimiter); - } - return _build_without_quotes (str, delimiter); -} - -int -_import_class_csv (Json::Value &request, Json::Value &response) -{ - string ip, db_name, db_user, dbpasswd, stmt, classname; - string import_path; - string import_filename; - FILE *fp; - char buf[1024]; - int con_handle, port, time_out, success = 0, fail = 0; - Json::Value result; - T_CCI_ERROR error; - - ip = request.get ("bip", "localhost").asString (); - port = request.get ("bport", sco.iCMS_port).asInt (); - time_out = request.get ("time_out", 120).asInt (); - - JSON_FIND_V (request, "dbname", - build_common_header (response, ERR_PARAM_MISSING, "dbname")); - db_name = request["dbname"].asString (); - - JSON_FIND_V (request, "dbid", - build_common_header (response, ERR_PARAM_MISSING, "dbid")); - db_user = request["dbid"].asString (); - - JSON_FIND_V (request, "dbpasswd", - build_common_header (response, ERR_PARAM_MISSING, "dbpasswd")); - dbpasswd = request["dbpasswd"].asString (); - - JSON_FIND_V (request, "classname", - build_common_header (response, ERR_PARAM_MISSING, "classname")); - classname = request["classname"].asString (); - - JSON_FIND_V (request, "import_filename", - build_common_header (response, ERR_PARAM_MISSING, - "Parameter(import_filename) missing in the request")); - import_filename = request["import_filename"].asString (); - import_path = string (sco.dbmt_tmp_dir) + "/" + import_filename; - - fp = fopen (import_path.c_str (), "r"); - if (NULL == fp) - { - return build_common_header (response, ERR_GENERAL_ERROR, "failed to open import file!"); - } - - con_handle = - cci_connect ((char *) ip.c_str (), port, (char *) db_name.c_str (), - (char *) db_user.c_str (), (char *) dbpasswd.c_str ()); - if (con_handle < 0) - { - cci_get_err_msg (con_handle, error.err_msg, 1024); - fclose (fp); - return build_common_header (response, con_handle, error.err_msg); - } - - while (fgets (buf, 1024, fp)) - { - ut_trim (buf); - stmt = - "insert into \"" + classname + "\" values (" + _build_quotes (buf, ',') + string (")"); - _execute_stmt (con_handle, stmt.c_str (), 0, 1, 0, result, time_out); - if (result["status"].asInt () != CCI_ER_NO_ERROR) - { - response["result"].append (stmt + " error"); - fail++; - } - else - { - success++; - } - - } - - fclose (fp); - response["fail_cnt"] = fail; - response["success_cnt"] = success; - cci_end_tran (con_handle, CCI_TRAN_COMMIT, &error); - cci_disconnect (con_handle, &error); - build_common_header (response, ERR_NO_ERROR, "none"); - return ERR_NO_ERROR; -} - -int -http_arniadb_importdb (Json::Value &request, Json::Value &response) -{ - int import_type, result = ERR_NO_ERROR; - string ip, db_name, db_user, dbpasswd; - string import_path, stmt; - - import_type = request.get ("import_type", DUMP_TYPE_SQL).asInt (); - switch (import_type) - { - case DUMP_TYPE_SQL: - result = _import_class_sql (request, response); - break; - case DUMP_TYPE_CSV: - result = _import_class_csv (request, response); - break; - default: - break; - } - return result; -} - -int -http_arniadb_sql (Json::Value &request, Json::Value &response) -{ - int con_handle, port, fetch_size, fetch_offset, dump_plan, time_out; - unsigned int i; - int return_err = 0, err_continue = 0; - int autocommit = 1; - string ip, db_name, db_user, dbpasswd; - Json::Value result; - T_CCI_ERROR error; - - ip = request.get ("bip", "localhost").asString (); - port = request.get ("bport", sco.iCMS_port).asInt (); - err_continue = request.get ("error_continue", 0).asInt (); - fetch_size = request.get ("fetch_size", 5000).asInt (); - fetch_offset = request.get ("fetch_offset", 1).asInt (); - dump_plan = request.get ("dump_plan", 0).asInt (); - time_out = request.get ("time_out", 120).asInt (); - autocommit = request.get ("autocommit", 1).asInt (); - - JSON_FIND_V (request, "dbname", - build_common_header (response, ERR_PARAM_MISSING, "dbname")); - db_name = request["dbname"].asString (); - - JSON_FIND_V (request, "dbid", - build_common_header (response, ERR_PARAM_MISSING, "dbid")); - db_user = request["dbid"].asString (); - - JSON_FIND_V (request, "dbpasswd", - build_common_header (response, ERR_PARAM_MISSING, "dbpasswd")); - dbpasswd = request["dbpasswd"].asString (); - - con_handle = - cci_connect ((char *) ip.c_str (), port, (char *) db_name.c_str (), - (char *) db_user.c_str (), (char *) dbpasswd.c_str ()); - if (con_handle < 0) - { - cci_get_err_msg (con_handle, error.err_msg, 1024); - return build_common_header (response, con_handle, error.err_msg); - } - - cci_set_autocommit (con_handle, (CCI_AUTOCOMMIT_MODE) autocommit); - - if (Json::Value::null != request["charset"]) - { - cci_set_charset (con_handle, (char *) request["charset"].asString ().c_str ()); - } - - JSON_FIND_V (request, "stmt", - build_common_header (response, ERR_PARAM_MISSING, "stmt")); - for (i = 0; i < request["stmt"].size (); i++) - { - result.clear (); - - if (_execute_stmt (con_handle, request["stmt"][i].asString ().c_str (), fetch_size, - fetch_offset, dump_plan, result, time_out) < 0 - && 0 == err_continue) - { - return_err = 1; - response["result"].append (result); - break; - } - - response["result"].append (result); - } - - cci_end_tran (con_handle, CCI_TRAN_COMMIT, &error); - cci_disconnect (con_handle, &error); - build_common_header (response, ERR_NO_ERROR, "none"); - return ERR_NO_ERROR; -} - -int -arn_cci_request_handler (Json::Value &request, Json::Value &response) -{ - int res; - int elapsed_msec = 0; - struct timeval task_begin, task_end; - string task_name; - T_HTTP_TASK_FUNC task_func = NULL; - - JSON_FIND_V (request, "task", - build_common_header (response, ERR_PARAM_MISSING, "task")); - task_name = request["task"].asString (); - - /* record the start time of running arn_manager task. */ - gettimeofday (&task_begin, NULL); - - get_cci_task_info (task_name.c_str (), &task_func); - if (task_func) - { - try - { - res = (*task_func) (request, response); - } - catch (exception &e) - { - res = build_common_header (response, ERR_REQUEST_FORMAT, e.what ()); - } - } - else - { - res = build_common_header (response, ERR_UNDEFINED_TASK, task_name.c_str ()); - } - - /* record the end time of running arn_manager task. */ - gettimeofday (&task_end, NULL); - - /* caculate the running time of arn_manager task. */ - _ut_timeval_diff (&task_begin, &task_end, &elapsed_msec); - response["__EXEC_TIME"] = elapsed_msec; - - return res; -} diff --git a/server/src/cm_cci_interface.h b/server/src/cm_cci_interface.h deleted file mode 100644 index 5bb3a6d..0000000 --- a/server/src/cm_cci_interface.h +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. - * - * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - -#ifndef __CM_CCI_H__ -#define __CM_CII_H__ -#include - -typedef int (*T_HTTP_TASK_FUNC) (Json::Value &request, - Json::Value &response); - -typedef struct -{ - const char *task_str; - int task_code; - T_HTTP_TASK_FUNC task_func; -} T_HTTP_TASK_INFO; - -typedef union tagUNI_CCI_A_TYPE -{ - char *str; - int i; - short s; - float f; - double d; -} UNI_CCI_A_TYPE; - -#define JSON_FIND_V(root, key, err) \ - if (Json::Value::null == root[key]) \ - return err; - -int http_arniadb_exportdb (Json::Value &request, Json::Value &response); -int http_arniadb_importdb (Json::Value &request, Json::Value &response); -int http_arniadb_sql (Json::Value &request, Json::Value &response); -int get_cci_task_info (const char *task, T_HTTP_TASK_FUNC *task_func); -int arn_cci_request_handler (Json::Value &request, Json::Value &response); - -#endif diff --git a/server/src/cm_cmd.cpp b/server/src/cm_cmd.cpp deleted file mode 100644 index f7e99ed..0000000 --- a/server/src/cm_cmd.cpp +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. - * - * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/* - * cm_cmd.cpp - - */ - -#include - -#if defined(WINDOWS) -#include -#include -#include -#else -#include -#include -#endif - -#include "cm_config.h" -#include "cm_cmd_task.h" -#include "cm_cmd_util.h" - -static void _print_help (void); - -int -main (int argc, char *argv[]) -{ - int retval = 0; - - if (argc < 2) - { - retval = 0; - goto print_help_msg; - } - - sys_config_init (); - if (uReadEnvVariables (argv[0]) < 0) - { - return -1; - } - - retval = run_task (argv[1], (argc - 1), (const char **) (&argv[1])); - - if (retval == E_CMD_NOT_EXIST) - { - retval = -1; - goto print_help_msg; - } - - return 0; - -print_help_msg: - _print_help (); - return retval; -} - -static void -_print_help (void) -{ - const char *title_pattern = - "cmserver utility, version R%s\nusage: %s [args]\n"; - printf (title_pattern, CM_ADMIN_VERSION, CM_ADMIN_NAME); - print_cmd (); - - return; -} diff --git a/server/src/cm_cmd_exec.cpp b/server/src/cm_cmd_exec.cpp deleted file mode 100644 index 8d344ce..0000000 --- a/server/src/cm_cmd_exec.cpp +++ /dev/null @@ -1,1406 +0,0 @@ -/* - * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. - * - * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/* - * cm_cmd_exec.cpp - - */ - -#include -#include -#include -#include -#include - -#if defined(WINDOWS) -#include -#else -#include -#include -#endif - -#include "cm_config.h" -#include "cm_cmd_exec.h" -#include "cm_server_util.h" -#include "cm_stat.h" -#include "cm_autojob.h" -#include "cm_log.h" - -#ifdef _DEBUG_ -#include "deb.h" -#endif - -#define new_servstat_result() (T_SERVER_STATUS_RESULT*) new_cmd_result() -#define new_asql_result() (T_ASQL_RESULT*) new_cmd_result() - -static T_CMD_RESULT *new_cmd_result (void); -static const char *get_arniadb_mode_opt (T_ARNIADB_MODE mode); -static void read_server_status_output (T_SERVER_STATUS_RESULT *res, - char *out_file); -static void read_spacedb_output (GeneralSpacedbResult *res, char *out_file); - -static int read_start_server_output (char *stdout_log_file, - char *stderr_log_file, - char *_dbmt_error); - -static int _size_to_byte_by_unit (double orgin_num, char unit); - -char * -arniadb_cmd_name (char *buf) -{ - buf[0] = '\0'; -#if !defined (DO_NOT_USE_ARNIADBENV) - sprintf (buf, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ARNIADB); -#else - sprintf (buf, "%s/%s", ARNIADB_BINDIR, UTIL_ARNIADB); -#endif - return buf; -} - -T_ASQL_RESULT * -cmd_asql (char *dbname, char *uid, char *passwd, T_ARNIADB_MODE mode, - char *infile, char *command, char *error_continue) -{ - char arniadb_err_file[PATH_MAX]; - char out_file[512]; - T_ASQL_RESULT *res; - char cmd_name[ARNIADB_CMD_NAME_LEN]; - const char *argv[15]; - int argc = 0; - - cmd_name[0] = '\0'; - arniadb_err_file[0] = '\0'; -#if !defined (DO_NOT_USE_ARNIADBENV) - sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ASQL_NAME); -#else - sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_ASQL_NAME); -#endif - argv[argc++] = cmd_name; - argv[argc++] = get_arniadb_mode_opt (mode); - if (uid) - { - argv[argc++] = "--" ASQL_USER_L; - argv[argc++] = uid; - - if (passwd) - { - argv[argc++] = "--" ASQL_PASSWORD_L; - argv[argc++] = passwd; - } - } - if (infile) - { - argv[argc++] = "--" ASQL_INPUT_FILE_L; - argv[argc++] = infile; - } - else if (command) - { - argv[argc++] = "--" ASQL_COMMAND_L; - argv[argc++] = command; - } - else - { - return NULL; - } - - if (uStringEqualIgnoreCase (error_continue, "y")) - { - argv[argc++] = "--" ASQL_ERROR_CONTINUE_L; - } - - argv[argc++] = dbname; - argv[argc++] = NULL; - -#if !defined (DO_NOT_USE_ARNIADBENV) - sprintf (out_file, "%s/tmp/DBMT_util_003.%d", sco.szArniadb, - (int) getpid ()); -#else - sprintf (out_file, "%s/DBMT_util_003.%d", ARNIADB_TMPDIR, (int) getpid ()); -#endif - snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", - sco.dbmt_tmp_dir, "cmd_asql", getpid ()); - SET_TRANSACTION_NO_WAIT_MODE_ENV (); - - run_child (argv, 1, NULL, NULL, out_file, NULL); /* asql */ - - res = new_asql_result (); - if (res == NULL) - { - return NULL; - } - - read_error_file (out_file, res->err_msg, ERR_MSG_SIZE); - - unlink (out_file); - return res; -} - -void find_and_parse_arn_admin_version (int &major_version, int &minor_version) -{ - const char *argv[3]; - char tmpfile[PATH_MAX], strbuf[BUFFER_MAX_LEN]; - FILE *infile; - char cmd_name[ARNIADB_CMD_NAME_LEN]; - - arniadb_cmd_name (cmd_name); - snprintf (tmpfile, PATH_MAX - 1, "%s/arn_admin_version", sco.dbmt_tmp_dir); - argv[0] = cmd_name; - argv[1] = "--version"; - argv[2] = NULL; - - run_child (argv, 1, NULL, tmpfile, NULL, NULL); - if ((infile = fopen (tmpfile, "r")) != NULL) - { - if (!fgets (strbuf, sizeof (strbuf), infile) || ! fgets (strbuf, sizeof (strbuf), infile)) - { - LOG_ERROR ("Spacedb is skipped due to temporarily insufficient resources"); - major_version = minor_version = -1; - return; - } - char version[10]; - sscanf (strbuf, "%*s %s", version); - - char *p = strtok (version, "."); - major_version = atoi (p); - p = strtok (NULL, "."); - minor_version = atoi (p); - - fclose (infile); - unlink (tmpfile); - } - else - { - major_version = minor_version = -1; - } -} - -GeneralSpacedbResult * -cmd_spacedb (const char *dbname, T_ARNIADB_MODE mode) -{ - GeneralSpacedbResult *res = NULL; - int minor_version, major_version; - char out_file[PATH_MAX]; - char arniadb_err_file[PATH_MAX]; - char cmd_name[ARNIADB_CMD_NAME_LEN]; - char err_message[ERR_MSG_SIZE]; - const char *argv[10]; - int argc = 0; - arniadb_err_file[0] = '\0'; - - if (IS_INVALID_ARNIADB_VERS_MAJOR (arniadb_version_major)) - { - LOG_ERROR ("Invalid ARNIADB Engine Version: %d.%d", arniadb_version_major, arniadb_version_minor); - find_and_parse_arn_admin_version (major_version, minor_version); - arniadb_version_major = major_version; - arniadb_version_minor = minor_version; - } - - if (arniadb_version_major < 10 || (arniadb_version_minor == 10 && arniadb_version_minor == 0)) - { - res = new SpaceDbResultOldFormat(); - } - else - { - res = new SpaceDbResultNewFormat(); - } - - sprintf (out_file, "%s/DBMT_util_002.%d", sco.dbmt_tmp_dir, - (int) getpid ()); - arniadb_cmd_name (cmd_name); - argv[argc++] = cmd_name; - argv[argc++] = UTIL_OPTION_SPACEDB; - argv[argc++] = get_arniadb_mode_opt (mode); - argv[argc++] = "--" SPACE_SIZE_UNIT_L; - argv[argc++] = "PAGE"; - argv[argc++] = "--" SPACE_OUTPUT_FILE_L; - argv[argc++] = out_file; - argv[argc++] = dbname; - argv[argc++] = "-p"; - argv[argc++] = NULL; - - snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", - sco.dbmt_tmp_dir, "cmd_spacedb", getpid ()); - run_child (argv, 1, NULL, NULL, arniadb_err_file, NULL); /* spacedb */ - read_error_file (arniadb_err_file, err_message, ERR_MSG_SIZE); - res->set_err_msg (err_message); - read_spacedb_output (res, out_file); - if (access (arniadb_err_file, F_OK) == 0) - { - unlink (arniadb_err_file); - } - unlink (out_file); - return res; -} - - -int -cmd_start_server (char *dbname, char *err_buf, int err_buf_size) -{ - char stdout_log_file[512]; - char stderr_log_file[512]; - int pid; - int ret_val; - char cmd_name[ARNIADB_CMD_NAME_LEN]; - const char *argv[5]; - -#ifdef HPUX - char jvm_env_string[32]; -#endif - - cmd_start_master (); - sprintf (stdout_log_file, "%s/cmserverstart.%d.err", sco.dbmt_tmp_dir, - (int) getpid ()); - sprintf (stderr_log_file, "%s/cmserverstart2.%d.err", sco.dbmt_tmp_dir, - (int) getpid ()); - - - /* unset ARNIADB_ERROR_LOG environment variable, using default value */ -#if defined(WINDOWS) - _putenv ("ARNIADB_ERROR_LOG="); -#else - unsetenv ("ARNIADB_ERROR_LOG"); -#endif - - cmd_name[0] = '\0'; -#if !defined (DO_NOT_USE_ARNIADBENV) - sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ARNIADB); -#else - sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_ARNIADB); -#endif - - argv[0] = cmd_name; - argv[1] = PRINT_CMD_SERVER; - argv[2] = PRINT_CMD_START; - argv[3] = dbname; - argv[4] = NULL; - -#ifdef HPUX -#ifdef HPUX_IA64 - strcpy (jvm_env_string, "LD_PRELOAD=libjvm.so"); -#else /* pa-risc */ - strcpy (jvm_env_string, "LD_PRELOAD=libjvm.sl"); -#endif - putenv (jvm_env_string); -#endif - - pid = run_child (argv, 1, NULL, stdout_log_file, stderr_log_file, NULL); /* start server */ - -#ifdef HPUX - putenv ("LD_PRELOAD="); -#endif - - if (pid < 0) - { - if (err_buf) - { - sprintf (err_buf, "system error : %s %s %s %s", cmd_name, PRINT_CMD_SERVER, PRINT_CMD_START, dbname); - } - unlink (stdout_log_file); - unlink (stderr_log_file); - return -1; - } - - ret_val = - read_start_server_output (stdout_log_file, stderr_log_file, err_buf); - unlink (stdout_log_file); - unlink (stderr_log_file); - - return ret_val; -} - -int -cmd_stop_server (char *dbname, char *err_buf, int err_buf_size) -{ - char strbuf[1024]; - int t, timeout = 30, interval = 3; /* sec */ - char cmd_name[ARNIADB_CMD_NAME_LEN]; - const char *argv[5]; - - if (err_buf) - { - memset (err_buf, 0, err_buf_size); - } - - cmd_name[0] = '\0'; -#if !defined (DO_NOT_USE_ARNIADBENV) - sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ARNIADB); -#else - sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_ARNIADB); -#endif - - argv[0] = cmd_name; - argv[1] = PRINT_CMD_SERVER; - argv[2] = PRINT_CMD_STOP; - argv[3] = dbname; - argv[4] = NULL; - if (run_child (argv, 1, NULL, NULL, NULL, NULL) < 0) - { - /* stop_server */ - if (err_buf) - { - sprintf (strbuf, "Command returned error : %s %s %s %s", cmd_name, - PRINT_CMD_SERVER, PRINT_CMD_STOP, dbname); - strncpy (err_buf, strbuf, err_buf_size - 1); - } - return -1; - } - - for (t = timeout; t > 0; t -= interval) - { - SLEEP_MILISEC (interval, 0); - if (!uIsDatabaseActive (dbname)) - { - return 0; - } - } - if (err_buf) - { - sprintf (strbuf, "%s server hasn't shut down after %d seconds", dbname, timeout); - strncpy (err_buf, strbuf, err_buf_size - 1); - } - return -1; -} - -void -cmd_start_master (void) -{ - int pid; - char cmd_name[ARNIADB_CMD_NAME_LEN]; - const char *argv[2]; - - cmd_name[0] = '\0'; -#if !defined (DO_NOT_USE_ARNIADBENV) - sprintf (cmd_name, "%s/%s%s", sco.szArniadb, - ARNIADB_DIR_BIN, UTIL_MASTER_NAME); -#else - sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_MASTER_NAME); -#endif - argv[0] = cmd_name; - argv[1] = NULL; - - pid = run_child (argv, 0, NULL, NULL, NULL, NULL); /* arn_master */ - SLEEP_MILISEC (0, 500); -} - - -int -read_asql_error_file (char *err_file, char *err_buf, int err_buf_size) -{ - FILE *fp; - char buf[1024]; - int msg_size = 0; - - if (err_buf) - { - memset (err_buf, 0, err_buf_size); - } - - if (err_file == NULL || err_file[0] == '\0') - { - return 0; - } - - fp = fopen (err_file, "r"); - if (fp == NULL) - { - return 0; - } - - while (1) - { - memset (buf, 0, sizeof (buf)); - if (fgets (buf, sizeof (buf) - 1, fp) == NULL) - { - break; - } - - ut_trim (buf); - - if ((strncasecmp (buf, "ERROR", 5) == 0)) - { - if (err_buf != NULL) - { - snprintf (err_buf, err_buf_size - 1, "%s", buf + 6); - } - msg_size = (int) strlen (buf + 6); - break; - } - else if (strstr (buf, "*** ERROR") != NULL) - { - memset (buf, 0, sizeof (buf)); - if (fgets (buf, sizeof (buf) - 1, fp) == NULL) - { - break; - } - if (err_buf != NULL) - { - snprintf (err_buf, err_buf_size - 1, "%s", buf); - } - msg_size = (int) strlen (buf); - break; - } - } - - fclose (fp); - - return (msg_size > 0 ? -1 : 0); -} - -int -read_error_file (const char *err_file, char *err_buf, int err_buf_size) -{ - FILE *fp; - char buf[1024]; - int msg_size = 0; - char rm_prev_flag = 0; - char is_debug = 0; - size_t i; - - if (err_buf == NULL || err_file == NULL || err_file[0] == '\0' - || err_buf_size == 0) - { - return 0; - } - - memset (err_buf, 0, err_buf_size); - - fp = fopen (err_file, "r"); - if (fp == NULL) - { - return 0; - } - - while (1) - { - memset (buf, 0, sizeof (buf)); - if (fgets (buf, sizeof (buf) - 1, fp) == NULL) - { - break; - } - for (i = 0; i < sizeof (buf) - 2; i++) - { - if (buf[i] == '\0') - { - if (buf[i + 1] == '\0') - { - break; - } - - buf[i] = ' '; - } - } - ut_trim (buf); - if (buf[0] == '\0') - { - continue; - } - if (strncmp (buf, "---", 3) == 0 || - strncmp (buf, "***", 3) == 0 || - strncmp (buf, "<<<", 3) == 0 || strncmp (buf, "Time:", 5) == 0) - { - if (strstr (buf, "- DEBUG") != NULL) - { - is_debug = 1; - } - else - { - is_debug = 0; - rm_prev_flag = 1; - } - continue; - } - /* ignore all the debug information, until find new line start with "---"|"***"|"<<<"|"Time:". */ - if (is_debug != 0) - { - continue; - } - - if (rm_prev_flag != 0) - { - msg_size = 0; - } - strcat (buf, ""); - if ((err_buf_size - msg_size - 1) > 0) - { - strncpy (err_buf + msg_size, buf, err_buf_size - msg_size - 1); - } - else - { - break; - } - msg_size += (int) strlen (buf); - rm_prev_flag = 0; - } - err_buf[err_buf_size - 1] = '\0'; - fclose (fp); - return (msg_size > 0 ? -1 : 0); -} - -int -read_error_file2 (char *err_file, char *err_buf, int err_buf_size, - int *err_code) -{ - FILE *fp; - char buf[1024]; - int found = 0; - int success = 1; - - if (err_buf == NULL || err_file == NULL) - { - return 0; - } - - err_buf[0] = 0; - - fp = fopen (err_file, "r"); - if (fp == NULL) - { - *err_code = 0; - return 0; /* not found error file */ - } - - while (1) - { - char *p = NULL; - size_t len; - if (fgets (buf, sizeof (buf), fp) == NULL) - { - break; - } - - /* start with "ERROR: " */ - len = strlen (buf); - if (len > 7 && memcmp (buf, "ERROR: ", 7) == 0) - { - /* ignore a newline character if it exists */ - if (buf[len - 1] == '\n') - { - len--; - } - len -= 7; - - if (len >= (size_t) err_buf_size) - { - len = (size_t) err_buf_size - 1; - } - - memcpy (err_buf, buf + 7, len); - err_buf[len] = 0; - - success = 0; - continue; - } - - /* find "CODE = " */ - p = strstr (buf, "CODE = "); - if (p != NULL) - { - if (sscanf (p, "CODE = %d", err_code) != 1) - { - continue; - } - - success = 0; - found = 1; - - /* read error description */ - if (fgets (buf, sizeof (buf), fp) == NULL) - { - break; - } - - len = strlen (buf); - if (len > 0 && buf[len - 1] == '\n') - { - len--; - } - - if (len >= (size_t) err_buf_size) - { - len = (size_t) err_buf_size - 1; - } - - memcpy (err_buf, buf, len); - err_buf[len] = 0; - } - } - - fclose (fp); - - if (success != 0) - { - *err_code = 0; - return 0; - } - else if (found == 0) - { - *err_code = -1; - } - - return -1; -} - -static T_CMD_RESULT * -new_cmd_result (void) -{ - T_CMD_RESULT *res; - - res = (T_CMD_RESULT *) malloc (sizeof (T_CMD_RESULT)); - if (res == NULL) - { - return NULL; - } - memset (res, 0, sizeof (T_CMD_RESULT)); - return res; -} - -static const char * -get_arniadb_mode_opt (T_ARNIADB_MODE mode) -{ - if (mode == ARNIADB_MODE_SA) - { - return ("--" ASQL_SA_MODE_L); - } - - return ("--" ASQL_CS_MODE_L); -} - -static bool is_valid_database_description (char *str) -{ - if (strncmp (str, "PERMANENT", 9) != 0 && strncmp (str, "TEMPORARY", 9) != 0) - { - return false; - } - - return true; -} - -static bool is_valid_volume_description (char *str) -{ - if (strstr (str, "PERMANENT") == NULL && strstr (str, "TEMPORARY") == NULL) - { - return false; - } - - return true; -} - -static bool is_valid_file_description (char *str) -{ - if (strncmp (str, "INDEX", 5) != 0 && strncmp (str, "HEAP", 4) != 0 && - strncmp (str, "SYSTEM", 6) != 0 && strncmp (str, "TEMP", 4) != 0) - { - return false; - } - - return true; -} - -static void -read_spacedb_output (GeneralSpacedbResult *res, char *out_file) -{ - FILE *fp; - - fp = fopen (out_file, "r"); - if (fp == NULL) - { - return; - } - - res->read_spacedb_output (fp); -} - -static int -read_start_server_output (char *stdout_file, char *stderr_file, - char *_dbmt_error) -{ - FILE *fp, *fp2; - char buf[1024]; - char *strp; - int retval = 0; - - if (access (stdout_file, F_OK) == 0) - { - fp = fopen (stdout_file, "r"); - if (fp != NULL) - { - while (fgets (buf, sizeof (buf), fp) != NULL) - { - if (strncmp (buf, "++", 2) == 0) - { - if ((strp = strchr (buf, ':')) && strstr (strp, "fail")) - { - retval = -1; - break; - } - } - } - fclose (fp); - } - } - - if (access (stderr_file, F_OK) == 0) - { - fp2 = fopen (stderr_file, "r"); - if (fp2 != NULL) - { - int len = 0; - while (fgets (buf, sizeof (buf), fp2) != NULL) - { - ut_trim (buf); - len += (int) strlen (buf); - if (len < (DBMT_ERROR_MSG_SIZE - 1)) - { - strcpy (_dbmt_error, buf); - _dbmt_error += len; - } - else - { - strcpy_limit (_dbmt_error, buf, DBMT_ERROR_MSG_SIZE); - strcpy_limit (_dbmt_error + DBMT_ERROR_MSG_SIZE - 4, "...", 4); - break; - } - } - - if (len != 0 && retval != -1) - { - retval = 1; - } - fclose (fp2); - } - } - - return retval; -} - -static int -_size_to_byte_by_unit (double orgin_num, char unit) -{ - switch (unit) - { - case 'B': - case 'b': - break; - case 'K': - case 'k': - orgin_num *= BYTES_IN_K; - break; - case 'M': - case 'm': - orgin_num *= BYTES_IN_M; - break; - case 'G': - case 'g': - orgin_num *= BYTES_IN_G; - break; - default: - /* if none of the above occur, return -1 to indicate error. */ - orgin_num = -1; - break; - } - - return (int) (orgin_num); -} - -void SpaceDbResultNewFormat::add_volume (char *str_buf) -{ - char purpose[128], volume_name[PATH_MAX], type[32]; - struct stat statbuf; - - SpaceDbVolumeInfoNewFormat volume; - sscanf (str_buf, "%d %s %s DATA %d %d %d %s", &volume.volid, type, purpose, - &volume.used_size, - &volume.free_size, - &volume.total_size, - volume_name); - strcpy (volume.purpose, purpose); - strcpy (volume.type, type); - strcpy (volume.volume_name, volume_name); - - stat (volume_name, &statbuf); - volume.date = statbuf.st_mtime; - - volumes.push_back (volume); -} - -int SpaceDbResultOldFormat::get_volume_info (char *str_buf, SpaceDbVolumeInfoOldFormat &volume) -{ - int volid, total_page, free_page; - char purpose[COLUMN_VALUE_MAX_SIZE], vol_name[PATH_MAX]; - char *token = NULL, *p; - struct stat statbuf; - - volid = total_page = free_page = 0; - purpose[0] = vol_name[0] = '\0'; - - token = strtok (str_buf, " "); - if (token == NULL) - { - return FALSE; - } - volid = atoi (token); - - token = strtok (NULL, " "); - if (token == NULL) - { - return FALSE; - } - strcpy (purpose, token); - - if (strcmp (purpose, "GENERIC") != 0 && strcmp (purpose, "DATA") != 0 - && strcmp (purpose, "INDEX") != 0 && strcmp (purpose, "TEMP") != 0) - { - return FALSE; - } - - token = strtok (NULL, " "); - if (token == NULL) - { - return FALSE; - } - - if (strcmp (token, "TEMP") == 0) - { - if (strcmp (purpose, "TEMP") != 0) - { - return FALSE; - } - else - { - strcat (purpose, " "); - strcat (purpose, token); - } - - token = strtok (NULL, " "); - if (token == NULL) - { - return FALSE; - } - } - total_page = atoi (token); - - token = strtok (NULL, " "); - if (token == NULL) - { - return FALSE; - } - free_page = atoi (token); - - token = strtok (NULL, "\n"); - if (token == NULL) - { - return FALSE; - } - strcpy (vol_name, token + 1); - - volume.volid = volid; - volume.total_size = total_page; - volume.free_size = free_page; - strcpy (volume.purpose, purpose); - - stat (vol_name, &statbuf); - volume.date = statbuf.st_mtime; - -#if defined(WINDOWS) - unix_style_path (vol_name); -#endif - - p = strrchr (vol_name, '/'); - if (p == NULL) - { - volume.location[0] = '\0'; - volume.vol_name[0] = '\0'; - } - else - { - *p = '\0'; - snprintf (volume.location, sizeof (volume.location) - 1, "%s", vol_name); - snprintf (volume.vol_name, sizeof (volume.vol_name) - 1, "%s", p + 1); - *p = '/'; - } - - return TRUE; - -} - -void SpaceDbResultOldFormat::create_result (nvplist *res) -{ - nv_update_val_int (res, "pagesize", page_size); - nv_update_val_int (res, "logpagesize", log_page_size); - - for (int i = 0; i < volumes.size(); i++) - { - nv_add_nvp (res, "open", "spaceinfo"); - nv_add_nvp (res, "spacename", volumes[i].vol_name); - nv_add_nvp (res, "type", volumes[i].purpose); - nv_add_nvp (res, "location", volumes[i].location); - nv_add_nvp_int (res, "totalpage", volumes[i].total_size); - nv_add_nvp_int (res, "freepage", volumes[i].free_size); - ts_add_nvp_time (res, "date", volumes[i].date, "%04d%02d%02d", - NV_ADD_DATE); - nv_add_nvp (res, "close", "spaceinfo"); - } - - for (int i = 0; i < temporary_volumes.size(); i++) - { - nv_add_nvp (res, "open", "spaceinfo"); - nv_add_nvp (res, "spacename", temporary_volumes[i].vol_name); - nv_add_nvp (res, "type", temporary_volumes[i].purpose); - nv_add_nvp (res, "location", temporary_volumes[i].location); - nv_add_nvp_int (res, "totalpage", temporary_volumes[i].total_size); - nv_add_nvp_int (res, "freepage", temporary_volumes[i].free_size); - ts_add_nvp_time (res, "date", temporary_volumes[i].date, "%04d%02d%02d", - NV_ADD_DATE); - nv_add_nvp (res, "close", "spaceinfo"); - } -} - -void SpaceDbResultNewFormat::create_result (nvplist *res) -{ - nv_update_val_int (res, "pagesize", page_size); - nv_update_val_int (res, "logpagesize", log_page_size); - - for (int i = 0; i < DATABASE_DESCRIPTION_NUM_LINES; i++) - { - nv_add_nvp (res, "open", "dbinfo"); - nv_add_nvp (res, "type", databaseSpaceDescriptions[i].type); - nv_add_nvp (res, "purpose", databaseSpaceDescriptions[i].purpose); - nv_add_nvp_int (res, "volume_count", databaseSpaceDescriptions[i].volume_count); - nv_add_nvp_int (res, "used_size", databaseSpaceDescriptions[i].used_size); - nv_add_nvp_int (res, "free_size", databaseSpaceDescriptions[i].free_size); - nv_add_nvp_int (res, "total_size", databaseSpaceDescriptions[i].total_size); - nv_add_nvp (res, "close", "dbinfo"); - } - - for (int i = 0; i < volumes.size(); i++) - { - nv_add_nvp (res, "open", "spaceinfo"); - nv_add_nvp (res, "type", volumes[i].type); - nv_add_nvp (res, "purpose", volumes[i].purpose); - nv_add_nvp (res, "location", volumes[i].volume_name); - nv_add_nvp (res, "spacename", volumes[i].volume_name); - nv_add_nvp_int (res, "volid", volumes[i].volid); - nv_add_nvp_int (res, "usedpage", volumes[i].used_size); - nv_add_nvp_int (res, "freepage", volumes[i].free_size); - nv_add_nvp_int (res, "totalpage", volumes[i].total_size); - ts_add_nvp_time (res, "date", volumes[i].date, "%04d%02d%02d", - NV_ADD_DATE); - nv_add_nvp (res, "close", "spaceinfo"); - } - - for (int i = 0; i < FILES_DESCRIPTION_NUM_LINES; i++) - { - nv_add_nvp (res, "open", "fileinfo"); - nv_add_nvp (res, "data_type", fileSpaceDescriptions[i].data_type); - nv_add_nvp_int (res, "file_count", fileSpaceDescriptions[i].file_count); - nv_add_nvp_int (res, "used_size", fileSpaceDescriptions[i].used_size); - nv_add_nvp_int (res, "file_table_size", fileSpaceDescriptions[i].file_table_size); - nv_add_nvp_int (res, "reserved_size", fileSpaceDescriptions[i].reserved_size); - nv_add_nvp_int (res, "total_size", fileSpaceDescriptions[i].total_size); - nv_add_nvp (res, "close", "fileinfo"); - } -} - -int SpaceDbResultOldFormat::get_cnt_tpage() -{ - int cnt_tpage = 0, i; - - for (i = 0; i < volumes.size(); i++) - { - cnt_tpage += volumes[i].total_size; - } - for (i = 0; i < temporary_volumes.size(); i++) - { - cnt_tpage += temporary_volumes[i].total_size; - } - - return cnt_tpage; -} - -int SpaceDbResultNewFormat::get_cnt_tpage() -{ - int cnt_tpage = 0; - - for (int i = 0; i < volumes.size(); i++) - { - cnt_tpage += volumes[i].total_size; - } - - return cnt_tpage; -} - -time_t SpaceDbResultOldFormat::get_my_time (char *dbloca) -{ - char strbuf[BUFFER_MAX_LEN]; - char volname[PATH_MAX] = { '\0' }; - time_t mytime = time (NULL);; - struct stat statbuf; - - for (int i = 0; i < volumes.size(); i++) - { - if (uStringEqual (volumes[i].purpose, "DATA") - || uStringEqual (volumes[i].purpose, "INDEX")) - { - strcpy (volname, volumes[i].vol_name); - snprintf (strbuf, BUFFER_MAX_LEN, "%s/%s", dbloca, volname); - if (!stat (strbuf, &statbuf)) - { - mytime = statbuf.st_mtime; - } - } - } - - return mytime; -} - -time_t SpaceDbResultNewFormat::get_my_time (char *dbloca) -{ - char strbuf[BUFFER_MAX_LEN]; - char volname[PATH_MAX] = { '\0' }; - time_t mytime = time (NULL);; - struct stat statbuf; - - for (int i = 0; i < volumes.size(); i++) - { - if (uStringEqual (volumes[i].purpose, "PERMANENT")) - { - strcpy (volname, volumes[i].volume_name); - snprintf (strbuf, BUFFER_MAX_LEN, "%s/%s", dbloca, volname); - if (!stat (strbuf, &statbuf)) - { - mytime = statbuf.st_mtime; - } - } - } - - return mytime; -} - -void SpaceDbResultOldFormat::auto_add_volume (autoaddvoldb_node *curr, int db_mode, char *dbname_at_hostname) -{ - double frate; - int page_add = curr->data_ext_page; - if ((curr->data_vol) && (page_add > 0)) - { - frate = ajFreeSpace (this, "DATA"); - if (page_add < MIN_AUTO_ADDVOL_PAGE_SIZE) - { - page_add = MIN_AUTO_ADDVOL_PAGE_SIZE; - } - if (curr->data_warn_outofspace >= frate) - { - if (db_mode == HA_MODE) - { - append_host_to_dbname (dbname_at_hostname, curr->dbname, - sizeof (dbname_at_hostname)); - aj_add_volume (dbname_at_hostname, "data", page_add, page_size); - } - else - { - aj_add_volume (curr->dbname, "data", page_add, page_size); - } - } - } - - page_add = curr->index_ext_page; - if ((curr->index_vol) && (page_add > 0)) - { - frate = ajFreeSpace (this, "INDEX"); - if (page_add < MIN_AUTO_ADDVOL_PAGE_SIZE) - { - page_add = MIN_AUTO_ADDVOL_PAGE_SIZE; - } - if (curr->index_warn_outofspace >= frate) - { - if (db_mode == HA_MODE) - { - append_host_to_dbname (dbname_at_hostname, curr->dbname, - sizeof (dbname_at_hostname)); - aj_add_volume (dbname_at_hostname, "index", page_add, page_size); - } - else - { - aj_add_volume (curr->dbname, "index", page_add, page_size); - } - } - } -} - -void SpaceDbResultNewFormat::auto_add_volume (autoaddvoldb_node *curr, int db_mode, char *dbname_at_hostname) -{ - double frate; - int page_add = curr->data_ext_page; - if ((curr->data_vol) && (page_add > 0)) - { - frate = ajFreeSpace (this, "PERMANENT"); - if (page_add < MIN_AUTO_ADDVOL_PAGE_SIZE) - { - page_add = MIN_AUTO_ADDVOL_PAGE_SIZE; - } - if (curr->data_warn_outofspace >= frate) - { - if (db_mode == 2) - { - append_host_to_dbname (dbname_at_hostname, curr->dbname, - sizeof (dbname_at_hostname)); - aj_add_volume (dbname_at_hostname, "data", page_add, page_size); - } - else - { - aj_add_volume (curr->dbname, "data", page_add, page_size); - } - } - } -} - -void SpaceDbResultOldFormat::read_spacedb_output (FILE *fp) -{ - char str_buf[1024]; - int db_page_size = 0, log_page_size = 0; - - while (fgets (str_buf, sizeof (str_buf), fp)) - { - char *tmp_p; - - ut_trim (str_buf); - - if (strncmp (str_buf, "Space", 5) == 0) - { - int matchs = 0; - double page_size = 0.0; - char page_unit = 'H'; - - /* - * The log format looks like the following: - * Space description for database 'demodb' with pagesize 16.0K. (log pagesize: 16.0K) - */ - tmp_p = strstr (str_buf, "pagesize"); - if (tmp_p == NULL) - { - goto spacedb_error; - } - - if ((matchs = - sscanf (tmp_p, "pagesize %lf%c", &page_size, &page_unit)) != 2) - { - goto spacedb_error; - } - - if ((db_page_size = - _size_to_byte_by_unit (page_size, page_unit)) < 0) - { - goto spacedb_error; - } - - tmp_p = strstr (str_buf, "log pagesize:"); - if (tmp_p != NULL) - { - if ((matchs = - sscanf (tmp_p, "log pagesize: %lf%c", &page_size, - &page_unit)) != 2) - { - goto spacedb_error; - } - - if ((log_page_size = - _size_to_byte_by_unit (page_size, page_unit)) < 0) - { - goto spacedb_error; - } - } - else - { - /* log pagesize default value */ - log_page_size = 4096; - } - } - - else if (strncmp (str_buf, "Volid", 5) == 0) - { - break; - } - } - - while (fgets (str_buf, sizeof (str_buf), fp)) - { - ut_trim (str_buf); - if (str_buf[0] == '\0' || str_buf[0] == '-') - { - continue; - } - if (strncmp (str_buf, "Volid", 5) == 0) - { - break; - } - - if (strncmp (str_buf, "Space", 5) == 0) - { - continue; - } - - if (add_volume (str_buf)) - { - continue; - } - } - - while (fgets (str_buf, sizeof (str_buf), fp)) - { - ut_trim (str_buf); - if (str_buf[0] == '\0' || str_buf[0] == '-') - { - continue; - } - if (strncmp (str_buf, "Volid", 5) == 0) - { - break; - } - - if (add_temporary_volume (str_buf)) - { - continue; - } - } - set_page_size (db_page_size); - set_log_page_size (log_page_size); - - fclose (fp); - return; - -spacedb_error: - fclose (fp); -} - -void SpaceDbResultNewFormat::read_spacedb_output (FILE *fp) -{ - char page_unit, log_page_unit, *p; - double page_size, log_page_size_double; - char str_buf[1024]; - int db_page_size = 0, log_page_size = 0; - int index = 0; - - while (fgets (str_buf, sizeof (str_buf), fp)) - { - ut_trim (str_buf); - - if (strncmp (str_buf, "Space", 5) == 0) - { - p = strstr (str_buf, "pagesize"); - if (p) - { - sscanf (p, "pagesize %lf%c", &page_size, &page_unit); - if ((db_page_size = - _size_to_byte_by_unit (page_size, page_unit)) < 0) - { - goto spacedb_error; - } - set_page_size (db_page_size); - } - p = strstr (str_buf, "log pagesize:"); - if (p) - { - sscanf (p, "log pagesize: %lf%c", &log_page_size_double, &log_page_unit); - if ((log_page_size = - _size_to_byte_by_unit (log_page_size_double, log_page_unit)) < 0) - { - goto spacedb_error; - } - set_log_page_size (log_page_size); - } - } - if (strncmp (str_buf, "type", 4) == 0) - { - break; - } - } - - while (fgets (str_buf, sizeof (str_buf), fp)) - { - ut_trim (str_buf); - - if (strncmp (str_buf, "Space", 5) == 0) - { - break; - } - if (!is_valid_database_description (str_buf)) - { - break; - } - sscanf (str_buf, "%s %s DATA %d %d %d %d", databaseSpaceDescriptions[index].type, - databaseSpaceDescriptions[index].purpose, &databaseSpaceDescriptions[index].volume_count, - &databaseSpaceDescriptions[index].used_size, - &databaseSpaceDescriptions[index].free_size, - &databaseSpaceDescriptions[index].total_size); - index++; - } - - while (fgets (str_buf, sizeof (str_buf), fp)) - { - ut_trim (str_buf); - - if (strncmp (str_buf, "Detailed", 8) == 0) - { - break; - } - - if (!is_valid_volume_description (str_buf)) - { - continue; - } - - add_volume (str_buf); - } - - while (fgets (str_buf, sizeof (str_buf), fp)) - { - ut_trim (str_buf); - - if (strncmp (str_buf, "data_type", 9) == 0) - { - break; - } - } - - index = 0; - - while (fgets (str_buf, sizeof (str_buf), fp)) - { - ut_trim (str_buf); - - if (!is_valid_file_description (str_buf)) - { - continue; - } - - sscanf (str_buf, "%s %d %d %d %d %d\n", fileSpaceDescriptions[index].data_type, - &fileSpaceDescriptions[index].file_count, - &fileSpaceDescriptions[index].used_size, - &fileSpaceDescriptions[index].file_table_size, - &fileSpaceDescriptions[index].reserved_size, - &fileSpaceDescriptions[index].total_size); - index++; - } - - fclose (fp); - return; - -spacedb_error: - fclose (fp); -} - diff --git a/server/src/cm_cmd_exec.h b/server/src/cm_cmd_exec.h deleted file mode 100644 index 54ed878..0000000 --- a/server/src/cm_cmd_exec.h +++ /dev/null @@ -1,279 +0,0 @@ -/* - * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. - * - * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/* - * cm_cmd_exec.h - - */ - -#ifndef _CM_COMMAND_EXECUTE_H_ -#define _CM_COMMAND_EXECUTE_H_ - -#include - -#include "cm_dep.h" - -#if defined(WINDOWS) -#define DBMT_EXE_EXT ".exe" -#else -#define DBMT_EXE_EXT "" -#endif - -#define cmd_servstat_result_free(RESULT) cmd_result_free(RESULT) -#define cmd_asql_result_free(RESULT) cmd_result_free(RESULT) - -#define ERR_MSG_SIZE 1024 -#define COLUMN_VALUE_MAX_SIZE 32 -#define DATABASE_DESCRIPTION_NUM_LINES 3 -#define FILES_DESCRIPTION_NUM_LINES 4 -#define BUFFER_MAX_LEN 128 - -#if !defined (DO_NOT_USE_ARNIADBENV) -#define ARNIADB_ERROR_LOG_DIR "log/server" -#define ARNIADB_BROKER_LOG_DIR "log/broker" -#else -#define ARNIADB_ERROR_LOG_DIR ARNIADB_LOGDIR "/server" -#define ARNIADB_BROKER_LOG_DIR ARNIADB_LOGDIR"/broker" -#endif - -#define ARNIADB_DATABASE_TXT "databases.txt" -#define ARNIADB_ARNIADB_CONF "arniadb.conf" -#define ARNIADB_DBMT_CONF "cm.conf" -#define ARNIADB_BROKER_CONF "arniadb_broker.conf" -#define ARNIADB_HA_CONF "arniadb_ha.conf" -#define ARNIADB_UNLOAD_EXT_INDEX "_indexes" -#define ARNIADB_UNLOAD_EXT_TRIGGER "_trigger" -#define ARNIADB_UNLOAD_EXT_OBJ "_objects" -#define ARNIADB_UNLOAD_EXT_SCHEMA "_schema" -#define ARNIADB_SERVER_LOCK_EXT "_lgat__lock" -#define ARNIADB_ACT_LOG_EXT "_lgat" -#define ARNIADB_ARC_LOG_EXT "_lgar" -#define ARNIADB_BACKUP_INFO_EXT "_bkvinf" -#define ARNIADB_ARC_LOG_EXT_LEN strlen(ARNIADB_ARC_LOG_EXT) - -#define ARNIADB_CMD_NAME_LEN 128 - -#if !defined (DO_NOT_USE_ARNIADBENV) -#if defined(WINDOWS) -#define ARNIADB_DIR_BIN "bin\\" -#else -#define ARNIADB_DIR_BIN "bin/" -#endif -#endif - -#include -#include "cm_autojob.h" - -typedef enum -{ - ARNIADB_MODE_CS = 0, - ARNIADB_MODE_SA = 1 -} T_ARNIADB_MODE; - -struct SpaceDbVolumeInfoOldFormat -{ - int volid; - int total_size; - int free_size; - int data_size; - int index_size; - char purpose[COLUMN_VALUE_MAX_SIZE]; - char location[PATH_MAX]; - char vol_name[PATH_MAX]; - time_t date; -}; - -struct SpaceDbVolumeInfoNewFormat -{ - int volid; - int used_size; - int free_size; - int total_size; - char type[COLUMN_VALUE_MAX_SIZE]; - char purpose[COLUMN_VALUE_MAX_SIZE]; - char volume_name[PATH_MAX]; - time_t date; -}; - -struct DatabaseSpaceDescription -{ - char type[COLUMN_VALUE_MAX_SIZE]; - char purpose[COLUMN_VALUE_MAX_SIZE]; - int volume_count; - int used_size; - int free_size; - int total_size; -}; - -struct FileSpaceDescription -{ - char data_type[COLUMN_VALUE_MAX_SIZE]; - int file_count; - int used_size; - int file_table_size; - int reserved_size; - int total_size; -}; - -class GeneralSpacedbResult -{ - protected: - int page_size; - int log_page_size; - char err_msg[ERR_MSG_SIZE]; - public: - GeneralSpacedbResult() - { - page_size = 0; - log_page_size = 0; - err_msg[0] = '\0'; - } - GeneralSpacedbResult (int page_size, int log_page_size) - { - this->page_size = page_size; - this->log_page_size = log_page_size; - err_msg[0] = '\0'; - } - int get_page_size() - { - return page_size; - } - int get_log_page_size() - { - return log_page_size; - } - void set_page_size (int page_size) - { - this->page_size = page_size; - } - void set_log_page_size (int log_page_size) - { - this->log_page_size = log_page_size; - } - const char *get_err_msg() - { - return err_msg; - } - void set_err_msg (char *str) - { - strncpy (err_msg, str, ERR_MSG_SIZE); - } - bool has_error() - { - return err_msg[0] != '\0'; - } - virtual void create_result (nvplist *res) = 0; - virtual int get_cnt_tpage() = 0; - virtual void get_total_and_free_page (const char *type, double &free_page, double &total_page) = 0; - virtual time_t get_my_time (char *dbloca) = 0; - virtual void auto_add_volume (autoaddvoldb_node *current, int db_mode, char *dbname) = 0; - virtual void read_spacedb_output (FILE *fp) = 0; - virtual ~GeneralSpacedbResult() {} -}; - -class SpaceDbResultNewFormat : public GeneralSpacedbResult -{ - public: - SpaceDbResultNewFormat() {} - void add_volume (char *); - int get_cnt_tpage(); - void get_total_and_free_page (const char *type, double &free_page, double &total_page) - { - for (unsigned int i = 0; i < volumes.size(); i++) - { - if (strcmp (volumes[i].purpose, type) == 0) - { - total_page += volumes[i].total_size; - free_page += volumes[i].free_size; - } - } - } - time_t get_my_time (char *dbloca); - void auto_add_volume (autoaddvoldb_node *current, int db_mode, char *dbname); - void read_spacedb_output (FILE *fp); - void create_result (nvplist *res); - - DatabaseSpaceDescription databaseSpaceDescriptions[DATABASE_DESCRIPTION_NUM_LINES]; - FileSpaceDescription fileSpaceDescriptions[FILES_DESCRIPTION_NUM_LINES]; - private: - std::vector volumes; -}; - -class SpaceDbResultOldFormat : public GeneralSpacedbResult -{ - public: - SpaceDbResultOldFormat() {} - int get_volume_info (char *, SpaceDbVolumeInfoOldFormat &); - int add_volume (char *str_buf) - { - SpaceDbVolumeInfoOldFormat volume; - int rc = get_volume_info (str_buf, volume); - if (rc == TRUE) - { - volumes.push_back (volume); - } - return rc; - } - - int add_temporary_volume (char *str_buf) - { - SpaceDbVolumeInfoOldFormat volume; - int rc = get_volume_info (str_buf, volume); - if (rc == TRUE) - { - temporary_volumes.push_back (volume); - } - return rc; - } - - void create_result (nvplist *); - void get_total_and_free_page (const char *type, double &free_page, double &total_page) - { - for (unsigned int i = 0; i < volumes.size(); i++) - { - if (strcmp (volumes[i].purpose, type) == 0) - { - total_page += volumes[i].total_size; - free_page += volumes[i].free_size; - } - } - } - int get_cnt_tpage(); - time_t get_my_time (char *dbloca); - void auto_add_volume (autoaddvoldb_node *current, int db_mode, char *dbname); - void read_spacedb_output (FILE *); - private: - std::vector volumes; - std::vector temporary_volumes; -}; - -typedef T_CMD_RESULT T_ASQL_RESULT; - -GeneralSpacedbResult *cmd_spacedb (const char *dbname, T_ARNIADB_MODE mode); -T_ASQL_RESULT *cmd_asql (char *dbname, char *uid, char *passwd, - T_ARNIADB_MODE mode, char *infile, char *command, char *error_continue); -int cmd_start_server (char *dbname, char *err_buf, int err_buf_size); -int cmd_stop_server (char *dbname, char *err_buf, int err_buf_size); -void cmd_start_master (void); -char *arniadb_cmd_name (char *buf); -int read_error_file (const char *err_file, char *err_buf, int err_buf_size); -int read_error_file2 (char *err_file, char *err_buf, int err_buf_size, int *err_code); -int read_asql_error_file (char *err_file, char *err_buf, int err_buf_size); - -#endif /* _CM_COMMAND_EXECUTE_H_ */ diff --git a/server/src/cm_cmd_task.cpp b/server/src/cm_cmd_task.cpp deleted file mode 100644 index 1508a81..0000000 --- a/server/src/cm_cmd_task.cpp +++ /dev/null @@ -1,1490 +0,0 @@ -/* - * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. - * - * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/* - * cm_cmd_task.cpp - - */ - -#include -#include -#include -#include - -#if defined(WINDOWS) -#include -#include -#include -#include -#include "cm_win_wsa.h" -#else -#include -#include -#include -#include -#include -#include -#include -#endif - -#include "cm_dep.h" -#include "cm_text_encryption.h" -#include "cm_server_util.h" -#include "cm_user.h" -#include "cm_cmd_task.h" -#include "cm_cmd_util.h" -#include "cm_config.h" - -static struct option adddbinfo_opt[] = -{ - {ARG_AUTH, 1, 0, 'a'}, - {ARG_UID, 1, 0, 'u'}, - {ARG_HOST, 1, 0, 'h'}, - {ARG_PORT, 1, 0, 'p'}, - {0, 0, 0, 0} -}; - -static struct option adduser_opt[] = -{ - {ARG_UNICAS, 1, 0, 'b'}, - {ARG_DBCREATE, 1, 0, 'c'}, - {ARG_MONITOR, 1, 0, 'm'}, - {ARG_DB_INFO, 1, 0, 'd'}, - {0, 0, 0, 0} -}; - -static struct option chguserpwd_opt[] = -{ - {ARG_NEW_PASS, 1, 0, 'n'}, - {ARG_OLD_PASS, 1, 0, 'o'}, - {ARG_ADMIN_PASS, 1, 0, ADMIN_FLAG}, - {0, 0, 0, 0} -}; - -static struct option chguserauth_opt[] = -{ - {ARG_UNICAS, 1, 0, 'b'}, - {ARG_DBCREATE, 1, 0, 'c'}, - {ARG_MONITOR, 1, 0, 'm'}, - {0, 0, 0, 0} -}; - -static struct option chgdbinfo_opt[] = -{ - {ARG_AUTH, 1, 0, 'a'}, - {ARG_UID, 1, 0, 'u'}, - {ARG_HOST, 1, 0, 'h'}, - {ARG_PORT, 1, 0, 'p'}, - {0, 0, 0, 0} -}; - -static const char *auth_list[] = -{ - "none", - "admin", - "monitor", - NULL -}; - -static const char *createdb_auth_list[] = -{ - "none", - "admin", - NULL -}; - -static int _get_dbmt_user_index (T_DBMT_USER *dbmt_user, const char *username); -static T_DBMT_USER *_dbmt_user_get (char *error_msg); -static void _dbmt_user_free (T_DBMT_USER *dbmt_user); -static void _errmsg_output (int cmd_id, const char *error_msg); -static void _print_dbmtuser_info (T_DBMT_USER_INFO *dbmtuser_info); -static int _add_dbinfo_to_dbinfo_array (const char *dbinfo_str, - T_DBMT_USER_DBINFO **dbmt_dbinfo, - int *num_db, char *error_msg); -static int _check_str_in_list (const char *str, const char *str_list[]); -static int _check_dbmt_user_passwd (T_DBMT_USER *dbmt_user, - const char *username, const char *passwd, - char *error_msg); - -static int -_get_cmd_nvplist (nvplist *arg_list, const char *argv[], int argc, - struct option opt[], const char *need_arg_list[], - char *error_msg); - -static int -_get_longname_by_shortname (struct option opt[], int shortname, - char *longname, int buflen); - -static int -_set_nvplist_by_arglist (nvplist *arg_list, const char *argnamearray[], - const char *argvalarray[]); - -static int -_dbmtuser_auth_arg_check (const char *unicas_auth, const char *dbcreate_auth, - const char *monitor_auth, char *error_msg); -static int _get_localhost_ip (char *ipaddr, int ipaddr_len); - - -/* *************************************** - * - * Command Task Interface - * - * ***************************************/ - -int -cmd_listdb (int argc, const char *in_argv[]) -{ - int i = 0; - int cmd_id = CMD_LISTDB; - char *tok[2]; - char buf[LINE_MAX]; - char db_txt_path[PATH_MAX]; - - FILE *fp = NULL; - - snprintf (db_txt_path, sizeof (db_txt_path) - 1, "%s/%s", - sco.szArniadb_databases, ARNIADB_DATABASE_TXT); - - if ((fp = fopen (db_txt_path, "r")) == NULL) - { - _errmsg_output (cmd_id, "The databases.txt file does not exist.\n"); - return E_FAILURE; - } - - while (fgets (buf, sizeof (buf), fp)) - { - ut_trim (buf); - - if (buf[0] == '#') - { - continue; - } - - if (string_tokenize (buf, tok, 2) < 0) - { - continue; - } - - printf (" %d. %s\n", ++i, ut_trim (tok[0])); - } - - fclose (fp); - - return E_SUCCESS; -} - -int -cmd_deluser (int argc, const char *in_argv[]) -{ - int retval = E_SUCCESS; - int cmd_id = CMD_DELUSER; - int dbmt_user_index = -1; - char error_msg[DBMT_ERROR_MSG_SIZE]; - char dbmt_user_name[DBMT_USER_NAME_LEN]; - T_DBMT_USER *dbmt_user = NULL; - - if (argc == 1) - { - print_help_msg (cmd_id); - return E_SUCCESS; - } - - if (argc != 2) - { - strcpy_limit (error_msg, get_msg_by_id (PTN_ARG_NUM_ERR), - DBMT_ERROR_MSG_SIZE); - retval = E_ARG_ERR; - goto error_clean_return; - } - - if ((dbmt_user = _dbmt_user_get (error_msg)) == NULL) - { - retval = E_FAILURE; - goto error_clean_return; - } - - strcpy_limit (dbmt_user_name, in_argv[1], sizeof (dbmt_user_name)); - - if (uStringEqual (DBMT_USER_ADMIN_NAME, dbmt_user_name)) - { - snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, - get_msg_by_id (PTN_DBMT_USER_NOT_DEL), DBMT_USER_ADMIN_NAME); - retval = E_FAILURE; - goto error_clean_return; - } - - dbmt_user_index = _get_dbmt_user_index (dbmt_user, dbmt_user_name); - - if (dbmt_user_index < 0) - { - snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, - get_msg_by_id (PTN_DBMT_USER_NOT_EXIST), dbmt_user_name); - retval = E_FAILURE; - goto error_clean_return; - } - - dbmt_user->user_info[dbmt_user_index].user_name[0] = '\0'; - - if (dbmt_user_write_auth (dbmt_user, error_msg) != ERR_NO_ERROR) - { - retval = E_FAILURE; - goto error_clean_return; - } - - retval = E_SUCCESS; - goto clean_return; - -error_clean_return: - _errmsg_output (cmd_id, error_msg); - if (retval == E_ARG_ERR) - { - print_help_msg (cmd_id); - } - -clean_return: - _dbmt_user_free (dbmt_user); - return retval; -} - -int -cmd_adduser (int argc, const char *in_argv[]) -{ - int i; - int num_dbmt_user; - int num_db = 0; - int retval = E_SUCCESS; - int cmd_id = CMD_ADDUSER; - char dbmt_pass[PASSWD_ENC_LENGTH]; - char error_msg[DBMT_ERROR_MSG_SIZE] = { '\0' }; - T_DBMT_USER *dbmt_user; - T_DBMT_USER_AUTHINFO *auth_info = NULL; - T_DBMT_USER_DBINFO *db_info = NULL; - - const char *username, *userpass, *unicas, *dbcreate, *monitor, *tmp; - const char *need_arg_list[] = - { - ARG_DBMT_USER_NAME, - ARG_DBMT_USER_PWD, - NULL - }; - - nvplist *arg_list; - - if (argc == 1) - { - print_help_msg (cmd_id); - return E_SUCCESS; - } - - arg_list = nv_create (5, NULL, "\n", ":", "\n"); - if ((retval = - _get_cmd_nvplist (arg_list, in_argv, argc, adduser_opt, - need_arg_list, error_msg)) != E_SUCCESS) - { - goto error_return; - } - - tmp = nv_get_val (arg_list, ARG_UNICAS); - unicas = (tmp == NULL ? "none" : tmp); - - tmp = nv_get_val (arg_list, ARG_DBCREATE); - dbcreate = (tmp == NULL ? "none" : tmp); - - tmp = nv_get_val (arg_list, ARG_MONITOR); - monitor = (tmp == NULL ? "none" : tmp); - - username = nv_get_val (arg_list, ARG_DBMT_USER_NAME); - userpass = nv_get_val (arg_list, ARG_DBMT_USER_PWD); - - if ((retval = - _dbmtuser_auth_arg_check (unicas, dbcreate, monitor, error_msg)) != E_SUCCESS) - { - goto error_return; - } - - for (i = 0; i < arg_list->nvplist_leng; i++) - { - char *n, *v; - nv_lookup (arg_list, i, &n, &v); - if (n != NULL && (uStringEqual (n, ARG_DB_INFO))) - { - if ((_add_dbinfo_to_dbinfo_array (v, &db_info, - &num_db, error_msg)) != E_SUCCESS) - { - retval = E_ARG_ERR; - goto error_return; - } - } - } - - if ((dbmt_user = _dbmt_user_get (error_msg)) == NULL) - { - retval = E_FAILURE; - goto error_return; - } - - if (_get_dbmt_user_index (dbmt_user, username) >= 0) - { - snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, - get_msg_by_id (PTN_DBMT_USER_EXIST), username); - retval = E_FAILURE; - goto error_clean_return; - } - - /* set dbmt user auth info. */ - if ((auth_info = - (T_DBMT_USER_AUTHINFO *) malloc (AUTH_NUM_TOTAL * sizeof (T_DBMT_USER_AUTHINFO))) == NULL) - { - goto error_mem_alloc_return; - } - - dbmt_user_set_authinfo (&auth_info[0], "unicas", unicas); - dbmt_user_set_authinfo (&auth_info[1], "dbcreate", dbcreate); - dbmt_user_set_authinfo (&auth_info[2], "statusmonitorauth", monitor); - - /* encrypt the password. */ - uEncrypt (PASSWD_LENGTH, userpass, dbmt_pass); - - num_dbmt_user = dbmt_user->num_dbmt_user; - - /* set dbmt user info struct. */ - dbmt_user->user_info = - (T_DBMT_USER_INFO *) increase_capacity (dbmt_user->user_info, sizeof (T_DBMT_USER_INFO), - num_dbmt_user, num_dbmt_user + 1); - - if (dbmt_user->user_info == NULL) - { - goto error_mem_alloc_return; - } - - dbmt_user_set_userinfo (& (dbmt_user->user_info[num_dbmt_user]), - (char *) username, (char *) dbmt_pass, - AUTH_NUM_TOTAL, auth_info, num_db, db_info); - dbmt_user->num_dbmt_user++; - - /* update the cmdbpass & cm.pass conf file. */ - if (dbmt_user_write_pass (dbmt_user, error_msg) != ERR_NO_ERROR) - { - retval = E_FAILURE; - goto error_clean_return; - } - - if (dbmt_user_write_auth (dbmt_user, error_msg) != ERR_NO_ERROR) - { - retval = E_FAILURE; - goto error_clean_return; - } - - _dbmt_user_free (dbmt_user); - nv_destroy (arg_list); - - return E_SUCCESS; - -error_mem_alloc_return: - retval = E_FAILURE; - strcpy_limit (error_msg, get_msg_by_id (PTN_MEM_ALLOC_ERR), DBMT_ERROR_MSG_SIZE); - -error_clean_return: - _dbmt_user_free (dbmt_user); - -error_return: - nv_destroy (arg_list); - _errmsg_output (cmd_id, error_msg); - if (db_info) - { - free (db_info); - } - if (auth_info) - { - free (auth_info); - } - if (retval == E_ARG_ERR) - { - print_help_msg (cmd_id); - } - - return retval; -} - -int -cmd_viewuser (int argc, const char *in_argv[]) -{ - int i; - int retval = E_SUCCESS; - int cmd_id = CMD_VIEWUSER; - char error_msg[DBMT_ERROR_MSG_SIZE] = { '\0' }; - T_DBMT_USER *dbmt_user = NULL; - - if ((dbmt_user = _dbmt_user_get (error_msg)) == NULL) - { - retval = E_FAILURE; - goto error_return; - } - - if (argc == 1) - { - /* show all the dbmtuser info. */ - for (i = 0; i < dbmt_user->num_dbmt_user; i++) - { - _print_dbmtuser_info (&dbmt_user->user_info[i]); - } - } - else if (argc == 2) - { - int index = -1; - /* user specified a dbmtuser name. */ - index = _get_dbmt_user_index (dbmt_user, (char *) in_argv[1]); - - if (index < 0) - { - snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, - get_msg_by_id (PTN_DBMT_USER_NOT_EXIST), in_argv[1]); - retval = E_FAILURE; - goto error_return; - } - - _print_dbmtuser_info (&dbmt_user->user_info[index]); - } - else - { - snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, - get_msg_by_id (PTN_ARG_NUM_ERR)); - retval = E_ARG_ERR; - goto error_return; - } - - goto clean_return; - -error_return: - _errmsg_output (cmd_id, error_msg); - if (retval == E_ARG_ERR) - { - print_help_msg (cmd_id); - } - -clean_return: - _dbmt_user_free (dbmt_user); - return retval; -} - -int -cmd_chguser_pwd (int argc, const char *in_argv[]) -{ - int retval = E_SUCCESS; - int dbmt_user_index = -1; - int cmd_id = CMD_CHGUSER_PWD; - char pwd_tmp[PASSWD_ENC_LENGTH]; - char error_msg[DBMT_ERROR_MSG_SIZE]; - const char *dbmtusername, *oldpass, *newpass, *adminpass; - T_DBMT_USER *dbmt_user = NULL; - - nvplist *arg_list = NULL; - const char *need_arg_list[] = - { - ARG_DBMT_USER_NAME, - NULL - }; - - arg_list = nv_create (5, NULL, "\n", ":", "\n"); - - if (argc == 1) - { - print_help_msg (cmd_id); - return E_SUCCESS; - } - - if ((retval = - _get_cmd_nvplist (arg_list, in_argv, argc, chguserpwd_opt, need_arg_list, error_msg)) != E_SUCCESS) - { - goto error_clean_return; - } - - dbmtusername = nv_get_val (arg_list, ARG_DBMT_USER_NAME); - oldpass = nv_get_val (arg_list, ARG_OLD_PASS); - newpass = nv_get_val (arg_list, ARG_NEW_PASS); - adminpass = nv_get_val (arg_list, ARG_ADMIN_PASS); - - /* get dbmt user. */ - if ((dbmt_user = _dbmt_user_get (error_msg)) == NULL) - { - retval = E_FAILURE; - goto error_clean_return; - } - - if ((dbmt_user_index = _get_dbmt_user_index (dbmt_user, dbmtusername)) < 0) - { - snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, - get_msg_by_id (PTN_DBMT_USER_NOT_EXIST), dbmtusername); - retval = E_FAILURE; - goto error_clean_return; - } - - if (oldpass != NULL) - { - /* check old password. */ - if (_check_dbmt_user_passwd - (dbmt_user, dbmtusername, oldpass, error_msg) < 0) - { - retval = E_FAILURE; - goto error_clean_return; - } - } - else if (adminpass != NULL) - { - /* check admin password. */ - if (_check_dbmt_user_passwd - (dbmt_user, DBMT_USER_ADMIN_NAME, adminpass, error_msg) < 0) - { - retval = E_FAILURE; - goto error_clean_return; - } - } - else - { - snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, - get_msg_by_id (PTN_ARG_MUST_APPEAR_ERR), - ARG_OLD_PASS ", " ARG_ADMIN_PASS); - retval = E_FAILURE; - goto error_clean_return; - } - - /* reset the new password. */ - uEncrypt (PASSWD_LENGTH, newpass, pwd_tmp); - strcpy_limit (dbmt_user->user_info[dbmt_user_index].user_passwd, pwd_tmp, - PASSWD_ENC_LENGTH); - - if (dbmt_user_write_pass (dbmt_user, error_msg) != ERR_NO_ERROR) - { - retval = E_FAILURE; - goto error_clean_return; - } - - nv_destroy (arg_list); - _dbmt_user_free (dbmt_user); - return E_SUCCESS; - -error_clean_return: - nv_destroy (arg_list); - _dbmt_user_free (dbmt_user); - _errmsg_output (cmd_id, error_msg); - - if (retval == E_ARG_ERR) - { - print_help_msg (cmd_id); - } - - return retval; -} - -int -cmd_chguser_auth (int argc, const char *in_argv[]) -{ - int i = 0; - int retval = E_SUCCESS; - int dbmt_user_index = -1; - int cmd_id = CMD_CHGUSER_AUTH; - char error_msg[DBMT_ERROR_MSG_SIZE]; - const char *unicas, *dbcreate, *monitor, *username; - T_DBMT_USER *dbmt_user = NULL; - T_DBMT_USER_INFO *dbmt_user_info_t = NULL; - - nvplist *arg_list = NULL; - const char *need_arg_list[] = - { - ARG_DBMT_USER_NAME, - NULL - }; - - arg_list = nv_create (5, NULL, "\n", ":", "\n"); - - if (argc == 1) - { - print_help_msg (cmd_id); - return E_SUCCESS; - } - - if ((retval = - _get_cmd_nvplist (arg_list, in_argv, argc, chguserauth_opt, need_arg_list, error_msg)) != E_SUCCESS) - { - goto error_clean_return; - } - - unicas = nv_get_val (arg_list, ARG_UNICAS); - dbcreate = nv_get_val (arg_list, ARG_DBCREATE); - monitor = nv_get_val (arg_list, ARG_MONITOR); - username = nv_get_val (arg_list, ARG_DBMT_USER_NAME); - - if ((retval = - _dbmtuser_auth_arg_check (unicas, dbcreate, monitor, error_msg)) != E_SUCCESS) - { - goto error_clean_return; - } - - if (unicas == NULL && dbcreate == NULL && monitor == NULL) - { - snprintf (error_msg, sizeof (error_msg) - 1, - get_msg_by_id (PTN_ARG_MUST_APPEAR_ERR), - ARG_UNICAS ", " ARG_DBCREATE ", " ARG_MONITOR); - retval = E_ARG_ERR; - goto error_clean_return; - } - - /* get dbmt user. */ - if ((dbmt_user = _dbmt_user_get (error_msg)) == NULL) - { - _errmsg_output (cmd_id, error_msg); - return E_FAILURE; - } - - if ((dbmt_user_index = _get_dbmt_user_index (dbmt_user, username)) < 0) - { - snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, - get_msg_by_id (PTN_DBMT_USER_NOT_EXIST), username); - retval = E_FAILURE; - goto error_clean_return; - } - - dbmt_user_info_t = & (dbmt_user->user_info[dbmt_user_index]); - - for (i = 0; i < dbmt_user_info_t->num_authinfo; i++) - { - T_DBMT_USER_AUTHINFO *auth_t; - - auth_t = & (dbmt_user_info_t->authinfo[i]); - - if (uStringEqual (auth_t->domain, "unicas") && unicas != NULL) - { - strcpy_limit (auth_t->auth, unicas, sizeof (auth_t->auth)); - } - else if (uStringEqual (auth_t->domain, "dbcreate") && dbcreate != NULL) - { - strcpy_limit (auth_t->auth, dbcreate, sizeof (auth_t->auth)); - } - else if (uStringEqual (auth_t->domain, "statusmonitorauth") - && monitor != NULL) - { - strcpy_limit (auth_t->auth, monitor, sizeof (auth_t->auth)); - } - } - - if (dbmt_user_write_auth (dbmt_user, error_msg) != ERR_NO_ERROR) - { - retval = E_FAILURE; - goto error_clean_return; - } - - nv_destroy (arg_list); - _dbmt_user_free (dbmt_user); - return E_SUCCESS; - -error_clean_return: - nv_destroy (arg_list); - _dbmt_user_free (dbmt_user); - _errmsg_output (cmd_id, error_msg); - - if (retval == E_ARG_ERR) - { - print_help_msg (cmd_id); - } - - return retval; -} - -int -cmd_adddbinfo (int argc, const char *in_argv[]) -{ - int i; - int num_db; - int dbmt_user_index; - int retval = E_SUCCESS; - int cmd_id = CMD_ADDDBINFO; - char error_msg[DBMT_ERROR_MSG_SIZE]; - char local_ip[64]; - char broker_addr[BROKER_ADDR_LEN]; - const char *username, *dbname, *auth, *uid, *host, *port, *tmp; - int flag = 0; - char *n, *v; - int dbexist = 0; - - T_DBMT_USER *dbmt_user = NULL; - T_DBMT_USER_INFO *t_info = NULL; - - nvplist *arg_list = NULL; - nvplist *db_list = NULL; - const char *need_arg_list[] = - { - ARG_DBMT_USER_NAME, - ARG_DB_NAME, - NULL - }; - - local_ip[0] = '\0'; - - if (argc == 1) - { - print_help_msg (cmd_id); - return E_SUCCESS; - } - - if (_get_localhost_ip (local_ip, sizeof (local_ip)) != 0) - { - snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, - "failed to get localhost ip"); - retval = E_FAILURE; - goto error_clean_return; - } - - arg_list = nv_create (5, NULL, "\n", ":", "\n"); - db_list = nv_create (5, NULL, "\n", ":", "\n"); - - if ((retval = - _get_cmd_nvplist (arg_list, in_argv, argc, adddbinfo_opt, need_arg_list, error_msg)) != E_SUCCESS) - { - goto error_clean_return; - } - - /* set default value of auth, uid, host & port. */ - tmp = nv_get_val (arg_list, ARG_AUTH); - auth = ((tmp == NULL) ? "admin" : tmp); - - tmp = nv_get_val (arg_list, ARG_UID); - uid = ((tmp == NULL) ? "dba" : tmp); - - tmp = nv_get_val (arg_list, ARG_HOST); - host = ((tmp == NULL) ? local_ip : tmp); - - tmp = nv_get_val (arg_list, ARG_PORT); - port = ((tmp == NULL) ? "30000" : tmp); - - username = nv_get_val (arg_list, ARG_DBMT_USER_NAME); - dbname = nv_get_val (arg_list, ARG_DB_NAME); - - /* does this database exist in database.txt? */ - - if (ut_get_dblist (db_list, 0) != ERR_NO_ERROR) - { - snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, - "failed to get database lists."); - retval = E_FAILURE; - goto error_clean_return; - } - for (i = 0; i < db_list->nvplist_leng; i++) - { - nv_lookup (db_list, i, &n, &v); - if (n == NULL || v == NULL) - { - snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, "malformed database lists."); - retval = E_FAILURE; - goto error_clean_return; - } - - if (!strcmp (n, "open") && !strcmp (v, "dblist")) - { - flag = 1; - } - else if (!strcmp (n, "close") && !strcmp (v, "dblist")) - { - flag = 0; - break; - } - else if (flag == 1) - { - if (!strcmp (n, "dbname") && !strcmp (v, dbname)) - { - dbexist = 1; - } - } /* close "else if (flag == 1)" */ - } - if (!dbexist) - { - snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, - get_msg_by_id (PTN_DB_NOT_EXIST), dbname); - retval = E_FAILURE; - goto error_clean_return; - } - - if ((dbmt_user = _dbmt_user_get (error_msg)) == NULL) - { - _errmsg_output (cmd_id, error_msg); - return E_FAILURE; - } - - if ((dbmt_user_index = _get_dbmt_user_index (dbmt_user, username)) < 0) - { - snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, - get_msg_by_id (PTN_DBMT_USER_NOT_EXIST), username); - retval = E_FAILURE; - goto error_clean_return; - } - - snprintf (broker_addr, sizeof (broker_addr), "%s,%s", host, port); - - t_info = & (dbmt_user->user_info[dbmt_user_index]); - - /* check whether this user has been authorized to this DB. */ - if (dbmt_user_search (t_info, dbname) >= 0) - { - snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, - get_msg_by_id (PTN_DB_ALREADY_AUTH), dbname, username); - retval = E_FAILURE; - goto error_clean_return; - } - - num_db = t_info->num_dbinfo; - t_info->dbinfo = (T_DBMT_USER_DBINFO *) increase_capacity (t_info->dbinfo, - sizeof (T_DBMT_USER_DBINFO), - num_db, num_db + 1); - if (t_info->dbinfo == NULL) - { - strcpy_limit (error_msg, get_msg_by_id (PTN_MEM_ALLOC_ERR), DBMT_ERROR_MSG_SIZE); - retval = E_FAILURE; - goto error_clean_return; - } - - /* add dbinfo to dbmt user. */ - dbmt_user_set_dbinfo (& (t_info->dbinfo[num_db]), dbname, auth, uid, broker_addr); - - t_info->num_dbinfo++; - - if (dbmt_user_write_auth (dbmt_user, error_msg) != ERR_NO_ERROR) - { - retval = E_FAILURE; - goto error_clean_return; - } - - retval = E_SUCCESS; - goto memory_clean_return; - -error_clean_return: - _errmsg_output (cmd_id, error_msg); - - if (retval == E_ARG_ERR) - { - print_help_msg (cmd_id); - } - -memory_clean_return: - if (db_list) - { - nv_destroy (db_list); - } - if (arg_list) - { - nv_destroy (arg_list); - } - if (dbmt_user) - { - _dbmt_user_free (dbmt_user); - } - return retval; -} - -int -cmd_deldbinfo (int argc, const char *in_argv[]) -{ - int db_index; - int dbmt_user_index; - int retval = E_SUCCESS; - int cmd_id = CMD_DELDBINFO; - char dbname[DBNAME_LEN]; - char error_msg[DBMT_ERROR_MSG_SIZE]; - char dbmt_user_name[DBMT_USER_NAME_LEN]; - - T_DBMT_USER *dbmt_user = NULL; - - if (argc == 1) - { - print_help_msg (cmd_id); - return E_SUCCESS; - } - - if (argc != 3) - { - snprintf (error_msg, DBMT_USER_NAME_LEN - 1, get_msg_by_id (PTN_ARG_NUM_ERR)); - retval = E_ARG_ERR; - goto error_clean_return; - } - - if ((dbmt_user = _dbmt_user_get (error_msg)) == NULL) - { - retval = E_FAILURE; - goto error_clean_return; - } - - strcpy_limit (dbmt_user_name, in_argv[1], sizeof (dbmt_user_name)); - strcpy_limit (dbname, in_argv[2], sizeof (dbname)); - - dbmt_user_index = _get_dbmt_user_index (dbmt_user, dbmt_user_name); - if (dbmt_user_index < 0) - { - snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, - get_msg_by_id (PTN_DBMT_USER_NOT_EXIST), dbmt_user_name); - - retval = E_FAILURE; - goto error_clean_return; - } - - if ((db_index = - dbmt_user_search (&dbmt_user->user_info[dbmt_user_index], dbname)) < 0) - { - snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, - get_msg_by_id (PTN_DB_NOT_AUTH), dbname, dbmt_user_name); - retval = E_FAILURE; - goto error_clean_return; - } - - dbmt_user->user_info[dbmt_user_index].dbinfo[db_index].dbname[0] = '\0'; - - if (dbmt_user_write_auth (dbmt_user, error_msg) != ERR_NO_ERROR) - { - retval = E_FAILURE; - goto error_clean_return; - } - - retval = E_SUCCESS; - goto clean_return; - -error_clean_return: - _errmsg_output (cmd_id, error_msg); - - if (retval == E_ARG_ERR) - { - print_help_msg (cmd_id); - } - -clean_return: - _dbmt_user_free (dbmt_user); - return retval; -} - -int -cmd_chgdbinfo (int argc, const char *in_argv[]) -{ - int dbinfo_index; - int dbmt_user_index; - int retval = E_SUCCESS; - int cmd_id = CMD_CHGDBINFO; - char *broker_tok[2]; - char broker_addr[BROKER_ADDR_LEN]; - char broker_addr_t[BROKER_ADDR_LEN]; - char error_msg[DBMT_ERROR_MSG_SIZE]; - char *auth, *uid, *host, *port, *username, *dbname; - const char *need_arg_list[] = - { - ARG_DBMT_USER_NAME, - ARG_DB_NAME, - NULL - }; - - T_DBMT_USER *dbmt_user = NULL; - T_DBMT_USER_INFO *userinfo_t = NULL; - T_DBMT_USER_DBINFO *dbinfo_t = NULL; - - nvplist *arg_list = NULL; - - arg_list = nv_create (5, NULL, "\n", ":", "\n"); - - if (argc == 1) - { - print_help_msg (cmd_id); - return E_SUCCESS; - } - - if ((retval = - _get_cmd_nvplist (arg_list, in_argv, argc, chgdbinfo_opt,need_arg_list, error_msg)) != E_SUCCESS) - { - goto error_clean_return; - } - - auth = nv_get_val (arg_list, ARG_AUTH); - uid = nv_get_val (arg_list, ARG_UID); - host = nv_get_val (arg_list, ARG_HOST); - port = nv_get_val (arg_list, ARG_PORT); - username = nv_get_val (arg_list, ARG_DBMT_USER_NAME); - dbname = nv_get_val (arg_list, ARG_DB_NAME); - - if ((dbmt_user = _dbmt_user_get (error_msg)) == NULL) - { - _errmsg_output (cmd_id, error_msg); - return E_FAILURE; - } - - if ((dbmt_user_index = _get_dbmt_user_index (dbmt_user, username)) < 0) - { - snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, - get_msg_by_id (PTN_DBMT_USER_NOT_EXIST), username); - retval = E_FAILURE; - goto error_clean_return; - } - - userinfo_t = & (dbmt_user->user_info[dbmt_user_index]); - - if ((dbinfo_index = dbmt_user_search (userinfo_t, dbname)) < 0) - { - snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, - get_msg_by_id (PTN_DB_NOT_EXIST), dbname, username); - retval = E_FAILURE; - goto error_clean_return; - } - - dbinfo_t = & (userinfo_t->dbinfo[dbinfo_index]); - - strcpy_limit (broker_addr_t, dbinfo_t->broker_address, - sizeof (broker_addr_t)); - if (string_tokenize2 (broker_addr_t, broker_tok, 2, ',') < 0) - { - snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, - get_msg_by_id (PTN_BROKER_ADDR_ERR), dbinfo_t->broker_address); - retval = E_FAILURE; - goto error_clean_return; - } - - snprintf (broker_addr, sizeof (broker_addr) - 1, "%s,%s", - ((host == NULL) ? broker_tok[0] : host), - ((port == NULL) ? broker_tok[1] : port)); - - strcpy_limit (dbinfo_t->broker_address, broker_addr, - sizeof (dbinfo_t->broker_address)); - - if (auth != NULL) - { - strcpy_limit (dbinfo_t->auth, auth, sizeof (dbinfo_t->auth)); - } - - if (uid != NULL) - { - strcpy_limit (dbinfo_t->uid, uid, sizeof (dbinfo_t->uid)); - } - - if (dbmt_user_write_auth (dbmt_user, error_msg) != ERR_NO_ERROR) - { - retval = E_FAILURE; - goto error_clean_return; - } - - retval = E_SUCCESS; - goto memory_clean_return; - -error_clean_return: - _errmsg_output (cmd_id, error_msg); - - if (retval == E_ARG_ERR) - { - print_help_msg (cmd_id); - } - -memory_clean_return: - nv_destroy (arg_list); - _dbmt_user_free (dbmt_user); - return retval; -} - -/* *************************************** - * - * Command Task Tools - * - * ***************************************/ - -static int -_check_dbmt_user_passwd (T_DBMT_USER *dbmt_user, const char *username, - const char *passwd, char *error_msg) -{ - int dbmt_user_index = -1; - char pwd_tmp[PASSWD_ENC_LENGTH]; - T_DBMT_USER_INFO *dbmt_user_info_t = NULL; - - /* check admin password. */ - if ((dbmt_user_index = _get_dbmt_user_index (dbmt_user, username)) < 0) - { - snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, - get_msg_by_id (PTN_DBMT_USER_NOT_EXIST), username); - return -1; - } - - dbmt_user_info_t = & (dbmt_user->user_info[dbmt_user_index]); - uDecrypt (PASSWD_LENGTH, dbmt_user_info_t->user_passwd, pwd_tmp); - - if (!uStringEqual (pwd_tmp, passwd)) - { - snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, - get_msg_by_id (PTN_DBMT_USER_PWD_ERR), passwd); - return -1; - } - - return 0; -} - -static T_DBMT_USER * -_dbmt_user_get (char *error_msg) -{ - T_DBMT_USER *dbmt_user = NULL; - - if ((dbmt_user = (T_DBMT_USER *) malloc (sizeof (T_DBMT_USER))) == NULL) - { - return NULL; - } - - if (dbmt_user_read (dbmt_user, error_msg) < 0) - { - return NULL; - } - - return dbmt_user; -} - -static void -_dbmt_user_free (T_DBMT_USER *dbmt_user) -{ - if (dbmt_user != NULL) - { - dbmt_user_free (dbmt_user); - } - - free (dbmt_user); - return; -} - -static int -_get_dbmt_user_index (T_DBMT_USER *dbmt_user, const char *username) -{ - int i; - - for (i = 0; i < dbmt_user->num_dbmt_user; i++) - { - if (uStringEqual (username, dbmt_user->user_info[i].user_name)) - { - return i; - } - } - - return -1; -} - -static void -_errmsg_output (int cmd_id, const char *error_msg) -{ - char cmd_name[OPT_STR_LEN]; - - if (get_cmdname_by_id (cmd_id, cmd_name, sizeof (cmd_name)) < 0) - { - fprintf (stderr, "ERROR: Command id (%d) is not exist.\n", cmd_id); - return; - } - - fprintf (stderr, "ERROR: %s: %s\n", cmd_name, error_msg); - return; -} - -static int -_get_cmd_nvplist (nvplist *arg_list, const char *argv[], int argc, - struct option opt[], const char *need_arg_list[], - char *error_msg) -{ - int retval = E_SUCCESS; - int i, need_arg_num; - char opt_str[OPT_STR_LEN]; - char *l_opt_arg; - - for (i = 0; need_arg_list[i] != NULL; i++) - ; - need_arg_num = i; - if (0 == need_arg_num) - { - return E_ARG_ERR; - } - utility_make_getopt_optstring (opt, opt_str); - - while (1) - { - int opt_key = 0; - int opt_index = 0; - char longname[OPT_STR_LEN]; - - opt_key = - getopt_long (argc, (char **const) argv, opt_str, opt, &opt_index); - - /* end of args */ - if (opt_key == -1) - { - break; - } - if (_get_longname_by_shortname - (opt, opt_key, longname, sizeof (longname)) < 0) - { - return E_ARG_ERR; - } - l_opt_arg = optarg; - - nv_add_nvp (arg_list, longname, l_opt_arg); - } - - if (argc - optind == need_arg_num) - { - _set_nvplist_by_arglist (arg_list, need_arg_list, & (argv[optind])); - } - else if (argc - optind < need_arg_num) - { - snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, - get_msg_by_id (PTN_ARG_MISS), need_arg_list[need_arg_num - 1]); - retval = E_ARG_ERR; - } - else - { - snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, - get_msg_by_id (PTN_ARG_MORE), argv[optind + 1]); - retval = E_ARG_ERR; - } - - return retval; -} - -static int -_get_longname_by_shortname (struct option opt[], int shortname, - char *longname, int buflen) -{ - int i; - - for (i = 0; opt[i].val != 0; i++) - { - if (shortname == opt[i].val) - { - strcpy_limit (longname, opt[i].name, buflen); - return 0; - } - } - - return -1; -} - -static int -_set_nvplist_by_arglist (nvplist *arg_list, const char *argnamelist[], - const char *argvalarray[]) -{ - int i; - - for (i = 0; argnamelist[i] != NULL; i++) - { - nv_add_nvp (arg_list, argnamelist[i], argvalarray[i]); - } - - return 0; -} - -/* the str_list should be end with NULL. */ -static int -_check_str_in_list (const char *str, const char *str_list[]) -{ - int i; - - if (str == NULL) - { - return -1; - } - - for (i = 0; str_list[i] != NULL; i++) - { - if (uStringEqual (str, str_list[i])) - { - return i; - } - } - - return -1; -} - -static int -_add_dbinfo_to_dbinfo_array (const char *dbinfo_str, - T_DBMT_USER_DBINFO **dbmt_dbinfo, int *num_db, - char *error_msg) -{ - char *tok[3]; - char str_t[1024]; - char *broker_tok[3]; - char broker_str[BROKER_ADDR_LEN]; - int i; - - strcpy_limit (str_t, dbinfo_str, sizeof (str_t)); - - if (string_tokenize2 (str_t, tok, 3, ';') < 0) - { - snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, get_msg_by_id (PTN_ARG_FORMAT_ERR), str_t); - return E_FAILURE; - } - - /* check broker ip & broker port. */ - if (string_tokenize2 (tok[2], broker_tok, 2, ',') < 0) - { - snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, get_msg_by_id (PTN_BROKER_ADDR_ERR), tok[2]); - return E_FAILURE; - } - - if ((*num_db) > 0) - { - for (i = 0; i < (*num_db); i++) - { - if (uStringEqual (tok[0], (*dbmt_dbinfo)[i].dbname)) - { - snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, get_msg_by_id (PTN_DB_ADD_TWICE), tok[0]); - return E_FAILURE; - } - } - } - - snprintf (broker_str, sizeof (broker_str) - 1, "%s,%s", ut_trim (broker_tok[0]), ut_trim (broker_tok[1])); - - *dbmt_dbinfo = (T_DBMT_USER_DBINFO *) increase_capacity (*dbmt_dbinfo, - sizeof (T_DBMT_USER_DBINFO), - (*num_db), (*num_db) + 1); - - if (*dbmt_dbinfo == NULL) - { - snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, get_msg_by_id (PTN_MEM_ALLOC_ERR)); - return E_FAILURE; - } - - dbmt_user_set_dbinfo (& (*dbmt_dbinfo)[ (*num_db)], ut_trim (tok[0]), - DBMT_USER_ADMIN_NAME, ut_trim (tok[1]), broker_str); - (*num_db)++; - - return E_SUCCESS; -} - -static void -_print_dbmtuser_info (T_DBMT_USER_INFO *dbmtuser_info) -{ - int i; - const char *dbinfo_pattern = " %-48s %-17s %-23s \n"; - char split[17 + 23 + 48 + 3]; - int len = 17 + 23 + 48 + 3; - - memset (split, '=', len - 1); - split[len - 1] = '\0'; - - printf ("DBMT USER: %s\n", dbmtuser_info->user_name); - printf (" Auth info: \n"); - - for (i = 0; i < dbmtuser_info->num_authinfo; i++) - { - T_DBMT_USER_AUTHINFO *t_authinfo = &dbmtuser_info->authinfo[i]; - if (strcmp (t_authinfo->domain, "unicas") == 0) - { - printf (" broker: %s\n", t_authinfo->auth); - } - else - { - printf (" %s: %s\n", t_authinfo->domain, t_authinfo->auth); - } - } - - printf (" DB info: \n"); - printf (" %s\n", split); - printf (dbinfo_pattern, "DBNAME", "UID", "BROKER INFO"); - printf (" %s\n", split); - - for (i = 0; i < dbmtuser_info->num_dbinfo; i++) - { - T_DBMT_USER_DBINFO *t_dbinfo = &dbmtuser_info->dbinfo[i]; - printf (dbinfo_pattern, - t_dbinfo->dbname, t_dbinfo->uid, t_dbinfo->broker_address); - } - printf ("\n"); - - return; -} - -static int -_dbmtuser_auth_arg_check (const char *unicas_auth, const char *dbcreate_auth, - const char *monitor_auth, char *error_msg) -{ - if (unicas_auth != NULL && _check_str_in_list (unicas_auth, auth_list) < 0) - { - snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, - get_msg_by_id (PTN_ARG_FORMAT_ERR), ARG_UNICAS); - return E_ARG_ERR; - } - if (dbcreate_auth != NULL - && _check_str_in_list (dbcreate_auth, createdb_auth_list) < 0) - { - snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, - get_msg_by_id (PTN_ARG_FORMAT_ERR), ARG_DBCREATE); - return E_ARG_ERR; - } - if (monitor_auth != NULL && _check_str_in_list (monitor_auth, auth_list) < 0) - { - snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, - get_msg_by_id (PTN_ARG_FORMAT_ERR), ARG_MONITOR); - return E_ARG_ERR; - } - - return E_SUCCESS; -} - -static int -_get_localhost_ip (char *ipaddr, int ipaddr_len) -{ - char hostname[64]; - char *ip = NULL; - int i = 0; - struct hostent *hostent_p = NULL; - -#if defined(WINDOWS) - WSADATA wsaData; - WSAStartup (MAKEWORD (2, 2), &wsaData); -#endif - - hostname[0] = '\0'; - - if (gethostname (hostname, sizeof (hostname)) < 0) - { - goto exit_err; - } - - hostent_p = gethostbyname (hostname); - - if (hostent_p == NULL) - { - ipaddr = NULL; - goto exit_err; - } - else - { - for (i = 0; hostent_p->h_addr_list[i] != NULL; i++) - { - ip = inet_ntoa (* ((struct in_addr *) hostent_p->h_addr_list[i])); - /* ignore the 127.0.0.1 */ - if (strcmp (ip, "127.0.0.1") == 0) - { - continue; - } - break; - } - if (ip) - { - strcpy_limit (ipaddr, ip, ipaddr_len); - return 0; - } - - goto exit_err; - } -exit_err: -#if defined(WINDOWS) - WSACleanup (); -#endif - return -1; -} diff --git a/server/src/cm_cmd_task.h b/server/src/cm_cmd_task.h deleted file mode 100644 index 907153c..0000000 --- a/server/src/cm_cmd_task.h +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. - * - * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/* - * cm_cmd_task.h - - */ - -#ifndef _CM_CMD_TASK_H_ -#define _CM_CMD_TASK_H_ - -#include -#ifdef HAVE_GETOPT_H -#include -#else -#include "getopt.h" -#endif - -typedef enum -{ - CMD_CHANGEDBPWD, - CMD_LISTDB, - CMD_ADDUSER, - CMD_DELUSER, - CMD_VIEWUSER, - CMD_CHGUSER_AUTH, - CMD_CHGUSER_PWD, - CMD_ADDDBINFO, - CMD_DELDBINFO, - CMD_CHGDBINFO, - CMD_UNDEFINED, -} CMD_ID; - - -int cmd_listdb (int argc, const char *in_argv[]); -int cmd_adduser (int argc, const char *in_argv[]); -int cmd_deluser (int argc, const char *in_argv[]); -int cmd_viewuser (int argc, const char *in_argv[]); -int cmd_chguser_pwd (int argc, const char *in_argv[]); -int cmd_chguser_auth (int argc, const char *in_argv[]); -int cmd_adddbinfo (int argc, const char *in_argv[]); -int cmd_deldbinfo (int argc, const char *in_argv[]); -int cmd_chgdbinfo (int argc, const char *in_argv[]); - -#endif /* ! _CM_CMD_TASK_H_ */ diff --git a/server/src/cm_cmd_util.cpp b/server/src/cm_cmd_util.cpp deleted file mode 100644 index e927cdb..0000000 --- a/server/src/cm_cmd_util.cpp +++ /dev/null @@ -1,282 +0,0 @@ -/* - * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. - * - * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/* - * cm_cmd_util.cpp - - */ - -#include -#include -#include -#include - -#include "cm_porting.h" -#include "cm_dep.h" -#include "cm_cmd_util.h" -#include "cm_cmd_task.h" - -typedef int (*CMD_FUNC) (int argc, const char *argv[]); - -#define DEF_CMD_FUNC(CMD_FUNC) CMD_FUNC; - -typedef struct -{ - const char *cmd_name; - CMD_FUNC cmd_func; - CMD_ID cmd_id; -} CMD_INFO; - -static CMD_INFO cmd_info[] = -{ - {"adduser", cmd_adduser, CMD_ADDUSER}, - {"deluser", cmd_deluser, CMD_DELUSER}, - {"viewuser", cmd_viewuser, CMD_VIEWUSER}, - {"changeuserauth", cmd_chguser_auth, CMD_CHGUSER_AUTH}, - {"changeuserpwd", cmd_chguser_pwd, CMD_CHGUSER_PWD}, - {"adddbinfo", cmd_adddbinfo, CMD_ADDDBINFO}, - {"deldbinfo", cmd_deldbinfo, CMD_DELDBINFO}, - {"changedbinfo", cmd_chgdbinfo, CMD_CHGDBINFO}, - {"listdb", cmd_listdb, CMD_LISTDB}, - {NULL, NULL, CMD_UNDEFINED}, -}; - -typedef struct -{ - PTN_ID ptn_id; - const char *ptn_msg; -} PTN_INFO; - -static PTN_INFO msg_str_ptn[] = -{ - {PTN_ARG_MISS, "Argument (%s) is missing."}, - {PTN_ARG_MORE, "Argument (%s) is not needed."}, - {PTN_ARG_NUM_ERR, "Argument number is not correct."}, - {PTN_ARG_FORMAT_ERR, "Argument (%s) not correct!"}, - {PTN_ARG_MUST_APPEAR_ERR, "Arg %s should appear at least one."}, - {PTN_DBMT_USER_NOT_EXIST, "DBMT user (%s) not exist."}, - {PTN_DBMT_USER_EXIST, "DBMT user (%s) already exist."}, - {PTN_DBMT_USER_NOT_DEL, "DBMT user (%s) is not allowed to be deleted."}, - {PTN_DBMT_USER_PWD_ERR, "Password (%s) is not correct."}, - {PTN_DB_NOT_AUTH, "Database (%s) is not authorized to DBMT user (%s)."}, - { - PTN_DB_ALREADY_AUTH, - "Database (%s) is already authorized to DBMT user (%s)." - }, - {PTN_DB_NOT_EXIST, "Database (%s) does not exist."}, - {PTN_DB_ADD_TWICE, "Database (%s) has been add twice."}, - {PTN_BROKER_ADDR_ERR, "Broker address (%s) format is wrong."}, - {PTN_MEM_ALLOC_ERR, "Memory Allocate Error!"}, - {PTN_UNDEFINE, NULL} -}; - -const char * -get_msg_by_id (int ptn_id) -{ - int i; - - for (i = 0; msg_str_ptn[i].ptn_id != PTN_UNDEFINE; i++) - { - if ((int) msg_str_ptn[i].ptn_id == ptn_id) - { - return msg_str_ptn[i].ptn_msg; - } - } - - return NULL; -} - -int -run_task (const char *task_name, int argc, const char *argv[]) -{ - int i; - int retval = E_FAILURE; - - for (i = 0; cmd_info[i].cmd_name != NULL; i++) - { - if (task_name != NULL && strcmp (task_name, cmd_info[i].cmd_name) == 0) - { - retval = (*cmd_info[i].cmd_func) (argc, argv); - return retval; - } - } - - return E_CMD_NOT_EXIST; -} - -char * -utility_make_getopt_optstring (struct option *opt_array, char *buf) -{ - int i; - char *p = buf; - - for (i = 0; opt_array[i].name; i++) - { - if (opt_array[i].val < 255) - { - *p++ = (char) opt_array[i].val; - if (opt_array[i].has_arg) - { - *p++ = ':'; - } - } - } - *p = '\0'; - return buf; -} - -void -print_cmd (void) -{ - int i; - - printf ("Available Utilities:\n"); - - for (i = 0; cmd_info[i].cmd_name != NULL; i++) - { - printf (" %s\n", cmd_info[i].cmd_name); - } - - printf ("\n"); - - return; -} - -int -get_cmdname_by_id (int cmd_id, char *cmd_name, int buf_size) -{ - int i; - - for (i = 0; cmd_info[i].cmd_name != NULL; i++) - { - if (cmd_id == (int) cmd_info[i].cmd_id) - { - snprintf (cmd_name, buf_size - 1, cmd_info[i].cmd_name); - return 0; - } - } - - return -1; -} - -void -print_help_msg (int cmd_id) -{ - const char *pattern = " %s, %-30s%s\n"; - const char *pattern2 = "%-36s%s\n"; - const char *pattern_long_only = " %-30s%s\n"; - const char *pattern_usage = "usage: " CM_ADMIN_NAME " %s\n\n"; - - switch (cmd_id) - { - case CMD_ADDUSER: - printf ("adduser: Add a DBMT user to the cmserver.\n"); - printf (pattern_usage, - "adduser [OPTIONS] <" ARG_DBMT_USER_NAME "> <" ARG_DBMT_USER_PWD - ">"); - printf ("valid options:\n"); - printf (pattern, "-b", "--broker", - "Authority of broker, default: none; allowed:"); - printf (pattern2, " ", "none, admin, monitor"); - printf (pattern, "-c", "--dbcreate", - "Authority of creating a database, only admin user has the auth to create a database;"); - printf (pattern2, " ", "default: none; allowed: none, admin"); - printf (pattern, "-m", "--monitor", - "Authority of monitoring host & database, default: none; allowed:"); - printf (pattern2, " ", "none, admin, monitor"); - printf (pattern, "-d", "--dbinfo", - "DBINFO should be formatted as follows:"); - printf (pattern2, " ", "\";;,\""); - break; - - case CMD_DELUSER: - printf ("deluser: Delete a DBMT user from the cmserver.\n"); - printf (pattern_usage, "deluser <" ARG_DBMT_USER_NAME ">"); - break; - - case CMD_VIEWUSER: - printf ("viewuser: View DBMT user info.\n"); - printf (pattern_usage, "viewuser [" ARG_DBMT_USER_NAME "]"); - break; - - case CMD_DELDBINFO: - printf ("deldbinfo: Delete a dbinfo of the specified DBMT user.\n"); - printf (pattern_usage, - "deldbinfo <" ARG_DBMT_USER_NAME "> <" ARG_DB_NAME ">"); - break; - - case CMD_ADDDBINFO: - printf ("adddbinfo: Add a dbinfo to a DBMT user.\n"); - printf (pattern_usage, - "adddbinfo [OPTIONS] <" ARG_DBMT_USER_NAME "> <" ARG_DB_NAME - ">"); - printf ("valid options:\n"); - printf (pattern, "-u", "--uid", - "Uid is the dbuser of the database; default: dba"); - printf (pattern, "-h", "--host", - "Host is the ipaddr of the broker; default: localhost"); - printf (pattern, "-p", "--port", - "Port is the port of broker; default: 30000"); - break; - - case CMD_CHGDBINFO: - printf ("changedbinfo: Add a dbinfo to a DBMT user.\n"); - printf (pattern_usage, - "changedbinfo [OPTIONS] <" ARG_DBMT_USER_NAME "> <" ARG_DB_NAME - ">"); - printf ("valid options:\n"); - printf (pattern, "-u", "--uid ", "Uid is the dbuser of the database"); - printf (pattern, "-h", "--host", "Host is the ipaddr of the broker"); - printf (pattern, "-p", "--port", "Port is the port of broker"); - break; - - case CMD_CHGUSER_PWD: - printf - ("changeuserpwd: Change the password of the specified DBMT user.\n"); - printf (pattern_usage, - "changeuserpwd [OPTIONS] <" ARG_DBMT_USER_NAME ">"); - printf ("valid options:\n"); - printf (pattern, "-o", "--oldpass", "Old password of the DBMT user."); - printf (pattern, "-n", "--newpass", "New password of the DBMT user."); - printf (pattern_long_only, "--adminpass", - "Admin password should be set when old password is not offered."); - break; - - case CMD_CHGUSER_AUTH: - printf - ("changeuserauth: Change the authority info of the DBMT user.\n"); - printf (pattern_usage, - "changeuserauth [OPTIONS] <" ARG_DBMT_USER_NAME ">"); - printf ("valid options:\n"); - printf (pattern, "-b", "--broker", "Authority of broker; allowed:"); - printf (pattern2, " ", "none, admin, monitor"); - printf (pattern, "-c", "--dbcreate", - "Authority of creating a database, only admin user has the authority to create database;"); - printf (pattern2, " ", "allowed: none, admin"); - printf (pattern, "-m", "--monitor", - "Authority of monitoring host and database; allowed:"); - printf (pattern2, " ", "none, admin, monitor"); - break; - - default: - break; - } - - return; -} diff --git a/server/src/cm_cmd_util.h b/server/src/cm_cmd_util.h deleted file mode 100644 index 6160452..0000000 --- a/server/src/cm_cmd_util.h +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. - * - * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/* - * cm_cmd_util.h - - */ - -#ifndef _CM_CMD_UTIL_H_ -#define _CM_CMD_UTIL_H_ - -#ifdef HAVE_GETOPT_H -#include -#else -#include "getopt.h" -#endif - - -/* typedef struct option GETOPT_LONG; */ - -/* - * CM_ADMIN COMMON MACRO. - */ -#define CM_ADMIN_NAME "cm_admin" -#define CM_ADMIN_VERSION "0.1" - -#define OPT_STR_LEN 128 -#define DBNAME_LEN 128 -#define UID_LEN 18 -#define PORT_LEN 8 -#define BROKER_ADDR_LEN MAXHOSTNAMELEN + PORT_LEN + 1 - -#define ADMIN_FLAG 1 - -#ifndef PATH_MAX -#define PATH_MAX 1024 -#endif - -#ifndef LINE_MAX -#define LINE_MAX 1024 -#endif - -#define SQL_STAT_LEN 1024 -#define DBMT_USER_ADMIN_NAME "admin" -#define AUTH_NUM_TOTAL 3 - - -/* - * CM_ADMIN ARG NAME DEFINITION. - */ - -#define ARG_DBMT_USER_NAME "dbmtuser-name" -#define ARG_DBMT_USER_PWD "dbmtuser-password" -#define ARG_DB_NAME "dbname" - -#define ARG_UNICAS "broker" -#define ARG_DBCREATE "dbcreate" -#define ARG_MONITOR "monitor" - -#define ARG_AUTH "auth" -#define ARG_UID "uid" -#define ARG_HOST "host" -#define ARG_PORT "port" - -#define ARG_OLD_PASS "old" -#define ARG_NEW_PASS "new" -#define ARG_ADMIN_PASS "adminpass" - -#define ARG_DB_INFO "dbinfo" - - -/* - * CM_ADMIN ERROR ID DEFINITION. - */ -#define E_SUCCESS 2000 -#define E_FAILURE 2001 -#define E_CMD_NOT_EXIST 2002 -#define E_ARG_ERR 2003 - -typedef enum -{ - PTN_ARG_MISS, - PTN_ARG_MORE, - PTN_ARG_NUM_ERR, - PTN_ARG_FORMAT_ERR, - PTN_ARG_MUST_APPEAR_ERR, - PTN_DBMT_USER_NOT_EXIST, - PTN_DBMT_USER_EXIST, - PTN_DBMT_USER_NOT_DEL, - PTN_DBMT_USER_PWD_ERR, - PTN_DB_NOT_AUTH, - PTN_DB_ALREADY_AUTH, - PTN_DB_NOT_EXIST, - PTN_DB_ADD_TWICE, - PTN_BROKER_ADDR_ERR, - PTN_MEM_ALLOC_ERR, - PTN_UNDEFINE, -} PTN_ID; - -void print_cmd (void); -void print_help_msg (int cmd_id); - -int run_task (const char *task_name, int argc, const char *argv[]); -int get_cmdname_by_id (int cmd_id, char *cmd_name, int buf_size); -const char *get_msg_by_id (int ptn_id); -char *utility_make_getopt_optstring (struct option *opt_array, char *buf); -#endif /* !_CM_CMD_UTIL_H_ */ diff --git a/server/src/cm_compress.h b/server/src/cm_compress.h deleted file mode 100644 index cf58c48..0000000 --- a/server/src/cm_compress.h +++ /dev/null @@ -1,6747 +0,0 @@ -/* miniz.c v1.12 - public domain deflate/inflate, zlib-subset, ZIP reading/writing/appending, PNG writing - See "unlicense" statement at the end of this file. - Rich Geldreich , last updated April 12, 2012 - Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt - - Most API's defined in miniz.c are optional. For example, to disable the archive related functions just define - MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO (see the list below for more macros). - - * Change History - 4/12/12 v1.12 - More comments, added low-level example5.c, fixed a couple minor level_and_flags issues in the archive API's. - level_and_flags can now be set to MZ_DEFAULT_COMPRESSION. Thanks to Bruce Dawson for the feedback/bug report. - 5/28/11 v1.11 - Added statement from unlicense.org - 5/27/11 v1.10 - Substantial compressor optimizations: - Level 1 is now ~4x faster than before. The L1 compressor's throughput now varies between 70-110MB/sec. on a - Core i7 (actual throughput varies depending on the type of data, and x64 vs. x86). - Improved baseline L2-L9 compression perf. Also, greatly improved compression perf. issues on some file types. - Refactored the compression code for better readability and maintainability. - Added level 10 compression level (L10 has slightly better ratio than level 9, but could have a potentially large - drop in throughput on some files). - 5/15/11 v1.09 - Initial stable release. - - * Low-level Deflate/Inflate implementation notes: - - Compression: Use the "tdefl" API's. The compressor supports raw, static, and dynamic blocks, lazy or - greedy parsing, match length filtering, RLE-only, and Huffman-only streams. It performs and compresses - approximately as well as zlib. - - Decompression: Use the "tinfl" API's. The entire decompressor is implemented as a single function - coroutine: see tinfl_decompress(). It supports decompression into a 32KB (or larger power of 2) wrapping buffer, or into a memory - block large enough to hold the entire file. - - The low-level tdefl/tinfl API's do not make any use of dynamic memory allocation. - - * zlib-style API notes: - - miniz.c implements a fairly large subset of zlib. There's enough functionality present for it to be a drop-in - zlib replacement in many apps: - The z_stream struct, optional memory allocation callbacks - deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound - inflateInit/inflateInit2/inflate/inflateEnd - compress, compress2, compressBound, uncompress - CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly routines. - Supports raw deflate streams or standard zlib streams with adler-32 checking. - - Limitations: - The callback API's are not implemented yet. No support for gzip headers or zlib static dictionaries. - I've tried to closely emulate zlib's various flavors of stream flushing and return status codes, but - there are no guarantees that miniz.c pulls this off perfectly. - - * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function, originally written by - Alex Evans. Supports 1-4 bytes/pixel images. - - * ZIP archive API notes: - - The ZIP archive API's where designed with simplicity and efficiency in mind, with just enough abstraction to - get the job done with minimal fuss. There are simple API's to retrieve file information, read files from - existing archives, create new archives, append new files to existing archives, or clone archive data from - one archive to another. It supports archives located in memory or the heap, on disk (using stdio.h), - or you can specify custom file read/write callbacks. - - - Archive reading: Just call this function to read a single file from a disk archive: - - void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, - size_t *pSize, mz_uint zip_flags); - - For more complex cases, use the "mz_zip_reader" functions. Upon opening an archive, the entire central - directory is located and read as-is into memory, and subsequent file access only occurs when reading individual files. - - - Archives file scanning: The simple way is to use this function to scan a loaded archive for a specific file: - - int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); - - The locate operation can optionally check file comments too, which (as one example) can be used to identify - multiple versions of the same file in an archive. This function uses a simple linear search through the central - directory, so it's not very fast. - - Alternately, you can iterate through all the files in an archive (using mz_zip_reader_get_num_files()) and - retrieve detailed info on each file by calling mz_zip_reader_file_stat(). - - - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer immediately writes compressed file data - to disk and builds an exact image of the central directory in memory. The central directory image is written - all at once at the end of the archive file when the archive is finalized. - - The archive writer can optionally align each file's local header and file data to any power of 2 alignment, - which can be useful when the archive will be read from optical media. Also, the writer supports placing - arbitrary data blobs at the very beginning of ZIP archives. Archives written using either feature are still - readable by any ZIP tool. - - - Archive appending: The simple way to add a single file to an archive is to call this function: - - mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, - const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); - - The archive will be created if it doesn't already exist, otherwise it'll be appended to. - Note the appending is done in-place and is not an atomic operation, so if something goes wrong - during the operation it's possible the archive could be left without a central directory (although the local - file headers and file data will be fine, so the archive will be recoverable). - - For more complex archive modification scenarios: - 1. The safest way is to use a mz_zip_reader to read the existing archive, cloning only those bits you want to - preserve into a new archive using using the mz_zip_writer_add_from_zip_reader() function (which compiles the - compressed file data as-is). When you're done, delete the old archive and rename the newly written archive, and - you're done. This is safe but requires a bunch of temporary disk space or heap memory. - - 2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using mz_zip_writer_init_from_reader(), - append new files as needed, then finalize the archive which will write an updated central directory to the - original archive. (This is basically what mz_zip_add_mem_to_archive_file_in_place() does.) There's a - possibility that the archive's central directory could be lost with this method if anything goes wrong, though. - - - ZIP archive support limitations: - No zip64 or spanning support. Extraction functions can only handle unencrypted, stored or deflated files. - Requires streams capable of seeking. - - * This is a header file library, like stb_image.c. To get only a header file, either cut and paste the - below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then include miniz.c from it. - - * Important: For best perf. be sure to customize the below macros for your target platform: - #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 - #define MINIZ_LITTLE_ENDIAN 1 - #define MINIZ_HAS_64BIT_REGISTERS 1 -*/ - -#ifndef MINIZ_HEADER_INCLUDED -#define MINIZ_HEADER_INCLUDED - -#include - -// Defines to completely disable specific portions of miniz.c: -// If all macros here are defined the only functionality remaining will be CRC-32, adler-32, tinfl, and tdefl. - -// Define MINIZ_NO_STDIO to disable all usage and any functions which rely on stdio for file I/O. -//#define MINIZ_NO_STDIO - -// If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able to get the current time, or -// get/set file times. -//#define MINIZ_NO_TIME - -// Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's. -//#define MINIZ_NO_ARCHIVE_APIS - -// Define MINIZ_NO_ARCHIVE_APIS to disable all writing related ZIP archive API's. -//#define MINIZ_NO_ARCHIVE_WRITING_APIS - -// Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression API's. -//#define MINIZ_NO_ZLIB_APIS - -// Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent conflicts against stock zlib. -//#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES - -// Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc. -// Note if MINIZ_NO_MALLOC is defined then the user must always provide custom user alloc/free/realloc -// callbacks to the zlib and archive API's, and a few stand-alone helper API's which don't provide custom user -// functions (such as tdefl_compress_mem_to_heap() and tinfl_decompress_mem_to_heap()) won't work. -//#define MINIZ_NO_MALLOC - -#if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || defined(__i386) || defined(__i486__) || defined(__i486) || defined(i386) || defined(__ia64__) || defined(__x86_64__) -// MINIZ_X86_OR_X64_CPU is only used to help set the below macros. -#define MINIZ_X86_OR_X64_CPU 1 -#endif - -#if (__BYTE_ORDER__==__ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU -// Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. -#define MINIZ_LITTLE_ENDIAN 1 -#endif - -#if MINIZ_X86_OR_X64_CPU -// Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient integer loads and stores from unaligned addresses. -#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 -#endif - -#if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || defined(__LP64__) || defined(__ia64__) || defined(__x86_64__) -// Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are reasonably fast (and don't involve compiler generated calls to helper functions). -#define MINIZ_HAS_64BIT_REGISTERS 1 -#endif - -#ifdef __cplusplus -extern "C" -{ -#endif - -// ------------------- zlib-style API Definitions. - -// For more compatibility with zlib, miniz.c uses unsigned long for some parameters/struct members. - typedef unsigned long mz_ulong; - -// Heap allocation callbacks. -// Note that mz_alloc_func parameter types purpsosely differ from zlib's: items/size is size_t, not unsigned long. - typedef void *(*mz_alloc_func) (void *opaque, size_t items, size_t size); - typedef void (*mz_free_func) (void *opaque, void *address); - typedef void *(*mz_realloc_func) (void *opaque, void *address, size_t items, - size_t size); - -#define MZ_ADLER32_INIT (1) -// mz_adler32() returns the initial adler-32 value to use when called with ptr==NULL. - mz_ulong mz_adler32 (mz_ulong adler, const unsigned char *ptr, - size_t buf_len); - -#define MZ_CRC32_INIT (0) -// mz_crc32() returns the initial CRC-32 value to use when called with ptr==NULL. - mz_ulong mz_crc32 (mz_ulong crc, const unsigned char *ptr, size_t buf_len); - -// Compression strategies. - enum - { MZ_DEFAULT_STRATEGY = 0, MZ_FILTERED = 1, MZ_HUFFMAN_ONLY = 2, MZ_RLE = - 3, MZ_FIXED = 4 - }; - -// Method -#define MZ_DEFLATED 8 - -#ifndef MINIZ_NO_ZLIB_APIS - -#define MZ_VERSION "9.1.12" -#define MZ_VERNUM 0x91C0 -#define MZ_VER_MAJOR 9 -#define MZ_VER_MINOR 1 -#define MZ_VER_REVISION 12 -#define MZ_VER_SUBREVISION 0 - -// Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The other values are for advanced use (refer to the zlib docs). - enum - { MZ_NO_FLUSH = 0, MZ_PARTIAL_FLUSH = 1, MZ_SYNC_FLUSH = 2, MZ_FULL_FLUSH = - 3, MZ_FINISH = 4, MZ_BLOCK = 5 - }; - -// Return status codes. MZ_PARAM_ERROR is non-standard. - enum - { MZ_OK = 0, MZ_STREAM_END = 1, MZ_NEED_DICT = 2, MZ_ERRNO = - -1, MZ_STREAM_ERROR = -2, MZ_DATA_ERROR = -3, MZ_MEM_ERROR = - -4, MZ_BUF_ERROR = -5, MZ_VERSION_ERROR = -6, MZ_PARAM_ERROR = -10000 - }; - -// Compression levels: 0-9 are the standard zlib-style levels, 10 is best possible compression (not zlib compatible, and may be very slow), MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL. - enum - { MZ_NO_COMPRESSION = 0, MZ_BEST_SPEED = 1, MZ_BEST_COMPRESSION = - 9, MZ_UBER_COMPRESSION = 10, MZ_DEFAULT_LEVEL = - 6, MZ_DEFAULT_COMPRESSION = -1 - }; - -// Window bits -#define MZ_DEFAULT_WINDOW_BITS 15 - - struct mz_internal_state; - -// Compression/decompression stream struct. - typedef struct mz_stream_s - { - const unsigned char *next_in; // pointer to next byte to read - unsigned int avail_in; // number of bytes available at next_in - mz_ulong total_in; // total number of bytes consumed so far - - unsigned char *next_out; // pointer to next byte to write - unsigned int avail_out; // number of bytes that can be written to next_out - mz_ulong total_out; // total number of bytes produced so far - - char *msg; // error msg (unused) - struct mz_internal_state *state; // internal state, allocated by zalloc/zfree - - mz_alloc_func zalloc; // optional heap allocation function (defaults to malloc) - mz_free_func zfree; // optional heap free function (defaults to free) - void *opaque; // heap alloc function user pointer - - int data_type; // data_type (unused) - mz_ulong adler; // adler32 of the source or uncompressed data - mz_ulong reserved; // not used - } mz_stream; - - typedef mz_stream *mz_streamp; - -// Returns the version string of miniz.c. - const char *mz_version (void); - -// mz_deflateInit() initializes a compressor with default options: -// Parameters: -// pStream must point to an initialized mz_stream struct. -// level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION]. -// level 1 enables a specially optimized compression function that's been optimized purely for performance, not ratio. -// (This special func. is currently only enabled when MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.) -// Return values: -// MZ_OK on success. -// MZ_STREAM_ERROR if the stream is bogus. -// MZ_PARAM_ERROR if the input parameters are bogus. -// MZ_MEM_ERROR on out of memory. - int mz_deflateInit (mz_streamp pStream, int level); - -// mz_deflateInit2() is like mz_deflate(), except with more control: -// Additional parameters: -// method must be MZ_DEFLATED -// window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no header or footer) -// mem_level must be between [1, 9] (it's checked but ignored by miniz.c) - int mz_deflateInit2 (mz_streamp pStream, int level, int method, - int window_bits, int mem_level, int strategy); - -// Quickly resets a compressor without having to reallocate anything. Same as calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2(). - int mz_deflateReset (mz_streamp pStream); - -// mz_deflate() compresses the input to output, consuming as much of the input and producing as much output as possible. -// Parameters: -// pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. -// flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or MZ_FINISH. -// Return values: -// MZ_OK on success (when flushing, or if more input is needed but not available, and/or there's more output to be written but the output buffer is full). -// MZ_STREAM_END if all input has been consumed and all output bytes have been written. Don't call mz_deflate() on the stream anymore. -// MZ_STREAM_ERROR if the stream is bogus. -// MZ_PARAM_ERROR if one of the parameters is invalid. -// MZ_BUF_ERROR if no forward progress is possible because the input and/or output buffers are empty. (Fill up the input buffer or free up some output space and try again.) - int mz_deflate (mz_streamp pStream, int flush); - -// mz_deflateEnd() deinitializes a compressor: -// Return values: -// MZ_OK on success. -// MZ_STREAM_ERROR if the stream is bogus. - int mz_deflateEnd (mz_streamp pStream); - -// mz_deflateBound() returns a (very) conservative upper bound on the amount of data that could be generated by deflate(), assuming flush is set to only MZ_NO_FLUSH or MZ_FINISH. - mz_ulong mz_deflateBound (mz_streamp pStream, mz_ulong source_len); - -// Single-call compression functions mz_compress() and mz_compress2(): -// Returns MZ_OK on success, or one of the error codes from mz_deflate() on failure. - int mz_compress (unsigned char *pDest, mz_ulong * pDest_len, - const unsigned char *pSource, mz_ulong source_len); - int mz_compress2 (unsigned char *pDest, mz_ulong * pDest_len, - const unsigned char *pSource, mz_ulong source_len, - int level); - -// mz_compressBound() returns a (very) conservative upper bound on the amount of data that could be generated by calling mz_compress(). - mz_ulong mz_compressBound (mz_ulong source_len); - -// Initializes a decompressor. - int mz_inflateInit (mz_streamp pStream); - -// mz_inflateInit2() is like mz_inflateInit() with an additional option that controls the window size and whether or not the stream has been wrapped with a zlib header/footer: -// window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate). - int mz_inflateInit2 (mz_streamp pStream, int window_bits); - -// Decompresses the input stream to the output, consuming only as much of the input as needed, and writing as much to the output as possible. -// Parameters: -// pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. -// flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH. -// On the first call, if flush is MZ_FINISH it's assumed the input and output buffers are both sized large enough to decompress the entire stream in a single call (this is slightly faster). -// MZ_FINISH implies that there are no more source bytes available beside what's already in the input buffer, and that the output buffer is large enough to hold the rest of the decompressed data. -// Return values: -// MZ_OK on success. Either more input is needed but not available, and/or there's more output to be written but the output buffer is full. -// MZ_STREAM_END if all needed input has been consumed and all output bytes have been written. For zlib streams, the adler-32 of the decompressed data has also been verified. -// MZ_STREAM_ERROR if the stream is bogus. -// MZ_DATA_ERROR if the deflate stream is invalid. -// MZ_PARAM_ERROR if one of the parameters is invalid. -// MZ_BUF_ERROR if no forward progress is possible because the input buffer is empty but the inflater needs more input to continue, or if the output buffer is not large enough. Call mz_inflate() again -// with more input data, or with more room in the output buffer (except when using single call decompression, described above). - int mz_inflate (mz_streamp pStream, int flush); - -// Deinitializes a decompressor. - int mz_inflateEnd (mz_streamp pStream); - -// Single-call decompression. -// Returns MZ_OK on success, or one of the error codes from mz_inflate() on failure. - int mz_uncompress (unsigned char *pDest, mz_ulong * pDest_len, - const unsigned char *pSource, mz_ulong source_len); - -// Returns a string description of the specified error code, or NULL if the error code is invalid. - const char *mz_error (int err); - -// Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used as a drop-in replacement for the subset of zlib that miniz.c supports. -// Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you use zlib in the same project. -#ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES - typedef unsigned char Byte; - typedef unsigned int uInt; - typedef mz_ulong uLong; - typedef Byte Bytef; - typedef uInt uIntf; - typedef char charf; - typedef int intf; - typedef void *voidpf; - typedef uLong uLongf; - typedef void *voidp; - typedef void *const voidpc; -#define Z_NULL 0 -#define Z_NO_FLUSH MZ_NO_FLUSH -#define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH -#define Z_SYNC_FLUSH MZ_SYNC_FLUSH -#define Z_FULL_FLUSH MZ_FULL_FLUSH -#define Z_FINISH MZ_FINISH -#define Z_BLOCK MZ_BLOCK -#define Z_OK MZ_OK -#define Z_STREAM_END MZ_STREAM_END -#define Z_NEED_DICT MZ_NEED_DICT -#define Z_ERRNO MZ_ERRNO -#define Z_STREAM_ERROR MZ_STREAM_ERROR -#define Z_DATA_ERROR MZ_DATA_ERROR -#define Z_MEM_ERROR MZ_MEM_ERROR -#define Z_BUF_ERROR MZ_BUF_ERROR -#define Z_VERSION_ERROR MZ_VERSION_ERROR -#define Z_PARAM_ERROR MZ_PARAM_ERROR -#define Z_NO_COMPRESSION MZ_NO_COMPRESSION -#define Z_BEST_SPEED MZ_BEST_SPEED -#define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION -#define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION -#define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY -#define Z_FILTERED MZ_FILTERED -#define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY -#define Z_RLE MZ_RLE -#define Z_FIXED MZ_FIXED -#define Z_DEFLATED MZ_DEFLATED -#define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS -#define alloc_func mz_alloc_func -#define free_func mz_free_func -#define internal_state mz_internal_state -#define z_stream mz_stream -#define deflateInit mz_deflateInit -#define deflateInit2 mz_deflateInit2 -#define deflateReset mz_deflateReset -#define deflate mz_deflate -#define deflateEnd mz_deflateEnd -#define deflateBound mz_deflateBound -#define compress mz_compress -#define compress2 mz_compress2 -#define compressBound mz_compressBound -#define inflateInit mz_inflateInit -#define inflateInit2 mz_inflateInit2 -#define inflate mz_inflate -#define inflateEnd mz_inflateEnd -#define uncompress mz_uncompress -#define crc32 mz_crc32 -#define adler32 mz_adler32 -#define MAX_WBITS 15 -#define MAX_MEM_LEVEL 9 -#define zError mz_error -#define ZLIB_VERSION MZ_VERSION -#define ZLIB_VERNUM MZ_VERNUM -#define ZLIB_VER_MAJOR MZ_VER_MAJOR -#define ZLIB_VER_MINOR MZ_VER_MINOR -#define ZLIB_VER_REVISION MZ_VER_REVISION -#define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION -#define zlibVersion mz_version -#define zlib_version mz_version() -#endif // #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES - -#endif // MINIZ_NO_ZLIB_APIS - -// ------------------- Types and macros - - typedef unsigned char mz_uint8; - typedef signed short mz_int16; - typedef unsigned short mz_uint16; - typedef unsigned int mz_uint32; - typedef unsigned int mz_uint; - typedef long long mz_int64; - typedef unsigned long long mz_uint64; - typedef int mz_bool; - -#define MZ_FALSE (0) -#define MZ_TRUE (1) - -// Works around MSVC's spammy "warning C4127: conditional expression is constant" message. -#define MZ_MACRO_END while (0, 0) - -// ------------------- ZIP archive reading/writing - -#ifndef MINIZ_NO_ARCHIVE_APIS - - enum - { - MZ_ZIP_MAX_IO_BUF_SIZE = 64 * 1024, - MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 260, - MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 256 - }; - - typedef struct - { - mz_uint32 m_file_index; - mz_uint32 m_central_dir_ofs; - mz_uint16 m_version_made_by; - mz_uint16 m_version_needed; - mz_uint16 m_bit_flag; - mz_uint16 m_method; -#ifndef MINIZ_NO_TIME - time_t m_time; -#endif - mz_uint32 m_crc32; - mz_uint64 m_comp_size; - mz_uint64 m_uncomp_size; - mz_uint16 m_internal_attr; - mz_uint32 m_external_attr; - mz_uint64 m_local_header_ofs; - mz_uint32 m_comment_size; - char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE]; - char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE]; - } mz_zip_archive_file_stat; - - typedef size_t (*mz_file_read_func) (void *pOpaque, mz_uint64 file_ofs, - void *pBuf, size_t n); - typedef size_t (*mz_file_write_func) (void *pOpaque, mz_uint64 file_ofs, - const void *pBuf, size_t n); - - struct mz_zip_internal_state_tag; - typedef struct mz_zip_internal_state_tag mz_zip_internal_state; - - typedef enum - { - MZ_ZIP_MODE_INVALID = 0, - MZ_ZIP_MODE_READING = 1, - MZ_ZIP_MODE_WRITING = 2, - MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3 - } mz_zip_mode; - - typedef struct - { - mz_uint64 m_archive_size; - mz_uint64 m_central_directory_file_ofs; - mz_uint m_total_files; - mz_zip_mode m_zip_mode; - - mz_uint m_file_offset_alignment; - - mz_alloc_func m_pAlloc; - mz_free_func m_pFree; - mz_realloc_func m_pRealloc; - void *m_pAlloc_opaque; - - mz_file_read_func m_pRead; - mz_file_write_func m_pWrite; - void *m_pIO_opaque; - - mz_zip_internal_state *m_pState; - - } mz_zip_archive; - - typedef enum - { - MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100, - MZ_ZIP_FLAG_IGNORE_PATH = 0x0200, - MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400, - MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800 - } mz_zip_flags; - -// ZIP archive reading - -// Inits a ZIP archive reader. -// These functions read and validate the archive's central directory. - mz_bool mz_zip_reader_init (mz_zip_archive * pZip, mz_uint64 size, - mz_uint32 flags); - mz_bool mz_zip_reader_init_mem (mz_zip_archive * pZip, const void *pMem, - size_t size, mz_uint32 flags); - -#ifndef MINIZ_NO_STDIO - mz_bool mz_zip_reader_init_file (mz_zip_archive * pZip, - const char *pFilename, mz_uint32 flags); -#endif - -// Returns the total number of files in the archive. - mz_uint mz_zip_reader_get_num_files (mz_zip_archive * pZip); - -// Returns detailed information about an archive file entry. - mz_bool mz_zip_reader_file_stat (mz_zip_archive * pZip, mz_uint file_index, - mz_zip_archive_file_stat * pStat); - -// Determines if an archive file entry is a directory entry. - mz_bool mz_zip_reader_is_file_a_directory (mz_zip_archive * pZip, - mz_uint file_index); - mz_bool mz_zip_reader_is_file_encrypted (mz_zip_archive * pZip, - mz_uint file_index); - -// Retrieves the filename of an archive file entry. -// Returns the number of bytes written to pFilename, or if filename_buf_size is 0 this function returns the number of bytes needed to fully store the filename. - mz_uint mz_zip_reader_get_filename (mz_zip_archive * pZip, - mz_uint file_index, char *pFilename, - mz_uint filename_buf_size); - -// Attempts to locates a file in the archive's central directory. -// Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH -// Returns -1 if the file cannot be found. - int mz_zip_reader_locate_file (mz_zip_archive * pZip, const char *pName, - const char *pComment, mz_uint flags); - -// Extracts a archive file to a memory buffer using no memory allocation. - mz_bool mz_zip_reader_extract_to_mem_no_alloc (mz_zip_archive * pZip, - mz_uint file_index, - void *pBuf, size_t buf_size, - mz_uint flags, - void *pUser_read_buf, - size_t user_read_buf_size); - mz_bool mz_zip_reader_extract_file_to_mem_no_alloc (mz_zip_archive * pZip, - const char *pFilename, - void *pBuf, - size_t buf_size, - mz_uint flags, - void *pUser_read_buf, - size_t - user_read_buf_size); - -// Extracts a archive file to a memory buffer. - mz_bool mz_zip_reader_extract_to_mem (mz_zip_archive * pZip, - mz_uint file_index, void *pBuf, - size_t buf_size, mz_uint flags); - mz_bool mz_zip_reader_extract_file_to_mem (mz_zip_archive * pZip, - const char *pFilename, - void *pBuf, size_t buf_size, - mz_uint flags); - -// Extracts a archive file to a dynamically allocated heap buffer. - void *mz_zip_reader_extract_to_heap (mz_zip_archive * pZip, - mz_uint file_index, size_t * pSize, - mz_uint flags); - void *mz_zip_reader_extract_file_to_heap (mz_zip_archive * pZip, - const char *pFilename, - size_t * pSize, mz_uint flags); - -// Extracts a archive file using a callback function to output the file's data. - mz_bool mz_zip_reader_extract_to_callback (mz_zip_archive * pZip, - mz_uint file_index, - mz_file_write_func pCallback, - void *pOpaque, mz_uint flags); - mz_bool mz_zip_reader_extract_file_to_callback (mz_zip_archive * pZip, - const char *pFilename, - mz_file_write_func - pCallback, void *pOpaque, - mz_uint flags); - -#ifndef MINIZ_NO_STDIO -// Extracts a archive file to a disk file and sets its last accessed and modified times. -// This function only extracts files, not archive directory records. - mz_bool mz_zip_reader_extract_to_file (mz_zip_archive * pZip, - mz_uint file_index, - const char *pDst_filename, - mz_uint flags); - mz_bool mz_zip_reader_extract_file_to_file (mz_zip_archive * pZip, - const char *pArchive_filename, - const char *pDst_filename, - mz_uint flags); -#endif - -// Ends archive reading, freeing all allocations, and closing the input archive file if mz_zip_reader_init_file() was used. - mz_bool mz_zip_reader_end (mz_zip_archive * pZip); - -// ZIP archive writing - -#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS - -// Inits a ZIP archive writer. - mz_bool mz_zip_writer_init (mz_zip_archive * pZip, mz_uint64 existing_size); - mz_bool mz_zip_writer_init_heap (mz_zip_archive * pZip, - size_t size_to_reserve_at_beginning, - size_t initial_allocation_size); - -#ifndef MINIZ_NO_STDIO - mz_bool mz_zip_writer_init_file (mz_zip_archive * pZip, - const char *pFilename, - mz_uint64 size_to_reserve_at_beginning); -#endif - -// Converts a ZIP archive reader object into a writer object, to allow efficient in-place file appends to occur on an existing archive. -// For archives opened using mz_zip_reader_init_file, pFilename must be the archive's filename so it can be reopened for writing. If the file can't be reopened, mz_zip_reader_end() will be called. -// For archives opened using mz_zip_reader_init_mem, the memory block must be growable using the realloc callback (which defaults to realloc unless you've overridden it). -// Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's user provided m_pWrite function cannot be NULL. -// Note: In-place archive modification is not recommended unless you know what you're doing, because if execution stops or something goes wrong before -// the archive is finalized the file's central directory will be hosed. - mz_bool mz_zip_writer_init_from_reader (mz_zip_archive * pZip, - const char *pFilename); - -// Adds the contents of a memory buffer to an archive. These functions record the current local time into the archive. -// To add a directory entry, call this method with an archive name ending in a forwardslash with empty buffer. -// level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. - mz_bool mz_zip_writer_add_mem (mz_zip_archive * pZip, - const char *pArchive_name, const void *pBuf, - size_t buf_size, mz_uint level_and_flags); - mz_bool mz_zip_writer_add_mem_ex (mz_zip_archive * pZip, - const char *pArchive_name, - const void *pBuf, size_t buf_size, - const void *pComment, - mz_uint16 comment_size, - mz_uint level_and_flags, - mz_uint64 uncomp_size, - mz_uint32 uncomp_crc32); - -#ifndef MINIZ_NO_STDIO -// Adds the contents of a disk file to an archive. This function also records the disk file's modified time into the archive. -// level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. - mz_bool mz_zip_writer_add_file (mz_zip_archive * pZip, - const char *pArchive_name, - const char *pSrc_filename, - const void *pComment, - mz_uint16 comment_size, - mz_uint level_and_flags); -#endif - -// Adds a file to an archive by fully cloning the data from another archive. -// This function fully clones the source file's compressed data (no recompression), along with its full filename, extra data, and comment fields. - mz_bool mz_zip_writer_add_from_zip_reader (mz_zip_archive * pZip, - mz_zip_archive * pSource_zip, - mz_uint file_index); - -// Finalizes the archive by writing the central directory records followed by the end of central directory record. -// After an archive is finalized, the only valid call on the mz_zip_archive struct is mz_zip_writer_end(). -// An archive must be manually finalized by calling this function for it to be valid. - mz_bool mz_zip_writer_finalize_archive (mz_zip_archive * pZip); - mz_bool mz_zip_writer_finalize_heap_archive (mz_zip_archive * pZip, - void **pBuf, size_t * pSize); - -// Ends archive writing, freeing all allocations, and closing the output file if mz_zip_writer_init_file() was used. -// Note for the archive to be valid, it must have been finalized before ending. - mz_bool mz_zip_writer_end (mz_zip_archive * pZip); - -// Misc. high-level helper functions: - -// mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) appends a memory blob to a ZIP archive. -// level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. - mz_bool mz_zip_add_mem_to_archive_file_in_place (const char *pZip_filename, - const char *pArchive_name, - const void *pBuf, - size_t buf_size, - const void *pComment, - mz_uint16 comment_size, - mz_uint level_and_flags); - -// Reads a single file from an archive into a heap block. -// Returns NULL on failure. - void *mz_zip_extract_archive_file_to_heap (const char *pZip_filename, - const char *pArchive_name, - size_t * pSize, - mz_uint zip_flags); - -#endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS - -#endif // #ifndef MINIZ_NO_ARCHIVE_APIS - -// ------------------- Low-level Decompression API Definitions - -// Decompression flags used by tinfl_decompress(). -// TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the input is a raw deflate stream. -// TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available beyond the end of the supplied input buffer. If clear, the input buffer contains all remaining input. -// TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large enough to hold the entire decompressed stream. If clear, the output buffer is at least the size of the dictionary (typically 32KB). -// TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes. - enum - { - TINFL_FLAG_PARSE_ZLIB_HEADER = 1, - TINFL_FLAG_HAS_MORE_INPUT = 2, - TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4, - TINFL_FLAG_COMPUTE_ADLER32 = 8 - }; - -// High level decompression functions: -// tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block allocated via malloc(). -// On entry: -// pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress. -// On return: -// Function returns a pointer to the decompressed data, or NULL on failure. -// *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on uncompressible data. -// The caller must free() the returned block when it's no longer needed. - void *tinfl_decompress_mem_to_heap (const void *pSrc_buf, - size_t src_buf_len, size_t * pOut_len, - int flags); - -// tinfl_decompress_mem_to_mem() decompresses a block in memory to another block in memory. -// Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success. -#define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1)) - size_t tinfl_decompress_mem_to_mem (void *pOut_buf, size_t out_buf_len, - const void *pSrc_buf, - size_t src_buf_len, int flags); - -// tinfl_decompress_mem_to_callback() decompresses a block in memory to an internal 32KB buffer, and a user provided callback function will be called to flush the buffer. -// Returns 1 on success or 0 on failure. - typedef int (*tinfl_put_buf_func_ptr) (const void *pBuf, int len, - void *pUser); - int tinfl_decompress_mem_to_callback (const void *pIn_buf, - size_t * pIn_buf_size, - tinfl_put_buf_func_ptr pPut_buf_func, - void *pPut_buf_user, int flags); - - struct tinfl_decompressor_tag; - typedef struct tinfl_decompressor_tag tinfl_decompressor; - -// Max size of LZ dictionary. -#define TINFL_LZ_DICT_SIZE 32768 - -// Return status. - typedef enum - { - TINFL_STATUS_BAD_PARAM = -3, - TINFL_STATUS_ADLER32_MISMATCH = -2, - TINFL_STATUS_FAILED = -1, - TINFL_STATUS_DONE = 0, - TINFL_STATUS_NEEDS_MORE_INPUT = 1, - TINFL_STATUS_HAS_MORE_OUTPUT = 2 - } tinfl_status; - -// Initializes the decompressor to its initial state. -#define tinfl_init(r) do { (r)->m_state = 0; } MZ_MACRO_END -#define tinfl_get_adler32(r) (r)->m_check_adler32 - -// Main low-level decompressor coroutine function. This is the only function actually needed for decompression. All the other functions are just high-level helpers for improved usability. -// This is a universal API, i.e. it can be used as a building block to build any desired higher level decompression API. In the limit case, it can be called once per every byte input or output. - tinfl_status tinfl_decompress (tinfl_decompressor * r, - const mz_uint8 * pIn_buf_next, - size_t * pIn_buf_size, - mz_uint8 * pOut_buf_start, - mz_uint8 * pOut_buf_next, - size_t * pOut_buf_size, - const mz_uint32 decomp_flags); - -// Internal/private bits follow. - enum - { - TINFL_MAX_HUFF_TABLES = 3, TINFL_MAX_HUFF_SYMBOLS_0 = - 288, TINFL_MAX_HUFF_SYMBOLS_1 = 32, TINFL_MAX_HUFF_SYMBOLS_2 = 19, - TINFL_FAST_LOOKUP_BITS = 10, TINFL_FAST_LOOKUP_SIZE = - 1 << TINFL_FAST_LOOKUP_BITS - }; - - typedef struct - { - mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0]; - mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], - m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2]; - } tinfl_huff_table; - -#if MINIZ_HAS_64BIT_REGISTERS -#define TINFL_USE_64BIT_BITBUF 1 -#endif - -#if TINFL_USE_64BIT_BITBUF - typedef mz_uint64 tinfl_bit_buf_t; -#define TINFL_BITBUF_SIZE (64) -#else - typedef mz_uint32 tinfl_bit_buf_t; -#define TINFL_BITBUF_SIZE (32) -#endif - - struct tinfl_decompressor_tag - { - mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, - m_type, m_check_adler32, m_dist, m_counter, m_num_extra, - m_table_sizes[TINFL_MAX_HUFF_TABLES]; - tinfl_bit_buf_t m_bit_buf; - size_t m_dist_from_out_buf_start; - tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES]; - mz_uint8 m_raw_header[4], - m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137]; - }; - -// ------------------- Low-level Compression API Definitions - -// Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly slower, and raw/dynamic blocks will be output more frequently). -#define TDEFL_LESS_MEMORY 0 - -// tdefl_init() compression flags logically OR'd together (low 12 bits contain the max. number of probes per dictionary search): -// TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap compression), 4095=Huffman+LZ (slowest/best compression). - enum - { - TDEFL_HUFFMAN_ONLY = 0, TDEFL_DEFAULT_MAX_PROBES = - 128, TDEFL_MAX_PROBES_MASK = 0xFFF - }; - -// TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before the deflate data, and the Adler-32 of the source data at the end. Otherwise, you'll get raw deflate data. -// TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even when not writing zlib headers). -// TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more efficient lazy parsing. -// TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's initialization time to the minimum, but the output may vary from run to run given the same input (depending on the contents of memory). -// TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1) -// TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled. -// TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables. -// TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks. - enum - { - TDEFL_WRITE_ZLIB_HEADER = 0x01000, - TDEFL_COMPUTE_ADLER32 = 0x02000, - TDEFL_GREEDY_PARSING_FLAG = 0x04000, - TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000, - TDEFL_RLE_MATCHES = 0x10000, - TDEFL_FILTER_MATCHES = 0x20000, - TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000, - TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000 - }; - -// High level compression functions: -// tdefl_compress_mem_to_heap() compresses a block in memory to a heap block allocated via malloc(). -// On entry: -// pSrc_buf, src_buf_len: Pointer and size of source block to compress. -// flags: The max match finder probes (default is 128) logically OR'd against the above flags. Higher probes are slower but improve compression. -// On return: -// Function returns a pointer to the compressed data, or NULL on failure. -// *pOut_len will be set to the compressed data's size, which could be larger than src_buf_len on uncompressible data. -// The caller must free() the returned block when it's no longer needed. - void *tdefl_compress_mem_to_heap (const void *pSrc_buf, size_t src_buf_len, - size_t * pOut_len, int flags); - -// tdefl_compress_mem_to_mem() compresses a block in memory to another block in memory. -// Returns 0 on failure. - size_t tdefl_compress_mem_to_mem (void *pOut_buf, size_t out_buf_len, - const void *pSrc_buf, size_t src_buf_len, - int flags); - -// Compresses an image to a compressed PNG file in memory. -// On entry: -// pImage, w, h, and num_chans describe the image to compress. num_chans may be 1, 2, 3, or 4. -// On return: -// Function returns a pointer to the compressed data, or NULL on failure. -// *pLen_out will be set to the size of the PNG image file. -// The caller must free() the returned heap block (which will typically be larger than *pLen_out) when it's no longer needed. - void *tdefl_write_image_to_png_file_in_memory (const void *pImage, int w, - int h, int num_chans, - size_t * pLen_out); - -// Output stream interface. The compressor uses this interface to write compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time. - typedef mz_bool (*tdefl_put_buf_func_ptr) (const void *pBuf, int len, - void *pUser); - -// tdefl_compress_mem_to_output() compresses a block to an output stream. The above helpers use this function internally. - mz_bool tdefl_compress_mem_to_output (const void *pBuf, size_t buf_len, - tdefl_put_buf_func_ptr pPut_buf_func, - void *pPut_buf_user, int flags); - - enum - { TDEFL_MAX_HUFF_TABLES = 3, TDEFL_MAX_HUFF_SYMBOLS_0 = - 288, TDEFL_MAX_HUFF_SYMBOLS_1 = 32, TDEFL_MAX_HUFF_SYMBOLS_2 = - 19, TDEFL_LZ_DICT_SIZE = 32768, TDEFL_LZ_DICT_SIZE_MASK = - TDEFL_LZ_DICT_SIZE - 1, TDEFL_MIN_MATCH_LEN = 3, TDEFL_MAX_MATCH_LEN = - 258 - }; - -// TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed output block (using static/fixed Huffman codes). -#if TDEFL_LESS_MEMORY - enum - { TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024, TDEFL_OUT_BUF_SIZE = - (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, TDEFL_MAX_HUFF_SYMBOLS = - 288, TDEFL_LZ_HASH_BITS = 12, TDEFL_LEVEL1_HASH_SIZE_MASK = - 4095, TDEFL_LZ_HASH_SHIFT = - (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = - 1 << TDEFL_LZ_HASH_BITS - }; -#else - enum - { TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, TDEFL_OUT_BUF_SIZE = - (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, TDEFL_MAX_HUFF_SYMBOLS = - 288, TDEFL_LZ_HASH_BITS = 15, TDEFL_LEVEL1_HASH_SIZE_MASK = - 4095, TDEFL_LZ_HASH_SHIFT = - (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = - 1 << TDEFL_LZ_HASH_BITS - }; -#endif - -// The low-level tdefl functions below may be used directly if the above helper functions aren't flexible enough. The low-level functions don't make any heap allocations, unlike the above helper functions. - typedef enum - { - TDEFL_STATUS_BAD_PARAM = -2, - TDEFL_STATUS_PUT_BUF_FAILED = -1, - TDEFL_STATUS_OKAY = 0, - TDEFL_STATUS_DONE = 1, - } tdefl_status; - -// Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums - typedef enum - { - TDEFL_NO_FLUSH = 0, - TDEFL_SYNC_FLUSH = 2, - TDEFL_FULL_FLUSH = 3, - TDEFL_FINISH = 4 - } tdefl_flush; - -// tdefl's compression state structure. - typedef struct - { - tdefl_put_buf_func_ptr m_pPut_buf_func; - void *m_pPut_buf_user; - mz_uint m_flags, m_max_probes[2]; - int m_greedy_parsing; - mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size; - mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, - *m_pOutput_buf_end; - mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, - m_bits_in, m_bit_buffer; - mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, - m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, - m_wants_to_finish; - tdefl_status m_prev_return_status; - const void *m_pIn_buf; - void *m_pOut_buf; - size_t *m_pIn_buf_size, *m_pOut_buf_size; - tdefl_flush m_flush; - const mz_uint8 *m_pSrc; - size_t m_src_buf_left, m_out_buf_ofs; - mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1]; - mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; - mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; - mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; - mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE]; - mz_uint16 m_next[TDEFL_LZ_DICT_SIZE]; - mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE]; - mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE]; - } tdefl_compressor; - -// Initializes the compressor. -// There is no corresponding deinit() function because the tdefl API's do not dynamically allocate memory. -// pBut_buf_func: If NULL, output data will be supplied to the specified callback. In this case, the user should call the tdefl_compress_buffer() API for compression. -// If pBut_buf_func is NULL the user should always call the tdefl_compress() API. -// flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, etc.) - tdefl_status tdefl_init (tdefl_compressor * d, - tdefl_put_buf_func_ptr pPut_buf_func, - void *pPut_buf_user, int flags); - -// Compresses a block of data, consuming as much of the specified input buffer as possible, and writing as much compressed data to the specified output buffer as possible. - tdefl_status tdefl_compress (tdefl_compressor * d, const void *pIn_buf, - size_t * pIn_buf_size, void *pOut_buf, - size_t * pOut_buf_size, tdefl_flush flush); - -// tdefl_compress_buffer() is only usable when the tdefl_init() is called with a non-NULL tdefl_put_buf_func_ptr. -// tdefl_compress_buffer() always consumes the entire input buffer. - tdefl_status tdefl_compress_buffer (tdefl_compressor * d, - const void *pIn_buf, size_t in_buf_size, - tdefl_flush flush); - - tdefl_status tdefl_get_prev_return_status (tdefl_compressor * d); - mz_uint32 tdefl_get_adler32 (tdefl_compressor * d); - -// Create tdefl_compress() flags given zlib-style compression parameters. -// level may range from [0,10] (where 10 is absolute max compression, but may be much slower on some files) -// window_bits may be -15 (raw deflate) or 15 (zlib) -// strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, MZ_RLE, or MZ_FIXED - mz_uint tdefl_create_comp_flags_from_zip_params (int level, int window_bits, - int strategy); - -#ifdef __cplusplus -} -#endif - -#endif // MINIZ_HEADER_INCLUDED - -// ------------------- End of Header: Implementation follows. (If you only want the header, define MINIZ_HEADER_FILE_ONLY.) - -#ifndef MINIZ_HEADER_FILE_ONLY - -typedef unsigned char mz_validate_uint16[sizeof (mz_uint16) == 2 ? 1 : -1]; -typedef unsigned char mz_validate_uint32[sizeof (mz_uint32) == 4 ? 1 : -1]; -typedef unsigned char mz_validate_uint64[sizeof (mz_uint64) == 8 ? 1 : -1]; - -#include -#include - -#define MZ_ASSERT(x) assert(x) - -#ifdef MINIZ_NO_MALLOC -#define MZ_MALLOC(x) NULL -#define MZ_FREE(x) x, ((void)0) -#define MZ_REALLOC(p, x) NULL -#else -#define MZ_MALLOC(x) malloc(x) -#define MZ_FREE(x) free(x) -#define MZ_REALLOC(p, x) realloc(p, x) -#endif - -#define MZ_MAX(a,b) (((a)>(b))?(a):(b)) -#define MZ_MIN(a,b) (((a)<(b))?(a):(b)) -#define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj)) - -#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN -#define MZ_READ_LE16(p) *((const mz_uint16 *)(p)) -#define MZ_READ_LE32(p) *((const mz_uint32 *)(p)) -#else -#define MZ_READ_LE16(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U)) -#define MZ_READ_LE32(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U)) -#endif - -#if !defined(_MSC_VER) && !defined(__MINGW32__) && !defined(__MINGW64__) && !defined(__forceinline) -#ifdef __cplusplus -#define __forceinline inline -#else -#define __forceinline -#endif -#endif - -#ifdef __cplusplus -extern "C" -{ -#endif - -// ------------------- zlib-style API's - - static void *def_alloc_func (void *opaque, size_t items, size_t size) - { - (void) opaque; - return MZ_MALLOC (items * size); - } - static void def_free_func (void *opaque, void *address) - { - (void) opaque, MZ_FREE (address); - } - static void *def_realloc_func (void *opaque, void *address, size_t items, - size_t size) - { - (void) opaque; - return MZ_REALLOC (address, items * size); - } - - mz_ulong mz_adler32 (mz_ulong adler, const unsigned char *ptr, - size_t buf_len) - { - mz_uint32 i, s1 = (mz_uint32) (adler & 0xffff), s2 = - (mz_uint32) (adler >> 16); - size_t block_len = buf_len % 5552; - if (!ptr) - return MZ_ADLER32_INIT; - while (buf_len) - { - for (i = 0; i + 7 < block_len; i += 8, ptr += 8) - { - s1 += ptr[0], s2 += s1; - s1 += ptr[1], s2 += s1; - s1 += ptr[2], s2 += s1; - s1 += ptr[3], s2 += s1; - s1 += ptr[4], s2 += s1; - s1 += ptr[5], s2 += s1; - s1 += ptr[6], s2 += s1; - s1 += ptr[7], s2 += s1; - } - for (; i < block_len; ++i) - s1 += *ptr++, s2 += s1; - s1 %= 65521U, s2 %= 65521U; - buf_len -= block_len; - block_len = 5552; - } - return (s2 << 16) + s1; - } - -// Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C implementation that balances processor cache usage against speed": http://www.geocities.com/malbrain/ - mz_ulong mz_crc32 (mz_ulong crc, const mz_uint8 * ptr, size_t buf_len) - { - static const mz_uint32 s_crc32[16] = - { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, - 0x4db26158, 0x5005713c, - 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, - 0xa00ae278, 0xbdbdf21c - }; - if (!ptr) - return MZ_CRC32_INIT; - crc = ~crc; - while (buf_len--) - { - mz_uint8 b = *ptr++; - crc = (crc >> 4) ^ s_crc32[(crc & 0xF) ^ (b & 0xF)]; - crc = (crc >> 4) ^ s_crc32[(crc & 0xF) ^ (b >> 4)]; - } - return ~crc; - } - -#ifndef MINIZ_NO_ZLIB_APIS - - const char *mz_version (void) - { - return MZ_VERSION; - } - - int mz_deflateInit (mz_streamp pStream, int level) - { - return mz_deflateInit2 (pStream, level, MZ_DEFLATED, - MZ_DEFAULT_WINDOW_BITS, 9, MZ_DEFAULT_STRATEGY); - } - - int mz_deflateInit2 (mz_streamp pStream, int level, int method, - int window_bits, int mem_level, int strategy) - { - tdefl_compressor *pComp; - mz_uint comp_flags = - TDEFL_COMPUTE_ADLER32 | tdefl_create_comp_flags_from_zip_params (level, - window_bits, - strategy); - - if (!pStream) - return MZ_STREAM_ERROR; - if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) - || ((window_bits != MZ_DEFAULT_WINDOW_BITS) - && (-window_bits != MZ_DEFAULT_WINDOW_BITS))) - return MZ_PARAM_ERROR; - - pStream->data_type = 0; - pStream->adler = MZ_ADLER32_INIT; - pStream->msg = NULL; - pStream->reserved = 0; - pStream->total_in = 0; - pStream->total_out = 0; - if (!pStream->zalloc) - pStream->zalloc = def_alloc_func; - if (!pStream->zfree) - pStream->zfree = def_free_func; - - pComp = - (tdefl_compressor *) pStream->zalloc (pStream->opaque, 1, - sizeof (tdefl_compressor)); - if (!pComp) - return MZ_MEM_ERROR; - - pStream->state = (struct mz_internal_state *) pComp; - - if (tdefl_init (pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY) - { - mz_deflateEnd (pStream); - return MZ_PARAM_ERROR; - } - - return MZ_OK; - } - - int mz_deflateReset (mz_streamp pStream) - { - if ((!pStream) || (!pStream->state) || (!pStream->zalloc) - || (!pStream->zfree)) - return MZ_STREAM_ERROR; - pStream->total_in = pStream->total_out = 0; - tdefl_init ((tdefl_compressor *) pStream->state, NULL, NULL, - ((tdefl_compressor *) pStream->state)->m_flags); - return MZ_OK; - } - - int mz_deflate (mz_streamp pStream, int flush) - { - size_t in_bytes, out_bytes; - mz_ulong orig_total_in, orig_total_out; - int mz_status = MZ_OK; - - if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) - || (!pStream->next_out)) - return MZ_STREAM_ERROR; - if (!pStream->avail_out) - return MZ_BUF_ERROR; - - if (flush == MZ_PARTIAL_FLUSH) - flush = MZ_SYNC_FLUSH; - - if (((tdefl_compressor *) pStream->state)->m_prev_return_status == - TDEFL_STATUS_DONE) - return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR; - - orig_total_in = pStream->total_in; - orig_total_out = pStream->total_out; - for (;;) - { - tdefl_status defl_status; - in_bytes = pStream->avail_in; - out_bytes = pStream->avail_out; - - defl_status = - tdefl_compress ((tdefl_compressor *) pStream->state, - pStream->next_in, &in_bytes, pStream->next_out, - &out_bytes, (tdefl_flush) flush); - pStream->next_in += (mz_uint) in_bytes; - pStream->avail_in -= (mz_uint) in_bytes; - pStream->total_in += (mz_uint) in_bytes; - pStream->adler = - tdefl_get_adler32 ((tdefl_compressor *) pStream->state); - - pStream->next_out += (mz_uint) out_bytes; - pStream->avail_out -= (mz_uint) out_bytes; - pStream->total_out += (mz_uint) out_bytes; - - if (defl_status < 0) - { - mz_status = MZ_STREAM_ERROR; - break; - } - else if (defl_status == TDEFL_STATUS_DONE) - { - mz_status = MZ_STREAM_END; - break; - } - else if (!pStream->avail_out) - break; - else if ((!pStream->avail_in) && (flush != MZ_FINISH)) - { - if ((flush) || (pStream->total_in != orig_total_in) - || (pStream->total_out != orig_total_out)) - break; - return MZ_BUF_ERROR; // Can't make forward progress without some input. - } - } - return mz_status; - } - - int mz_deflateEnd (mz_streamp pStream) - { - if (!pStream) - return MZ_STREAM_ERROR; - if (pStream->state) - { - pStream->zfree (pStream->opaque, pStream->state); - pStream->state = NULL; - } - return MZ_OK; - } - - mz_ulong mz_deflateBound (mz_streamp pStream, mz_ulong source_len) - { - // This is really over conservative. (And lame, but it's actually pretty tricky to compute a true upper bound given the way tdefl's blocking works.) - return MZ_MAX (128 + (source_len * 110) / 100, - 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5); - } - - int mz_compress2 (unsigned char *pDest, mz_ulong * pDest_len, - const unsigned char *pSource, mz_ulong source_len, - int level) - { - int status; - mz_stream stream; - memset (&stream, 0, sizeof (stream)); - - // In case mz_ulong is 64-bits (argh I hate longs). - if ((source_len | *pDest_len) > 0xFFFFFFFFU) - return MZ_PARAM_ERROR; - - stream.next_in = pSource; - stream.avail_in = (mz_uint32) source_len; - stream.next_out = pDest; - stream.avail_out = (mz_uint32) * pDest_len; - - status = mz_deflateInit (&stream, level); - if (status != MZ_OK) - return status; - - status = mz_deflate (&stream, MZ_FINISH); - if (status != MZ_STREAM_END) - { - mz_deflateEnd (&stream); - return (status == MZ_OK) ? MZ_BUF_ERROR : status; - } - - *pDest_len = stream.total_out; - return mz_deflateEnd (&stream); - } - - int mz_compress (unsigned char *pDest, mz_ulong * pDest_len, - const unsigned char *pSource, mz_ulong source_len) - { - return mz_compress2 (pDest, pDest_len, pSource, source_len, - MZ_DEFAULT_COMPRESSION); - } - - mz_ulong mz_compressBound (mz_ulong source_len) - { - return mz_deflateBound (NULL, source_len); - } - - typedef struct - { - tinfl_decompressor m_decomp; - mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed; - int m_window_bits; - mz_uint8 m_dict[TINFL_LZ_DICT_SIZE]; - tinfl_status m_last_status; - } inflate_state; - - int mz_inflateInit2 (mz_streamp pStream, int window_bits) - { - inflate_state *pDecomp; - if (!pStream) - return MZ_STREAM_ERROR; - if ((window_bits != MZ_DEFAULT_WINDOW_BITS) - && (-window_bits != MZ_DEFAULT_WINDOW_BITS)) - return MZ_PARAM_ERROR; - - pStream->data_type = 0; - pStream->adler = 0; - pStream->msg = NULL; - pStream->total_in = 0; - pStream->total_out = 0; - pStream->reserved = 0; - if (!pStream->zalloc) - pStream->zalloc = def_alloc_func; - if (!pStream->zfree) - pStream->zfree = def_free_func; - - pDecomp = - (inflate_state *) pStream->zalloc (pStream->opaque, 1, - sizeof (inflate_state)); - if (!pDecomp) - return MZ_MEM_ERROR; - - pStream->state = (struct mz_internal_state *) pDecomp; - - tinfl_init (&pDecomp->m_decomp); - pDecomp->m_dict_ofs = 0; - pDecomp->m_dict_avail = 0; - pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT; - pDecomp->m_first_call = 1; - pDecomp->m_has_flushed = 0; - pDecomp->m_window_bits = window_bits; - - return MZ_OK; - } - - int mz_inflateInit (mz_streamp pStream) - { - return mz_inflateInit2 (pStream, MZ_DEFAULT_WINDOW_BITS); - } - - int mz_inflate (mz_streamp pStream, int flush) - { - inflate_state *pState; - mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32; - size_t in_bytes, out_bytes, orig_avail_in; - tinfl_status status; - - if ((!pStream) || (!pStream->state)) - return MZ_STREAM_ERROR; - if (flush == MZ_PARTIAL_FLUSH) - flush = MZ_SYNC_FLUSH; - if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH)) - return MZ_STREAM_ERROR; - - pState = (inflate_state *) pStream->state; - if (pState->m_window_bits > 0) - decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER; - orig_avail_in = pStream->avail_in; - - first_call = pState->m_first_call; - pState->m_first_call = 0; - if (pState->m_last_status < 0) - return MZ_DATA_ERROR; - - if (pState->m_has_flushed && (flush != MZ_FINISH)) - return MZ_STREAM_ERROR; - pState->m_has_flushed |= (flush == MZ_FINISH); - - if ((flush == MZ_FINISH) && (first_call)) - { - // MZ_FINISH on the first call implies that the input and output buffers are large enough to hold the entire compressed/decompressed file. - decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF; - in_bytes = pStream->avail_in; - out_bytes = pStream->avail_out; - status = - tinfl_decompress (&pState->m_decomp, pStream->next_in, &in_bytes, - pStream->next_out, pStream->next_out, &out_bytes, - decomp_flags); - pState->m_last_status = status; - pStream->next_in += (mz_uint) in_bytes; - pStream->avail_in -= (mz_uint) in_bytes; - pStream->total_in += (mz_uint) in_bytes; - pStream->adler = tinfl_get_adler32 (&pState->m_decomp); - pStream->next_out += (mz_uint) out_bytes; - pStream->avail_out -= (mz_uint) out_bytes; - pStream->total_out += (mz_uint) out_bytes; - - if (status < 0) - return MZ_DATA_ERROR; - else if (status != TINFL_STATUS_DONE) - { - pState->m_last_status = TINFL_STATUS_FAILED; - return MZ_BUF_ERROR; - } - return MZ_STREAM_END; - } - // flush != MZ_FINISH then we must assume there's more input. - if (flush != MZ_FINISH) - decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT; - - if (pState->m_dict_avail) - { - n = MZ_MIN (pState->m_dict_avail, pStream->avail_out); - memcpy (pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); - pStream->next_out += n; - pStream->avail_out -= n; - pStream->total_out += n; - pState->m_dict_avail -= n; - pState->m_dict_ofs = - (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); - return ((pState->m_last_status == TINFL_STATUS_DONE) - && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; - } - - for (;;) - { - in_bytes = pStream->avail_in; - out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs; - - status = - tinfl_decompress (&pState->m_decomp, pStream->next_in, &in_bytes, - pState->m_dict, - pState->m_dict + pState->m_dict_ofs, &out_bytes, - decomp_flags); - pState->m_last_status = status; - - pStream->next_in += (mz_uint) in_bytes; - pStream->avail_in -= (mz_uint) in_bytes; - pStream->total_in += (mz_uint) in_bytes; - pStream->adler = tinfl_get_adler32 (&pState->m_decomp); - - pState->m_dict_avail = (mz_uint) out_bytes; - - n = MZ_MIN (pState->m_dict_avail, pStream->avail_out); - memcpy (pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); - pStream->next_out += n; - pStream->avail_out -= n; - pStream->total_out += n; - pState->m_dict_avail -= n; - pState->m_dict_ofs = - (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); - - if (status < 0) - return MZ_DATA_ERROR; // Stream is corrupted (there could be some uncompressed data left in the output dictionary - oh well). - else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) - && (!orig_avail_in)) - return MZ_BUF_ERROR; // Signal caller that we can't make forward progress without supplying more input or by setting flush to MZ_FINISH. - else if (flush == MZ_FINISH) - { - // The output buffer MUST be large to hold the remaining uncompressed data when flush==MZ_FINISH. - if (status == TINFL_STATUS_DONE) - return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END; - // status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's at least 1 more byte on the way. If there's no more room left in the output buffer then something is wrong. - else if (!pStream->avail_out) - return MZ_BUF_ERROR; - } - else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) - || (!pStream->avail_out) || (pState->m_dict_avail)) - break; - } - - return ((status == TINFL_STATUS_DONE) - && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; - } - - int mz_inflateEnd (mz_streamp pStream) - { - if (!pStream) - return MZ_STREAM_ERROR; - if (pStream->state) - { - pStream->zfree (pStream->opaque, pStream->state); - pStream->state = NULL; - } - return MZ_OK; - } - - int mz_uncompress (unsigned char *pDest, mz_ulong * pDest_len, - const unsigned char *pSource, mz_ulong source_len) - { - mz_stream stream; - int status; - memset (&stream, 0, sizeof (stream)); - - // In case mz_ulong is 64-bits (argh I hate longs). - if ((source_len | *pDest_len) > 0xFFFFFFFFU) - return MZ_PARAM_ERROR; - - stream.next_in = pSource; - stream.avail_in = (mz_uint32) source_len; - stream.next_out = pDest; - stream.avail_out = (mz_uint32) * pDest_len; - - status = mz_inflateInit (&stream); - if (status != MZ_OK) - return status; - - status = mz_inflate (&stream, MZ_FINISH); - if (status != MZ_STREAM_END) - { - mz_inflateEnd (&stream); - return ((status == MZ_BUF_ERROR) - && (!stream.avail_in)) ? MZ_DATA_ERROR : status; - } - *pDest_len = stream.total_out; - - return mz_inflateEnd (&stream); - } - - const char *mz_error (int err) - { - static struct - { - int m_err; - const char *m_pDesc; - } s_error_descs[] = - { - { - MZ_OK, ""}, - { - MZ_STREAM_END, "stream end"}, - { - MZ_NEED_DICT, "need dictionary"}, - { - MZ_ERRNO, "file error"}, - { - MZ_STREAM_ERROR, "stream error"}, - { - MZ_DATA_ERROR, "data error"}, - { - MZ_MEM_ERROR, "out of memory"}, - { - MZ_BUF_ERROR, "buf error"}, - { - MZ_VERSION_ERROR, "version error"}, - { - MZ_PARAM_ERROR, "parameter error"} - }; - mz_uint i; - for (i = 0; i < sizeof (s_error_descs) / sizeof (s_error_descs[0]); ++i) - if (s_error_descs[i].m_err == err) - return s_error_descs[i].m_pDesc; - return NULL; - } - -#endif //MINIZ_NO_ZLIB_APIS - -// ------------------- Low-level Decompression (completely independent from all compression API's) - -#define TINFL_MEMCPY(d, s, l) memcpy(d, s, l) -#define TINFL_MEMSET(p, c, l) memset(p, c, l) - -#define TINFL_CR_BEGIN switch(r->m_state) { case 0: -#define TINFL_CR_RETURN(state_index, result) do { status = result; r->m_state = state_index; goto common_exit; case state_index:; } MZ_MACRO_END -#define TINFL_CR_RETURN_FOREVER(state_index, result) do { for ( ; ; ) { TINFL_CR_RETURN(state_index, result); } } MZ_MACRO_END -#define TINFL_CR_FINISH } - -// TODO: If the caller has indicated that there's no more input, and we attempt to read beyond the input buf, then something is wrong with the input because the inflator never -// reads ahead more than it needs to. Currently TINFL_GET_BYTE() pads the end of the stream with 0's in this scenario. -#define TINFL_GET_BYTE(state_index, c) do { \ - if (pIn_buf_cur >= pIn_buf_end) { \ - for ( ; ; ) { \ - if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { \ - TINFL_CR_RETURN(state_index, TINFL_STATUS_NEEDS_MORE_INPUT); \ - if (pIn_buf_cur < pIn_buf_end) { \ - c = *pIn_buf_cur++; \ - break; \ - } \ - } else { \ - c = 0; \ - break; \ - } \ - } \ - } else c = *pIn_buf_cur++; } MZ_MACRO_END - -#define TINFL_NEED_BITS(state_index, n) do { mz_uint c; TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; } while (num_bits < (mz_uint)(n)) -#define TINFL_SKIP_BITS(state_index, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END -#define TINFL_GET_BITS(state_index, b, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } b = bit_buf & ((1 << (n)) - 1); bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END - -// TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes remaining in the input buffer falls below 2. -// It reads just enough bytes from the input stream that are needed to decode the next Huffman code (and absolutely no more). It works by trying to fully decode a -// Huffman code by using whatever bits are currently present in the bit buffer. If this fails, it reads another byte, and tries again until it succeeds or until the -// bit buffer contains >=15 bits (deflate's max. Huffman code size). -#define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \ - do { \ - temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \ - if (temp >= 0) { \ - code_len = temp >> 9; \ - if ((code_len) && (num_bits >= code_len)) \ - break; \ - } else if (num_bits > TINFL_FAST_LOOKUP_BITS) { \ - code_len = TINFL_FAST_LOOKUP_BITS; \ - do { \ - temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ - } while ((temp < 0) && (num_bits >= (code_len + 1))); if (temp >= 0) break; \ - } TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; \ - } while (num_bits < 15); - -// TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex than you would initially expect because the zlib API expects the decompressor to never read -// beyond the final byte of the deflate stream. (In other words, when this macro wants to read another byte from the input, it REALLY needs another byte in order to fully -// decode the next Huffman code.) Handling this properly is particularly important on raw deflate (non-zlib) streams, which aren't followed by a byte aligned adler-32. -// The slow path is only executed at the very end of the input buffer. -#define TINFL_HUFF_DECODE(state_index, sym, pHuff) do { \ - int temp; mz_uint code_len, c; \ - if (num_bits < 15) { \ - if ((pIn_buf_end - pIn_buf_cur) < 2) { \ - TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \ - } else { \ - bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); pIn_buf_cur += 2; num_bits += 16; \ - } \ - } \ - if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) \ - code_len = temp >> 9, temp &= 511; \ - else { \ - code_len = TINFL_FAST_LOOKUP_BITS; do { temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; } while (temp < 0); \ - } sym = temp; bit_buf >>= code_len; num_bits -= code_len; } MZ_MACRO_END - - tinfl_status tinfl_decompress (tinfl_decompressor * r, - const mz_uint8 * pIn_buf_next, - size_t * pIn_buf_size, - mz_uint8 * pOut_buf_start, - mz_uint8 * pOut_buf_next, - size_t * pOut_buf_size, - const mz_uint32 decomp_flags) - { - static const int s_length_base[31] = - { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, - 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 - }; - static const int s_length_extra[31] = - { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, - 4, 5, 5, 5, 5, 0, 0, 0 - }; - static const int s_dist_base[32] = - { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, - 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, - 0, 0 - }; - static const int s_dist_extra[32] = - { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, - 10, 11, 11, 12, 12, 13, 13 - }; - static const mz_uint8 s_length_dezigzag[19] = - { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; - static const int s_min_table_sizes[3] = { 257, 1, 4 }; - - tinfl_status status = TINFL_STATUS_FAILED; - mz_uint32 num_bits, dist, counter, num_extra; - tinfl_bit_buf_t bit_buf; - const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = - pIn_buf_next + *pIn_buf_size; - mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = - pOut_buf_next + *pOut_buf_size; - size_t out_buf_size_mask = - (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF) ? (size_t) - - 1 : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, - dist_from_out_buf_start; - - // Ensure the output buffer's size is a power of 2, unless the output buffer is large enough to hold the entire output file (in which case it doesn't matter). - if (((out_buf_size_mask + 1) & out_buf_size_mask) - || (pOut_buf_next < pOut_buf_start)) - { - *pIn_buf_size = *pOut_buf_size = 0; - return TINFL_STATUS_BAD_PARAM; - } - - num_bits = r->m_num_bits; - bit_buf = r->m_bit_buf; - dist = r->m_dist; - counter = r->m_counter; - num_extra = r->m_num_extra; - dist_from_out_buf_start = r->m_dist_from_out_buf_start; - TINFL_CR_BEGIN - bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = - r->m_zhdr1 = 0; - r->m_z_adler32 = r->m_check_adler32 = 1; - if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) - { - TINFL_GET_BYTE (1, r->m_zhdr0); - TINFL_GET_BYTE (2, r->m_zhdr1); - counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) - || (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8)); - if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) - counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) - || ((out_buf_size_mask + 1) < - (size_t) (1U << (8U + (r->m_zhdr0 >> 4))))); - if (counter) - { - TINFL_CR_RETURN_FOREVER (36, TINFL_STATUS_FAILED); - } - } - - do - { - TINFL_GET_BITS (3, r->m_final, 3); - r->m_type = r->m_final >> 1; - if (r->m_type == 0) - { - TINFL_SKIP_BITS (5, num_bits & 7); - for (counter = 0; counter < 4; ++counter) - { - if (num_bits) - TINFL_GET_BITS (6, r->m_raw_header[counter], 8); - else - TINFL_GET_BYTE (7, r->m_raw_header[counter]); - } - if ((counter = - (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != - (mz_uint) (0xFFFF ^ - (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) - { - TINFL_CR_RETURN_FOREVER (39, TINFL_STATUS_FAILED); - } - while ((counter) && (num_bits)) - { - TINFL_GET_BITS (51, dist, 8); - while (pOut_buf_cur >= pOut_buf_end) - { - TINFL_CR_RETURN (52, TINFL_STATUS_HAS_MORE_OUTPUT); - } - *pOut_buf_cur++ = (mz_uint8) dist; - counter--; - } - while (counter) - { - size_t n; - while (pOut_buf_cur >= pOut_buf_end) - { - TINFL_CR_RETURN (9, TINFL_STATUS_HAS_MORE_OUTPUT); - } - while (pIn_buf_cur >= pIn_buf_end) - { - if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) - { - TINFL_CR_RETURN (38, TINFL_STATUS_NEEDS_MORE_INPUT); - } - else - { - TINFL_CR_RETURN_FOREVER (40, TINFL_STATUS_FAILED); - } - } - n = - MZ_MIN (MZ_MIN - ((size_t) (pOut_buf_end - pOut_buf_cur), - (size_t) (pIn_buf_end - pIn_buf_cur)), counter); - TINFL_MEMCPY (pOut_buf_cur, pIn_buf_cur, n); - pIn_buf_cur += n; - pOut_buf_cur += n; - counter -= (mz_uint) n; - } - } - else if (r->m_type == 3) - { - TINFL_CR_RETURN_FOREVER (10, TINFL_STATUS_FAILED); - } - else - { - if (r->m_type == 1) - { - mz_uint8 *p = r->m_tables[0].m_code_size; - mz_uint i; - r->m_table_sizes[0] = 288; - r->m_table_sizes[1] = 32; - TINFL_MEMSET (r->m_tables[1].m_code_size, 5, 32); - for (i = 0; i <= 143; ++i) - *p++ = 8; - for (; i <= 255; ++i) - *p++ = 9; - for (; i <= 279; ++i) - *p++ = 7; - for (; i <= 287; ++i) - *p++ = 8; - } - else - { - for (counter = 0; counter < 3; counter++) - { - TINFL_GET_BITS (11, r->m_table_sizes[counter], - "\05\05\04"[counter]); - r->m_table_sizes[counter] += s_min_table_sizes[counter]; - } - MZ_CLEAR_OBJ (r->m_tables[2].m_code_size); - for (counter = 0; counter < r->m_table_sizes[2]; counter++) - { - mz_uint s; - TINFL_GET_BITS (14, s, 3); - r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = - (mz_uint8) s; - } - r->m_table_sizes[2] = 19; - } - for (; (int) r->m_type >= 0; r->m_type--) - { - int tree_next, tree_cur; - tinfl_huff_table *pTable; - mz_uint i, j, used_syms, total, sym_index, next_code[17], - total_syms[16]; - pTable = &r->m_tables[r->m_type]; - MZ_CLEAR_OBJ (total_syms); - MZ_CLEAR_OBJ (pTable->m_look_up); - MZ_CLEAR_OBJ (pTable->m_tree); - for (i = 0; i < r->m_table_sizes[r->m_type]; ++i) - total_syms[pTable->m_code_size[i]]++; - used_syms = 0, total = 0; - next_code[0] = next_code[1] = 0; - for (i = 1; i <= 15; ++i) - { - used_syms += total_syms[i]; - next_code[i + 1] = (total = - ((total + total_syms[i]) << 1)); - } - if ((65536 != total) && (used_syms > 1)) - { - TINFL_CR_RETURN_FOREVER (35, TINFL_STATUS_FAILED); - } - for (tree_next = -1, sym_index = 0; - sym_index < r->m_table_sizes[r->m_type]; ++sym_index) - { - mz_uint rev_code = 0, l, cur_code, code_size = - pTable->m_code_size[sym_index]; - if (!code_size) - continue; - cur_code = next_code[code_size]++; - for (l = code_size; l > 0; l--, cur_code >>= 1) - rev_code = (rev_code << 1) | (cur_code & 1); - if (code_size <= TINFL_FAST_LOOKUP_BITS) - { - mz_int16 k = - (mz_int16) ((code_size << 9) | sym_index); - while (rev_code < TINFL_FAST_LOOKUP_SIZE) - { - pTable->m_look_up[rev_code] = k; - rev_code += (1 << code_size); - } - continue; - } - if (0 == - (tree_cur = - pTable-> - m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)])) - { - pTable-> - m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = - (mz_int16) tree_next; - tree_cur = tree_next; - tree_next -= 2; - } - rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1); - for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--) - { - tree_cur -= ((rev_code >>= 1) & 1); - if (!pTable->m_tree[-tree_cur - 1]) - { - pTable->m_tree[-tree_cur - 1] = - (mz_int16) tree_next; - tree_cur = tree_next; - tree_next -= 2; - } - else - tree_cur = pTable->m_tree[-tree_cur - 1]; - } - tree_cur -= ((rev_code >>= 1) & 1); - pTable->m_tree[-tree_cur - 1] = (mz_int16) sym_index; - } - if (r->m_type == 2) - { - for (counter = 0; - counter < - (r->m_table_sizes[0] + r->m_table_sizes[1]);) - { - mz_uint s; - TINFL_HUFF_DECODE (16, dist, &r->m_tables[2]); - if (dist < 16) - { - r->m_len_codes[counter++] = (mz_uint8) dist; - continue; - } - if ((dist == 16) && (!counter)) - { - TINFL_CR_RETURN_FOREVER (17, TINFL_STATUS_FAILED); - } - num_extra = "\02\03\07"[dist - 16]; - TINFL_GET_BITS (18, s, num_extra); - s += "\03\03\013"[dist - 16]; - TINFL_MEMSET (r->m_len_codes + counter, - (dist == - 16) ? r->m_len_codes[counter - 1] : 0, - s); - counter += s; - } - if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != - counter) - { - TINFL_CR_RETURN_FOREVER (21, TINFL_STATUS_FAILED); - } - TINFL_MEMCPY (r->m_tables[0].m_code_size, r->m_len_codes, - r->m_table_sizes[0]); - TINFL_MEMCPY (r->m_tables[1].m_code_size, - r->m_len_codes + r->m_table_sizes[0], - r->m_table_sizes[1]); - } - } - for (;;) - { - mz_uint8 *pSrc; - for (;;) - { - if (((pIn_buf_end - pIn_buf_cur) < 4) - || ((pOut_buf_end - pOut_buf_cur) < 2)) - { - TINFL_HUFF_DECODE (23, counter, &r->m_tables[0]); - if (counter >= 256) - break; - while (pOut_buf_cur >= pOut_buf_end) - { - TINFL_CR_RETURN (24, - TINFL_STATUS_HAS_MORE_OUTPUT); - } - *pOut_buf_cur++ = (mz_uint8) counter; - } - else - { - int sym2; - mz_uint code_len; -#if TINFL_USE_64BIT_BITBUF - if (num_bits < 30) - { - bit_buf |= - (((tinfl_bit_buf_t) MZ_READ_LE32 (pIn_buf_cur)) - << num_bits); - pIn_buf_cur += 4; - num_bits += 32; - } -#else - if (num_bits < 15) - { - bit_buf |= - (((tinfl_bit_buf_t) MZ_READ_LE16 (pIn_buf_cur)) - << num_bits); - pIn_buf_cur += 2; - num_bits += 16; - } -#endif - if ((sym2 = - r->m_tables[0]. - m_look_up[bit_buf & - (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) - code_len = sym2 >> 9; - else - { - code_len = TINFL_FAST_LOOKUP_BITS; - do - { - sym2 = - r->m_tables[0].m_tree[~sym2 + - ((bit_buf >> - code_len++) & 1)]; - } - while (sym2 < 0); - } - counter = sym2; - bit_buf >>= code_len; - num_bits -= code_len; - if (counter & 256) - break; - -#if !TINFL_USE_64BIT_BITBUF - if (num_bits < 15) - { - bit_buf |= - (((tinfl_bit_buf_t) MZ_READ_LE16 (pIn_buf_cur)) - << num_bits); - pIn_buf_cur += 2; - num_bits += 16; - } -#endif - if ((sym2 = - r->m_tables[0]. - m_look_up[bit_buf & - (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) - code_len = sym2 >> 9; - else - { - code_len = TINFL_FAST_LOOKUP_BITS; - do - { - sym2 = - r->m_tables[0].m_tree[~sym2 + - ((bit_buf >> - code_len++) & 1)]; - } - while (sym2 < 0); - } - bit_buf >>= code_len; - num_bits -= code_len; - - pOut_buf_cur[0] = (mz_uint8) counter; - if (sym2 & 256) - { - pOut_buf_cur++; - counter = sym2; - break; - } - pOut_buf_cur[1] = (mz_uint8) sym2; - pOut_buf_cur += 2; - } - } - if ((counter &= 511) == 256) - break; - - num_extra = s_length_extra[counter - 257]; - counter = s_length_base[counter - 257]; - if (num_extra) - { - mz_uint extra_bits; - TINFL_GET_BITS (25, extra_bits, num_extra); - counter += extra_bits; - } - - TINFL_HUFF_DECODE (26, dist, &r->m_tables[1]); - num_extra = s_dist_extra[dist]; - dist = s_dist_base[dist]; - if (num_extra) - { - mz_uint extra_bits; - TINFL_GET_BITS (27, extra_bits, num_extra); - dist += extra_bits; - } - - dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start; - if ((dist > dist_from_out_buf_start) - && (decomp_flags & - TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) - { - TINFL_CR_RETURN_FOREVER (37, TINFL_STATUS_FAILED); - } - - pSrc = - pOut_buf_start + - ((dist_from_out_buf_start - dist) & out_buf_size_mask); - - if ((MZ_MAX (pOut_buf_cur, pSrc) + counter) > pOut_buf_end) - { - while (counter--) - { - while (pOut_buf_cur >= pOut_buf_end) - { - TINFL_CR_RETURN (53, - TINFL_STATUS_HAS_MORE_OUTPUT); - } - *pOut_buf_cur++ = - pOut_buf_start[(dist_from_out_buf_start++ - - dist) & out_buf_size_mask]; - } - continue; - } -#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES - else if ((counter >= 9) && (counter <= dist)) - { - const mz_uint8 *pSrc_end = pSrc + (counter & ~7); - do - { - ((mz_uint32 *) pOut_buf_cur)[0] = - ((const mz_uint32 *) pSrc)[0]; - ((mz_uint32 *) pOut_buf_cur)[1] = - ((const mz_uint32 *) pSrc)[1]; - pOut_buf_cur += 8; - } - while ((pSrc += 8) < pSrc_end); - if ((counter &= 7) < 3) - { - if (counter) - { - pOut_buf_cur[0] = pSrc[0]; - if (counter > 1) - pOut_buf_cur[1] = pSrc[1]; - pOut_buf_cur += counter; - } - continue; - } - } -#endif - do - { - pOut_buf_cur[0] = pSrc[0]; - pOut_buf_cur[1] = pSrc[1]; - pOut_buf_cur[2] = pSrc[2]; - pOut_buf_cur += 3; - pSrc += 3; - } - while ((int) (counter -= 3) > 2); - if ((int) counter > 0) - { - pOut_buf_cur[0] = pSrc[0]; - if ((int) counter > 1) - pOut_buf_cur[1] = pSrc[1]; - pOut_buf_cur += counter; - } - } - } - } - while (!(r->m_final & 1)); - if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) - { - TINFL_SKIP_BITS (32, num_bits & 7); - for (counter = 0; counter < 4; ++counter) - { - mz_uint s; - if (num_bits) - TINFL_GET_BITS (41, s, 8); - else - TINFL_GET_BYTE (42, s); - r->m_z_adler32 = (r->m_z_adler32 << 8) | s; - } - } - TINFL_CR_RETURN_FOREVER (34, TINFL_STATUS_DONE); - TINFL_CR_FINISH common_exit: - r->m_num_bits = num_bits; - r->m_bit_buf = bit_buf; - r->m_dist = dist; - r->m_counter = counter; - r->m_num_extra = num_extra; - r->m_dist_from_out_buf_start = dist_from_out_buf_start; - *pIn_buf_size = pIn_buf_cur - pIn_buf_next; - *pOut_buf_size = pOut_buf_cur - pOut_buf_next; - if ((decomp_flags & - (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) - && (status >= 0)) - { - const mz_uint8 *ptr = pOut_buf_next; - size_t buf_len = *pOut_buf_size; - mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = - r->m_check_adler32 >> 16; - size_t block_len = buf_len % 5552; - while (buf_len) - { - for (i = 0; i + 7 < block_len; i += 8, ptr += 8) - { - s1 += ptr[0], s2 += s1; - s1 += ptr[1], s2 += s1; - s1 += ptr[2], s2 += s1; - s1 += ptr[3], s2 += s1; - s1 += ptr[4], s2 += s1; - s1 += ptr[5], s2 += s1; - s1 += ptr[6], s2 += s1; - s1 += ptr[7], s2 += s1; - } - for (; i < block_len; ++i) - s1 += *ptr++, s2 += s1; - s1 %= 65521U, s2 %= 65521U; - buf_len -= block_len; - block_len = 5552; - } - r->m_check_adler32 = (s2 << 16) + s1; - if ((status == TINFL_STATUS_DONE) - && (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) - && (r->m_check_adler32 != r->m_z_adler32)) - status = TINFL_STATUS_ADLER32_MISMATCH; - } - return status; - } - -// Higher level helper functions. - void *tinfl_decompress_mem_to_heap (const void *pSrc_buf, - size_t src_buf_len, size_t * pOut_len, - int flags) - { - tinfl_decompressor decomp; - void *pBuf = NULL, *pNew_buf; - size_t src_buf_ofs = 0, out_buf_capacity = 0; - *pOut_len = 0; - tinfl_init (&decomp); - for (;;) - { - size_t src_buf_size = src_buf_len - src_buf_ofs, dst_buf_size = - out_buf_capacity - *pOut_len, new_out_buf_capacity; - tinfl_status status = - tinfl_decompress (&decomp, - (const mz_uint8 *) pSrc_buf + src_buf_ofs, - &src_buf_size, (mz_uint8 *) pBuf, - pBuf ? (mz_uint8 *) pBuf + *pOut_len : NULL, - &dst_buf_size, - (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | - TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); - if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT)) - { - MZ_FREE (pBuf); - *pOut_len = 0; - return NULL; - } - src_buf_ofs += src_buf_size; - *pOut_len += dst_buf_size; - if (status == TINFL_STATUS_DONE) - break; - new_out_buf_capacity = out_buf_capacity * 2; - if (new_out_buf_capacity < 128) - new_out_buf_capacity = 128; - pNew_buf = MZ_REALLOC (pBuf, new_out_buf_capacity); - if (!pNew_buf) - { - MZ_FREE (pBuf); - *pOut_len = 0; - return NULL; - } - pBuf = pNew_buf; - out_buf_capacity = new_out_buf_capacity; - } - return pBuf; - } - - size_t tinfl_decompress_mem_to_mem (void *pOut_buf, size_t out_buf_len, - const void *pSrc_buf, - size_t src_buf_len, int flags) - { - tinfl_decompressor decomp; - tinfl_status status; - tinfl_init (&decomp); - status = - tinfl_decompress (&decomp, (const mz_uint8 *) pSrc_buf, &src_buf_len, - (mz_uint8 *) pOut_buf, (mz_uint8 *) pOut_buf, - &out_buf_len, - (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | - TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); - return (status != - TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED : - out_buf_len; - } - - int tinfl_decompress_mem_to_callback (const void *pIn_buf, - size_t * pIn_buf_size, - tinfl_put_buf_func_ptr pPut_buf_func, - void *pPut_buf_user, int flags) - { - int result = 0; - tinfl_decompressor decomp; - mz_uint8 *pDict = (mz_uint8 *) MZ_MALLOC (TINFL_LZ_DICT_SIZE); - size_t in_buf_ofs = 0, dict_ofs = 0; - if (!pDict) - return TINFL_STATUS_FAILED; - tinfl_init (&decomp); - for (;;) - { - size_t in_buf_size = *pIn_buf_size - in_buf_ofs, dst_buf_size = - TINFL_LZ_DICT_SIZE - dict_ofs; - tinfl_status status = - tinfl_decompress (&decomp, (const mz_uint8 *) pIn_buf + in_buf_ofs, - &in_buf_size, pDict, pDict + dict_ofs, - &dst_buf_size, - (flags & - ~(TINFL_FLAG_HAS_MORE_INPUT | - TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))); - in_buf_ofs += in_buf_size; - if ((dst_buf_size) - && - (!(*pPut_buf_func) - (pDict + dict_ofs, (int) dst_buf_size, pPut_buf_user))) - break; - if (status != TINFL_STATUS_HAS_MORE_OUTPUT) - { - result = (status == TINFL_STATUS_DONE); - break; - } - dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1); - } - MZ_FREE (pDict); - *pIn_buf_size = in_buf_ofs; - return result; - } - -// ------------------- Low-level Compression (independent from all decompression API's) - -// Purposely making these tables static for faster init and thread safety. - static const mz_uint16 s_tdefl_len_sym[256] = { - 257, 258, 259, 260, 261, 262, 263, 264, 265, 265, 266, 266, 267, 267, 268, - 268, 269, 269, 269, 269, 270, 270, 270, 270, 271, 271, 271, 271, 272, - 272, 272, 272, - 273, 273, 273, 273, 273, 273, 273, 273, 274, 274, 274, 274, 274, 274, 274, - 274, 275, 275, 275, 275, 275, 275, 275, 275, 276, 276, 276, 276, 276, - 276, 276, 276, - 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, - 277, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, - 278, 278, 278, - 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, - 279, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, - 280, 280, 280, - 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, - 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, - 281, 281, 281, - 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, - 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, - 282, 282, 282, - 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, - 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, - 283, 283, 283, - 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, - 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, - 284, 284, 285 - }; - - static const mz_uint8 s_tdefl_len_extra[256] = { - 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0 - }; - - static const mz_uint8 s_tdefl_small_dist_sym[512] = { - 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, - 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, - 10, 10, 10, 11, 11, 11, 11, 11, 11, - 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, - 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, - 12, 12, 12, 12, 12, 12, 13, - 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, - 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, - 14, 14, 14, 14, 14, 14, 14, - 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, - 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, - 14, 14, 14, 14, 14, 14, 14, - 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, - 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, - 15, 15, 15, 15, 15, 15, 15, - 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, - 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, - 17, 17, 17, 17, 17, 17, 17, - 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, - 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, - 17, 17, 17, 17, 17, 17, 17, - 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, - 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, - 17, 17, 17, 17, 17, 17, 17, - 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, - 17, 17, 17, 17, 17, 17, 17, 17, 17, 17 - }; - - static const mz_uint8 s_tdefl_small_dist_extra[512] = { - 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, - 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, - 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, - 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, - 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, - 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 7, 7, 7, 7, 7, 7, 7, 7 - }; - - static const mz_uint8 s_tdefl_large_dist_sym[128] = { - 0, 0, 18, 19, 20, 20, 21, 21, 22, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24, - 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, - 26, 26, 26, 26, 26, 26, 26, - 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, - 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, - 28, 28, 28, 28, 28, 28, 28, 28, - 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, - 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, - 29, 29, 29, 29 - }; - - static const mz_uint8 s_tdefl_large_dist_extra[128] = { - 0, 0, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, - 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, - 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, - 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, - 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, - 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, - 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, - 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13 - }; - -// Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted values. - typedef struct - { - mz_uint16 m_key, m_sym_index; - } tdefl_sym_freq; - static tdefl_sym_freq *tdefl_radix_sort_syms (mz_uint num_syms, - tdefl_sym_freq * pSyms0, - tdefl_sym_freq * pSyms1) - { - mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2]; - tdefl_sym_freq *pCur_syms = pSyms0, *pNew_syms = pSyms1; - MZ_CLEAR_OBJ (hist); - for (i = 0; i < num_syms; i++) - { - mz_uint freq = pSyms0[i].m_key; - hist[freq & 0xFF]++; - hist[256 + ((freq >> 8) & 0xFF)]++; - } - while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256])) - total_passes--; - for (pass_shift = 0, pass = 0; pass < total_passes; - pass++, pass_shift += 8) - { - const mz_uint32 *pHist = &hist[pass << 8]; - mz_uint offsets[256], cur_ofs = 0; - for (i = 0; i < 256; i++) - { - offsets[i] = cur_ofs; - cur_ofs += pHist[i]; - } - for (i = 0; i < num_syms; i++) - pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = - pCur_syms[i]; - { - tdefl_sym_freq *t = pCur_syms; - pCur_syms = pNew_syms; - pNew_syms = t; - } - } - return pCur_syms; - } - -// tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat, alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996. - static void tdefl_calculate_minimum_redundancy (tdefl_sym_freq * A, int n) - { - int root, leaf, next, avbl, used, dpth; - if (n == 0) - return; - else if (n == 1) - { - A[0].m_key = 1; - return; - } - A[0].m_key += A[1].m_key; - root = 0; - leaf = 2; - for (next = 1; next < n - 1; next++) - { - if (leaf >= n || A[root].m_key < A[leaf].m_key) - { - A[next].m_key = A[root].m_key; - A[root++].m_key = (mz_uint16) next; - } - else - A[next].m_key = A[leaf++].m_key; - if (leaf >= n || (root < next && A[root].m_key < A[leaf].m_key)) - { - A[next].m_key = (mz_uint16) (A[next].m_key + A[root].m_key); - A[root++].m_key = (mz_uint16) next; - } - else - A[next].m_key = (mz_uint16) (A[next].m_key + A[leaf++].m_key); - } - A[n - 2].m_key = 0; - for (next = n - 3; next >= 0; next--) - A[next].m_key = A[A[next].m_key].m_key + 1; - avbl = 1; - used = dpth = 0; - root = n - 2; - next = n - 1; - while (avbl > 0) - { - while (root >= 0 && (int) A[root].m_key == dpth) - { - used++; - root--; - } - while (avbl > used) - { - A[next--].m_key = (mz_uint16) (dpth); - avbl--; - } - avbl = 2 * used; - dpth++; - used = 0; - } - } - -// Limits canonical Huffman code table's max code size. - enum - { TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 }; - static void tdefl_huffman_enforce_max_code_size (int *pNum_codes, - int code_list_len, - int max_code_size) - { - int i; - mz_uint32 total = 0; - if (code_list_len <= 1) - return; - for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++) - pNum_codes[max_code_size] += pNum_codes[i]; - for (i = max_code_size; i > 0; i--) - total += (((mz_uint32) pNum_codes[i]) << (max_code_size - i)); - while (total != (1UL << max_code_size)) - { - pNum_codes[max_code_size]--; - for (i = max_code_size - 1; i > 0; i--) - if (pNum_codes[i]) - { - pNum_codes[i]--; - pNum_codes[i + 1] += 2; - break; - } - total--; - } - } - - static void tdefl_optimize_huffman_table (tdefl_compressor * d, - int table_num, int table_len, - int code_size_limit, - int static_table) - { - int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE]; - mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1]; - MZ_CLEAR_OBJ (num_codes); - if (static_table) - { - for (i = 0; i < table_len; i++) - num_codes[d->m_huff_code_sizes[table_num][i]]++; - } - else - { - tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], - syms1[TDEFL_MAX_HUFF_SYMBOLS], *pSyms; - int num_used_syms = 0; - const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0]; - for (i = 0; i < table_len; i++) - if (pSym_count[i]) - { - syms0[num_used_syms].m_key = (mz_uint16) pSym_count[i]; - syms0[num_used_syms++].m_sym_index = (mz_uint16) i; - } - - pSyms = tdefl_radix_sort_syms (num_used_syms, syms0, syms1); - tdefl_calculate_minimum_redundancy (pSyms, num_used_syms); - - for (i = 0; i < num_used_syms; i++) - num_codes[pSyms[i].m_key]++; - - tdefl_huffman_enforce_max_code_size (num_codes, num_used_syms, - code_size_limit); - - MZ_CLEAR_OBJ (d->m_huff_code_sizes[table_num]); - MZ_CLEAR_OBJ (d->m_huff_codes[table_num]); - for (i = 1, j = num_used_syms; i <= code_size_limit; i++) - for (l = num_codes[i]; l > 0; l--) - d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = - (mz_uint8) (i); - } - - next_code[1] = 0; - for (j = 0, i = 2; i <= code_size_limit; i++) - next_code[i] = j = ((j + num_codes[i - 1]) << 1); - - for (i = 0; i < table_len; i++) - { - mz_uint rev_code = 0, code, code_size; - if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0) - continue; - code = next_code[code_size]++; - for (l = code_size; l > 0; l--, code >>= 1) - rev_code = (rev_code << 1) | (code & 1); - d->m_huff_codes[table_num][i] = (mz_uint16) rev_code; - } - } - -#define TDEFL_PUT_BITS(b, l) do { \ - mz_uint bits = b; mz_uint len = l; MZ_ASSERT(bits <= ((1U << len) - 1U)); \ - d->m_bit_buffer |= (bits << d->m_bits_in); d->m_bits_in += len; \ - while (d->m_bits_in >= 8) { \ - if (d->m_pOutput_buf < d->m_pOutput_buf_end) \ - *d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \ - d->m_bit_buffer >>= 8; \ - d->m_bits_in -= 8; \ - } \ -} MZ_MACRO_END - -#define TDEFL_RLE_PREV_CODE_SIZE() { if (rle_repeat_count) { \ - if (rle_repeat_count < 3) { \ - d->m_huff_count[2][prev_code_size] = (mz_uint16)(d->m_huff_count[2][prev_code_size] + rle_repeat_count); \ - while (rle_repeat_count--) packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \ - } else { \ - d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); packed_code_sizes[num_packed_code_sizes++] = 16; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_repeat_count - 3); \ -} rle_repeat_count = 0; } } - -#define TDEFL_RLE_ZERO_CODE_SIZE() { if (rle_z_count) { \ - if (rle_z_count < 3) { \ - d->m_huff_count[2][0] = (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); while (rle_z_count--) packed_code_sizes[num_packed_code_sizes++] = 0; \ - } else if (rle_z_count <= 10) { \ - d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); packed_code_sizes[num_packed_code_sizes++] = 17; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 3); \ - } else { \ - d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); packed_code_sizes[num_packed_code_sizes++] = 18; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 11); \ -} rle_z_count = 0; } } - - static mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = - { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; - - static void tdefl_start_dynamic_block (tdefl_compressor * d) - { - int num_lit_codes, num_dist_codes, num_bit_lengths; - mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count, - rle_repeat_count, packed_code_sizes_index; - mz_uint8 code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + - TDEFL_MAX_HUFF_SYMBOLS_1], - packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], - prev_code_size = 0xFF; - - d->m_huff_count[0][256] = 1; - - tdefl_optimize_huffman_table (d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, - MZ_FALSE); - tdefl_optimize_huffman_table (d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, - MZ_FALSE); - - for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--) - if (d->m_huff_code_sizes[0][num_lit_codes - 1]) - break; - for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--) - if (d->m_huff_code_sizes[1][num_dist_codes - 1]) - break; - - memcpy (code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes); - memcpy (code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0], - num_dist_codes); - total_code_sizes_to_pack = num_lit_codes + num_dist_codes; - num_packed_code_sizes = 0; - rle_z_count = 0; - rle_repeat_count = 0; - - memset (&d->m_huff_count[2][0], 0, - sizeof (d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2); - for (i = 0; i < total_code_sizes_to_pack; i++) - { - mz_uint8 code_size = code_sizes_to_pack[i]; - if (!code_size) - { - TDEFL_RLE_PREV_CODE_SIZE (); - if (++rle_z_count == 138) - { - TDEFL_RLE_ZERO_CODE_SIZE (); - } - } - else - { - TDEFL_RLE_ZERO_CODE_SIZE (); - if (code_size != prev_code_size) - { - TDEFL_RLE_PREV_CODE_SIZE (); - d->m_huff_count[2][code_size] = - (mz_uint16) (d->m_huff_count[2][code_size] + 1); - packed_code_sizes[num_packed_code_sizes++] = code_size; - } - else if (++rle_repeat_count == 6) - { - TDEFL_RLE_PREV_CODE_SIZE (); - } - } - prev_code_size = code_size; - } - if (rle_repeat_count) - { - TDEFL_RLE_PREV_CODE_SIZE (); - } - else - { - TDEFL_RLE_ZERO_CODE_SIZE (); - } - - tdefl_optimize_huffman_table (d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, - MZ_FALSE); - - TDEFL_PUT_BITS (2, 2); - - TDEFL_PUT_BITS (num_lit_codes - 257, 5); - TDEFL_PUT_BITS (num_dist_codes - 1, 5); - - for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--) - if (d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle - [num_bit_lengths]]) - break; - num_bit_lengths = MZ_MAX (4, (num_bit_lengths + 1)); - TDEFL_PUT_BITS (num_bit_lengths - 4, 4); - for (i = 0; (int) i < num_bit_lengths; i++) - TDEFL_PUT_BITS (d->m_huff_code_sizes[2] - [s_tdefl_packed_code_size_syms_swizzle[i]], 3); - - for (packed_code_sizes_index = 0; - packed_code_sizes_index < num_packed_code_sizes;) - { - mz_uint code = packed_code_sizes[packed_code_sizes_index++]; - MZ_ASSERT (code < TDEFL_MAX_HUFF_SYMBOLS_2); - TDEFL_PUT_BITS (d->m_huff_codes[2][code], - d->m_huff_code_sizes[2][code]); - if (code >= 16) - TDEFL_PUT_BITS (packed_code_sizes[packed_code_sizes_index++], - "\02\03\07"[code - 16]); - } - } - - static void tdefl_start_static_block (tdefl_compressor * d) - { - mz_uint i; - mz_uint8 *p = &d->m_huff_code_sizes[0][0]; - - for (i = 0; i <= 143; ++i) - *p++ = 8; - for (; i <= 255; ++i) - *p++ = 9; - for (; i <= 279; ++i) - *p++ = 7; - for (; i <= 287; ++i) - *p++ = 8; - - memset (d->m_huff_code_sizes[1], 5, 32); - - tdefl_optimize_huffman_table (d, 0, 288, 15, MZ_TRUE); - tdefl_optimize_huffman_table (d, 1, 32, 15, MZ_TRUE); - - TDEFL_PUT_BITS (1, 2); - } - - static const mz_uint mz_bitmasks[17] = - { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, - 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF - }; - -#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS - static mz_bool tdefl_compress_lz_codes (tdefl_compressor * d) - { - mz_uint flags; - mz_uint8 *pLZ_codes; - mz_uint8 *pOutput_buf = d->m_pOutput_buf; - mz_uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf; - mz_uint64 bit_buffer = d->m_bit_buffer; - mz_uint bits_in = d->m_bits_in; - -#define TDEFL_PUT_BITS_FAST(b, l) { bit_buffer |= (((mz_uint64)(b)) << bits_in); bits_in += (l); } - - flags = 1; - for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end; - flags >>= 1) - { - if (flags == 1) - flags = *pLZ_codes++ | 0x100; - - if (flags & 1) - { - mz_uint s0, s1, n0, n1, sym, num_extra_bits; - mz_uint match_len = pLZ_codes[0], match_dist = - *(const mz_uint16 *) (pLZ_codes + 1); - pLZ_codes += 3; - - MZ_ASSERT (d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); - TDEFL_PUT_BITS_FAST (d-> - m_huff_codes[0][s_tdefl_len_sym[match_len]], - d-> - m_huff_code_sizes[0][s_tdefl_len_sym - [match_len]]); - TDEFL_PUT_BITS_FAST (match_len & - mz_bitmasks[s_tdefl_len_extra[match_len]], - s_tdefl_len_extra[match_len]); - - // This sequence coaxes MSVC into using cmov's vs. jmp's. - s0 = s_tdefl_small_dist_sym[match_dist & 511]; - n0 = s_tdefl_small_dist_extra[match_dist & 511]; - s1 = s_tdefl_large_dist_sym[match_dist >> 8]; - n1 = s_tdefl_large_dist_extra[match_dist >> 8]; - sym = (match_dist < 512) ? s0 : s1; - num_extra_bits = (match_dist < 512) ? n0 : n1; - - MZ_ASSERT (d->m_huff_code_sizes[1][sym]); - TDEFL_PUT_BITS_FAST (d->m_huff_codes[1][sym], - d->m_huff_code_sizes[1][sym]); - TDEFL_PUT_BITS_FAST (match_dist & mz_bitmasks[num_extra_bits], - num_extra_bits); - } - else - { - mz_uint lit = *pLZ_codes++; - MZ_ASSERT (d->m_huff_code_sizes[0][lit]); - TDEFL_PUT_BITS_FAST (d->m_huff_codes[0][lit], - d->m_huff_code_sizes[0][lit]); - - if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) - { - flags >>= 1; - lit = *pLZ_codes++; - MZ_ASSERT (d->m_huff_code_sizes[0][lit]); - TDEFL_PUT_BITS_FAST (d->m_huff_codes[0][lit], - d->m_huff_code_sizes[0][lit]); - - if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) - { - flags >>= 1; - lit = *pLZ_codes++; - MZ_ASSERT (d->m_huff_code_sizes[0][lit]); - TDEFL_PUT_BITS_FAST (d->m_huff_codes[0][lit], - d->m_huff_code_sizes[0][lit]); - } - } - } - - if (pOutput_buf >= d->m_pOutput_buf_end) - return MZ_FALSE; - - *(mz_uint64 *) pOutput_buf = bit_buffer; - pOutput_buf += (bits_in >> 3); - bit_buffer >>= (bits_in & ~7); - bits_in &= 7; - } - -#undef TDEFL_PUT_BITS_FAST - - d->m_pOutput_buf = pOutput_buf; - d->m_bits_in = 0; - d->m_bit_buffer = 0; - - while (bits_in) - { - mz_uint32 n = MZ_MIN (bits_in, 16); - TDEFL_PUT_BITS ((mz_uint) bit_buffer & mz_bitmasks[n], n); - bit_buffer >>= n; - bits_in -= n; - } - - TDEFL_PUT_BITS (d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); - - return (d->m_pOutput_buf < d->m_pOutput_buf_end); - } -#else - static mz_bool tdefl_compress_lz_codes (tdefl_compressor * d) - { - mz_uint flags; - mz_uint8 *pLZ_codes; - - flags = 1; - for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf; - flags >>= 1) - { - if (flags == 1) - flags = *pLZ_codes++ | 0x100; - if (flags & 1) - { - mz_uint sym, num_extra_bits; - mz_uint match_len = pLZ_codes[0], match_dist = - (pLZ_codes[1] | (pLZ_codes[2] << 8)); - pLZ_codes += 3; - - MZ_ASSERT (d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); - TDEFL_PUT_BITS (d->m_huff_codes[0][s_tdefl_len_sym[match_len]], - d->m_huff_code_sizes[0][s_tdefl_len_sym - [match_len]]); - TDEFL_PUT_BITS (match_len & - mz_bitmasks[s_tdefl_len_extra[match_len]], - s_tdefl_len_extra[match_len]); - - if (match_dist < 512) - { - sym = s_tdefl_small_dist_sym[match_dist]; - num_extra_bits = s_tdefl_small_dist_extra[match_dist]; - } - else - { - sym = s_tdefl_large_dist_sym[match_dist >> 8]; - num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8]; - } - MZ_ASSERT (d->m_huff_code_sizes[1][sym]); - TDEFL_PUT_BITS (d->m_huff_codes[1][sym], - d->m_huff_code_sizes[1][sym]); - TDEFL_PUT_BITS (match_dist & mz_bitmasks[num_extra_bits], - num_extra_bits); - } - else - { - mz_uint lit = *pLZ_codes++; - MZ_ASSERT (d->m_huff_code_sizes[0][lit]); - TDEFL_PUT_BITS (d->m_huff_codes[0][lit], - d->m_huff_code_sizes[0][lit]); - } - } - - TDEFL_PUT_BITS (d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); - - return (d->m_pOutput_buf < d->m_pOutput_buf_end); - } -#endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS - - static mz_bool tdefl_compress_block (tdefl_compressor * d, - mz_bool static_block) - { - if (static_block) - tdefl_start_static_block (d); - else - tdefl_start_dynamic_block (d); - return tdefl_compress_lz_codes (d); - } - - static int tdefl_flush_block (tdefl_compressor * d, int flush) - { - mz_uint saved_bit_buf, saved_bits_in; - mz_uint8 *pSaved_output_buf; - mz_bool comp_block_succeeded = MZ_FALSE; - int n, use_raw_block = ((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) - && (d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size; - mz_uint8 *pOutput_buf_start = ((d->m_pPut_buf_func == NULL) - && - ((*d->m_pOut_buf_size - - d->m_out_buf_ofs) >= - TDEFL_OUT_BUF_SIZE)) ? ((mz_uint8 *) - d->m_pOut_buf + - d->m_out_buf_ofs) - : d->m_output_buf; - - d->m_pOutput_buf = pOutput_buf_start; - d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16; - - MZ_ASSERT (!d->m_output_flush_remaining); - d->m_output_flush_ofs = 0; - d->m_output_flush_remaining = 0; - - *d->m_pLZ_flags = (mz_uint8) (*d->m_pLZ_flags >> d->m_num_flags_left); - d->m_pLZ_code_buf -= (d->m_num_flags_left == 8); - - if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index)) - { - TDEFL_PUT_BITS (0x78, 8); - TDEFL_PUT_BITS (0x01, 8); - } - - TDEFL_PUT_BITS (flush == TDEFL_FINISH, 1); - - pSaved_output_buf = d->m_pOutput_buf; - saved_bit_buf = d->m_bit_buffer; - saved_bits_in = d->m_bits_in; - - if (!use_raw_block) - comp_block_succeeded = - tdefl_compress_block (d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) - || (d->m_total_lz_bytes < 48)); - - // If the block gets expanded, forget the current contents of the output buffer and send a raw block instead. - if (((use_raw_block) - || ((d->m_total_lz_bytes) - && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >= - d->m_total_lz_bytes))) - && ((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= - d->m_dict_size)) - { - mz_uint i; - d->m_pOutput_buf = pSaved_output_buf; - d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; - TDEFL_PUT_BITS (0, 2); - if (d->m_bits_in) - { - TDEFL_PUT_BITS (0, 8 - d->m_bits_in); - } - for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF) - { - TDEFL_PUT_BITS (d->m_total_lz_bytes & 0xFFFF, 16); - } - for (i = 0; i < d->m_total_lz_bytes; ++i) - { - TDEFL_PUT_BITS (d->m_dict[(d->m_lz_code_buf_dict_pos + - i) & TDEFL_LZ_DICT_SIZE_MASK], 8); - } - } - // Check for the extremely unlikely (if not impossible) case of the compressed block not fitting into the output buffer when using dynamic codes. - else if (!comp_block_succeeded) - { - d->m_pOutput_buf = pSaved_output_buf; - d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; - tdefl_compress_block (d, MZ_TRUE); - } - - if (flush) - { - if (flush == TDEFL_FINISH) - { - if (d->m_bits_in) - { - TDEFL_PUT_BITS (0, 8 - d->m_bits_in); - } - if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER) - { - mz_uint i, a = d->m_adler32; - for (i = 0; i < 4; i++) - { - TDEFL_PUT_BITS ((a >> 24) & 0xFF, 8); - a <<= 8; - } - } - } - else - { - mz_uint i, z = 0; - TDEFL_PUT_BITS (0, 3); - if (d->m_bits_in) - { - TDEFL_PUT_BITS (0, 8 - d->m_bits_in); - } - for (i = 2; i; --i, z ^= 0xFFFF) - { - TDEFL_PUT_BITS (z & 0xFFFF, 16); - } - } - } - - MZ_ASSERT (d->m_pOutput_buf < d->m_pOutput_buf_end); - - memset (&d->m_huff_count[0][0], 0, - sizeof (d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); - memset (&d->m_huff_count[1][0], 0, - sizeof (d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); - - d->m_pLZ_code_buf = d->m_lz_code_buf + 1; - d->m_pLZ_flags = d->m_lz_code_buf; - d->m_num_flags_left = 8; - d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes; - d->m_total_lz_bytes = 0; - d->m_block_index++; - - if ((n = (int) (d->m_pOutput_buf - pOutput_buf_start)) != 0) - { - if (d->m_pPut_buf_func) - { - *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *) d->m_pIn_buf; - if (!(*d->m_pPut_buf_func) - (d->m_output_buf, n, d->m_pPut_buf_user)) - return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED); - } - else if (pOutput_buf_start == d->m_output_buf) - { - int bytes_to_copy = (int) MZ_MIN ((size_t) n, - (size_t) (*d->m_pOut_buf_size - - d->m_out_buf_ofs)); - memcpy ((mz_uint8 *) d->m_pOut_buf + d->m_out_buf_ofs, - d->m_output_buf, bytes_to_copy); - d->m_out_buf_ofs += bytes_to_copy; - if ((n -= bytes_to_copy) != 0) - { - d->m_output_flush_ofs = bytes_to_copy; - d->m_output_flush_remaining = n; - } - } - else - { - d->m_out_buf_ofs += n; - } - } - - return d->m_output_flush_remaining; - } - -#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES -#define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16*)(p) - static __forceinline void tdefl_find_match (tdefl_compressor * d, - mz_uint lookahead_pos, - mz_uint max_dist, - mz_uint max_match_len, - mz_uint * pMatch_dist, - mz_uint * pMatch_len) - { - mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = - *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; - mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; - const mz_uint16 *s = (const mz_uint16 *) (d->m_dict + pos), *p, *q; - mz_uint16 c01 = - TDEFL_READ_UNALIGNED_WORD (&d->m_dict[pos + match_len - 1]), s01 = - TDEFL_READ_UNALIGNED_WORD (s); - MZ_ASSERT (max_match_len <= TDEFL_MAX_MATCH_LEN); - if (max_match_len <= match_len) - return; - for (;;) - { - for (;;) - { - if (--num_probes_left == 0) - return; -#define TDEFL_PROBE \ - next_probe_pos = d->m_next[probe_pos]; \ - if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) return; \ - probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ - if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) break; - TDEFL_PROBE; - TDEFL_PROBE; - TDEFL_PROBE; - } - if (!dist) - break; - q = (const mz_uint16 *) (d->m_dict + probe_pos); - if (TDEFL_READ_UNALIGNED_WORD (q) != s01) - continue; - p = s; - probe_len = 32; - do - { - } - while ((TDEFL_READ_UNALIGNED_WORD (++p) == - TDEFL_READ_UNALIGNED_WORD (++q)) - && (TDEFL_READ_UNALIGNED_WORD (++p) == - TDEFL_READ_UNALIGNED_WORD (++q)) - && (TDEFL_READ_UNALIGNED_WORD (++p) == - TDEFL_READ_UNALIGNED_WORD (++q)) - && (TDEFL_READ_UNALIGNED_WORD (++p) == - TDEFL_READ_UNALIGNED_WORD (++q)) && (--probe_len > 0)); - if (!probe_len) - { - *pMatch_dist = dist; - *pMatch_len = MZ_MIN (max_match_len, (mz_uint) TDEFL_MAX_MATCH_LEN); - break; - } - else - if ((probe_len = - ((mz_uint) (p - s) * 2) + (mz_uint) (*(const mz_uint8 *) p == - *(const mz_uint8 *) q)) > - match_len) - { - *pMatch_dist = dist; - if ((*pMatch_len = match_len = - MZ_MIN (max_match_len, probe_len)) == max_match_len) - break; - c01 = TDEFL_READ_UNALIGNED_WORD (&d->m_dict[pos + match_len - 1]); - } - } - } -#else - static __forceinline void tdefl_find_match (tdefl_compressor * d, - mz_uint lookahead_pos, - mz_uint max_dist, - mz_uint max_match_len, - mz_uint * pMatch_dist, - mz_uint * pMatch_len) - { - mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = - *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; - mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; - const mz_uint8 *s = d->m_dict + pos, *p, *q; - mz_uint8 c0 = d->m_dict[pos + match_len], c1 = - d->m_dict[pos + match_len - 1]; - MZ_ASSERT (max_match_len <= TDEFL_MAX_MATCH_LEN); - if (max_match_len <= match_len) - return; - for (;;) - { - for (;;) - { - if (--num_probes_left == 0) - return; -#define TDEFL_PROBE \ - next_probe_pos = d->m_next[probe_pos]; \ - if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) return; \ - probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ - if ((d->m_dict[probe_pos + match_len] == c0) && (d->m_dict[probe_pos + match_len - 1] == c1)) break; - TDEFL_PROBE; - TDEFL_PROBE; - TDEFL_PROBE; - } - if (!dist) - break; - p = s; - q = d->m_dict + probe_pos; - for (probe_len = 0; probe_len < max_match_len; probe_len++) - if (*p++ != *q++) - break; - if (probe_len > match_len) - { - *pMatch_dist = dist; - if ((*pMatch_len = match_len = probe_len) == max_match_len) - return; - c0 = d->m_dict[pos + match_len]; - c1 = d->m_dict[pos + match_len - 1]; - } - } - } -#endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES - -#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN - static mz_bool tdefl_compress_fast (tdefl_compressor * d) - { - // Faster, minimally featured LZRW1-style match+parse loop with better register utilization. Intended for applications where raw throughput is valued more highly than ratio. - mz_uint lookahead_pos = d->m_lookahead_pos, lookahead_size = - d->m_lookahead_size, dict_size = d->m_dict_size, total_lz_bytes = - d->m_total_lz_bytes, num_flags_left = d->m_num_flags_left; - mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags; - mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; - - while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size))) - { - const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096; - mz_uint dst_pos = - (lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; - mz_uint num_bytes_to_process = (mz_uint) MZ_MIN (d->m_src_buf_left, - TDEFL_COMP_FAST_LOOKAHEAD_SIZE - - lookahead_size); - d->m_src_buf_left -= num_bytes_to_process; - lookahead_size += num_bytes_to_process; - - while (num_bytes_to_process) - { - mz_uint32 n = - MZ_MIN (TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process); - memcpy (d->m_dict + dst_pos, d->m_pSrc, n); - if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) - memcpy (d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc, - MZ_MIN (n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos)); - d->m_pSrc += n; - dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK; - num_bytes_to_process -= n; - } - - dict_size = MZ_MIN (TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size); - if ((!d->m_flush) - && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE)) - break; - - while (lookahead_size >= 4) - { - mz_uint cur_match_dist, cur_match_len = 1; - mz_uint8 *pCur_dict = d->m_dict + cur_pos; - mz_uint first_trigram = - (*(const mz_uint32 *) pCur_dict) & 0xFFFFFF; - mz_uint hash = - (first_trigram ^ - (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) & - TDEFL_LEVEL1_HASH_SIZE_MASK; - mz_uint probe_pos = d->m_hash[hash]; - d->m_hash[hash] = (mz_uint16) lookahead_pos; - - if (((cur_match_dist = - (mz_uint16) (lookahead_pos - probe_pos)) <= dict_size) - && - ((*(const mz_uint32 *) - (d->m_dict + - (probe_pos &= - TDEFL_LZ_DICT_SIZE_MASK)) & 0xFFFFFF) == first_trigram)) - { - const mz_uint16 *p = (const mz_uint16 *) pCur_dict; - const mz_uint16 *q = - (const mz_uint16 *) (d->m_dict + probe_pos); - mz_uint32 probe_len = 32; - do - { - } - while ((TDEFL_READ_UNALIGNED_WORD (++p) == - TDEFL_READ_UNALIGNED_WORD (++q)) - && (TDEFL_READ_UNALIGNED_WORD (++p) == - TDEFL_READ_UNALIGNED_WORD (++q)) - && (TDEFL_READ_UNALIGNED_WORD (++p) == - TDEFL_READ_UNALIGNED_WORD (++q)) - && (TDEFL_READ_UNALIGNED_WORD (++p) == - TDEFL_READ_UNALIGNED_WORD (++q)) - && (--probe_len > 0)); - cur_match_len = - ((mz_uint) (p - (const mz_uint16 *) pCur_dict) * 2) + - (mz_uint) (*(const mz_uint8 *) p == *(const mz_uint8 *) q); - if (!probe_len) - cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0; - - if ((cur_match_len < TDEFL_MIN_MATCH_LEN) - || ((cur_match_len == TDEFL_MIN_MATCH_LEN) - && (cur_match_dist >= 8U * 1024U))) - { - cur_match_len = 1; - *pLZ_code_buf++ = (mz_uint8) first_trigram; - *pLZ_flags = (mz_uint8) (*pLZ_flags >> 1); - d->m_huff_count[0][(mz_uint8) first_trigram]++; - } - else - { - mz_uint32 s0, s1; - cur_match_len = MZ_MIN (cur_match_len, lookahead_size); - - MZ_ASSERT ((cur_match_len >= TDEFL_MIN_MATCH_LEN) - && (cur_match_dist >= 1) - && (cur_match_dist <= TDEFL_LZ_DICT_SIZE)); - - cur_match_dist--; - - pLZ_code_buf[0] = - (mz_uint8) (cur_match_len - TDEFL_MIN_MATCH_LEN); - *(mz_uint16 *) (&pLZ_code_buf[1]) = - (mz_uint16) cur_match_dist; - pLZ_code_buf += 3; - *pLZ_flags = (mz_uint8) ((*pLZ_flags >> 1) | 0x80); - - s0 = s_tdefl_small_dist_sym[cur_match_dist & 511]; - s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8]; - d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++; - - d->m_huff_count[0][s_tdefl_len_sym - [cur_match_len - - TDEFL_MIN_MATCH_LEN]]++; - } - } - else - { - *pLZ_code_buf++ = (mz_uint8) first_trigram; - *pLZ_flags = (mz_uint8) (*pLZ_flags >> 1); - d->m_huff_count[0][(mz_uint8) first_trigram]++; - } - - if (--num_flags_left == 0) - { - num_flags_left = 8; - pLZ_flags = pLZ_code_buf++; - } - - total_lz_bytes += cur_match_len; - lookahead_pos += cur_match_len; - dict_size = - MZ_MIN (dict_size + cur_match_len, (mz_uint) TDEFL_LZ_DICT_SIZE); - - cur_pos = (cur_pos + cur_match_len) & TDEFL_LZ_DICT_SIZE_MASK; - MZ_ASSERT (lookahead_size >= cur_match_len); - lookahead_size -= cur_match_len; - - if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) - { - int n; - d->m_lookahead_pos = lookahead_pos; - d->m_lookahead_size = lookahead_size; - d->m_dict_size = dict_size; - d->m_total_lz_bytes = total_lz_bytes; - d->m_pLZ_code_buf = pLZ_code_buf; - d->m_pLZ_flags = pLZ_flags; - d->m_num_flags_left = num_flags_left; - if ((n = tdefl_flush_block (d, 0)) != 0) - return (n < 0) ? MZ_FALSE : MZ_TRUE; - total_lz_bytes = d->m_total_lz_bytes; - pLZ_code_buf = d->m_pLZ_code_buf; - pLZ_flags = d->m_pLZ_flags; - num_flags_left = d->m_num_flags_left; - } - } - - while (lookahead_size) - { - mz_uint8 lit = d->m_dict[cur_pos]; - - total_lz_bytes++; - *pLZ_code_buf++ = lit; - *pLZ_flags = (mz_uint8) (*pLZ_flags >> 1); - if (--num_flags_left == 0) - { - num_flags_left = 8; - pLZ_flags = pLZ_code_buf++; - } - - d->m_huff_count[0][lit]++; - - lookahead_pos++; - dict_size = MZ_MIN (dict_size + 1, (mz_uint) TDEFL_LZ_DICT_SIZE); - cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; - lookahead_size--; - - if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) - { - int n; - d->m_lookahead_pos = lookahead_pos; - d->m_lookahead_size = lookahead_size; - d->m_dict_size = dict_size; - d->m_total_lz_bytes = total_lz_bytes; - d->m_pLZ_code_buf = pLZ_code_buf; - d->m_pLZ_flags = pLZ_flags; - d->m_num_flags_left = num_flags_left; - if ((n = tdefl_flush_block (d, 0)) != 0) - return (n < 0) ? MZ_FALSE : MZ_TRUE; - total_lz_bytes = d->m_total_lz_bytes; - pLZ_code_buf = d->m_pLZ_code_buf; - pLZ_flags = d->m_pLZ_flags; - num_flags_left = d->m_num_flags_left; - } - } - } - - d->m_lookahead_pos = lookahead_pos; - d->m_lookahead_size = lookahead_size; - d->m_dict_size = dict_size; - d->m_total_lz_bytes = total_lz_bytes; - d->m_pLZ_code_buf = pLZ_code_buf; - d->m_pLZ_flags = pLZ_flags; - d->m_num_flags_left = num_flags_left; - return MZ_TRUE; - } -#endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN - - static __forceinline void tdefl_record_literal (tdefl_compressor * d, - mz_uint8 lit) - { - d->m_total_lz_bytes++; - *d->m_pLZ_code_buf++ = lit; - *d->m_pLZ_flags = (mz_uint8) (*d->m_pLZ_flags >> 1); - if (--d->m_num_flags_left == 0) - { - d->m_num_flags_left = 8; - d->m_pLZ_flags = d->m_pLZ_code_buf++; - } - d->m_huff_count[0][lit]++; - } - - static __forceinline void tdefl_record_match (tdefl_compressor * d, - mz_uint match_len, - mz_uint match_dist) - { - mz_uint32 s0, s1; - - MZ_ASSERT ((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) - && (match_dist <= TDEFL_LZ_DICT_SIZE)); - - d->m_total_lz_bytes += match_len; - - d->m_pLZ_code_buf[0] = (mz_uint8) (match_len - TDEFL_MIN_MATCH_LEN); - - match_dist -= 1; - d->m_pLZ_code_buf[1] = (mz_uint8) (match_dist & 0xFF); - d->m_pLZ_code_buf[2] = (mz_uint8) (match_dist >> 8); - d->m_pLZ_code_buf += 3; - - *d->m_pLZ_flags = (mz_uint8) ((*d->m_pLZ_flags >> 1) | 0x80); - if (--d->m_num_flags_left == 0) - { - d->m_num_flags_left = 8; - d->m_pLZ_flags = d->m_pLZ_code_buf++; - } - - s0 = s_tdefl_small_dist_sym[match_dist & 511]; - s1 = s_tdefl_large_dist_sym[match_dist >> 8]; - d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++; - - d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++; - } - - static mz_bool tdefl_compress_normal (tdefl_compressor * d) - { - const mz_uint8 *pSrc = d->m_pSrc; - size_t src_buf_left = d->m_src_buf_left; - tdefl_flush flush = d->m_flush; - - while ((src_buf_left) || ((flush) && (d->m_lookahead_size))) - { - mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos; - // Update dictionary and hash chains. Keeps the lookahead size equal to TDEFL_MAX_MATCH_LEN. - if ((d->m_lookahead_size + d->m_dict_size) >= - (TDEFL_MIN_MATCH_LEN - 1)) - { - mz_uint dst_pos = - (d->m_lookahead_pos + - d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK, ins_pos = - d->m_lookahead_pos + d->m_lookahead_size - 2; - mz_uint hash = - (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << - TDEFL_LZ_HASH_SHIFT) ^ d->m_dict[(ins_pos + - 1) & - TDEFL_LZ_DICT_SIZE_MASK]; - mz_uint num_bytes_to_process = (mz_uint) MZ_MIN (src_buf_left, - TDEFL_MAX_MATCH_LEN - - - d->m_lookahead_size); - const mz_uint8 *pSrc_end = pSrc + num_bytes_to_process; - src_buf_left -= num_bytes_to_process; - d->m_lookahead_size += num_bytes_to_process; - while (pSrc != pSrc_end) - { - mz_uint8 c = *pSrc++; - d->m_dict[dst_pos] = c; - if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) - d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; - hash = - ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - - 1); - d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = - d->m_hash[hash]; - d->m_hash[hash] = (mz_uint16) (ins_pos); - dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; - ins_pos++; - } - } - else - { - while ((src_buf_left) - && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) - { - mz_uint8 c = *pSrc++; - mz_uint dst_pos = - (d->m_lookahead_pos + - d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; - src_buf_left--; - d->m_dict[dst_pos] = c; - if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) - d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; - if ((++d->m_lookahead_size + d->m_dict_size) >= - TDEFL_MIN_MATCH_LEN) - { - mz_uint ins_pos = - d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2; - mz_uint hash = - ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << - (TDEFL_LZ_HASH_SHIFT * - 2)) ^ (d->m_dict[(ins_pos + - 1) & TDEFL_LZ_DICT_SIZE_MASK] << - TDEFL_LZ_HASH_SHIFT) ^ c) & - (TDEFL_LZ_HASH_SIZE - 1); - d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = - d->m_hash[hash]; - d->m_hash[hash] = (mz_uint16) (ins_pos); - } - } - } - d->m_dict_size = - MZ_MIN (TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size); - if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) - break; - - // Simple lazy/greedy parsing state machine. - len_to_move = 1; - cur_match_dist = 0; - cur_match_len = - d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - - 1); - cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; - if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS)) - { - if ((d->m_dict_size) - && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) - { - mz_uint8 c = - d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK]; - cur_match_len = 0; - while (cur_match_len < d->m_lookahead_size) - { - if (d->m_dict[cur_pos + cur_match_len] != c) - break; - cur_match_len++; - } - if (cur_match_len < TDEFL_MIN_MATCH_LEN) - cur_match_len = 0; - else - cur_match_dist = 1; - } - } - else - { - tdefl_find_match (d, d->m_lookahead_pos, d->m_dict_size, - d->m_lookahead_size, &cur_match_dist, - &cur_match_len); - } - if (((cur_match_len == TDEFL_MIN_MATCH_LEN) - && (cur_match_dist >= 8U * 1024U)) || (cur_pos == cur_match_dist) - || ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5))) - { - cur_match_dist = cur_match_len = 0; - } - if (d->m_saved_match_len) - { - if (cur_match_len > d->m_saved_match_len) - { - tdefl_record_literal (d, (mz_uint8) d->m_saved_lit); - if (cur_match_len >= 128) - { - tdefl_record_match (d, cur_match_len, cur_match_dist); - d->m_saved_match_len = 0; - len_to_move = cur_match_len; - } - else - { - d->m_saved_lit = d->m_dict[cur_pos]; - d->m_saved_match_dist = cur_match_dist; - d->m_saved_match_len = cur_match_len; - } - } - else - { - tdefl_record_match (d, d->m_saved_match_len, - d->m_saved_match_dist); - len_to_move = d->m_saved_match_len - 1; - d->m_saved_match_len = 0; - } - } - else if (!cur_match_dist) - tdefl_record_literal (d, d->m_dict[cur_pos]); - else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) - || (cur_match_len >= 128)) - { - tdefl_record_match (d, cur_match_len, cur_match_dist); - len_to_move = cur_match_len; - } - else - { - d->m_saved_lit = d->m_dict[cur_pos]; - d->m_saved_match_dist = cur_match_dist; - d->m_saved_match_len = cur_match_len; - } - // Move the lookahead forward by len_to_move bytes. - d->m_lookahead_pos += len_to_move; - MZ_ASSERT (d->m_lookahead_size >= len_to_move); - d->m_lookahead_size -= len_to_move; - d->m_dict_size = - MZ_MIN (d->m_dict_size + len_to_move, (mz_uint) TDEFL_LZ_DICT_SIZE); - // Check if it's time to flush the current LZ codes to the internal output buffer. - if ((d->m_pLZ_code_buf > - &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) - || ((d->m_total_lz_bytes > 31 * 1024) - && - (((((mz_uint) (d->m_pLZ_code_buf - d->m_lz_code_buf) * - 115) >> 7) >= d->m_total_lz_bytes) - || (d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS)))) - { - int n; - d->m_pSrc = pSrc; - d->m_src_buf_left = src_buf_left; - if ((n = tdefl_flush_block (d, 0)) != 0) - return (n < 0) ? MZ_FALSE : MZ_TRUE; - } - } - - d->m_pSrc = pSrc; - d->m_src_buf_left = src_buf_left; - return MZ_TRUE; - } - - static tdefl_status tdefl_flush_output_buffer (tdefl_compressor * d) - { - if (d->m_pIn_buf_size) - { - *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *) d->m_pIn_buf; - } - - if (d->m_pOut_buf_size) - { - size_t n = MZ_MIN (*d->m_pOut_buf_size - d->m_out_buf_ofs, - d->m_output_flush_remaining); - memcpy ((mz_uint8 *) d->m_pOut_buf + d->m_out_buf_ofs, - d->m_output_buf + d->m_output_flush_ofs, n); - d->m_output_flush_ofs += (mz_uint) n; - d->m_output_flush_remaining -= (mz_uint) n; - d->m_out_buf_ofs += n; - - *d->m_pOut_buf_size = d->m_out_buf_ofs; - } - - return (d->m_finished - && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE : - TDEFL_STATUS_OKAY; - } - - tdefl_status tdefl_compress (tdefl_compressor * d, const void *pIn_buf, - size_t * pIn_buf_size, void *pOut_buf, - size_t * pOut_buf_size, tdefl_flush flush) - { - if (!d) - { - if (pIn_buf_size) - *pIn_buf_size = 0; - if (pOut_buf_size) - *pOut_buf_size = 0; - return TDEFL_STATUS_BAD_PARAM; - } - - d->m_pIn_buf = pIn_buf; - d->m_pIn_buf_size = pIn_buf_size; - d->m_pOut_buf = pOut_buf; - d->m_pOut_buf_size = pOut_buf_size; - d->m_pSrc = (const mz_uint8 *) (pIn_buf); - d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0; - d->m_out_buf_ofs = 0; - d->m_flush = flush; - - if (((d->m_pPut_buf_func != NULL) == - ((pOut_buf != NULL) || (pOut_buf_size != NULL))) - || (d->m_prev_return_status != TDEFL_STATUS_OKAY) - || (d->m_wants_to_finish && (flush != TDEFL_FINISH)) || (pIn_buf_size - && - *pIn_buf_size - && !pIn_buf) - || (pOut_buf_size && *pOut_buf_size && !pOut_buf)) - { - if (pIn_buf_size) - *pIn_buf_size = 0; - if (pOut_buf_size) - *pOut_buf_size = 0; - return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM); - } - d->m_wants_to_finish |= (flush == TDEFL_FINISH); - - if ((d->m_output_flush_remaining) || (d->m_finished)) - return (d->m_prev_return_status = tdefl_flush_output_buffer (d)); - -#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN - if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) && - ((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) && - ((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS | - TDEFL_RLE_MATCHES)) == 0)) - { - if (!tdefl_compress_fast (d)) - return d->m_prev_return_status; - } - else -#endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN - { - if (!tdefl_compress_normal (d)) - return d->m_prev_return_status; - } - - if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) - && (pIn_buf)) - d->m_adler32 = - (mz_uint32) mz_adler32 (d->m_adler32, (const mz_uint8 *) pIn_buf, - d->m_pSrc - (const mz_uint8 *) pIn_buf); - - if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) - && (!d->m_output_flush_remaining)) - { - if (tdefl_flush_block (d, flush) < 0) - return d->m_prev_return_status; - d->m_finished = (flush == TDEFL_FINISH); - if (flush == TDEFL_FULL_FLUSH) - { - MZ_CLEAR_OBJ (d->m_hash); - MZ_CLEAR_OBJ (d->m_next); - d->m_dict_size = 0; - } - } - - return (d->m_prev_return_status = tdefl_flush_output_buffer (d)); - } - - tdefl_status tdefl_compress_buffer (tdefl_compressor * d, - const void *pIn_buf, size_t in_buf_size, - tdefl_flush flush) - { - MZ_ASSERT (d->m_pPut_buf_func); - return tdefl_compress (d, pIn_buf, &in_buf_size, NULL, NULL, flush); - } - - tdefl_status tdefl_init (tdefl_compressor * d, - tdefl_put_buf_func_ptr pPut_buf_func, - void *pPut_buf_user, int flags) - { - d->m_pPut_buf_func = pPut_buf_func; - d->m_pPut_buf_user = pPut_buf_user; - d->m_flags = (mz_uint) (flags); - d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3; - d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0; - d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3; - if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) - MZ_CLEAR_OBJ (d->m_hash); - d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size = - d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0; - d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished = - d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0; - d->m_pLZ_code_buf = d->m_lz_code_buf + 1; - d->m_pLZ_flags = d->m_lz_code_buf; - d->m_num_flags_left = 8; - d->m_pOutput_buf = d->m_output_buf; - d->m_pOutput_buf_end = d->m_output_buf; - d->m_prev_return_status = TDEFL_STATUS_OKAY; - d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0; - d->m_adler32 = 1; - d->m_pIn_buf = NULL; - d->m_pOut_buf = NULL; - d->m_pIn_buf_size = NULL; - d->m_pOut_buf_size = NULL; - d->m_flush = TDEFL_NO_FLUSH; - d->m_pSrc = NULL; - d->m_src_buf_left = 0; - d->m_out_buf_ofs = 0; - memset (&d->m_huff_count[0][0], 0, - sizeof (d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); - memset (&d->m_huff_count[1][0], 0, - sizeof (d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); - return TDEFL_STATUS_OKAY; - } - - tdefl_status tdefl_get_prev_return_status (tdefl_compressor * d) - { - return d->m_prev_return_status; - } - - mz_uint32 tdefl_get_adler32 (tdefl_compressor * d) - { - return d->m_adler32; - } - - mz_bool tdefl_compress_mem_to_output (const void *pBuf, size_t buf_len, - tdefl_put_buf_func_ptr pPut_buf_func, - void *pPut_buf_user, int flags) - { - tdefl_compressor *pComp; - mz_bool succeeded; - if (((buf_len) && (!pBuf)) || (!pPut_buf_func)) - return MZ_FALSE; - pComp = (tdefl_compressor *) MZ_MALLOC (sizeof (tdefl_compressor)); - if (!pComp) - return MZ_FALSE; - succeeded = - (tdefl_init (pComp, pPut_buf_func, pPut_buf_user, flags) == - TDEFL_STATUS_OKAY); - succeeded = succeeded - && (tdefl_compress_buffer (pComp, pBuf, buf_len, TDEFL_FINISH) == - TDEFL_STATUS_DONE); - MZ_FREE (pComp); - return succeeded; - } - - typedef struct - { - size_t m_size, m_capacity; - mz_uint8 *m_pBuf; - mz_bool m_expandable; - } tdefl_output_buffer; - - static mz_bool tdefl_output_buffer_putter (const void *pBuf, int len, - void *pUser) - { - tdefl_output_buffer *p = (tdefl_output_buffer *) pUser; - size_t new_size = p->m_size + len; - if (new_size > p->m_capacity) - { - size_t new_capacity = p->m_capacity; - mz_uint8 *pNew_buf; - if (!p->m_expandable) - return MZ_FALSE; - do - { - new_capacity = MZ_MAX (128U, new_capacity << 1U); - } - while (new_size > new_capacity); - pNew_buf = (mz_uint8 *) MZ_REALLOC (p->m_pBuf, new_capacity); - if (!pNew_buf) - return MZ_FALSE; - p->m_pBuf = pNew_buf; - p->m_capacity = new_capacity; - } - memcpy ((mz_uint8 *) p->m_pBuf + p->m_size, pBuf, len); - p->m_size = new_size; - return MZ_TRUE; - } - - void *tdefl_compress_mem_to_heap (const void *pSrc_buf, size_t src_buf_len, - size_t * pOut_len, int flags) - { - tdefl_output_buffer out_buf; - MZ_CLEAR_OBJ (out_buf); - if (!pOut_len) - return MZ_FALSE; - else - *pOut_len = 0; - out_buf.m_expandable = MZ_TRUE; - if (!tdefl_compress_mem_to_output - (pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) - return NULL; - *pOut_len = out_buf.m_size; - return out_buf.m_pBuf; - } - - size_t tdefl_compress_mem_to_mem (void *pOut_buf, size_t out_buf_len, - const void *pSrc_buf, size_t src_buf_len, - int flags) - { - tdefl_output_buffer out_buf; - MZ_CLEAR_OBJ (out_buf); - if (!pOut_buf) - return 0; - out_buf.m_pBuf = (mz_uint8 *) pOut_buf; - out_buf.m_capacity = out_buf_len; - if (!tdefl_compress_mem_to_output - (pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) - return 0; - return out_buf.m_size; - } - - static const mz_uint s_tdefl_num_probes[11] = - { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 }; - -// level may actually range from [0,10] (10 is a "hidden" max level, where we want a bit more compression and it's fine if throughput to fall off a cliff on some files). - mz_uint tdefl_create_comp_flags_from_zip_params (int level, int window_bits, - int strategy) - { - mz_uint comp_flags = s_tdefl_num_probes[(level >= 0) ? MZ_MIN (10, - level) : - MZ_DEFAULT_LEVEL] | ((level <= - 3) ? - TDEFL_GREEDY_PARSING_FLAG - : 0); - if (window_bits > 0) - comp_flags |= TDEFL_WRITE_ZLIB_HEADER; - - if (!level) - comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS; - else if (strategy == MZ_FILTERED) - comp_flags |= TDEFL_FILTER_MATCHES; - else if (strategy == MZ_HUFFMAN_ONLY) - comp_flags &= ~TDEFL_MAX_PROBES_MASK; - else if (strategy == MZ_FIXED) - comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS; - else if (strategy == MZ_RLE) - comp_flags |= TDEFL_RLE_MATCHES; - - return comp_flags; - } - -#ifdef _MSC_VER -#pragma warning (push) -#pragma warning (disable:4204) // nonstandard extension used : non-constant aggregate initializer (also supported by GNU C and C99, so no big deal) -#endif - -// Simple PNG writer function by Alex Evans, 2011. Released into the public domain: https://gist.github.com/908299, more context at -// http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/. - void *tdefl_write_image_to_png_file_in_memory (const void *pImage, int w, - int h, int num_chans, - size_t * pLen_out) - { - tdefl_compressor *pComp = - (tdefl_compressor *) MZ_MALLOC (sizeof (tdefl_compressor)); - tdefl_output_buffer out_buf; - int i, bpl = w * num_chans, y, z; - mz_uint32 c; - *pLen_out = 0; - if (!pComp) - return NULL; - MZ_CLEAR_OBJ (out_buf); - out_buf.m_expandable = MZ_TRUE; - out_buf.m_capacity = 57 + MZ_MAX (64, (1 + bpl) * h); - if (NULL == - (out_buf.m_pBuf = (mz_uint8 *) MZ_MALLOC (out_buf.m_capacity))) - { - MZ_FREE (pComp); - return NULL; - } - // write dummy header - for (z = 41; z; --z) - tdefl_output_buffer_putter (&z, 1, &out_buf); - // compress image data - tdefl_init (pComp, tdefl_output_buffer_putter, &out_buf, - TDEFL_DEFAULT_MAX_PROBES | TDEFL_WRITE_ZLIB_HEADER); - for (y = 0; y < h; ++y) - { - tdefl_compress_buffer (pComp, &z, 1, TDEFL_NO_FLUSH); - tdefl_compress_buffer (pComp, (mz_uint8 *) pImage + y * bpl, bpl, - TDEFL_NO_FLUSH); - } - if (tdefl_compress_buffer (pComp, NULL, 0, TDEFL_FINISH) != - TDEFL_STATUS_DONE) - { - MZ_FREE (pComp); - MZ_FREE (out_buf.m_pBuf); - return NULL; - } - // write real header - *pLen_out = out_buf.m_size - 41; - { - mz_uint8 pnghdr[41] = - { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, - 0x0d, 0x49, 0x48, 0x44, 0x52, - 0, 0, (mz_uint8) (w >> 8), (mz_uint8) w, 0, 0, (mz_uint8) (h >> 8), - (mz_uint8) h, 8, "\0\0\04\02\06"[num_chans], 0, 0, 0, 0, 0, 0, 0, - (mz_uint8) (*pLen_out >> 24), (mz_uint8) (*pLen_out >> 16), - (mz_uint8) (*pLen_out >> 8), (mz_uint8) * pLen_out, 0x49, 0x44, - 0x41, 0x54 - }; - c = (mz_uint32) mz_crc32 (MZ_CRC32_INIT, pnghdr + 12, 17); - for (i = 0; i < 4; ++i, c <<= 8) - ((mz_uint8 *) (pnghdr + 29))[i] = (mz_uint8) (c >> 24); - memcpy (out_buf.m_pBuf, pnghdr, 41); - } - // write footer (IDAT CRC-32, followed by IEND chunk) - if (!tdefl_output_buffer_putter - ("\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf)) - { - *pLen_out = 0; - MZ_FREE (pComp); - MZ_FREE (out_buf.m_pBuf); - return NULL; - } - c = - (mz_uint32) mz_crc32 (MZ_CRC32_INIT, out_buf.m_pBuf + 41 - 4, - *pLen_out + 4); - for (i = 0; i < 4; ++i, c <<= 8) - (out_buf.m_pBuf + out_buf.m_size - 16)[i] = (mz_uint8) (c >> 24); - // compute final size of file, grab compressed data buffer and return - *pLen_out += 57; - MZ_FREE (pComp); - return out_buf.m_pBuf; - } - -#ifdef _MSC_VER -#pragma warning (pop) -#endif - -// ------------------- .ZIP archive reading - -#ifndef MINIZ_NO_ARCHIVE_APIS - -#ifndef MINIZ_NO_TIME -#include -#endif - -#ifdef MINIZ_NO_STDIO -#define MZ_FILE void * -#else -#include -#include -#if defined(_MSC_VER) || defined(__MINGW32__) || defined(__MINGW64__) -#include -#define MZ_FILE FILE -#define MZ_FOPEN fopen -#define MZ_FCLOSE fclose -#define MZ_FREAD fread -#define MZ_FWRITE fwrite -#define MZ_FTELL64 _ftelli64 -#define MZ_FSEEK64 _fseeki64 -#define MZ_FILE_STAT_STRUCT _stat -#define MZ_FILE_STAT _stat -#define MZ_FFLUSH fflush -#define MZ_FREOPEN freopen -#define MZ_DELETE_FILE remove -#else -#include -#define MZ_FILE FILE -#define MZ_FOPEN fopen -#define MZ_FCLOSE fclose -#define MZ_FREAD fread -#define MZ_FWRITE fwrite -#define MZ_FTELL64 ftello -#define MZ_FSEEK64 fseeko -#define MZ_FILE_STAT_STRUCT stat -#define MZ_FILE_STAT stat -#define MZ_FFLUSH fflush -#define MZ_FREOPEN freopen -#define MZ_DELETE_FILE remove -#endif // #ifdef _MSC_VER -#endif // #ifdef MINIZ_NO_STDIO - -#define MZ_TOLOWER(c) ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c)) - -// Various ZIP archive enums. To completely avoid cross platform compiler alignment and platform endian issues, miniz.c doesn't use structs for any of this stuff. - enum - { - // ZIP archive identifiers and record sizes - MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG = - 0x06054b50, MZ_ZIP_CENTRAL_DIR_HEADER_SIG = - 0x02014b50, MZ_ZIP_LOCAL_DIR_HEADER_SIG = 0x04034b50, - MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE = - 46, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE = 22, - // Central directory header record offsets - MZ_ZIP_CDH_SIG_OFS = 0, MZ_ZIP_CDH_VERSION_MADE_BY_OFS = - 4, MZ_ZIP_CDH_VERSION_NEEDED_OFS = 6, MZ_ZIP_CDH_BIT_FLAG_OFS = 8, - MZ_ZIP_CDH_METHOD_OFS = 10, MZ_ZIP_CDH_FILE_TIME_OFS = - 12, MZ_ZIP_CDH_FILE_DATE_OFS = 14, MZ_ZIP_CDH_CRC32_OFS = 16, - MZ_ZIP_CDH_COMPRESSED_SIZE_OFS = 20, MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS = - 24, MZ_ZIP_CDH_FILENAME_LEN_OFS = 28, MZ_ZIP_CDH_EXTRA_LEN_OFS = 30, - MZ_ZIP_CDH_COMMENT_LEN_OFS = 32, MZ_ZIP_CDH_DISK_START_OFS = - 34, MZ_ZIP_CDH_INTERNAL_ATTR_OFS = 36, MZ_ZIP_CDH_EXTERNAL_ATTR_OFS = - 38, MZ_ZIP_CDH_LOCAL_HEADER_OFS = 42, - // Local directory header offsets - MZ_ZIP_LDH_SIG_OFS = 0, MZ_ZIP_LDH_VERSION_NEEDED_OFS = - 4, MZ_ZIP_LDH_BIT_FLAG_OFS = 6, MZ_ZIP_LDH_METHOD_OFS = - 8, MZ_ZIP_LDH_FILE_TIME_OFS = 10, - MZ_ZIP_LDH_FILE_DATE_OFS = 12, MZ_ZIP_LDH_CRC32_OFS = - 14, MZ_ZIP_LDH_COMPRESSED_SIZE_OFS = - 18, MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS = 22, - MZ_ZIP_LDH_FILENAME_LEN_OFS = 26, MZ_ZIP_LDH_EXTRA_LEN_OFS = 28, - // End of central directory offsets - MZ_ZIP_ECDH_SIG_OFS = 0, MZ_ZIP_ECDH_NUM_THIS_DISK_OFS = - 4, MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS = - 6, MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 8, - MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS = 10, MZ_ZIP_ECDH_CDIR_SIZE_OFS = - 12, MZ_ZIP_ECDH_CDIR_OFS_OFS = 16, MZ_ZIP_ECDH_COMMENT_SIZE_OFS = 20, - }; - - typedef struct - { - void *m_p; - size_t m_size, m_capacity; - mz_uint m_element_size; - } mz_zip_array; - - struct mz_zip_internal_state_tag - { - mz_zip_array m_central_dir; - mz_zip_array m_central_dir_offsets; - mz_zip_array m_sorted_central_dir_offsets; - MZ_FILE *m_pFile; - void *m_pMem; - size_t m_mem_size; - size_t m_mem_capacity; - }; - -#define MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(array_ptr, element_size) (array_ptr)->m_element_size = element_size -#define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) ((element_type *)((array_ptr)->m_p))[index] - - static __forceinline void mz_zip_array_clear (mz_zip_archive * pZip, - mz_zip_array * pArray) - { - pZip->m_pFree (pZip->m_pAlloc_opaque, pArray->m_p); - memset (pArray, 0, sizeof (mz_zip_array)); - } - - static mz_bool mz_zip_array_ensure_capacity (mz_zip_archive * pZip, - mz_zip_array * pArray, - size_t min_new_capacity, - mz_uint growing) - { - void *pNew_p; - size_t new_capacity = min_new_capacity; - MZ_ASSERT (pArray->m_element_size); - if (pArray->m_capacity >= min_new_capacity) - return MZ_TRUE; - if (growing) - { - new_capacity = MZ_MAX (1, pArray->m_capacity); - while (new_capacity < min_new_capacity) - new_capacity *= 2; - } - if (NULL == - (pNew_p = - pZip->m_pRealloc (pZip->m_pAlloc_opaque, pArray->m_p, - pArray->m_element_size, new_capacity))) - return MZ_FALSE; - pArray->m_p = pNew_p; - pArray->m_capacity = new_capacity; - return MZ_TRUE; - } - - static __forceinline mz_bool mz_zip_array_reserve (mz_zip_archive * pZip, - mz_zip_array * pArray, - size_t new_capacity, - mz_uint growing) - { - if (new_capacity > pArray->m_capacity) - { - if (!mz_zip_array_ensure_capacity - (pZip, pArray, new_capacity, growing)) - return MZ_FALSE; - } - return MZ_TRUE; - } - - static __forceinline mz_bool mz_zip_array_resize (mz_zip_archive * pZip, - mz_zip_array * pArray, - size_t new_size, - mz_uint growing) - { - if (new_size > pArray->m_capacity) - { - if (!mz_zip_array_ensure_capacity (pZip, pArray, new_size, growing)) - return MZ_FALSE; - } - pArray->m_size = new_size; - return MZ_TRUE; - } - - static __forceinline mz_bool mz_zip_array_ensure_room (mz_zip_archive * - pZip, - mz_zip_array * - pArray, size_t n) - { - return mz_zip_array_reserve (pZip, pArray, pArray->m_size + n, MZ_TRUE); - } - - static __forceinline mz_bool mz_zip_array_push_back (mz_zip_archive * pZip, - mz_zip_array * pArray, - const void *pElements, - size_t n) - { - size_t orig_size = pArray->m_size; - if (!mz_zip_array_resize (pZip, pArray, orig_size + n, MZ_TRUE)) - return MZ_FALSE; - memcpy ((mz_uint8 *) pArray->m_p + orig_size * pArray->m_element_size, - pElements, n * pArray->m_element_size); - return MZ_TRUE; - } - -#ifndef MINIZ_NO_TIME - static time_t mz_zip_dos_to_time_t (int dos_time, int dos_date) - { - struct tm tm; - memset (&tm, 0, sizeof (tm)); - tm.tm_isdst = -1; - tm.tm_year = ((dos_date >> 9) & 127) + 1980 - 1900; - tm.tm_mon = ((dos_date >> 5) & 15) - 1; - tm.tm_mday = dos_date & 31; - tm.tm_hour = (dos_time >> 11) & 31; - tm.tm_min = (dos_time >> 5) & 63; - tm.tm_sec = (dos_time << 1) & 62; - return mktime (&tm); - } - - static void mz_zip_time_to_dos_time (time_t time, mz_uint16 * pDOS_time, - mz_uint16 * pDOS_date) - { - struct tm *tm = localtime (&time); - if (tm) - { - *pDOS_time = - (mz_uint16) (((tm->tm_hour) << 11) + ((tm->tm_min) << 5) + - ((tm->tm_sec) >> 1)); - *pDOS_date = - (mz_uint16) (((tm->tm_year + 1900 - 1980) << 9) + - ((tm->tm_mon + 1) << 5) + tm->tm_mday); - } - } -#endif - -#ifndef MINIZ_NO_STDIO - static mz_bool mz_zip_get_file_modified_time (const char *pFilename, - mz_uint16 * pDOS_time, - mz_uint16 * pDOS_date) - { -#ifdef MINIZ_NO_TIME - (void) pFilename; - *pDOS_date = *pDOS_time = 0; -#else - struct MZ_FILE_STAT_STRUCT file_stat; - if (MZ_FILE_STAT (pFilename, &file_stat) != 0) - return MZ_FALSE; - mz_zip_time_to_dos_time (file_stat.st_mtime, pDOS_time, pDOS_date); -#endif // #ifdef MINIZ_NO_TIME - return MZ_TRUE; - } - - static mz_bool mz_zip_set_file_times (const char *pFilename, - time_t access_time, - time_t modified_time) - { -#ifndef MINIZ_NO_TIME - struct utimbuf t; - t.actime = access_time; - t.modtime = modified_time; - return !utime (pFilename, &t); -#else - pFilename, access_time, modified_time; - return MZ_TRUE; -#endif // #ifndef MINIZ_NO_TIME - } -#endif - - static mz_bool mz_zip_reader_init_internal (mz_zip_archive * pZip, - mz_uint32 flags) - { - (void) flags; - if ((!pZip) || (pZip->m_pState) - || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) - return MZ_FALSE; - - if (!pZip->m_pAlloc) - pZip->m_pAlloc = def_alloc_func; - if (!pZip->m_pFree) - pZip->m_pFree = def_free_func; - if (!pZip->m_pRealloc) - pZip->m_pRealloc = def_realloc_func; - - pZip->m_zip_mode = MZ_ZIP_MODE_READING; - pZip->m_archive_size = 0; - pZip->m_central_directory_file_ofs = 0; - pZip->m_total_files = 0; - - if (NULL == - (pZip->m_pState = - (mz_zip_internal_state *) pZip->m_pAlloc (pZip->m_pAlloc_opaque, 1, - sizeof - (mz_zip_internal_state)))) - return MZ_FALSE; - memset (pZip->m_pState, 0, sizeof (mz_zip_internal_state)); - MZ_ZIP_ARRAY_SET_ELEMENT_SIZE (&pZip->m_pState->m_central_dir, - sizeof (mz_uint8)); - MZ_ZIP_ARRAY_SET_ELEMENT_SIZE (&pZip->m_pState->m_central_dir_offsets, - sizeof (mz_uint32)); - MZ_ZIP_ARRAY_SET_ELEMENT_SIZE (&pZip->m_pState-> - m_sorted_central_dir_offsets, - sizeof (mz_uint32)); - return MZ_TRUE; - } - - static __forceinline mz_bool mz_zip_reader_filename_less (const mz_zip_array - * - pCentral_dir_array, - const mz_zip_array - * - pCentral_dir_offsets, - mz_uint l_index, - mz_uint r_index) - { - const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT (pCentral_dir_array, mz_uint8, - MZ_ZIP_ARRAY_ELEMENT - (pCentral_dir_offsets, - mz_uint32, l_index)), *pE; - const mz_uint8 *pR = &MZ_ZIP_ARRAY_ELEMENT (pCentral_dir_array, mz_uint8, - MZ_ZIP_ARRAY_ELEMENT - (pCentral_dir_offsets, - mz_uint32, r_index)); - mz_uint l_len = MZ_READ_LE16 (pL + MZ_ZIP_CDH_FILENAME_LEN_OFS), r_len = - MZ_READ_LE16 (pR + MZ_ZIP_CDH_FILENAME_LEN_OFS); - mz_uint8 l = 0, r = 0; - pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; - pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; - pE = pL + MZ_MIN (l_len, r_len); - while (pL < pE) - { - if ((l = MZ_TOLOWER (*pL)) != (r = MZ_TOLOWER (*pR))) - break; - pL++; - pR++; - } - return (pL == pE) ? (l_len < r_len) : (l < r); - } - -#define MZ_SWAP_UINT32(a, b) do { mz_uint32 t = a; a = b; b = t; } MZ_MACRO_END - -// Heap sort of lowercased filenames, used to help accelerate plain central directory searches by mz_zip_reader_locate_file(). (Could also use qsort(), but it could allocate memory.) - static void - mz_zip_reader_sort_central_dir_offsets_by_filename (mz_zip_archive * pZip) - { - mz_zip_internal_state *pState = pZip->m_pState; - const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; - const mz_zip_array *pCentral_dir = &pState->m_central_dir; - mz_uint32 *pIndices = - &MZ_ZIP_ARRAY_ELEMENT (&pState->m_sorted_central_dir_offsets, mz_uint32, - 0); - const int size = pZip->m_total_files; - int start = (size - 2) >> 1, end; - while (start >= 0) - { - int child, root = start; - for (;;) - { - if ((child = (root << 1) + 1) >= size) - break; - child += (((child + 1) < size) - && - (mz_zip_reader_filename_less - (pCentral_dir, pCentral_dir_offsets, pIndices[child], - pIndices[child + 1]))); - if (!mz_zip_reader_filename_less - (pCentral_dir, pCentral_dir_offsets, pIndices[root], - pIndices[child])) - break; - MZ_SWAP_UINT32 (pIndices[root], pIndices[child]); - root = child; - } - start--; - } - - end = size - 1; - while (end > 0) - { - int child, root = 0; - MZ_SWAP_UINT32 (pIndices[end], pIndices[0]); - for (;;) - { - if ((child = (root << 1) + 1) >= end) - break; - child += (((child + 1) < end) - && mz_zip_reader_filename_less (pCentral_dir, - pCentral_dir_offsets, - pIndices[child], - pIndices[child + 1])); - if (!mz_zip_reader_filename_less - (pCentral_dir, pCentral_dir_offsets, pIndices[root], - pIndices[child])) - break; - MZ_SWAP_UINT32 (pIndices[root], pIndices[child]); - root = child; - } - end--; - } - } - - static mz_bool mz_zip_reader_read_central_dir (mz_zip_archive * pZip, - mz_uint32 flags) - { - mz_uint i, n, cdir_size, num_this_disk, cdir_disk_index; - mz_uint64 cdir_ofs; - mz_int64 cur_file_ofs; - const mz_uint8 *p; - mz_uint32 buf_u32[4096 / sizeof (mz_uint32)]; - mz_uint8 *pBuf = (mz_uint8 *) buf_u32; - // Basic sanity checks - reject files which are too small, and check the first 4 bytes of the file to make sure a local header is there. - if (pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) - return MZ_FALSE; - // Find the end of central directory record by scanning the file from the end towards the beginning. - cur_file_ofs = - MZ_MAX ((mz_int64) pZip->m_archive_size - (mz_int64) sizeof (buf_u32), - 0); - for (;;) - { - int i, n = (int) MZ_MIN (sizeof (buf_u32), - pZip->m_archive_size - cur_file_ofs); - if (pZip->m_pRead (pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != - (mz_uint) n) - return MZ_FALSE; - for (i = n - 4; i >= 0; --i) - if (MZ_READ_LE32 (pBuf + i) == MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) - break; - if (i >= 0) - { - cur_file_ofs += i; - break; - } - if ((!cur_file_ofs) - || ((pZip->m_archive_size - cur_file_ofs) >= - (0xFFFF + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE))) - return MZ_FALSE; - cur_file_ofs = MZ_MAX (cur_file_ofs - (sizeof (buf_u32) - 3), 0); - } - // Read and verify the end of central directory record. - if (pZip->m_pRead (pZip->m_pIO_opaque, cur_file_ofs, pBuf, - MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != - MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) - return MZ_FALSE; - if ((MZ_READ_LE32 (pBuf + MZ_ZIP_ECDH_SIG_OFS) != - MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) - || - ((pZip->m_total_files = - MZ_READ_LE16 (pBuf + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS)) != - MZ_READ_LE16 (pBuf + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS))) - return MZ_FALSE; - - num_this_disk = MZ_READ_LE16 (pBuf + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS); - cdir_disk_index = MZ_READ_LE16 (pBuf + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS); - if (((num_this_disk | cdir_disk_index) != 0) - && ((num_this_disk != 1) || (cdir_disk_index != 1))) - return MZ_FALSE; - - if ((cdir_size = - MZ_READ_LE32 (pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS)) < - pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) - return MZ_FALSE; - - cdir_ofs = MZ_READ_LE32 (pBuf + MZ_ZIP_ECDH_CDIR_OFS_OFS); - if ((cdir_ofs + (mz_uint64) cdir_size) > pZip->m_archive_size) - return MZ_FALSE; - - pZip->m_central_directory_file_ofs = cdir_ofs; - - if (pZip->m_total_files) - { - // Read the entire central directory into a heap block, and allocate another heap block to hold the unsorted central dir file record offsets, and another to hold the sorted indices. - if ((!mz_zip_array_resize - (pZip, &pZip->m_pState->m_central_dir, cdir_size, MZ_FALSE)) - || - (!mz_zip_array_resize - (pZip, &pZip->m_pState->m_central_dir_offsets, - pZip->m_total_files, MZ_FALSE)) - || - (!mz_zip_array_resize - (pZip, &pZip->m_pState->m_sorted_central_dir_offsets, - pZip->m_total_files, MZ_FALSE))) - return MZ_FALSE; - if (pZip->m_pRead (pZip->m_pIO_opaque, cdir_ofs, - pZip->m_pState->m_central_dir.m_p, - cdir_size) != cdir_size) - return MZ_FALSE; - - // Now create an index into the central directory file records, do some basic sanity checking on each record, and check for zip64 entries (which are not yet supported). - p = (const mz_uint8 *) pZip->m_pState->m_central_dir.m_p; - for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i) - { - mz_uint total_header_size, comp_size, decomp_size, disk_index; - if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) - || (MZ_READ_LE32 (p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG)) - return MZ_FALSE; - MZ_ZIP_ARRAY_ELEMENT (&pZip->m_pState->m_central_dir_offsets, - mz_uint32, i) = - (mz_uint32) (p - - (const mz_uint8 *) pZip->m_pState->m_central_dir. - m_p); - MZ_ZIP_ARRAY_ELEMENT (&pZip->m_pState-> - m_sorted_central_dir_offsets, mz_uint32, - i) = i; - comp_size = MZ_READ_LE32 (p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); - decomp_size = MZ_READ_LE32 (p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); - if (((!MZ_READ_LE32 (p + MZ_ZIP_CDH_METHOD_OFS)) - && (decomp_size != comp_size)) || (decomp_size && !comp_size) - || (decomp_size == 0xFFFFFFFF) || (comp_size == 0xFFFFFFFF)) - return MZ_FALSE; - disk_index = MZ_READ_LE16 (p + MZ_ZIP_CDH_DISK_START_OFS); - if ((disk_index != num_this_disk) && (disk_index != 1)) - return MZ_FALSE; - if (((mz_uint64) MZ_READ_LE32 (p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) + - MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > - pZip->m_archive_size) - return MZ_FALSE; - if ((total_header_size = - MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16 (p + - MZ_ZIP_CDH_FILENAME_LEN_OFS) - + MZ_READ_LE16 (p + MZ_ZIP_CDH_EXTRA_LEN_OFS) + - MZ_READ_LE16 (p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) > n) - return MZ_FALSE; - n -= total_header_size; - p += total_header_size; - } - } - - if ((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0) - mz_zip_reader_sort_central_dir_offsets_by_filename (pZip); - - return MZ_TRUE; - } - - mz_bool mz_zip_reader_init (mz_zip_archive * pZip, mz_uint64 size, - mz_uint32 flags) - { - if ((!pZip) || (!pZip->m_pRead)) - return MZ_FALSE; - if (!mz_zip_reader_init_internal (pZip, flags)) - return MZ_FALSE; - pZip->m_archive_size = size; - if (!mz_zip_reader_read_central_dir (pZip, flags)) - { - mz_zip_reader_end (pZip); - return MZ_FALSE; - } - return MZ_TRUE; - } - - static size_t mz_zip_mem_read_func (void *pOpaque, mz_uint64 file_ofs, - void *pBuf, size_t n) - { - mz_zip_archive *pZip = (mz_zip_archive *) pOpaque; - size_t s = - (file_ofs >= - pZip->m_archive_size) ? 0 : (size_t) MZ_MIN (pZip->m_archive_size - - file_ofs, n); - memcpy (pBuf, (const mz_uint8 *) pZip->m_pState->m_pMem + file_ofs, s); - return s; - } - - mz_bool mz_zip_reader_init_mem (mz_zip_archive * pZip, const void *pMem, - size_t size, mz_uint32 flags) - { - if (!mz_zip_reader_init_internal (pZip, flags)) - return MZ_FALSE; - pZip->m_archive_size = size; - pZip->m_pRead = mz_zip_mem_read_func; - pZip->m_pIO_opaque = pZip; - pZip->m_pState->m_pMem = (void *) pMem; - pZip->m_pState->m_mem_size = size; - if (!mz_zip_reader_read_central_dir (pZip, flags)) - { - mz_zip_reader_end (pZip); - return MZ_FALSE; - } - return MZ_TRUE; - } - -#ifndef MINIZ_NO_STDIO - static size_t mz_zip_file_read_func (void *pOpaque, mz_uint64 file_ofs, - void *pBuf, size_t n) - { - mz_zip_archive *pZip = (mz_zip_archive *) pOpaque; - mz_int64 cur_ofs = MZ_FTELL64 (pZip->m_pState->m_pFile); - if (((mz_int64) file_ofs < 0) - || (((cur_ofs != (mz_int64) file_ofs)) - && - (MZ_FSEEK64 - (pZip->m_pState->m_pFile, (mz_int64) file_ofs, SEEK_SET)))) - return 0; - return MZ_FREAD (pBuf, 1, n, pZip->m_pState->m_pFile); - } - - mz_bool mz_zip_reader_init_file (mz_zip_archive * pZip, - const char *pFilename, mz_uint32 flags) - { - mz_uint64 file_size; - MZ_FILE *pFile = MZ_FOPEN (pFilename, "rb"); - if (!pFile) - return MZ_FALSE; - if (MZ_FSEEK64 (pFile, 0, SEEK_END)) - { - MZ_FCLOSE (pFile); - return MZ_FALSE; - } - file_size = MZ_FTELL64 (pFile); - if (!mz_zip_reader_init_internal (pZip, flags)) - { - MZ_FCLOSE (pFile); - return MZ_FALSE; - } - pZip->m_pRead = mz_zip_file_read_func; - pZip->m_pIO_opaque = pZip; - pZip->m_pState->m_pFile = pFile; - pZip->m_archive_size = file_size; - if (!mz_zip_reader_read_central_dir (pZip, flags)) - { - mz_zip_reader_end (pZip); - return MZ_FALSE; - } - return MZ_TRUE; - } -#endif // #ifndef MINIZ_NO_STDIO - - mz_uint mz_zip_reader_get_num_files (mz_zip_archive * pZip) - { - return pZip ? pZip->m_total_files : 0; - } - - static __forceinline const mz_uint8 *mz_zip_reader_get_cdh (mz_zip_archive * - pZip, - mz_uint - file_index) - { - if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files) - || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) - return NULL; - return &MZ_ZIP_ARRAY_ELEMENT (&pZip->m_pState->m_central_dir, mz_uint8, - MZ_ZIP_ARRAY_ELEMENT (&pZip->m_pState-> - m_central_dir_offsets, - mz_uint32, - file_index)); - } - - mz_bool mz_zip_reader_is_file_encrypted (mz_zip_archive * pZip, - mz_uint file_index) - { - mz_uint m_bit_flag; - const mz_uint8 *p = mz_zip_reader_get_cdh (pZip, file_index); - if (!p) - return MZ_FALSE; - m_bit_flag = MZ_READ_LE16 (p + MZ_ZIP_CDH_BIT_FLAG_OFS); - return (m_bit_flag & 1); - } - - mz_bool mz_zip_reader_is_file_a_directory (mz_zip_archive * pZip, - mz_uint file_index) - { - mz_uint filename_len, internal_attr, external_attr; - const mz_uint8 *p = mz_zip_reader_get_cdh (pZip, file_index); - if (!p) - return MZ_FALSE; - - internal_attr = MZ_READ_LE16 (p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS); - external_attr = MZ_READ_LE32 (p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); - if ((!internal_attr) && ((external_attr & 0x10) != 0)) - return MZ_TRUE; - - filename_len = MZ_READ_LE16 (p + MZ_ZIP_CDH_FILENAME_LEN_OFS); - if (filename_len) - { - if (*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/') - return MZ_TRUE; - } - - return MZ_FALSE; - } - - mz_bool mz_zip_reader_file_stat (mz_zip_archive * pZip, mz_uint file_index, - mz_zip_archive_file_stat * pStat) - { - mz_uint n; - const mz_uint8 *p = mz_zip_reader_get_cdh (pZip, file_index); - if ((!p) || (!pStat)) - return MZ_FALSE; - - // Unpack the central directory record. - pStat->m_file_index = file_index; - pStat->m_central_dir_ofs = - MZ_ZIP_ARRAY_ELEMENT (&pZip->m_pState->m_central_dir_offsets, mz_uint32, - file_index); - pStat->m_version_made_by = - MZ_READ_LE16 (p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS); - pStat->m_version_needed = - MZ_READ_LE16 (p + MZ_ZIP_CDH_VERSION_NEEDED_OFS); - pStat->m_bit_flag = MZ_READ_LE16 (p + MZ_ZIP_CDH_BIT_FLAG_OFS); - pStat->m_method = MZ_READ_LE16 (p + MZ_ZIP_CDH_METHOD_OFS); -#ifndef MINIZ_NO_TIME - pStat->m_time = - mz_zip_dos_to_time_t (MZ_READ_LE16 (p + MZ_ZIP_CDH_FILE_TIME_OFS), - MZ_READ_LE16 (p + MZ_ZIP_CDH_FILE_DATE_OFS)); -#endif - pStat->m_crc32 = MZ_READ_LE32 (p + MZ_ZIP_CDH_CRC32_OFS); - pStat->m_comp_size = MZ_READ_LE32 (p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); - pStat->m_uncomp_size = - MZ_READ_LE32 (p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); - pStat->m_internal_attr = MZ_READ_LE16 (p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS); - pStat->m_external_attr = MZ_READ_LE32 (p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); - pStat->m_local_header_ofs = - MZ_READ_LE32 (p + MZ_ZIP_CDH_LOCAL_HEADER_OFS); - - // Copy as much of the filename and comment as possible. - n = MZ_READ_LE16 (p + MZ_ZIP_CDH_FILENAME_LEN_OFS); - n = MZ_MIN (n, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE - 1); - memcpy (pStat->m_filename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); - pStat->m_filename[n] = '\0'; - - n = MZ_READ_LE16 (p + MZ_ZIP_CDH_COMMENT_LEN_OFS); - n = MZ_MIN (n, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE - 1); - pStat->m_comment_size = n; - memcpy (pStat->m_comment, - p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16 (p + - MZ_ZIP_CDH_FILENAME_LEN_OFS) - + MZ_READ_LE16 (p + MZ_ZIP_CDH_EXTRA_LEN_OFS), n); - pStat->m_comment[n] = '\0'; - - return MZ_TRUE; - } - - mz_uint mz_zip_reader_get_filename (mz_zip_archive * pZip, - mz_uint file_index, char *pFilename, - mz_uint filename_buf_size) - { - mz_uint n; - const mz_uint8 *p = mz_zip_reader_get_cdh (pZip, file_index); - if (!p) - { - if (filename_buf_size) - pFilename[0] = '\0'; - return 0; - } - n = MZ_READ_LE16 (p + MZ_ZIP_CDH_FILENAME_LEN_OFS); - if (filename_buf_size) - { - n = MZ_MIN (n, filename_buf_size - 1); - memcpy (pFilename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); - pFilename[n] = '\0'; - } - return n + 1; - } - - static __forceinline mz_bool mz_zip_reader_string_equal (const char *pA, - const char *pB, - mz_uint len, - mz_uint flags) - { - mz_uint i; - if (flags & MZ_ZIP_FLAG_CASE_SENSITIVE) - return 0 == memcmp (pA, pB, len); - for (i = 0; i < len; ++i) - if (MZ_TOLOWER (pA[i]) != MZ_TOLOWER (pB[i])) - return MZ_FALSE; - return MZ_TRUE; - } - - static __forceinline int mz_zip_reader_filename_compare (const mz_zip_array - * - pCentral_dir_array, - const mz_zip_array - * - pCentral_dir_offsets, - mz_uint l_index, - const char *pR, - mz_uint r_len) - { - const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT (pCentral_dir_array, mz_uint8, - MZ_ZIP_ARRAY_ELEMENT - (pCentral_dir_offsets, - mz_uint32, l_index)), *pE; - mz_uint l_len = MZ_READ_LE16 (pL + MZ_ZIP_CDH_FILENAME_LEN_OFS); - mz_uint8 l = 0, r = 0; - pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; - pE = pL + MZ_MIN (l_len, r_len); - while (pL < pE) - { - if ((l = MZ_TOLOWER (*pL)) != (r = MZ_TOLOWER (*pR))) - break; - pL++; - pR++; - } - return (pL == pE) ? (int) (l_len - r_len) : (l - r); - } - - static int mz_zip_reader_locate_file_binary_search (mz_zip_archive * pZip, - const char *pFilename) - { - mz_zip_internal_state *pState = pZip->m_pState; - const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; - const mz_zip_array *pCentral_dir = &pState->m_central_dir; - mz_uint32 *pIndices = - &MZ_ZIP_ARRAY_ELEMENT (&pState->m_sorted_central_dir_offsets, mz_uint32, - 0); - const int size = pZip->m_total_files; - const mz_uint filename_len = (mz_uint) strlen (pFilename); - int l = 0, h = size - 1; - while (l <= h) - { - int m = (l + h) >> 1, file_index = pIndices[m], comp = - mz_zip_reader_filename_compare (pCentral_dir, pCentral_dir_offsets, - file_index, pFilename, - filename_len); - if (!comp) - return file_index; - else if (comp < 0) - l = m + 1; - else - h = m - 1; - } - return -1; - } - - int mz_zip_reader_locate_file (mz_zip_archive * pZip, const char *pName, - const char *pComment, mz_uint flags) - { - mz_uint file_index; - size_t name_len, comment_len; - if ((!pZip) || (!pZip->m_pState) || (!pName) - || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) - return -1; - if (((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == - 0) && (!pComment) - && (pZip->m_pState->m_sorted_central_dir_offsets.m_p)) - return mz_zip_reader_locate_file_binary_search (pZip, pName); - name_len = strlen (pName); - if (name_len > 0xFFFF) - return -1; - comment_len = pComment ? strlen (pComment) : 0; - if (comment_len > 0xFFFF) - return -1; - for (file_index = 0; file_index < pZip->m_total_files; file_index++) - { - const mz_uint8 *pHeader = - &MZ_ZIP_ARRAY_ELEMENT (&pZip->m_pState->m_central_dir, mz_uint8, - MZ_ZIP_ARRAY_ELEMENT (&pZip->m_pState-> - m_central_dir_offsets, - mz_uint32, - file_index)); - mz_uint filename_len = - MZ_READ_LE16 (pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS); - const char *pFilename = - (const char *) pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; - if (filename_len < name_len) - continue; - if (comment_len) - { - mz_uint file_extra_len = - MZ_READ_LE16 (pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS), - file_comment_len = - MZ_READ_LE16 (pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS); - const char *pFile_comment = - pFilename + filename_len + file_extra_len; - if ((file_comment_len != comment_len) - || - (!mz_zip_reader_string_equal - (pComment, pFile_comment, file_comment_len, flags))) - continue; - } - if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len)) - { - int ofs = filename_len - 1; - do - { - if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') - || (pFilename[ofs] == ':')) - break; - } - while (--ofs >= 0); - ofs++; - pFilename += ofs; - filename_len -= ofs; - } - if ((filename_len == name_len) - && - (mz_zip_reader_string_equal - (pName, pFilename, filename_len, flags))) - return file_index; - } - return -1; - } - - mz_bool mz_zip_reader_extract_to_mem_no_alloc (mz_zip_archive * pZip, - mz_uint file_index, - void *pBuf, size_t buf_size, - mz_uint flags, - void *pUser_read_buf, - size_t user_read_buf_size) - { - int status = TINFL_STATUS_DONE; - mz_uint64 needed_size, cur_file_ofs, comp_remaining, out_buf_ofs = - 0, read_buf_size, read_buf_ofs = 0, read_buf_avail; - mz_zip_archive_file_stat file_stat; - void *pRead_buf; - mz_uint32 - local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof (mz_uint32) - - 1) / sizeof (mz_uint32)]; - mz_uint8 *pLocal_header = (mz_uint8 *) local_header_u32; - tinfl_decompressor inflator; - - if ((buf_size) && (!pBuf)) - return MZ_FALSE; - - if (!mz_zip_reader_file_stat (pZip, file_index, &file_stat)) - return MZ_FALSE; - - if (!file_stat.m_comp_size) - return MZ_TRUE; - - // Encryption and patch files are not supported. - if (file_stat.m_bit_flag & (1 | 32)) - return MZ_FALSE; - - // This function only supports stored and deflate. - if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) - && (file_stat.m_method != MZ_DEFLATED)) - return MZ_FALSE; - - // Ensure supplied output buffer is large enough. - needed_size = - (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat. - m_comp_size : file_stat.m_uncomp_size; - if (buf_size < needed_size) - return MZ_FALSE; - - // Read and parse the local directory entry. - cur_file_ofs = file_stat.m_local_header_ofs; - if (pZip->m_pRead (pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, - MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != - MZ_ZIP_LOCAL_DIR_HEADER_SIZE) - return MZ_FALSE; - if (MZ_READ_LE32 (pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) - return MZ_FALSE; - - cur_file_ofs += - MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16 (pLocal_header + - MZ_ZIP_LDH_FILENAME_LEN_OFS) - + MZ_READ_LE16 (pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); - if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) - return MZ_FALSE; - - if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) - { - // The file is stored or the caller has requested the compressed data. - if (pZip->m_pRead (pZip->m_pIO_opaque, cur_file_ofs, pBuf, - (size_t) needed_size) != needed_size) - return MZ_FALSE; - return ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) != 0) - || - (mz_crc32 - (MZ_CRC32_INIT, (const mz_uint8 *) pBuf, - (size_t) file_stat.m_uncomp_size) == file_stat.m_crc32); - } - - // Decompress the file either directly from memory or from a file input buffer. - tinfl_init (&inflator); - - if (pZip->m_pState->m_pMem) - { - // Read directly from the archive in memory. - pRead_buf = (mz_uint8 *) pZip->m_pState->m_pMem + cur_file_ofs; - read_buf_size = read_buf_avail = file_stat.m_comp_size; - comp_remaining = 0; - } - else if (pUser_read_buf) - { - // Use a user provided read buffer. - if (!user_read_buf_size) - return MZ_FALSE; - pRead_buf = (mz_uint8 *) pUser_read_buf; - read_buf_size = user_read_buf_size; - read_buf_avail = 0; - comp_remaining = file_stat.m_uncomp_size; - } - else - { - // Temporarily allocate a read buffer. - read_buf_size = - MZ_MIN (file_stat.m_comp_size, (mz_uint64) MZ_ZIP_MAX_IO_BUF_SIZE); - if (((0, sizeof (size_t) == sizeof (mz_uint32))) - && (read_buf_size > 0x7FFFFFFF)) - return MZ_FALSE; - if (NULL == - (pRead_buf = - pZip->m_pAlloc (pZip->m_pAlloc_opaque, 1, - (size_t) read_buf_size))) - return MZ_FALSE; - read_buf_avail = 0; - comp_remaining = file_stat.m_comp_size; - } - - do - { - size_t in_buf_size, out_buf_size = - (size_t) (file_stat.m_uncomp_size - out_buf_ofs); - if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) - { - read_buf_avail = MZ_MIN (read_buf_size, comp_remaining); - if (pZip->m_pRead (pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, - (size_t) read_buf_avail) != read_buf_avail) - { - status = TINFL_STATUS_FAILED; - break; - } - cur_file_ofs += read_buf_avail; - comp_remaining -= read_buf_avail; - read_buf_ofs = 0; - } - in_buf_size = (size_t) read_buf_avail; - status = - tinfl_decompress (&inflator, (mz_uint8 *) pRead_buf + read_buf_ofs, - &in_buf_size, (mz_uint8 *) pBuf, - (mz_uint8 *) pBuf + out_buf_ofs, &out_buf_size, - TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF | - (comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0)); - read_buf_avail -= in_buf_size; - read_buf_ofs += in_buf_size; - out_buf_ofs += out_buf_size; - } - while (status == TINFL_STATUS_NEEDS_MORE_INPUT); - - if (status == TINFL_STATUS_DONE) - { - // Make sure the entire file was decompressed, and check its CRC. - if ((out_buf_ofs != file_stat.m_uncomp_size) - || - (mz_crc32 - (MZ_CRC32_INIT, (const mz_uint8 *) pBuf, - (size_t) file_stat.m_uncomp_size) != file_stat.m_crc32)) - status = TINFL_STATUS_FAILED; - } - - if ((!pZip->m_pState->m_pMem) && (!pUser_read_buf)) - pZip->m_pFree (pZip->m_pAlloc_opaque, pRead_buf); - - return status == TINFL_STATUS_DONE; - } - - mz_bool mz_zip_reader_extract_file_to_mem_no_alloc (mz_zip_archive * pZip, - const char *pFilename, - void *pBuf, - size_t buf_size, - mz_uint flags, - void *pUser_read_buf, - size_t - user_read_buf_size) - { - int file_index = mz_zip_reader_locate_file (pZip, pFilename, NULL, flags); - if (file_index < 0) - return MZ_FALSE; - return mz_zip_reader_extract_to_mem_no_alloc (pZip, file_index, pBuf, - buf_size, flags, - pUser_read_buf, - user_read_buf_size); - } - - mz_bool mz_zip_reader_extract_to_mem (mz_zip_archive * pZip, - mz_uint file_index, void *pBuf, - size_t buf_size, mz_uint flags) - { - return mz_zip_reader_extract_to_mem_no_alloc (pZip, file_index, pBuf, - buf_size, flags, NULL, 0); - } - - mz_bool mz_zip_reader_extract_file_to_mem (mz_zip_archive * pZip, - const char *pFilename, - void *pBuf, size_t buf_size, - mz_uint flags) - { - return mz_zip_reader_extract_file_to_mem_no_alloc (pZip, pFilename, pBuf, - buf_size, flags, NULL, - 0); - } - - void *mz_zip_reader_extract_to_heap (mz_zip_archive * pZip, - mz_uint file_index, size_t * pSize, - mz_uint flags) - { - mz_uint64 comp_size, uncomp_size, alloc_size; - const mz_uint8 *p = mz_zip_reader_get_cdh (pZip, file_index); - void *pBuf; - - if (pSize) - *pSize = 0; - if (!p) - return NULL; - - comp_size = MZ_READ_LE32 (p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); - uncomp_size = MZ_READ_LE32 (p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); - - alloc_size = - (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? comp_size : uncomp_size; - if (((0, sizeof (size_t) == sizeof (mz_uint32))) - && (alloc_size > 0x7FFFFFFF)) - return NULL; - if (NULL == - (pBuf = - pZip->m_pAlloc (pZip->m_pAlloc_opaque, 1, (size_t) alloc_size))) - return NULL; - - if (!mz_zip_reader_extract_to_mem - (pZip, file_index, pBuf, (size_t) alloc_size, flags)) - { - pZip->m_pFree (pZip->m_pAlloc_opaque, pBuf); - return NULL; - } - - if (pSize) - *pSize = (size_t) alloc_size; - return pBuf; - } - - void *mz_zip_reader_extract_file_to_heap (mz_zip_archive * pZip, - const char *pFilename, - size_t * pSize, mz_uint flags) - { - int file_index = mz_zip_reader_locate_file (pZip, pFilename, NULL, flags); - if (file_index < 0) - { - if (pSize) - *pSize = 0; - return MZ_FALSE; - } - return mz_zip_reader_extract_to_heap (pZip, file_index, pSize, flags); - } - - mz_bool mz_zip_reader_extract_to_callback (mz_zip_archive * pZip, - mz_uint file_index, - mz_file_write_func pCallback, - void *pOpaque, mz_uint flags) - { - int status = TINFL_STATUS_DONE; - mz_uint file_crc32 = MZ_CRC32_INIT; - mz_uint64 read_buf_size, read_buf_ofs = - 0, read_buf_avail, comp_remaining, out_buf_ofs = 0, cur_file_ofs; - mz_zip_archive_file_stat file_stat; - void *pRead_buf = NULL; - void *pWrite_buf = NULL; - mz_uint32 - local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof (mz_uint32) - - 1) / sizeof (mz_uint32)]; - mz_uint8 *pLocal_header = (mz_uint8 *) local_header_u32; - - if (!mz_zip_reader_file_stat (pZip, file_index, &file_stat)) - return MZ_FALSE; - - if (!file_stat.m_comp_size) - return MZ_TRUE; - - // Encryption and patch files are not supported. - if (file_stat.m_bit_flag & (1 | 32)) - return MZ_FALSE; - - // This function only supports stored and deflate. - if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) - && (file_stat.m_method != MZ_DEFLATED)) - return MZ_FALSE; - - // Read and parse the local directory entry. - cur_file_ofs = file_stat.m_local_header_ofs; - if (pZip->m_pRead (pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, - MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != - MZ_ZIP_LOCAL_DIR_HEADER_SIZE) - return MZ_FALSE; - if (MZ_READ_LE32 (pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) - return MZ_FALSE; - - cur_file_ofs += - MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16 (pLocal_header + - MZ_ZIP_LDH_FILENAME_LEN_OFS) - + MZ_READ_LE16 (pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); - if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) - return MZ_FALSE; - - // Decompress the file either directly from memory or from a file input buffer. - if (pZip->m_pState->m_pMem) - { - pRead_buf = (mz_uint8 *) pZip->m_pState->m_pMem + cur_file_ofs; - read_buf_size = read_buf_avail = file_stat.m_comp_size; - comp_remaining = 0; - } - else - { - read_buf_size = - MZ_MIN (file_stat.m_comp_size, (mz_uint64) MZ_ZIP_MAX_IO_BUF_SIZE); - if (NULL == - (pRead_buf = - pZip->m_pAlloc (pZip->m_pAlloc_opaque, 1, - (size_t) read_buf_size))) - return MZ_FALSE; - read_buf_avail = 0; - comp_remaining = file_stat.m_comp_size; - } - - if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) - { - // The file is stored or the caller has requested the compressed data. - if (pZip->m_pState->m_pMem) - { - if (((0, sizeof (size_t) == sizeof (mz_uint32))) - && (file_stat.m_comp_size > 0xFFFFFFFF)) - return MZ_FALSE; - if (pCallback - (pOpaque, out_buf_ofs, pRead_buf, - (size_t) file_stat.m_comp_size) != file_stat.m_comp_size) - status = TINFL_STATUS_FAILED; - else if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) - file_crc32 = - (mz_uint32) mz_crc32 (file_crc32, - (const mz_uint8 *) pRead_buf, - (size_t) file_stat.m_comp_size); - cur_file_ofs += file_stat.m_comp_size; - out_buf_ofs += file_stat.m_comp_size; - comp_remaining = 0; - } - else - { - while (comp_remaining) - { - read_buf_avail = MZ_MIN (read_buf_size, comp_remaining); - if (pZip->m_pRead - (pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, - (size_t) read_buf_avail) != read_buf_avail) - { - status = TINFL_STATUS_FAILED; - break; - } - - if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) - file_crc32 = - (mz_uint32) mz_crc32 (file_crc32, - (const mz_uint8 *) pRead_buf, - (size_t) read_buf_avail); - - if (pCallback - (pOpaque, out_buf_ofs, pRead_buf, - (size_t) read_buf_avail) != read_buf_avail) - { - status = TINFL_STATUS_FAILED; - break; - } - cur_file_ofs += read_buf_avail; - out_buf_ofs += read_buf_avail; - comp_remaining -= read_buf_avail; - } - } - } - else - { - tinfl_decompressor inflator; - tinfl_init (&inflator); - - if (NULL == - (pWrite_buf = - pZip->m_pAlloc (pZip->m_pAlloc_opaque, 1, TINFL_LZ_DICT_SIZE))) - status = TINFL_STATUS_FAILED; - else - { - do - { - mz_uint8 *pWrite_buf_cur = - (mz_uint8 *) pWrite_buf + - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); - size_t in_buf_size, out_buf_size = - TINFL_LZ_DICT_SIZE - - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); - if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) - { - read_buf_avail = MZ_MIN (read_buf_size, comp_remaining); - if (pZip->m_pRead - (pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, - (size_t) read_buf_avail) != read_buf_avail) - { - status = TINFL_STATUS_FAILED; - break; - } - cur_file_ofs += read_buf_avail; - comp_remaining -= read_buf_avail; - read_buf_ofs = 0; - } - - in_buf_size = (size_t) read_buf_avail; - status = - tinfl_decompress (&inflator, - (const mz_uint8 *) pRead_buf + - read_buf_ofs, &in_buf_size, - (mz_uint8 *) pWrite_buf, pWrite_buf_cur, - &out_buf_size, - comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT - : 0); - read_buf_avail -= in_buf_size; - read_buf_ofs += in_buf_size; - - if (out_buf_size) - { - if (pCallback - (pOpaque, out_buf_ofs, pWrite_buf_cur, - out_buf_size) != out_buf_size) - { - status = TINFL_STATUS_FAILED; - break; - } - file_crc32 = - (mz_uint32) mz_crc32 (file_crc32, pWrite_buf_cur, - out_buf_size); - if ((out_buf_ofs += - out_buf_size) > file_stat.m_uncomp_size) - { - status = TINFL_STATUS_FAILED; - break; - } - } - } - while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) - || (status == TINFL_STATUS_HAS_MORE_OUTPUT)); - } - } -#if 0 - if ((status == TINFL_STATUS_DONE) - && (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) - { - // Make sure the entire file was decompressed, and check its CRC. - if ((out_buf_ofs != file_stat.m_uncomp_size) - || (file_crc32 != file_stat.m_crc32)) - status = TINFL_STATUS_FAILED; - } -#endif - if (!pZip->m_pState->m_pMem) - pZip->m_pFree (pZip->m_pAlloc_opaque, pRead_buf); - if (pWrite_buf) - pZip->m_pFree (pZip->m_pAlloc_opaque, pWrite_buf); - - return status == TINFL_STATUS_DONE; - } - - mz_bool mz_zip_reader_extract_file_to_callback (mz_zip_archive * pZip, - const char *pFilename, - mz_file_write_func - pCallback, void *pOpaque, - mz_uint flags) - { - int file_index = mz_zip_reader_locate_file (pZip, pFilename, NULL, flags); - if (file_index < 0) - return MZ_FALSE; - return mz_zip_reader_extract_to_callback (pZip, file_index, pCallback, - pOpaque, flags); - } - -#ifndef MINIZ_NO_STDIO - static size_t mz_zip_file_write_callback (void *pOpaque, mz_uint64 ofs, - const void *pBuf, size_t n) - { - (void) ofs; - return MZ_FWRITE (pBuf, 1, n, (MZ_FILE *) pOpaque); - } - - mz_bool mz_zip_reader_extract_to_file (mz_zip_archive * pZip, - mz_uint file_index, - const char *pDst_filename, - mz_uint flags) - { - mz_bool status; - mz_zip_archive_file_stat file_stat; - MZ_FILE *pFile; - if (!mz_zip_reader_file_stat (pZip, file_index, &file_stat)) - return MZ_FALSE; - pFile = MZ_FOPEN (pDst_filename, "wb"); - if (!pFile) - return MZ_FALSE; - status = - mz_zip_reader_extract_to_callback (pZip, file_index, - mz_zip_file_write_callback, pFile, - flags); - if (MZ_FCLOSE (pFile) == EOF) - return MZ_FALSE; -#ifndef MINIZ_NO_TIME - if (status) - mz_zip_set_file_times (pDst_filename, file_stat.m_time, - file_stat.m_time); -#endif - return status; - } -#endif // #ifndef MINIZ_NO_STDIO - - mz_bool mz_zip_reader_end (mz_zip_archive * pZip) - { - if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) - || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) - return MZ_FALSE; - - if (pZip->m_pState) - { - mz_zip_internal_state *pState = pZip->m_pState; - pZip->m_pState = NULL; - mz_zip_array_clear (pZip, &pState->m_central_dir); - mz_zip_array_clear (pZip, &pState->m_central_dir_offsets); - mz_zip_array_clear (pZip, &pState->m_sorted_central_dir_offsets); - -#ifndef MINIZ_NO_STDIO - if (pState->m_pFile) - { - MZ_FCLOSE (pState->m_pFile); - pState->m_pFile = NULL; - } -#endif // #ifndef MINIZ_NO_STDIO - - pZip->m_pFree (pZip->m_pAlloc_opaque, pState); - } - pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; - - return MZ_TRUE; - } - - mz_bool mz_zip_reader_extract_file_to_file (mz_zip_archive * pZip, - const char *pArchive_filename, - const char *pDst_filename, - mz_uint flags) - { - int file_index = - mz_zip_reader_locate_file (pZip, pArchive_filename, NULL, flags); - if (file_index < 0) - return MZ_FALSE; - return mz_zip_reader_extract_to_file (pZip, file_index, pDst_filename, - flags); - } - -// ------------------- .ZIP archive writing - -#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS - - static void mz_write_le16 (mz_uint8 * p, mz_uint16 v) - { - p[0] = (mz_uint8) v; - p[1] = (mz_uint8) (v >> 8); - } - static void mz_write_le32 (mz_uint8 * p, mz_uint32 v) - { - p[0] = (mz_uint8) v; - p[1] = (mz_uint8) (v >> 8); - p[2] = (mz_uint8) (v >> 16); - p[3] = (mz_uint8) (v >> 24); - } -#define MZ_WRITE_LE16(p, v) mz_write_le16((mz_uint8 *)(p), (mz_uint16)(v)) -#define MZ_WRITE_LE32(p, v) mz_write_le32((mz_uint8 *)(p), (mz_uint32)(v)) - - mz_bool mz_zip_writer_init (mz_zip_archive * pZip, mz_uint64 existing_size) - { - if ((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) - || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) - return MZ_FALSE; - - if (pZip->m_file_offset_alignment) - { - // Ensure user specified file offset alignment is a power of 2. - if (pZip->m_file_offset_alignment & - (pZip->m_file_offset_alignment - 1)) - return MZ_FALSE; - } - - if (!pZip->m_pAlloc) - pZip->m_pAlloc = def_alloc_func; - if (!pZip->m_pFree) - pZip->m_pFree = def_free_func; - if (!pZip->m_pRealloc) - pZip->m_pRealloc = def_realloc_func; - - pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; - pZip->m_archive_size = existing_size; - pZip->m_central_directory_file_ofs = 0; - pZip->m_total_files = 0; - - if (NULL == - (pZip->m_pState = - (mz_zip_internal_state *) pZip->m_pAlloc (pZip->m_pAlloc_opaque, 1, - sizeof - (mz_zip_internal_state)))) - return MZ_FALSE; - memset (pZip->m_pState, 0, sizeof (mz_zip_internal_state)); - MZ_ZIP_ARRAY_SET_ELEMENT_SIZE (&pZip->m_pState->m_central_dir, - sizeof (mz_uint8)); - MZ_ZIP_ARRAY_SET_ELEMENT_SIZE (&pZip->m_pState->m_central_dir_offsets, - sizeof (mz_uint32)); - MZ_ZIP_ARRAY_SET_ELEMENT_SIZE (&pZip->m_pState-> - m_sorted_central_dir_offsets, - sizeof (mz_uint32)); - return MZ_TRUE; - } - - static size_t mz_zip_heap_write_func (void *pOpaque, mz_uint64 file_ofs, - const void *pBuf, size_t n) - { - mz_zip_archive *pZip = (mz_zip_archive *) pOpaque; - mz_zip_internal_state *pState = pZip->m_pState; - mz_uint64 new_size = MZ_MAX (file_ofs + n, pState->m_mem_size); - if ((!n) - || ((0, sizeof (size_t) == sizeof (mz_uint32)) - && (new_size > 0x7FFFFFFF))) - return 0; - if (new_size > pState->m_mem_capacity) - { - void *pNew_block; - size_t new_capacity = MZ_MAX (64, pState->m_mem_capacity); - while (new_capacity < new_size) - new_capacity *= 2; - if (NULL == - (pNew_block = - pZip->m_pRealloc (pZip->m_pAlloc_opaque, pState->m_pMem, 1, - new_capacity))) - return 0; - pState->m_pMem = pNew_block; - pState->m_mem_capacity = new_capacity; - } - memcpy ((mz_uint8 *) pState->m_pMem + file_ofs, pBuf, n); - pState->m_mem_size = (size_t) new_size; - return n; - } - - mz_bool mz_zip_writer_init_heap (mz_zip_archive * pZip, - size_t size_to_reserve_at_beginning, - size_t initial_allocation_size) - { - pZip->m_pWrite = mz_zip_heap_write_func; - pZip->m_pIO_opaque = pZip; - if (!mz_zip_writer_init (pZip, size_to_reserve_at_beginning)) - return MZ_FALSE; - if (0 != - (initial_allocation_size = - MZ_MAX (initial_allocation_size, size_to_reserve_at_beginning))) - { - if (NULL == - (pZip->m_pState->m_pMem = - pZip->m_pAlloc (pZip->m_pAlloc_opaque, 1, - initial_allocation_size))) - { - mz_zip_writer_end (pZip); - return MZ_FALSE; - } - pZip->m_pState->m_mem_capacity = initial_allocation_size; - } - return MZ_TRUE; - } - -#ifndef MINIZ_NO_STDIO - static size_t mz_zip_file_write_func (void *pOpaque, mz_uint64 file_ofs, - const void *pBuf, size_t n) - { - mz_zip_archive *pZip = (mz_zip_archive *) pOpaque; - mz_int64 cur_ofs = MZ_FTELL64 (pZip->m_pState->m_pFile); - if (((mz_int64) file_ofs < 0) - || (((cur_ofs != (mz_int64) file_ofs)) - && - (MZ_FSEEK64 - (pZip->m_pState->m_pFile, (mz_int64) file_ofs, SEEK_SET)))) - return 0; - return MZ_FWRITE (pBuf, 1, n, pZip->m_pState->m_pFile); - } - - mz_bool mz_zip_writer_init_file (mz_zip_archive * pZip, - const char *pFilename, - mz_uint64 size_to_reserve_at_beginning) - { - MZ_FILE *pFile; - pZip->m_pWrite = mz_zip_file_write_func; - pZip->m_pIO_opaque = pZip; - if (!mz_zip_writer_init (pZip, size_to_reserve_at_beginning)) - return MZ_FALSE; - if (NULL == (pFile = MZ_FOPEN (pFilename, "wb"))) - { - mz_zip_writer_end (pZip); - return MZ_FALSE; - } - pZip->m_pState->m_pFile = pFile; - if (size_to_reserve_at_beginning) - { - mz_uint64 cur_ofs = 0; - char buf[4096]; - MZ_CLEAR_OBJ (buf); - do - { - size_t n = - (size_t) MZ_MIN (sizeof (buf), size_to_reserve_at_beginning); - if (pZip->m_pWrite (pZip->m_pIO_opaque, cur_ofs, buf, n) != n) - { - mz_zip_writer_end (pZip); - return MZ_FALSE; - } - cur_ofs += n; - size_to_reserve_at_beginning -= n; - } - while (size_to_reserve_at_beginning); - } - return MZ_TRUE; - } -#endif // #ifndef MINIZ_NO_STDIO - - mz_bool mz_zip_writer_init_from_reader (mz_zip_archive * pZip, - const char *pFilename) - { - mz_zip_internal_state *pState; - if ((!pZip) || (!pZip->m_pState) - || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) - return MZ_FALSE; - // No sense in trying to write to an archive that's already at the support max size - if ((pZip->m_total_files == 0xFFFF) - || - ((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + - MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) - return MZ_FALSE; - - pState = pZip->m_pState; - - if (pState->m_pFile) - { -#ifdef MINIZ_NO_STDIO - pFilename; - return MZ_FALSE; -#else - // Archive is being read from stdio - try to reopen as writable. - if (pZip->m_pIO_opaque != pZip) - return MZ_FALSE; - if (!pFilename) - return MZ_FALSE; - pZip->m_pWrite = mz_zip_file_write_func; - if (NULL == - (pState->m_pFile = - MZ_FREOPEN (pFilename, "r+b", pState->m_pFile))) - { - // The mz_zip_archive is now in a bogus state because pState->m_pFile is NULL, so just close it. - mz_zip_reader_end (pZip); - return MZ_FALSE; - } -#endif // #ifdef MINIZ_NO_STDIO - } - else if (pState->m_pMem) - { - // Archive lives in a memory block. Assume it's from the heap that we can resize using the realloc callback. - if (pZip->m_pIO_opaque != pZip) - return MZ_FALSE; - pState->m_mem_capacity = pState->m_mem_size; - pZip->m_pWrite = mz_zip_heap_write_func; - } - // Archive is being read via a user provided read function - make sure the user has specified a write function too. - else if (!pZip->m_pWrite) - return MZ_FALSE; - - // Start writing new files at the archive's current central directory location. - pZip->m_archive_size = pZip->m_central_directory_file_ofs; - pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; - pZip->m_central_directory_file_ofs = 0; - - return MZ_TRUE; - } - - mz_bool mz_zip_writer_add_mem (mz_zip_archive * pZip, - const char *pArchive_name, const void *pBuf, - size_t buf_size, mz_uint level_and_flags) - { - return mz_zip_writer_add_mem_ex (pZip, pArchive_name, pBuf, buf_size, - NULL, 0, level_and_flags, 0, 0); - } - - typedef struct - { - mz_zip_archive *m_pZip; - mz_uint64 m_cur_archive_file_ofs; - mz_uint64 m_comp_size; - } mz_zip_writer_add_state; - - static mz_bool mz_zip_writer_add_put_buf_callback (const void *pBuf, - int len, void *pUser) - { - mz_zip_writer_add_state *pState = (mz_zip_writer_add_state *) pUser; - if ((int) pState->m_pZip->m_pWrite (pState->m_pZip->m_pIO_opaque, - pState->m_cur_archive_file_ofs, pBuf, - len) != len) - return MZ_FALSE; - pState->m_cur_archive_file_ofs += len; - pState->m_comp_size += len; - return MZ_TRUE; - } - - static mz_bool mz_zip_writer_create_local_dir_header (mz_zip_archive * pZip, - mz_uint8 * pDst, - mz_uint16 - filename_size, - mz_uint16 extra_size, - mz_uint64 uncomp_size, - mz_uint64 comp_size, - mz_uint32 - uncomp_crc32, - mz_uint16 method, - mz_uint16 bit_flags, - mz_uint16 dos_time, - mz_uint16 dos_date) - { - (void) pZip; - memset (pDst, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE); - MZ_WRITE_LE32 (pDst + MZ_ZIP_LDH_SIG_OFS, MZ_ZIP_LOCAL_DIR_HEADER_SIG); - MZ_WRITE_LE16 (pDst + MZ_ZIP_LDH_VERSION_NEEDED_OFS, method ? 20 : 0); - MZ_WRITE_LE16 (pDst + MZ_ZIP_LDH_BIT_FLAG_OFS, bit_flags); - MZ_WRITE_LE16 (pDst + MZ_ZIP_LDH_METHOD_OFS, method); - MZ_WRITE_LE16 (pDst + MZ_ZIP_LDH_FILE_TIME_OFS, dos_time); - MZ_WRITE_LE16 (pDst + MZ_ZIP_LDH_FILE_DATE_OFS, dos_date); - MZ_WRITE_LE32 (pDst + MZ_ZIP_LDH_CRC32_OFS, uncomp_crc32); - MZ_WRITE_LE32 (pDst + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS, comp_size); - MZ_WRITE_LE32 (pDst + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS, uncomp_size); - MZ_WRITE_LE16 (pDst + MZ_ZIP_LDH_FILENAME_LEN_OFS, filename_size); - MZ_WRITE_LE16 (pDst + MZ_ZIP_LDH_EXTRA_LEN_OFS, extra_size); - return MZ_TRUE; - } - - static mz_bool mz_zip_writer_create_central_dir_header (mz_zip_archive * - pZip, - mz_uint8 * pDst, - mz_uint16 - filename_size, - mz_uint16 - extra_size, - mz_uint16 - comment_size, - mz_uint64 - uncomp_size, - mz_uint64 comp_size, - mz_uint32 - uncomp_crc32, - mz_uint16 method, - mz_uint16 bit_flags, - mz_uint16 dos_time, - mz_uint16 dos_date, - mz_uint64 - local_header_ofs, - mz_uint32 - ext_attributes) - { - (void) pZip; - memset (pDst, 0, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); - MZ_WRITE_LE32 (pDst + MZ_ZIP_CDH_SIG_OFS, MZ_ZIP_CENTRAL_DIR_HEADER_SIG); - MZ_WRITE_LE16 (pDst + MZ_ZIP_CDH_VERSION_NEEDED_OFS, method ? 20 : 0); - MZ_WRITE_LE16 (pDst + MZ_ZIP_CDH_BIT_FLAG_OFS, bit_flags); - MZ_WRITE_LE16 (pDst + MZ_ZIP_CDH_METHOD_OFS, method); - MZ_WRITE_LE16 (pDst + MZ_ZIP_CDH_FILE_TIME_OFS, dos_time); - MZ_WRITE_LE16 (pDst + MZ_ZIP_CDH_FILE_DATE_OFS, dos_date); - MZ_WRITE_LE32 (pDst + MZ_ZIP_CDH_CRC32_OFS, uncomp_crc32); - MZ_WRITE_LE32 (pDst + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, comp_size); - MZ_WRITE_LE32 (pDst + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, uncomp_size); - MZ_WRITE_LE16 (pDst + MZ_ZIP_CDH_FILENAME_LEN_OFS, filename_size); - MZ_WRITE_LE16 (pDst + MZ_ZIP_CDH_EXTRA_LEN_OFS, extra_size); - MZ_WRITE_LE16 (pDst + MZ_ZIP_CDH_COMMENT_LEN_OFS, comment_size); - MZ_WRITE_LE32 (pDst + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS, ext_attributes); - MZ_WRITE_LE32 (pDst + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_header_ofs); - return MZ_TRUE; - } - - static mz_bool mz_zip_writer_add_to_central_dir (mz_zip_archive * pZip, - const char *pFilename, - mz_uint16 filename_size, - const void *pExtra, - mz_uint16 extra_size, - const void *pComment, - mz_uint16 comment_size, - mz_uint64 uncomp_size, - mz_uint64 comp_size, - mz_uint32 uncomp_crc32, - mz_uint16 method, - mz_uint16 bit_flags, - mz_uint16 dos_time, - mz_uint16 dos_date, - mz_uint64 local_header_ofs, - mz_uint32 ext_attributes) - { - mz_zip_internal_state *pState = pZip->m_pState; - mz_uint32 central_dir_ofs = (mz_uint32) pState->m_central_dir.m_size; - size_t orig_central_dir_size = pState->m_central_dir.m_size; - mz_uint8 central_dir_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; - - // No zip64 support yet - if ((local_header_ofs > 0xFFFFFFFF) - || - (((mz_uint64) pState->m_central_dir.m_size + - MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size + - comment_size) > 0xFFFFFFFF)) - return MZ_FALSE; - - if (!mz_zip_writer_create_central_dir_header - (pZip, central_dir_header, filename_size, extra_size, comment_size, - uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, - dos_date, local_header_ofs, ext_attributes)) - return MZ_FALSE; - - if ((!mz_zip_array_push_back - (pZip, &pState->m_central_dir, central_dir_header, - MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) - || - (!mz_zip_array_push_back - (pZip, &pState->m_central_dir, pFilename, filename_size)) - || - (!mz_zip_array_push_back - (pZip, &pState->m_central_dir, pExtra, extra_size)) - || - (!mz_zip_array_push_back - (pZip, &pState->m_central_dir, pComment, comment_size)) - || - (!mz_zip_array_push_back - (pZip, &pState->m_central_dir_offsets, ¢ral_dir_ofs, 1))) - { - // Try to push the central directory array back into its original state. - mz_zip_array_resize (pZip, &pState->m_central_dir, - orig_central_dir_size, MZ_FALSE); - return MZ_FALSE; - } - - return MZ_TRUE; - } - - static mz_bool mz_zip_writer_validate_archive_name (const char - *pArchive_name) - { - // Basic ZIP archive filename validity checks: Valid filenames cannot start with a forward slash, cannot contain a drive letter, and cannot use DOS-style backward slashes. - if (*pArchive_name == '/') - return MZ_FALSE; - while (*pArchive_name) - { - if ((*pArchive_name == '\\') || (*pArchive_name == ':')) - return MZ_FALSE; - pArchive_name++; - } - return MZ_TRUE; - } - - static mz_uint - mz_zip_writer_compute_padding_needed_for_file_alignment (mz_zip_archive * - pZip) - { - mz_uint32 n; - if (!pZip->m_file_offset_alignment) - return 0; - n = - (mz_uint32) (pZip->m_archive_size & - (pZip->m_file_offset_alignment - 1)); - return (pZip->m_file_offset_alignment - - n) & (pZip->m_file_offset_alignment - 1); - } - - static mz_bool mz_zip_writer_write_zeros (mz_zip_archive * pZip, - mz_uint64 cur_file_ofs, - mz_uint32 n) - { - char buf[4096]; - memset (buf, 0, MZ_MIN (sizeof (buf), n)); - while (n) - { - mz_uint32 s = MZ_MIN (sizeof (buf), n); - if (pZip->m_pWrite (pZip->m_pIO_opaque, cur_file_ofs, buf, s) != s) - return MZ_FALSE; - cur_file_ofs += s; - n -= s; - } - return MZ_TRUE; - } - - mz_bool mz_zip_writer_add_mem_ex (mz_zip_archive * pZip, - const char *pArchive_name, - const void *pBuf, size_t buf_size, - const void *pComment, - mz_uint16 comment_size, - mz_uint level_and_flags, - mz_uint64 uncomp_size, - mz_uint32 uncomp_crc32) - { - mz_uint16 method = 0, dos_time = 0, dos_date = 0; - mz_uint level, ext_attributes = 0, num_alignment_padding_bytes; - mz_uint64 local_dir_header_ofs = 0, cur_archive_file_ofs = 0, comp_size = - 0; - size_t archive_name_size; - mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; - tdefl_compressor *pComp = NULL; - mz_bool store_data_uncompressed; - mz_zip_internal_state *pState; - - if ((int) level_and_flags < 0) - level_and_flags = MZ_DEFAULT_LEVEL; - level = level_and_flags & 0xF; - store_data_uncompressed = ((!level) - || (level_and_flags & - MZ_ZIP_FLAG_COMPRESSED_DATA)); - - if ((!pZip) || (!pZip->m_pState) - || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) - && (!pBuf)) - || (!pArchive_name) || ((comment_size) && (!pComment)) - || (pZip->m_total_files == 0xFFFF) || (level > MZ_UBER_COMPRESSION)) - return MZ_FALSE; - - local_dir_header_ofs = pZip->m_archive_size; - cur_archive_file_ofs = pZip->m_archive_size; - pState = pZip->m_pState; - - if ((!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (uncomp_size)) - return MZ_FALSE; - // No zip64 support yet - if ((buf_size > 0xFFFFFFFF) || (uncomp_size > 0xFFFFFFFF)) - return MZ_FALSE; - if (!mz_zip_writer_validate_archive_name (pArchive_name)) - return MZ_FALSE; - -#ifndef MINIZ_NO_TIME - { - time_t cur_time; - time (&cur_time); - mz_zip_time_to_dos_time (cur_time, &dos_time, &dos_date); - } -#endif // #ifndef MINIZ_NO_TIME - - archive_name_size = strlen (pArchive_name); - if (archive_name_size > 0xFFFF) - return MZ_FALSE; - - num_alignment_padding_bytes = - mz_zip_writer_compute_padding_needed_for_file_alignment (pZip); - - // no zip64 support yet - if ((pZip->m_total_files == 0xFFFF) - || - ((pZip->m_archive_size + num_alignment_padding_bytes + - MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + - comment_size + archive_name_size) > 0xFFFFFFFF)) - return MZ_FALSE; - - if ((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/')) - { - // Set DOS Subdirectory attribute bit. - ext_attributes |= 0x10; - // Subdirectories cannot contain data. - if ((buf_size) || (uncomp_size)) - return MZ_FALSE; - } - - // Try to do any allocations before writing to the archive, so if an allocation fails the file remains unmodified. (A good idea if we're doing an in-place modification.) - if ((!mz_zip_array_ensure_room - (pZip, &pState->m_central_dir, - MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size)) - || - (!mz_zip_array_ensure_room (pZip, &pState->m_central_dir_offsets, 1))) - return MZ_FALSE; - - if ((!store_data_uncompressed) && (buf_size)) - { - if (NULL == - (pComp = - (tdefl_compressor *) pZip->m_pAlloc (pZip->m_pAlloc_opaque, 1, - sizeof (tdefl_compressor)))) - return MZ_FALSE; - } - - if (!mz_zip_writer_write_zeros - (pZip, cur_archive_file_ofs, - num_alignment_padding_bytes + sizeof (local_dir_header))) - { - pZip->m_pFree (pZip->m_pAlloc_opaque, pComp); - return MZ_FALSE; - } - local_dir_header_ofs += num_alignment_padding_bytes; - if (pZip->m_file_offset_alignment) - { - MZ_ASSERT ((local_dir_header_ofs & - (pZip->m_file_offset_alignment - 1)) == 0); - } - cur_archive_file_ofs += - num_alignment_padding_bytes + sizeof (local_dir_header); - - MZ_CLEAR_OBJ (local_dir_header); - if (pZip->m_pWrite - (pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, - archive_name_size) != archive_name_size) - { - pZip->m_pFree (pZip->m_pAlloc_opaque, pComp); - return MZ_FALSE; - } - cur_archive_file_ofs += archive_name_size; - - if (!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) - { - uncomp_crc32 = - (mz_uint32) mz_crc32 (MZ_CRC32_INIT, (const mz_uint8 *) pBuf, - buf_size); - uncomp_size = buf_size; - if (uncomp_size <= 3) - { - level = 0; - store_data_uncompressed = MZ_TRUE; - } - } - - if (store_data_uncompressed) - { - if (pZip->m_pWrite (pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf, - buf_size) != buf_size) - { - pZip->m_pFree (pZip->m_pAlloc_opaque, pComp); - return MZ_FALSE; - } - - cur_archive_file_ofs += buf_size; - comp_size = buf_size; - - if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) - method = MZ_DEFLATED; - } - else if (buf_size) - { - mz_zip_writer_add_state state; - - state.m_pZip = pZip; - state.m_cur_archive_file_ofs = cur_archive_file_ofs; - state.m_comp_size = 0; - - if ((tdefl_init - (pComp, mz_zip_writer_add_put_buf_callback, &state, - tdefl_create_comp_flags_from_zip_params (level, -15, - MZ_DEFAULT_STRATEGY)) - != TDEFL_STATUS_OKAY) - || (tdefl_compress_buffer (pComp, pBuf, buf_size, TDEFL_FINISH) != - TDEFL_STATUS_DONE)) - { - pZip->m_pFree (pZip->m_pAlloc_opaque, pComp); - return MZ_FALSE; - } - - comp_size = state.m_comp_size; - cur_archive_file_ofs = state.m_cur_archive_file_ofs; - - method = MZ_DEFLATED; - } - - pZip->m_pFree (pZip->m_pAlloc_opaque, pComp); - pComp = NULL; - - // no zip64 support yet - if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF)) - return MZ_FALSE; - - if (!mz_zip_writer_create_local_dir_header - (pZip, local_dir_header, (mz_uint16) archive_name_size, 0, - uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date)) - return MZ_FALSE; - - if (pZip->m_pWrite - (pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, - sizeof (local_dir_header)) != sizeof (local_dir_header)) - return MZ_FALSE; - - if (!mz_zip_writer_add_to_central_dir - (pZip, pArchive_name, (mz_uint16) archive_name_size, NULL, 0, - pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, - 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes)) - return MZ_FALSE; - - pZip->m_total_files++; - pZip->m_archive_size = cur_archive_file_ofs; - - return MZ_TRUE; - } - -#ifndef MINIZ_NO_STDIO - mz_bool mz_zip_writer_add_file (mz_zip_archive * pZip, - const char *pArchive_name, - const char *pSrc_filename, - const void *pComment, - mz_uint16 comment_size, - mz_uint level_and_flags) - { - mz_uint uncomp_crc32 = MZ_CRC32_INIT, level, num_alignment_padding_bytes; - mz_uint16 method = 0, dos_time = 0, dos_date = 0, ext_attributes = 0; - mz_uint64 local_dir_header_ofs = 0, cur_archive_file_ofs = - 0, uncomp_size = 0, comp_size = 0; - size_t archive_name_size; - mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; - MZ_FILE *pSrc_file = NULL; - - if ((int) level_and_flags < 0) - level_and_flags = MZ_DEFAULT_LEVEL; - level = level_and_flags & 0xF; - - if ((!pZip) || (!pZip->m_pState) - || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) - || ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION)) - return MZ_FALSE; - if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) - return MZ_FALSE; - if (!mz_zip_writer_validate_archive_name (pArchive_name)) - return MZ_FALSE; - - archive_name_size = strlen (pArchive_name); - if (archive_name_size > 0xFFFF) - return MZ_FALSE; - local_dir_header_ofs = pZip->m_archive_size; - cur_archive_file_ofs = pZip->m_archive_size; - num_alignment_padding_bytes = - mz_zip_writer_compute_padding_needed_for_file_alignment (pZip); - - // no zip64 support yet - if ((pZip->m_total_files == 0xFFFF) - || - ((pZip->m_archive_size + num_alignment_padding_bytes + - MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + - comment_size + archive_name_size) > 0xFFFFFFFF)) - return MZ_FALSE; - - if (!mz_zip_get_file_modified_time (pSrc_filename, &dos_time, &dos_date)) - return MZ_FALSE; - - pSrc_file = MZ_FOPEN (pSrc_filename, "rb"); - if (!pSrc_file) - return MZ_FALSE; - MZ_FSEEK64 (pSrc_file, 0, SEEK_END); - uncomp_size = MZ_FTELL64 (pSrc_file); - MZ_FSEEK64 (pSrc_file, 0, SEEK_SET); - - if (uncomp_size > 0xFFFFFFFF) - { - // No zip64 support yet - MZ_FCLOSE (pSrc_file); - return MZ_FALSE; - } - if (uncomp_size <= 3) - level = 0; - - if (!mz_zip_writer_write_zeros - (pZip, cur_archive_file_ofs, - num_alignment_padding_bytes + sizeof (local_dir_header))) - { - MZ_FCLOSE (pSrc_file); - return MZ_FALSE; - } - local_dir_header_ofs += num_alignment_padding_bytes; - if (pZip->m_file_offset_alignment) - { - MZ_ASSERT ((local_dir_header_ofs & - (pZip->m_file_offset_alignment - 1)) == 0); - } - cur_archive_file_ofs += - num_alignment_padding_bytes + sizeof (local_dir_header); - - MZ_CLEAR_OBJ (local_dir_header); - if (pZip->m_pWrite - (pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, - archive_name_size) != archive_name_size) - { - MZ_FCLOSE (pSrc_file); - return MZ_FALSE; - } - cur_archive_file_ofs += archive_name_size; - - if (uncomp_size) - { - mz_uint64 uncomp_remaining = uncomp_size; - void *pRead_buf = - pZip->m_pAlloc (pZip->m_pAlloc_opaque, 1, MZ_ZIP_MAX_IO_BUF_SIZE); - if (!pRead_buf) - { - MZ_FCLOSE (pSrc_file); - return MZ_FALSE; - } - - if (!level) - { - while (uncomp_remaining) - { - mz_uint n = - (mz_uint) MZ_MIN ((mz_uint64) MZ_ZIP_MAX_IO_BUF_SIZE, uncomp_remaining); - if ((MZ_FREAD (pRead_buf, 1, n, pSrc_file) != n) - || (pZip-> - m_pWrite (pZip->m_pIO_opaque, cur_archive_file_ofs, - pRead_buf, n) != n)) - { - pZip->m_pFree (pZip->m_pAlloc_opaque, pRead_buf); - MZ_FCLOSE (pSrc_file); - return MZ_FALSE; - } - uncomp_crc32 = - (mz_uint32) mz_crc32 (uncomp_crc32, - (const mz_uint8 *) pRead_buf, n); - uncomp_remaining -= n; - cur_archive_file_ofs += n; - } - comp_size = uncomp_size; - } - else - { - mz_bool result = MZ_FALSE; - mz_zip_writer_add_state state; - tdefl_compressor *pComp = - (tdefl_compressor *) pZip->m_pAlloc (pZip->m_pAlloc_opaque, 1, - sizeof (tdefl_compressor)); - if (!pComp) - { - pZip->m_pFree (pZip->m_pAlloc_opaque, pRead_buf); - MZ_FCLOSE (pSrc_file); - return MZ_FALSE; - } - - state.m_pZip = pZip; - state.m_cur_archive_file_ofs = cur_archive_file_ofs; - state.m_comp_size = 0; - - if (tdefl_init - (pComp, mz_zip_writer_add_put_buf_callback, &state, - tdefl_create_comp_flags_from_zip_params (level, -15, - MZ_DEFAULT_STRATEGY)) - != TDEFL_STATUS_OKAY) - { - pZip->m_pFree (pZip->m_pAlloc_opaque, pComp); - pZip->m_pFree (pZip->m_pAlloc_opaque, pRead_buf); - MZ_FCLOSE (pSrc_file); - return MZ_FALSE; - } - - for (;;) - { - size_t in_buf_size = (mz_uint32) MZ_MIN (uncomp_remaining, - (mz_uint64) MZ_ZIP_MAX_IO_BUF_SIZE); - tdefl_status status; - - if (MZ_FREAD (pRead_buf, 1, in_buf_size, pSrc_file) != - in_buf_size) - break; - - uncomp_crc32 = - (mz_uint32) mz_crc32 (uncomp_crc32, - (const mz_uint8 *) pRead_buf, - in_buf_size); - uncomp_remaining -= in_buf_size; - - status = - tdefl_compress_buffer (pComp, pRead_buf, in_buf_size, - uncomp_remaining ? TDEFL_NO_FLUSH : - TDEFL_FINISH); - if (status == TDEFL_STATUS_DONE) - { - result = MZ_TRUE; - break; - } - else if (status != TDEFL_STATUS_OKAY) - break; - } - - pZip->m_pFree (pZip->m_pAlloc_opaque, pComp); - - if (!result) - { - pZip->m_pFree (pZip->m_pAlloc_opaque, pRead_buf); - MZ_FCLOSE (pSrc_file); - return MZ_FALSE; - } - - comp_size = state.m_comp_size; - cur_archive_file_ofs = state.m_cur_archive_file_ofs; - - method = MZ_DEFLATED; - } - - pZip->m_pFree (pZip->m_pAlloc_opaque, pRead_buf); - } - - MZ_FCLOSE (pSrc_file); - pSrc_file = NULL; - - // no zip64 support yet - if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF)) - return MZ_FALSE; - - if (!mz_zip_writer_create_local_dir_header - (pZip, local_dir_header, (mz_uint16) archive_name_size, 0, - uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date)) - return MZ_FALSE; - - if (pZip->m_pWrite - (pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, - sizeof (local_dir_header)) != sizeof (local_dir_header)) - return MZ_FALSE; - - if (!mz_zip_writer_add_to_central_dir - (pZip, pArchive_name, (mz_uint16) archive_name_size, NULL, 0, - pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, - 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes)) - return MZ_FALSE; - - pZip->m_total_files++; - pZip->m_archive_size = cur_archive_file_ofs; - - return MZ_TRUE; - } -#endif // #ifndef MINIZ_NO_STDIO - - mz_bool mz_zip_writer_add_from_zip_reader (mz_zip_archive * pZip, - mz_zip_archive * pSource_zip, - mz_uint file_index) - { - mz_uint n, bit_flags, num_alignment_padding_bytes; - mz_uint64 comp_bytes_remaining, local_dir_header_ofs; - mz_uint64 cur_src_file_ofs, cur_dst_file_ofs; - mz_uint32 - local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof (mz_uint32) - - 1) / sizeof (mz_uint32)]; - mz_uint8 *pLocal_header = (mz_uint8 *) local_header_u32; - mz_uint8 central_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; - size_t orig_central_dir_size; - mz_zip_internal_state *pState; - void *pBuf; - const mz_uint8 *pSrc_central_header; - - if ((!pZip) || (!pZip->m_pState) - || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) - return MZ_FALSE; - if (NULL == - (pSrc_central_header = - mz_zip_reader_get_cdh (pSource_zip, file_index))) - return MZ_FALSE; - pState = pZip->m_pState; - - num_alignment_padding_bytes = - mz_zip_writer_compute_padding_needed_for_file_alignment (pZip); - - // no zip64 support yet - if ((pZip->m_total_files == 0xFFFF) - || - ((pZip->m_archive_size + num_alignment_padding_bytes + - MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) > - 0xFFFFFFFF)) - return MZ_FALSE; - - cur_src_file_ofs = - MZ_READ_LE32 (pSrc_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS); - cur_dst_file_ofs = pZip->m_archive_size; - - if (pSource_zip->m_pRead - (pSource_zip->m_pIO_opaque, cur_src_file_ofs, pLocal_header, - MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) - return MZ_FALSE; - if (MZ_READ_LE32 (pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) - return MZ_FALSE; - cur_src_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; - - if (!mz_zip_writer_write_zeros - (pZip, cur_dst_file_ofs, num_alignment_padding_bytes)) - return MZ_FALSE; - cur_dst_file_ofs += num_alignment_padding_bytes; - local_dir_header_ofs = cur_dst_file_ofs; - if (pZip->m_file_offset_alignment) - { - MZ_ASSERT ((local_dir_header_ofs & - (pZip->m_file_offset_alignment - 1)) == 0); - } - - if (pZip->m_pWrite (pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header, - MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != - MZ_ZIP_LOCAL_DIR_HEADER_SIZE) - return MZ_FALSE; - cur_dst_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; - - n = - MZ_READ_LE16 (pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + - MZ_READ_LE16 (pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); - comp_bytes_remaining = - n + MZ_READ_LE32 (pSrc_central_header + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); - - if (NULL == - (pBuf = - pZip->m_pAlloc (pZip->m_pAlloc_opaque, 1, - (size_t) MZ_MAX (sizeof (mz_uint32) * 4, - MZ_MIN ((mz_uint64) MZ_ZIP_MAX_IO_BUF_SIZE, - comp_bytes_remaining))))) - return MZ_FALSE; - - while (comp_bytes_remaining) - { - n = (mz_uint) MZ_MIN ((mz_uint64) MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining); - if (pSource_zip->m_pRead - (pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, n) != n) - { - pZip->m_pFree (pZip->m_pAlloc_opaque, pBuf); - return MZ_FALSE; - } - cur_src_file_ofs += n; - - if (pZip->m_pWrite (pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != - n) - { - pZip->m_pFree (pZip->m_pAlloc_opaque, pBuf); - return MZ_FALSE; - } - cur_dst_file_ofs += n; - - comp_bytes_remaining -= n; - } - - bit_flags = MZ_READ_LE16 (pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS); - if (bit_flags & 8) - { - // Copy data descriptor - if (pSource_zip->m_pRead - (pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, - sizeof (mz_uint32) * 4) != sizeof (mz_uint32) * 4) - { - pZip->m_pFree (pZip->m_pAlloc_opaque, pBuf); - return MZ_FALSE; - } - - n = - sizeof (mz_uint32) * ((MZ_READ_LE32 (pBuf) == 0x08074b50) ? 4 : 3); - if (pZip->m_pWrite (pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != - n) - { - pZip->m_pFree (pZip->m_pAlloc_opaque, pBuf); - return MZ_FALSE; - } - - cur_src_file_ofs += n; - cur_dst_file_ofs += n; - } - pZip->m_pFree (pZip->m_pAlloc_opaque, pBuf); - - // no zip64 support yet - if (cur_dst_file_ofs > 0xFFFFFFFF) - return MZ_FALSE; - - orig_central_dir_size = pState->m_central_dir.m_size; - - memcpy (central_header, pSrc_central_header, - MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); - MZ_WRITE_LE32 (central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, - local_dir_header_ofs); - if (!mz_zip_array_push_back - (pZip, &pState->m_central_dir, central_header, - MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) - return MZ_FALSE; - - n = - MZ_READ_LE16 (pSrc_central_header + MZ_ZIP_CDH_FILENAME_LEN_OFS) + - MZ_READ_LE16 (pSrc_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS) + - MZ_READ_LE16 (pSrc_central_header + MZ_ZIP_CDH_COMMENT_LEN_OFS); - if (!mz_zip_array_push_back - (pZip, &pState->m_central_dir, - pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n)) - { - mz_zip_array_resize (pZip, &pState->m_central_dir, - orig_central_dir_size, MZ_FALSE); - return MZ_FALSE; - } - - if (pState->m_central_dir.m_size > 0xFFFFFFFF) - return MZ_FALSE; - n = (mz_uint32) pState->m_central_dir.m_size; - if (!mz_zip_array_push_back (pZip, &pState->m_central_dir_offsets, &n, 1)) - { - mz_zip_array_resize (pZip, &pState->m_central_dir, - orig_central_dir_size, MZ_FALSE); - return MZ_FALSE; - } - - pZip->m_total_files++; - pZip->m_archive_size = cur_dst_file_ofs; - - return MZ_TRUE; - } - - mz_bool mz_zip_writer_finalize_archive (mz_zip_archive * pZip) - { - mz_zip_internal_state *pState; - mz_uint64 central_dir_ofs, central_dir_size; - mz_uint8 hdr[MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE]; - - if ((!pZip) || (!pZip->m_pState) - || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) - return MZ_FALSE; - - pState = pZip->m_pState; - - // no zip64 support yet - if ((pZip->m_total_files > 0xFFFF) - || - ((pZip->m_archive_size + pState->m_central_dir.m_size + - MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) - return MZ_FALSE; - - central_dir_ofs = 0; - central_dir_size = 0; - if (pZip->m_total_files) - { - // Write central directory - central_dir_ofs = pZip->m_archive_size; - central_dir_size = pState->m_central_dir.m_size; - pZip->m_central_directory_file_ofs = central_dir_ofs; - if (pZip->m_pWrite (pZip->m_pIO_opaque, central_dir_ofs, - pState->m_central_dir.m_p, - (size_t) central_dir_size) != central_dir_size) - return MZ_FALSE; - pZip->m_archive_size += central_dir_size; - } - - // Write end of central directory record - MZ_CLEAR_OBJ (hdr); - MZ_WRITE_LE32 (hdr + MZ_ZIP_ECDH_SIG_OFS, - MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG); - MZ_WRITE_LE16 (hdr + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, - pZip->m_total_files); - MZ_WRITE_LE16 (hdr + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS, - pZip->m_total_files); - MZ_WRITE_LE32 (hdr + MZ_ZIP_ECDH_CDIR_SIZE_OFS, central_dir_size); - MZ_WRITE_LE32 (hdr + MZ_ZIP_ECDH_CDIR_OFS_OFS, central_dir_ofs); - - if (pZip->m_pWrite (pZip->m_pIO_opaque, pZip->m_archive_size, hdr, - sizeof (hdr)) != sizeof (hdr)) - return MZ_FALSE; -#ifndef MINIZ_NO_STDIO - if ((pState->m_pFile) && (MZ_FFLUSH (pState->m_pFile) == EOF)) - return MZ_FALSE; -#endif // #ifndef MINIZ_NO_STDIO - - pZip->m_archive_size += sizeof (hdr); - - pZip->m_zip_mode = MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED; - return MZ_TRUE; - } - - mz_bool mz_zip_writer_finalize_heap_archive (mz_zip_archive * pZip, - void **pBuf, size_t * pSize) - { - if ((!pZip) || (!pZip->m_pState) || (!pBuf) || (!pSize)) - return MZ_FALSE; - if (pZip->m_pWrite != mz_zip_heap_write_func) - return MZ_FALSE; - if (!mz_zip_writer_finalize_archive (pZip)) - return MZ_FALSE; - - *pBuf = pZip->m_pState->m_pMem; - *pSize = pZip->m_pState->m_mem_size; - pZip->m_pState->m_pMem = NULL; - pZip->m_pState->m_mem_size = pZip->m_pState->m_mem_capacity = 0; - return MZ_TRUE; - } - - mz_bool mz_zip_writer_end (mz_zip_archive * pZip) - { - mz_zip_internal_state *pState; - mz_bool status = MZ_TRUE; - if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) - || ((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) - && (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED))) - return MZ_FALSE; - - pState = pZip->m_pState; - pZip->m_pState = NULL; - mz_zip_array_clear (pZip, &pState->m_central_dir); - mz_zip_array_clear (pZip, &pState->m_central_dir_offsets); - mz_zip_array_clear (pZip, &pState->m_sorted_central_dir_offsets); - -#ifndef MINIZ_NO_STDIO - if (pState->m_pFile) - { - MZ_FCLOSE (pState->m_pFile); - pState->m_pFile = NULL; - } -#endif // #ifndef MINIZ_NO_STDIO - - if ((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem)) - { - pZip->m_pFree (pZip->m_pAlloc_opaque, pState->m_pMem); - pState->m_pMem = NULL; - } - - pZip->m_pFree (pZip->m_pAlloc_opaque, pState); - pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; - return status; - } - -#ifndef MINIZ_NO_STDIO - mz_bool mz_zip_add_mem_to_archive_file_in_place (const char *pZip_filename, - const char *pArchive_name, - const void *pBuf, - size_t buf_size, - const void *pComment, - mz_uint16 comment_size, - mz_uint level_and_flags) - { - mz_bool status, created_new_archive = MZ_FALSE; - mz_zip_archive zip_archive; - struct MZ_FILE_STAT_STRUCT file_stat; - MZ_CLEAR_OBJ (zip_archive); - if ((int) level_and_flags < 0) - level_and_flags = MZ_DEFAULT_LEVEL; - if ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) - || ((comment_size) && (!pComment)) - || ((level_and_flags & 0xF) > MZ_UBER_COMPRESSION)) - return MZ_FALSE; - if (!mz_zip_writer_validate_archive_name (pArchive_name)) - return MZ_FALSE; - if (MZ_FILE_STAT (pZip_filename, &file_stat) != 0) - { - // Create a new archive. - if (!mz_zip_writer_init_file (&zip_archive, pZip_filename, 0)) - return MZ_FALSE; - created_new_archive = MZ_TRUE; - } - else - { - // Append to an existing archive. - if (!mz_zip_reader_init_file - (&zip_archive, pZip_filename, - level_and_flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY)) - return MZ_FALSE; - if (!mz_zip_writer_init_from_reader (&zip_archive, pZip_filename)) - { - mz_zip_reader_end (&zip_archive); - return MZ_FALSE; - } - } - status = - mz_zip_writer_add_mem_ex (&zip_archive, pArchive_name, pBuf, buf_size, - pComment, comment_size, level_and_flags, 0, - 0); - // Always finalize, even if adding failed for some reason, so we have a valid central directory. (This may not always succeed, but we can try.) - status = status && mz_zip_writer_finalize_archive (&zip_archive); - status = status && mz_zip_writer_end (&zip_archive); - if ((!status) && (created_new_archive)) - { - // It's a new archive and something went wrong, so just delete it. - MZ_DELETE_FILE (pZip_filename); - } - return status; - } - - void *mz_zip_extract_archive_file_to_heap (const char *pZip_filename, - const char *pArchive_name, - size_t * pSize, mz_uint flags) - { - int file_index; - mz_zip_archive zip_archive; - void *p = NULL; - - if (pSize) - *pSize = 0; - - if ((!pZip_filename) || (!pArchive_name)) - return NULL; - - MZ_CLEAR_OBJ (zip_archive); - if (!mz_zip_reader_init_file - (&zip_archive, pZip_filename, - flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY)) - return NULL; - - if ((file_index = - mz_zip_reader_locate_file (&zip_archive, pArchive_name, NULL, - flags)) >= 0) - p = - mz_zip_reader_extract_to_heap (&zip_archive, file_index, pSize, - flags); - - mz_zip_reader_end (&zip_archive); - return p; - } - -#endif // #ifndef MINIZ_NO_STDIO - -#endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS - -#endif // #ifndef MINIZ_NO_ARCHIVE_APIS - -#ifdef __cplusplus -} -#endif - -#endif // MINIZ_HEADER_FILE_ONLY - -/* - This is free and unencumbered software released into the public domain. - - Anyone is free to copy, modify, publish, use, compile, sell, or - distribute this software, either in source code form or as a compiled - binary, for any purpose, commercial or non-commercial, and by any - means. - - In jurisdictions that recognize copyright laws, the author or authors - of this software dedicate any and all copyright interest in the - software to the public domain. We make this dedication for the benefit - of the public at large and to the detriment of our heirs and - successors. We intend this dedication to be an overt act of - relinquishment in perpetuity of all present and future rights to this - software under copyright law. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. - - For more information, please refer to -*/ diff --git a/server/src/cm_config.cpp b/server/src/cm_config.cpp deleted file mode 100644 index 565d870..0000000 --- a/server/src/cm_config.cpp +++ /dev/null @@ -1,809 +0,0 @@ -/* - * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. - * - * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/* - * cm_config.cpp - - */ - -#include -#include -#include -#include -#include - -#if defined(WINDOWS) -#include -#include -#else -#include -#include -#endif - -#include "cm_porting.h" -#include "cm_config.h" -#include "cm_dep.h" -#include "cm_server_util.h" - -#define DEFAULT_MONITOR_INTERVAL 5 -#define DEFAULT_THREAD_NUM 8 -#define DEFAULT_CMS_PORT 8001 - -#define DEFAULT_ALLOW_MULTI_CON 0 /* no */ -#define DEFAULT_AUTOJOB_TIMEOUT 43200 /* timeout for all autojobs, 12 hours */ -#define MIN_AUTOJOB_TIMEOUT 60 /* min timeout for all autojobs, 60 sec */ - -#define MAX_THREAD_NUM 64 -#define MIN_THREAD_NUM 1 -/* Reject multi connection with "ALL USER" */ - -#define NUM_DBMT_FILE 23 - -#define DEFAULT_CWM_PATH_SHORT "/share/webmanager" -#define DEFAULT_SSL_CERTIFICATE "cm_ssl_cert.crt" -#define DEFAULT_SSL_PRIVATEKEY "cm_ssl_cert.key" - -#define DEFAULT_LOG_FILE_COUNT 10 -#define DEFAULT_LOG_FILE_SIZE (4 * 1024 * 1024) - -const char *autobackup_conf_entry[AUTOBACKUP_CONF_ENTRY_NUM] = -{ - "dbname", "backupid", "path", "period_type", "period_date", "time", - "level", "archivedel", "updatestatus", "storeold", "onoff", - "zip", "check", "mt", "bknum" -}; - -const char *autobackup_period_type[AUTOBACKUP_PERIOD_TYPE_NUM] = -{ - AUTO_BACKUP_PERIOD_TYPE_MONTHLY, AUTO_BACKUP_PERIOD_TYPE_WEEKLY, - AUTO_BACKUP_PERIOD_TYPE_DAILY, AUTO_BACKUP_PERIOD_TYPE_HOURLY, - AUTO_BACKUP_PERIOD_TYPE_SPECIAL -}; - -const char *autobackup_period_week[AUTOBACKUP_PERIOD_WEEK_NUM] = -{ - WEEK_SUNDAY_L, WEEK_MONDAY_L, WEEK_TUESDAY_L, WEEK_WEDNESDAY_L, - WEEK_THURSDAY_L, WEEK_FRIDAY_L, WEEK_SATURDAY_L -}; - -const char *autoaddvol_conf_entry[AUTOADDVOL_CONF_ENTRY_NUM] = -{ - "dbname", "data", "data_warn_outofspace", "data_ext_page", - "index", "index_warn_outofspace", "index_ext_page" -}; - -const char *autohistory_conf_entry[AUTOHISTORY_CONF_ENTRY_NUM] = -{ - "onoff", - "startyear", "startmonth", "startday", - "starthour", "startminute", "startsecond", - "endyear", "endmonth", "endday", - "endhour", "endminute", "endsecond", - "memory", "cpu" -}; - -const char *autounicas_conf_entry[AUTOUNICAS_CONF_ENTRY_NUM] = -{ - "bname", "cpumonitor", "busymonitor", "logcpu", "logbusy", - "cpurestart", "busyrestart", "cpulimit", "busytimelimit" -}; - -static T_DBMT_FILE_INFO dbmt_file[NUM_DBMT_FILE] = -{ - {FID_DBMT_CONF, DBMT_CONF_DIR, "cm.conf"}, - {FID_DBMT_PASS, DBMT_CONF_DIR, "cm.pass"}, - {FID_DBMT_ARNIADB_PASS, DBMT_CONF_DIR, "cmdb.pass"}, - {FID_CONN_LIST, DBMT_LOG_DIR, "conlist"}, - {FID_AUTO_ADDVOLDB_CONF, DBMT_CONF_DIR, "autoaddvoldb.conf"}, - {FID_AUTO_ADDVOLDB_LOG, DBMT_LOG_DIR, "autoaddvoldb.log"}, - {FID_AUTO_BACKUPDB_CONF, DBMT_CONF_DIR, "autobackupdb.conf"}, - {FID_AUTO_HISTORY_CONF, DBMT_CONF_DIR, "autohistory.conf"}, - {FID_AUTO_EXECQUERY_CONF, DBMT_CONF_DIR, "autoexecquery.conf"}, - {FID_PSVR_DBINFO_TEMP, DBMT_LOG_DIR, "cmdbinfo.temp"}, - {FID_LOCK_CONN_LIST, DBMT_TMP_DIR, "conlist.lock"}, - {FID_LOCK_PSVR_DBINFO, DBMT_TMP_DIR, "cmdbinfo.lock"}, - {FID_LOCK_SVR_LOG, DBMT_TMP_DIR, "cmlog.lock"}, - {FID_LOCK_DBMT_PASS, DBMT_TMP_DIR, "cmpass.lock"}, - {FID_DIAG_ACTIVITY_LOG, DBMT_CONF_DIR, "diagactivitylog.conf"}, - {FID_DIAG_STATUS_TEMPLATE, DBMT_CONF_DIR, "diagstatustemplate.conf"}, - {FID_DIAG_ACTIVITY_TEMPLATE, DBMT_CONF_DIR, "diagactivitytemplate.conf"}, - {FID_DIAG_SERVER_PID, DBMT_LOG_DIR, "diag.pid"}, - {FID_CMSERVER_PID, DBMT_PID_DIR, DBMT_ARN_CMS_PID}, - {FID_CMS_LOG, DBMT_LOG_DIR, "arn_manager.log"}, - {FID_CMS_ERROR_LOG, DBMT_LOG_DIR, "arn_manager.err"}, - {FID_AUTO_JOBS_CONF, DBMT_CONF_DIR, "autojobs.conf"}, - {FID_SHARD_CONF, DBMT_CONF_DIR, "shard.conf"}, -}; - -sys_config sco; - -static int check_file (char *fname, char *pname); -static int check_path (char *path, char *pname); - -void -sys_config_init (void) -{ - memset (&sco, 0, sizeof (sco)); -} - -int -uReadEnvVariables (char *progname) -{ - char tmpstrbuf[DBMT_ERROR_MSG_SIZE]; - tmpstrbuf[0] = '\0'; - -#if !defined (DO_NOT_USE_ARNIADBENV) - sco.szArniadb = getenv ("ARNIADB"); - sco.szArniadb_databases = getenv ("ARNIADB_DATABASES"); -#else - sco.szArniadb = ARNIADB_PREFIXDIR; - sco.szArniadb_databases = ARNIADB_VARDIR; -#endif - sco.szProgname = strdup (progname); /* not an env variable */ - if (sco.szArniadb == NULL) - { -#if !defined (DO_NOT_USE_ARNIADBENV) - snprintf (tmpstrbuf, DBMT_ERROR_MSG_SIZE, - "ARNIADB Manager Server : Environment variable ARNIADB not set. - %s\n", - sco.szProgname); -#else - snprintf (tmpstrbuf, DBMT_ERROR_MSG_SIZE, - "ARNIADB Manager Server : ARNIADB prefix directory was not set. - %s\n", - sco.szProgname); -#endif - ut_record_arniadb_utility_log_stderr (tmpstrbuf); - return -1; - } - if (sco.szArniadb_databases == NULL) - { -#if !defined (DO_NOT_USE_ARNIADBENV) - snprintf (tmpstrbuf, DBMT_ERROR_MSG_SIZE, - "ARNIADB Manager Server : Environment variable ARNIADB_DATABASES not set. - %s\n", - sco.szProgname); -#else - snprintf (tmpstrbuf, DBMT_ERROR_MSG_SIZE, - "ARNIADB Manager Server : ARNIADB databases directory was not set. - %s\n", - sco.szProgname); -#endif - ut_record_arniadb_utility_log_stderr (tmpstrbuf); - return -1; - } - -#if !defined (DO_NOT_USE_ARNIADBENV) - sco.dbmt_tmp_dir = - (char *) malloc (strlen (sco.szArniadb) + strlen (DBMT_TMP_DIR) + 2); -#else - sco.dbmt_tmp_dir = (char *) malloc (strlen (ARNIADB_TMPDIR) + 1); -#endif - if (sco.dbmt_tmp_dir == NULL) - { - perror ("malloc"); - return -1; - } -#if !defined (DO_NOT_USE_ARNIADBENV) -#ifdef WINDOWS - sprintf (sco.dbmt_tmp_dir, "%s\\%s", sco.szArniadb, DBMT_TMP_DIR); -#else - sprintf (sco.dbmt_tmp_dir, "%s/%s", sco.szArniadb, DBMT_TMP_DIR); -#endif -#else - sprintf (sco.dbmt_tmp_dir, "%s", ARNIADB_TMPDIR); -#endif - - return 1; -} - -/* Read cm.conf and fill system configuration structure */ -/* It fills the global variable 'sco' */ -int -uReadSystemConfig (void) -{ - FILE *conf_file; - char cbuf[1024]; - char ent_name[128], ent_val[128]; - const char *separator = " \t="; - char *token; - int cm_port = 0; - int str_len = 0; - char access_log_buf[PATH_MAX]; - char error_log_buf[PATH_MAX]; - - conf_file = fopen (conf_get_dbmt_file (FID_DBMT_CONF, cbuf), "rt"); - if (conf_file == NULL) - { - return -1; - } - - sco.iCMS_port = DEFAULT_CMS_PORT; - sco.iMonitorInterval = DEFAULT_MONITOR_INTERVAL; - sco.iAllow_AdminMultiCon = DEFAULT_ALLOW_MULTI_CON; - sco.iSupportWebManager = FALSE; - sco.iSupportMonStat = FALSE; - sco.iHttpTimeout = 500; - sco.iAutoJobTimeout = DEFAULT_AUTOJOB_TIMEOUT; - sco.iMaxLogFiles = DEFAULT_LOG_FILE_COUNT; - sco.iMaxLogFileSize = DEFAULT_LOG_FILE_SIZE; - strcpy (sco.szAutoUpdateURL, ""); - strcpy (sco.szCMSVersion, ""); - strncpy (sco.szTokenActiveTime, "7200", PATH_MAX); - snprintf (sco.szCWMPath, PATH_MAX, "%s%s", sco.szArniadb, - DEFAULT_CWM_PATH_SHORT); - - conf_get_dbmt_file (FID_CMS_LOG, access_log_buf); - conf_get_dbmt_file (FID_CMS_ERROR_LOG, error_log_buf); - - snprintf (sco.szAccessLog, PATH_MAX, "%s", access_log_buf); - snprintf (sco.szErrorLog, PATH_MAX, "%s", error_log_buf); - - while (fgets (cbuf, sizeof (cbuf), conf_file)) - { - ut_trim (cbuf); - if (cbuf[0] == '\0' || cbuf[0] == '#') - { - continue; - } - - /* - * put the first token into var ent_name, - * the separator is ' ', '\t', '=' - */ - if ((token = strtok (cbuf, separator)) == NULL) - { - continue; - } - ut_trim (token); - strcpy_limit (ent_name, token, sizeof (ent_name)); - - /* - * put the rest of the string into var ent_val. - */ - if ((token = strtok (NULL, "\0")) == NULL) - { - continue; - } - if (ut_trim (token) == NULL) - { - continue; - } - - /* - * if the first charactor is '=', - * the token should move one more step. - */ - if (token[0] == '=') - { - token++; - } - - if (ut_trim (token) == NULL) - { - continue; - } - strcpy_limit (ent_val, token, sizeof (ent_val)); - - if (strcasecmp (ent_name, "cm_port") == 0) - { - cm_port = atoi (ent_val); - sco.iCMS_port = cm_port; - } - else if (strcasecmp (ent_name, "MonitorInterval") == 0 || - strcasecmp (ent_name, "cm_process_monitor_interval") == 0) - { - sco.iMonitorInterval = atoi (ent_val); - - /* check value range of system parameters */ - if (sco.iMonitorInterval < DEFAULT_MONITOR_INTERVAL) - { - sco.iMonitorInterval = DEFAULT_MONITOR_INTERVAL; - } - - } - else if (strcasecmp (ent_name, "Allow_UserMultiCon") == 0 || - strcasecmp (ent_name, "allow_user_multi_connection") == 0) - { - if (strcasecmp (ent_val, "yes") == 0) - { - sco.iAllow_AdminMultiCon = 1; - } - else - { - sco.iAllow_AdminMultiCon = 0; - } - } - else if (strcasecmp (ent_name, "auto_job_timeout") == 0) - { - int timeout = atoi (ent_val); - if (MIN_AUTOJOB_TIMEOUT <= timeout) - { - sco.iAutoJobTimeout = timeout; - } - else - { - sco.iAutoJobTimeout = DEFAULT_AUTOJOB_TIMEOUT; - } - } - else if (strcasecmp (ent_name, "max_log_filesize") == 0) - { - str_len = (int) strlen(ent_val); - if ((ent_val[str_len - 1] == 'M') || (ent_val[str_len - 1] == 'm')) - { - ent_val[str_len - 1] = '\0'; - } - if (atoi (ent_val) > 0) - { - sco.iMaxLogFileSize = (atoi (ent_val) * 1024 * 1024); - } - } - else if (strcasecmp (ent_name, "max_log_files") == 0) - { - if (atoi (ent_val) > 0) - { - sco.iMaxLogFiles = atoi (ent_val); - } - } - else if (strcasecmp (ent_name, "support_web_manager") == 0) - { - if (strcasecmp (ent_val, "yes") == 0) - { - sco.iSupportWebManager = TRUE; - } - else - { - sco.iSupportWebManager = FALSE; - } - } - else if (strcasecmp (ent_name, "web_manager_path") == 0) - { - /* The path validation will be checked in uCheckSystemConfig */ - snprintf (sco.szCWMPath, PATH_MAX, "%s", ent_val); - } - - else if (strcasecmp (ent_name, "support_mon_statistic") == 0) - { - if (strcasecmp (ent_val, "yes") == 0) - { - sco.iSupportMonStat = TRUE; - } - else - { - sco.iSupportMonStat = FALSE; - } - } - else if (strcasecmp (ent_name, "http_timeout") == 0 || - strcasecmp (ent_name, "HttpTimeout") == 0) - { - sco.iHttpTimeout = atoi (ent_val); - } - else if (strcasecmp (ent_name, "auto_update_url") == 0 || - strcasecmp (ent_name, "AutoUpdateURL") == 0) - { - snprintf (sco.szAutoUpdateURL, PATH_MAX, "%s", ent_val); - } - else if (strcasecmp (ent_name, "arniadb_server_ver") == 0 || - strcasecmp (ent_name, "ArniadbServerVer") == 0) - { - snprintf (sco.szCMSVersion, PATH_MAX, "%s", ent_val); - } - else if (strcasecmp (ent_name, "token_active_time") == 0 || - strcasecmp (ent_name, "TokenActiveTime") == 0) - { - ut_trim (ent_val); - snprintf (sco.szTokenActiveTime, PATH_MAX, "%s", ent_val); - } - } - fclose (conf_file); - -#ifdef HOST_MONITOR_PROC - sco.hmtab1 = 1; - sco.hmtab2 = 1; - sco.hmtab3 = 1; -#ifdef HOST_MONITOR_IO - sco.hmtab4 = 1; -#else - sco.hmtab4 = 0; -#endif /* HOST_MONITOR_IO */ -#else - sco.hmtab1 = 0; - sco.hmtab2 = 0; - sco.hmtab3 = 0; - sco.hmtab4 = 0; -#endif /* HOST_MONITOR_PROC */ - - return 1; -} - -/* Check system configuration */ -/* It is to be called after uReadSystemConfig() */ -int -uCheckSystemConfig (char *progname) -{ - int retval; - char filepath[PATH_MAX]; - char tmpstrbuf[DBMT_ERROR_MSG_SIZE]; - - tmpstrbuf[0] = '\0'; - - if (progname == NULL) - { - fprintf (stderr, "progname should not be NULL.\n"); - return -1; - } - - /* create tmp directory */ - if (access (sco.dbmt_tmp_dir, F_OK) < 0) - { - mkdir (sco.dbmt_tmp_dir, 0755); - } - - /* ARNIADB databases.txt file check */ - sprintf (filepath, "%s/%s", sco.szArniadb_databases, ARNIADB_DATABASE_TXT); - if (access (filepath, F_OK) < 0) - { - FILE *fp; - fp = fopen (filepath, "w"); - if (fp) - { - fclose (fp); - } - } - retval = check_file (filepath, progname); - if (retval < 0) - { - return -1; - } - - if (check_file (conf_get_dbmt_file (FID_DBMT_PASS, filepath), progname) < 0) - { - return -1; - } - if (check_file (conf_get_dbmt_file (FID_DBMT_ARNIADB_PASS, filepath), progname) < 0) - { - return -1; - } - /* arniadb manager only support https connections, - * Thus private key and certificate must be checked before process starting. - */ - snprintf (sco.szSSLKey, PATH_MAX, "%s/conf/%s", sco.szArniadb, DEFAULT_SSL_PRIVATEKEY); - if (check_file (sco.szSSLKey, progname) < 0) - { - return -1; - } - snprintf (sco.szSSLCertificate, PATH_MAX, "%s/conf/%s", sco.szArniadb, DEFAULT_SSL_CERTIFICATE); - if (check_file (sco.szSSLCertificate, progname) < 0) - { - return -1; - } - -#if !defined (DO_NOT_USE_ARNIADBENV) - sprintf (filepath, "%s/%s", sco.szArniadb, DBMT_LOG_DIR); -#else - sprintf (filepath, "%s", DBMT_LOG_DIR); -#endif - if (check_path (filepath, progname) < 0) - { - return -1; - } -#if !defined (DO_NOT_USE_ARNIADBENV) - sprintf (filepath, "%s/%s", sco.szArniadb, DBMT_CONF_DIR); -#else - sprintf (filepath, "%s", DBMT_CONF_DIR); -#endif - if (check_path (filepath, progname) < 0) - { - return -1; - } -#if !defined (DO_NOT_USE_ARNIADBENV) - sprintf (filepath, "%s/%s", sco.szArniadb, DBMT_TMP_DIR); -#else - sprintf (filepath, "%s", DBMT_TMP_DIR); -#endif - if (check_path (filepath, progname) < 0) - { - return -1; - } - - return 1; -} - -char * -conf_get_dbmt_file (T_DBMT_FILE_ID dbmt_fid, char *buf) -{ - int i; - - buf[0] = '\0'; - for (i = 0; i < NUM_DBMT_FILE; i++) - { - if (dbmt_fid == dbmt_file[i].fid) - { -#if !defined (DO_NOT_USE_ARNIADBENV) - sprintf (buf, "%s/%s/%s", sco.szArniadb, dbmt_file[i].dir_name, - dbmt_file[i].file_name); -#else - sprintf (buf, "%s/%s", dbmt_file[i].dir_name, dbmt_file[i].file_name); -#endif - break; - } - } - return buf; -} - -char * -conf_get_dbmt_file2 (T_DBMT_FILE_ID dbmt_fid, char *buf) -{ - int i; - - buf[0] = '\0'; - for (i = 0; i < NUM_DBMT_FILE; i++) - { - if (dbmt_fid == dbmt_file[i].fid) - { - strcpy (buf, dbmt_file[i].file_name); - break; - } - } - return buf; -} - -int -auto_conf_delete (T_DBMT_FILE_ID fid, char *dbname) -{ - char conf_file[PATH_MAX], tmpfile[512]; - char conf_dbname[128]; - char strbuf[MAX_JOB_CONFIG_FILE_LINE_LENGTH]; - FILE *infp, *outfp; - - conf_get_dbmt_file (fid, conf_file); - if ((infp = fopen (conf_file, "r")) == NULL) - { - return -1; - } - sprintf (tmpfile, "%s/DBMT_task_ac_del.%d", sco.dbmt_tmp_dir, (int) getpid ()); - if ((outfp = fopen (tmpfile, "w")) == NULL) - { - fclose (infp); - return -1; - } - - while (fgets (strbuf, sizeof (strbuf), infp)) - { - if (sscanf (strbuf, "%127s", conf_dbname) < 1) - { - continue; - } - if (strcmp (dbname, conf_dbname) != 0) - { - fputs (strbuf, outfp); - } - } - fclose (infp); - fclose (outfp); - - if (move_file (tmpfile, conf_file) < 0) - { - return -1; - } - return 0; -} - -int -auto_conf_rename (T_DBMT_FILE_ID fid, char *src_dbname, char *dest_dbname) -{ - char conf_file[PATH_MAX], tmpfile[512]; - char conf_dbname[128]; - char strbuf[1024], *p; - FILE *infp, *outfp; - - conf_get_dbmt_file (fid, conf_file); - if ((infp = fopen (conf_file, "r")) == NULL) - { - return -1; - } - sprintf (tmpfile, "%s/DBMT_task_ac_ren.%d", sco.dbmt_tmp_dir, (int) getpid ()); - if ((outfp = fopen (tmpfile, "w")) == NULL) - { - fclose (infp); - return -1; - } - - while (fgets (strbuf, sizeof (strbuf), infp)) - { - if (sscanf (strbuf, "%127s", conf_dbname) < 1) - { - continue; - } - if (strcmp (conf_dbname, src_dbname) == 0) - { - p = strstr (strbuf, src_dbname); - p += strlen (src_dbname); - fprintf (outfp, "%s%s", dest_dbname, p); - } - else - { - fputs (strbuf, outfp); - } - } - fclose (infp); - fclose (outfp); - - if (move_file (tmpfile, conf_file) < 0) - { - return -1; - } - return 0; -} - -int -auto_conf_execquery_update_dbuser (const char *src_db_uid, - const char *dest_db_uid, - const char *dest_db_passwd) -{ - char conf_file_path[PATH_MAX], tmpfile_path[PATH_MAX]; - char dbname[64], query_id[64], db_uid[64], dbmt_uid[64]; - char *strbuf, *p; - int buf_len, get_len; - FILE *conf_file, *tmpfile; - - conf_get_dbmt_file (FID_AUTO_EXECQUERY_CONF, conf_file_path); - if ((conf_file = fopen (conf_file_path, "r")) == NULL) - { - return -1; - } - sprintf (tmpfile_path, "%s/DBMT_task_ac_swit.%d", sco.dbmt_tmp_dir, (int) getpid ()); - if ((tmpfile = fopen (tmpfile_path, "w")) == NULL) - { - fclose (conf_file); - return -1; - } - - strbuf = NULL; - buf_len = get_len = 0; - while ((get_len = ut_getline (&strbuf, &buf_len, conf_file)) != -1) - { - if (sscanf - (strbuf, "%64s %64s %64s %*s %64s", dbname, query_id, db_uid, dbmt_uid) < 4) - { - continue; - } - - if (uStringEqual (db_uid, src_db_uid)) - { - p = strstr (strbuf, dbmt_uid); - if (p) - { - p = strchr (p, ' '); - } - fprintf (tmpfile, "%s %s %s %s %s%s", dbname, query_id, dest_db_uid, - dest_db_passwd, dbmt_uid, p); - } - else - { - fputs (strbuf, tmpfile); - } - FREE_MEM (strbuf); - buf_len = 0; - } - - if (strbuf != NULL) - { - FREE_MEM (strbuf); - } - - fclose (conf_file); - fclose (tmpfile); - - if (move_file (tmpfile_path, conf_file_path) < 0) - { - return -1; - } - - return 0; -} - -int -auto_conf_execquery_delete_by_dbuser (const char *target_db_uid) -{ - char conf_file_path[PATH_MAX], tmpfile_path[PATH_MAX]; - char db_uid[64]; - char *strbuf; - int buf_len, get_len; - FILE *conf_file, *tmpfile; - - conf_get_dbmt_file (FID_AUTO_EXECQUERY_CONF, conf_file_path); - if ((conf_file = fopen (conf_file_path, "r")) == NULL) - { - return -1; - } - sprintf (tmpfile_path, "%s/DBMT_task_ac_del_user.%d", sco.dbmt_tmp_dir, (int) getpid ()); - if ((tmpfile = fopen (tmpfile_path, "w")) == NULL) - { - fclose (conf_file); - return -1; - } - - strbuf = NULL; - buf_len = get_len = 0; - while ((get_len = ut_getline (&strbuf, &buf_len, conf_file)) != -1) - { - if (sscanf (strbuf, "%*s %*s %64s", db_uid) < 1) - { - continue; - } - - if (uStringEqual (db_uid, target_db_uid)) - { - continue; - } - else - { - fputs (strbuf, tmpfile); - } - FREE_MEM (strbuf); - buf_len = 0; - } - - if (strbuf != NULL) - { - FREE_MEM (strbuf); - } - - fclose (conf_file); - fclose (tmpfile); - - if (move_file (tmpfile_path, conf_file_path) < 0) - { - return -1; - } - - return 0; -} - -static int -check_file (char *fname, char *pname) -{ - char tmpstrbuf[DBMT_ERROR_MSG_SIZE]; - - tmpstrbuf[0] = '\0'; - - if (access (fname, F_OK | R_OK | W_OK) < 0) - { - snprintf (tmpstrbuf, DBMT_ERROR_MSG_SIZE, - "ARNIADB Manager Server : %s - %s. - %s\n", fname, strerror (errno), pname); - ut_record_arniadb_utility_log_stderr (tmpstrbuf); - return -1; - } - return 1; -} - -static int -check_path (char *dirname, char *pname) -{ - /* check if directory exists */ - char tmpstrbuf[DBMT_ERROR_MSG_SIZE]; - - tmpstrbuf[0] = '\0'; - - if (access (dirname, F_OK | W_OK | R_OK | X_OK) < 0) - { - snprintf (tmpstrbuf, DBMT_ERROR_MSG_SIZE, - "ARNIADB Manager Server : %s - %s. - %s\n", dirname, strerror (errno), pname); - ut_record_arniadb_utility_log_stderr (tmpstrbuf); - return -1; - } - return 1; -} diff --git a/server/src/cm_config.h b/server/src/cm_config.h deleted file mode 100644 index a71a83b..0000000 --- a/server/src/cm_config.h +++ /dev/null @@ -1,629 +0,0 @@ -/* - * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. - * - * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/* - * cm_config.h - - */ - -#ifndef _CM_CONFIG_H_ -#define _CM_CONFIG_H_ - -#include -#include -#include "cm_porting.h" - -#define MAX_INSTALLED_DB 256 -#define MAX_UNICAS_PROC 40 - -#define MIN_ENCRYPT_LEN 32 -#define ENCRYPT_SIGN "@" -#define ENCRYPT_ARG(arg) (ENCRYPT_SIGN arg) - -#define AUTOBACKUP_CONF_ENTRY_NUM 15 -#define AUTOADDVOL_CONF_ENTRY_NUM 7 -#define AUTOHISTORY_CONF_ENTRY_NUM 15 -#define AUTOUNICAS_CONF_ENTRY_NUM 9 -#define AUTOEXECQUERY_CONF_ENTRY_NUM 9 -#define AUTOBACKUP_PERIOD_TYPE_NUM 5 -#define AUTOBACKUP_PERIOD_WEEK_NUM 7 - -#define CMS_NAME "arn_manager" - -#if !defined (DO_NOT_USE_ARNIADBENV) -#define DBMT_CONF_DIR "conf" -#define DBMT_LOG_DIR "log/manager" -#define DBMT_PID_DIR "var/manager" -#define DBMT_MON_DATA_DIR "var/manager/mon_data" -#define DBMT_TMP_DIR "tmp" -#else -#define DBMT_CONF_DIR ARNIADB_CONFDIR -#define DBMT_LOG_DIR ARNIADB_VARDIR "/manager" -#define DBMT_PID_DIR ARNIADB_VARDIR "/manager" -#define DBMT_MON_DATA_DIR ARNIADB_VARDIR "/manager/mon_data" -#define DBMT_TMP_DIR ARNIADB_TMPDIR -#endif - -#define DBMT_ARN_CMS_PID "arn_manager.pid" - -/* utility option list, from executables/utility.h */ -#define UTIL_OPTION_CREATEDB "createdb" -#define UTIL_OPTION_RENAMEDB "renamedb" -#define UTIL_OPTION_COPYDB "copydb" -#define UTIL_OPTION_DELETEDB "deletedb" -#define UTIL_OPTION_BACKUPDB "backupdb" -#define UTIL_OPTION_RESTOREDB "restoredb" -#define UTIL_OPTION_ADDVOLDB "addvoldb" -#define UTIL_OPTION_SPACEDB "spacedb" -#define UTIL_OPTION_LOCKDB "lockdb" -#define UTIL_OPTION_KILLTRAN "killtran" -#define UTIL_OPTION_TRANLIST "tranlist" -#define UTIL_OPTION_OPTIMIZEDB "optimizedb" -#define UTIL_OPTION_INSTALLDB "installdb" -#define UTIL_OPTION_DIAGDB "diagdb" -#define UTIL_OPTION_PATCHDB "emergency_patchlog" -#define UTIL_OPTION_CHECKDB "checkdb" -#define UTIL_OPTION_ALTERDBHOST "alterdbhost" -#define UTIL_OPTION_PLANDUMP "plandump" -#define UTIL_OPTION_ESTIMATE_DATA "estimate_data" -#define UTIL_OPTION_ESTIMATE_INDEX "estimate_index" -#define UTIL_OPTION_LOADDB "loaddb" -#define UTIL_OPTION_UNLOADDB "unloaddb" -#define UTIL_OPTION_COMPACTDB "compactdb" -#define UTIL_OPTION_PARAMDUMP "paramdump" -#define UTIL_OPTION_CHANGEMODE "changemode" -#define UTIL_OPTION_COPYLOGDB "copylogdb" -#define UTIL_OPTION_APPLYLOGDB "applylogdb" -#define UTIL_OPTION_LOGFILEDUMP "logfiledump" - -/* killtran option list */ -#define KILLTRAN_KILL_TRANSACTION_INDEX_S 'i' -#define KILLTRAN_KILL_TRANSACTION_INDEX_L "kill-transaction-index" -#define KILLTRAN_KILL_USER_NAME_S 11701 -#define KILLTRAN_KILL_USER_NAME_L "kill-user-name" -#define KILLTRAN_KILL_HOST_NAME_S 11702 -#define KILLTRAN_KILL_HOST_NAME_L "kill-host-name" -#define KILLTRAN_KILL_PROGRAM_NAME_S 11703 -#define KILLTRAN_KILL_PROGRAM_NAME_L "kill-program-name" -#define KILLTRAN_KILL_SQL_ID_S 11704 -#define KILLTRAN_KILL_SQL_ID_L "kill-sql-id" -#define KILLTRAN_KILL_QUERY_INFO_S 'q' -#define KILLTRAN_KILL_QUERY_INFO_L "query-exec-info" -#define KILLTRAN_DBA_PASSWORD_S 'p' -#define KILLTRAN_DBA_PASSWORD_L "dba-password" -#define KILLTRAN_DISPLAY_INFORMATION_S 'd' -#define KILLTRAN_DISPLAY_INFORMATION_L "display-information" -#define KILLTRAN_FORCE_S 'f' -#define KILLTRAN_FORCE_L "force" - -/* tranlist option list */ -#define TRANLIST_USER_S 'u' -#define TRANLIST_USER_L "user" -#define TRANLIST_PASSWORD_S 'p' -#define TRANLIST_PASSWORD_L "password" - - -/* sqlx option list */ -#define ASQL_SA_MODE_S 'S' -#define ASQL_SA_MODE_L "SA-mode" -#define ASQL_CS_MODE_S 'C' -#define ASQL_CS_MODE_L "CS-mode" -#define ASQL_USER_S 'u' -#define ASQL_USER_L "user" -#define ASQL_PASSWORD_S 'p' -#define ASQL_PASSWORD_L "password" -#define ASQL_ERROR_CONTINUE_S 'e' -#define ASQL_ERROR_CONTINUE_L "error-continue" -#define ASQL_INPUT_FILE_S 'i' -#define ASQL_INPUT_FILE_L "input-file" -#define ASQL_OUTPUT_FILE_S 'o' -#define ASQL_OUTPUT_FILE_L "output-file" -#define ASQL_SINGLE_LINE_S 's' -#define ASQL_SINGLE_LINE_L "single-line" -#define ASQL_COMMAND_S 'c' -#define ASQL_COMMAND_L "command" -#define ASQL_LINE_OUTPUT_S 'l' -#define ASQL_LINE_OUTPUT_L "line-output" -#define ASQL_READ_ONLY_S 'r' -#define ASQL_READ_ONLY_L "read-only" -#define ASQL_NO_AUTO_COMMIT_S 12010 -#define ASQL_NO_AUTO_COMMIT_L "no-auto-commit" -#define ASQL_NO_PAGER_S 12011 -#define ASQL_NO_PAGER_L "no-pager" -#define ASQL_SYSADM_S 12012 -#define ASQL_SYSADM_L "sysadm" - -/* addvoldb option list */ -#define ADDVOL_VOLUME_NAME_S 'n' -#define ADDVOL_VOLUME_NAME_L "volume-name" -#define ADDVOL_FILE_PATH_S 'F' -#define ADDVOL_FILE_PATH_L "file-path" -#define ADDVOL_COMMENT_S 10702 -#define ADDVOL_COMMENT_L "comment" -#define ADDVOL_PURPOSE_S 'p' -#define ADDVOL_PURPOSE_L "purpose" -#define ADDVOL_SA_MODE_S 'S' -#define ADDVOL_SA_MODE_L "SA-mode" -#define ADDVOL_CS_MODE_S 'C' -#define ADDVOL_CS_MODE_L "CS-mode" -#define ADDVOL_DB_VOLUMN_SIZE_L "db-volume-size" - -/* backupdb option list */ -#define BACKUP_DESTINATION_PATH_S 'D' -#define BACKUP_DESTINATION_PATH_L "destination-path" -#define BACKUP_REMOVE_ARCHIVE_S 'r' -#define BACKUP_REMOVE_ARCHIVE_L "remove-archive" -#define BACKUP_LEVEL_S 'l' -#define BACKUP_LEVEL_L "level" -#define BACKUP_OUTPUT_FILE_S 'o' -#define BACKUP_OUTPUT_FILE_L "output-file" -#define BACKUP_SA_MODE_S 'S' -#define BACKUP_SA_MODE_L "SA-mode" -#define BACKUP_CS_MODE_S 'C' -#define BACKUP_CS_MODE_L "CS-mode" -#define BACKUP_NO_CHECK_S 10506 -#define BACKUP_NO_CHECK_L "no-check" -#define BACKUP_THREAD_COUNT_S 't' -#define BACKUP_THREAD_COUNT_L "thread-count" -#define BACKUP_COMPRESS_S 'z' -#define BACKUP_COMPRESS_L "compress" -#define BACKUP_EXCEPT_ACTIVE_LOG_S 'e' -#define BACKUP_EXCEPT_ACTIVE_LOG_L "except-active-log" -#define BACKUP_SAFE_PAGE_ID_S 10510 -#define BACKUP_SAFE_PAGE_ID_L "safe-page-id" - -/* restoredb option list */ -#define RESTORE_UP_TO_DATE_S 'd' -#define RESTORE_UP_TO_DATE_L "up-to-date" -#define RESTORE_LIST_S 10601 -#define RESTORE_LIST_L "list" -#define RESTORE_BACKUP_FILE_PATH_S 'B' -#define RESTORE_BACKUP_FILE_PATH_L "backup-file-path" -#define RESTORE_LEVEL_S 'l' -#define RESTORE_LEVEL_L "level" -#define RESTORE_PARTIAL_RECOVERY_S 'p' -#define RESTORE_PARTIAL_RECOVERY_L "partial-recovery" -#define RESTORE_OUTPUT_FILE_S 'o' -#define RESTORE_OUTPUT_FILE_L "output-file" -#define RESTORE_REPLICATION_MODE_S 'r' -#define RESTORE_REPLICATION_MODE_L "replication-mode" -#define RESTORE_USE_DATABASE_LOCATION_PATH_S 'u' -#define RESTORE_USE_DATABASE_LOCATION_PATH_L "use-database-location-path" - - -/* spacedb option list */ -#define SPACE_OUTPUT_FILE_S 'o' -#define SPACE_OUTPUT_FILE_L "output-file" -#define SPACE_SA_MODE_S 'S' -#define SPACE_SA_MODE_L "SA-mode" -#define SPACE_CS_MODE_S 'C' -#define SPACE_CS_MODE_L "CS-mode" -#define SPACE_SIZE_UNIT_S 10803 -#define SPACE_SIZE_UNIT_L "size-unit" - -/* checkdb option list */ -#define CHECK_SA_MODE_S 'S' -#define CHECK_SA_MODE_L "SA-mode" -#define CHECK_CS_MODE_S 'C' -#define CHECK_CS_MODE_L "CS-mode" -#define CHECK_REPAIR_S 'r' -#define CHECK_REPAIR_L "repair" - -/* renamedb option list */ -#define RENAME_EXTENTED_VOLUME_PATH_S 'E' -#define RENAME_EXTENTED_VOLUME_PATH_L "extended-volume-path" -#define RENAME_CONTROL_FILE_S 'i' -#define RENAME_CONTROL_FILE_L "control-file" -#define RENAME_DELETE_BACKUP_S 'd' -#define RENAME_DELETE_BACKUP_L "delete-backup" - - -/* copydb option list */ -#define COPY_SERVER_NAME_S 10300 -#define COPY_SERVER_NAME_L "server-name" -#define COPY_FILE_PATH_S 'F' -#define COPY_FILE_PATH_L "file-path" -#define COPY_LOG_PATH_S 'L' -#define COPY_LOG_PATH_L "log-path" -#define COPY_EXTENTED_VOLUME_PATH_S 'E' -#define COPY_EXTENTED_VOLUME_PATH_L "extended-volume-path" -#define COPY_CONTROL_FILE_S 'i' -#define COPY_CONTROL_FILE_L "control-file" -#define COPY_REPLACE_S 'r' -#define COPY_REPLACE_L "replace" -#define COPY_DELETE_SOURCE_S 'd' -#define COPY_DELETE_SOURCE_L "delete-source" -#define COPY_LOB_BASE_PATH_S "B" -#define COPY_LOB_BASE_PATH_L "lob-base-path" - -/* deletedb option list */ -#define DELETE_OUTPUT_FILE_S 'o' -#define DELETE_OUTPUT_FILE_L "output-file" -#define DELETE_DELETE_BACKUP_S 'd' -#define DELETE_DELETE_BACKUP_L "delete-backup" - - -/* createdb option list */ -#define CREATE_PAGES_S 'p' -#define CREATE_PAGES_L "pages" -#define CREATE_COMMENT_S 10102 -#define CREATE_COMMENT_L "comment" -#define CREATE_FILE_PATH_S 'F' -#define CREATE_FILE_PATH_L "file-path" -#define CREATE_LOG_PATH_S 'L' -#define CREATE_LOG_PATH_L "log-path" -#define CREATE_SERVER_NAME_S 10105 -#define CREATE_SERVER_NAME_L "server-name" -#define CREATE_REPLACE_S 'r' -#define CREATE_REPLACE_L "replace" -#define CREATE_MORE_VOLUME_FILE_S 10107 -#define CREATE_MORE_VOLUME_FILE_L "more-volume-file" -#define CREATE_USER_DEFINITION_FILE_S 10108 -#define CREATE_USER_DEFINITION_FILE_L "user-definition-file" -#define CREATE_ASQL_INITIALIZATION_FILE_S 10109 -#define CREATE_ASQL_INITIALIZATION_FILE_L "asql-initialization-file" -#define CREATE_OUTPUT_FILE_S 'o' -#define CREATE_OUTPUT_FILE_L "output-file" -#define CREATE_VERBOSE_S 'v' -#define CREATE_VERBOSE_L "verbose" -#define CREATE_CHARSET_S 10112 -#define CREATE_CHARSET_L "charset" -#define CREATE_DB_PAGE_SIZE_L "db-page-size" -#define CREATE_LOG_PAGE_SIZE_L "log-page-size" -#define CREATE_DB_VOLUMN_SIZE_L "db-volume-size" -#define CREATE_LOG_VOLUMN_SIZE_L "log-volume-size" - -/* loaddb option list */ -#define LOAD_USER_S 'u' -#define LOAD_USER_L "user" -#define LOAD_PASSWORD_S 'p' -#define LOAD_PASSWORD_L "password" -#define LOAD_CHECK_ONLY_S 11802 -#define LOAD_CHECK_ONLY_L "data-file-check-only" -#define LOAD_LOAD_ONLY_S 'l' -#define LOAD_LOAD_ONLY_L "load-only" -#define LOAD_ESTIMATED_SIZE_S 11804 -#define LOAD_ESTIMATED_SIZE_L "estimated-size" -#define LOAD_VERBOSE_S 'v' -#define LOAD_VERBOSE_L "verbose" -#define LOAD_NO_STATISTICS_S 11806 -#define LOAD_NO_STATISTICS_L "no-statistics" -#define LOAD_PERIODIC_COMMIT_S 'c' -#define LOAD_PERIODIC_COMMIT_L "periodic-commit" -#define LOAD_NO_OID_S 11808 -#define LOAD_NO_OID_L "no-oid" -#define LOAD_SCHEMA_FILE_S 's' -#define LOAD_SCHEMA_FILE_L "schema-file" -#define LOAD_INDEX_FILE_S 'i' -#define LOAD_INDEX_FILE_L "index-file" -#define LOAD_IGNORE_LOGGING_S 11811 -#define LOAD_IGNORE_LOGGING_L "no-logging" -#define LOAD_DATA_FILE_S 'd' -#define LOAD_DATA_FILE_L "data-file" -#define LOAD_ERROR_CONTROL_FILE_S 'e' -#define LOAD_ERROR_CONTROL_FILE_L "error-control-file" -#define LOAD_IGNORE_CLASS_S 11814 -#define LOAD_IGNORE_CLASS_L "ignore-class-file" -#define LOAD_SA_MODE_S 'S' -#define LOAD_SA_MODE_L "SA-mode" -#define LOAD_CS_MODE_S 11815 -#define LOAD_CS_MODE_L "CS-hidden" - -/* unloaddb option list */ -#define UNLOAD_INPUT_CLASS_FILE_S 'i' -#define UNLOAD_INPUT_CLASS_FILE_L "input-class-file" -#define UNLOAD_INCLUDE_REFERENCE_S 11901 -#define UNLOAD_INCLUDE_REFERENCE_L "include-reference" -#define UNLOAD_INPUT_CLASS_ONLY_S 11902 -#define UNLOAD_INPUT_CLASS_ONLY_L "input-class-only" -#define UNLOAD_LO_COUNT_S 11903 -#define UNLOAD_LO_COUNT_L "lo-count" -#define UNLOAD_ESTIMATED_SIZE_S 11904 -#define UNLOAD_ESTIMATED_SIZE_L "estimated-size" -#define UNLOAD_CACHED_PAGES_S 11905 -#define UNLOAD_CACHED_PAGES_L "cached-pages" -#define UNLOAD_OUTPUT_PATH_S 'O' -#define UNLOAD_OUTPUT_PATH_L "output-path" -#define UNLOAD_SCHEMA_ONLY_S 's' -#define UNLOAD_SCHEMA_ONLY_L "schema-only" -#define UNLOAD_DATA_ONLY_S 'd' -#define UNLOAD_DATA_ONLY_L "data-only" -#define UNLOAD_OUTPUT_PREFIX_S 11909 -#define UNLOAD_OUTPUT_PREFIX_L "output-prefix" -#define UNLOAD_HASH_FILE_S 11910 -#define UNLOAD_HASH_FILE_L "hash-file" -#define UNLOAD_VERBOSE_S 'v' -#define UNLOAD_VERBOSE_L "verbose" -#define UNLOAD_USE_DELIMITER_S 11912 -#define UNLOAD_USE_DELIMITER_L "use-delimiter" -#define UNLOAD_SA_MODE_S 'S' -#define UNLOAD_SA_MODE_L "SA-mode" -#define UNLOAD_CS_MODE_S 'C' -#define UNLOAD_CS_MODE_L "CS-mode" -#define UNLOAD_USER_S "u" -#define UNLOAD_USER_L "user" -#define UNLOAD_PASSWORD_S "p" -#define UNLOAD_PASSWORD_L "password" - -/* compactdb option list */ -#define COMPACT_VERBOSE_S 'v' -#define COMPACT_VERBOSE_L "verbose" -#define COMPACT_SA_MODE_S 'S' -#define COMPACT_SA_MODE_L "SA-mode" -#define COMPACT_CS_MODE_S 'C' -#define COMPACT_CS_MODE_L "CS-mode" - -/* paramdump option list */ -#define PARAMDUMP_BOTH_S 'b' -#define PARAMDUMP_BOTH_L "both" -#define PARAMDUMP_SA_MODE_S 'S' -#define PARAMDUMP_SA_MODE_L "SA-mode" -#define PARAMDUMP_CS_MODE_S 'C' -#define PARAMDUMP_CS_MODE_L "CS-mode" - -/* plandump option list */ -#define PLANDUMP_DROP_S 'd' -#define PLANDUMP_DROP_L "drop" - -/* lockdb option list */ -#define LOCK_OUTPUT_FILE_S 'o' -#define LOCK_OUTPUT_FILE_L "output-file" - -/* changemode option list */ -#define CHANGEMODE_MODE_S 'm' -#define CHANGEMODE_MODE_L "mode" -#define CHANGEMODE_WAIT_S 'w' -#define CHANGEMODE_WAIT_L "wait" -#define CHANGEMODE_FORCE_S 'f' -#define CHANGEMODE_FORCE_L "force" - -#if defined(WINDOWS) -#define UTIL_EXE_EXT ".exe" -#else -#define UTIL_EXE_EXT "" -#endif -#if defined(WINDOWS) -#define UTIL_SCRIPT_EXT ".bat" -#else -#define UTIL_SCRIPT_EXT ".sh" -#endif -#define UTIL_MASTER_NAME "arn_master" UTIL_EXE_EXT -#define UTIL_COMMDB_NAME "arn_commdb" UTIL_EXE_EXT -#define UTIL_ARNIADB_NAME "arn_server" UTIL_EXE_EXT -#define UTIL_BROKER_NAME "arniadb_broker" UTIL_EXE_EXT -#define UTIL_MONITOR_NAME "broker_monitor" UTIL_EXE_EXT -#define UTIL_REPL_SERVER_NAME "repl_server" UTIL_EXE_EXT -#define UTIL_REPL_AGENT_NAME "repl_agent" UTIL_EXE_EXT -#define UTIL_ADMIN_NAME "arn_admin" UTIL_EXE_EXT -#define UTIL_SQLX_NAME "sqlx" UTIL_EXE_EXT -#define UTIL_ASQL_NAME "asql" UTIL_EXE_EXT -#define UTIL_ARNIADB_REL_NAME "arniadb_rel" UTIL_EXE_EXT -#define UTIL_OLD_COMMDB_NAME "commdb" UTIL_EXE_EXT -#define UTIL_ARNIADB "arniadb" UTIL_EXE_EXT -#define UTIL_CM_SERVER CMS_NAME UTIL_EXE_EXT -#define UTIL_BROKER_CHANGER "broker_changer" UTIL_EXE_EXT - -#define COMMDB_SERVER_STOP "-S" -#define COMMDB_SERVER_STATUS "-P" -#define COMMDB_REPL_STATUS "-R" -#define COMMDB_ALL_STATUS "-O" -#define COMMDB_ALL_STOP "-A" - -#define PRINT_CMD_SERVER "server" -#define PRINT_CMD_SHARD "shard" -#define PRINT_CMD_REPL_SERVER "repl_server" -#define PRINT_CMD_REPL_AGENT "repl_agent" -#define PRINT_CMD_START "start" -#define PRINT_CMD_STOP "stop" -#define PRINT_CMD_STATUS "status" -#define PRINT_CMD_RELOAD "reload" -#define PRINT_CMD_ON "on" -#define PRINT_CMD_OFF "off" - -#define PRINT_CMD_HEARTBEAT "heartbeat" -#define PRINT_CMD_LIST "list" -#define PRINT_CMD_DEACT "deact" -#define PRINT_CMD_ACT "act" - -/* from perf_monitor.h */ -#define MAX_SERVER_THREAD_COUNT 500 - -/* rename auto_conf_* function name more readably */ -#define auto_conf_execquery_delete(FID, DBNAME) auto_conf_delete(FID, DBNAME) -#define auto_conf_execquery_rename(FID, OLD, NEW) auto_conf_rename(FID, OLD, NEW) -#define auto_conf_addvol_delete(FID, DBNAME) auto_conf_delete(FID, DBNAME) -#define auto_conf_backup_delete(FID, DBNAME) auto_conf_delete(FID, DBNAME) -#define auto_conf_history_delete(FID, DBNAME) auto_conf_delete(FID, DBNAME) -#define auto_conf_start_delete(FID, DBNAME) auto_conf_delete(FID, DBNAME) -#define auto_conf_addvol_rename(FID, OLD, NEW) auto_conf_rename(FID, OLD, NEW) -#define auto_conf_backup_rename(FID, OLD, NEW) auto_conf_rename(FID, OLD, NEW) -#define auto_conf_history_rename(FID, OLD, NEW) auto_conf_rename(FID, OLD, NEW) -#define auto_conf_start_rename(FID, OLD, NEW) auto_conf_rename(FID, OLD, NEW) - -/* auto backup database plan - period_type */ -#define AUTO_BACKUP_PERIOD_TYPE_MONTHLY "Monthly" -#define AUTO_BACKUP_PERIOD_TYPE_WEEKLY "Weekly" -#define AUTO_BACKUP_PERIOD_TYPE_DAILY "Daily" -#define AUTO_BACKUP_PERIOD_TYPE_HOURLY "Hourly" -#define AUTO_BACKUP_PERIOD_TYPE_SPECIAL "Special" - -/* week */ -#define WEEK_SUNDAY_L "Sunday" -#define WEEK_SUNDAY_S "Sun" -#define WEEK_CAPITAL_SUNDAY_L "SUNDAY" -#define WEEK_CAPITAL_SUNDAY_S "SUN" -#define WEEK_MONDAY_L "Monday" -#define WEEK_MONDAY_S "Mon" -#define WEEK_CAPITAL_MONDAY_L "MONDAY" -#define WEEK_CAPITAL_MONDAY_S "MON" -#define WEEK_TUESDAY_L "Tuesday" -#define WEEK_TUESDAY_S "Tue" -#define WEEK_CAPITAL_TUESDAY_L "TUESDAY" -#define WEEK_CAPITAL_TUESDAY_S "TUE" -#define WEEK_WEDNESDAY_L "Wednesday" -#define WEEK_WEDNESDAY_S "Wed" -#define WEEK_CAPITAL_WEDNESDAY_L "WEDNESDAY" -#define WEEK_CAPITAL_WEDNESDAY_S "WED" -#define WEEK_THURSDAY_L "Thursday" -#define WEEK_THURSDAY_S "Thu" -#define WEEK_CAPITAL_THURSDAY_L "THURSDAY" -#define WEEK_CAPITAL_THURSDAY_S "THU" -#define WEEK_FRIDAY_L "Friday" -#define WEEK_FRIDAY_S "Fri" -#define WEEK_CAPITAL_FRIDAY_L "FRIDAY" -#define WEEK_CAPITAL_FRIDAY_S "FRI" -#define WEEK_SATURDAY_L "Saturday" -#define WEEK_SATURDAY_S "Sat" -#define WEEK_CAPITAL_SATURDAY_L "SATURDAY" -#define WEEK_CAPITAL_SATURDAY_S "SAT" - -#define ACCESS_LOG "access_log" -#define ACCESS_ERR "access_err" - -#define HA_MODE 2 - -typedef enum -{ - CMS_TRAN_UNKNOWN_ISOLATION = 0x00, /* 0 0000 */ - CMS_TRAN_COMMIT_CLASS_UNCOMMIT_INSTANCE = 0x01, /* 0 0001 */ - CMS_TRAN_DEGREE_1_CONSISTENCY = 0x01, /* Alias of above */ - - CMS_TRAN_COMMIT_CLASS_COMMIT_INSTANCE = 0x02, /* 0 0010 */ - CMS_TRAN_DEGREE_2_CONSISTENCY = 0x02, /* Alias of above */ - - CMS_TRAN_REP_CLASS_UNCOMMIT_INSTANCE = 0x03, /* 0 0011 */ - CMS_TRAN_READ_UNCOMMITTED = 0x03, /* Alias of above */ - - CMS_TRAN_REP_CLASS_COMMIT_INSTANCE = 0x04, /* 0 0100 */ - CMS_TRAN_READ_COMMITTED = 0x04, /* Alias of above */ - CMS_TRAN_CURSOR_STABILITY = 0x04, /* Alias of above */ - - CMS_TRAN_REP_CLASS_REP_INSTANCE = 0x05, /* 0 0101 */ - CMS_TRAN_REP_READ = 0x05, /* Alias of above */ - CMS_TRAN_DEGREE_2_9999_CONSISTENCY = 0x05, /* Alias of above */ - - CMS_TRAN_SERIALIZABLE = 0x06, /* 0 0110 */ - CMS_TRAN_DEGREE_3_CONSISTENCY = 0x06, /* Alias of above */ - CMS_TRAN_NO_PHANTOM_READ = 0x06, /* Alias of above */ - - CMS_TRAN_DEFAULT_ISOLATION = CMS_TRAN_REP_CLASS_UNCOMMIT_INSTANCE, - -} CMS_DB_TRAN_ISOLATION; /* extract from dbi.h */ - - -typedef enum -{ - FID_DBMT_CONF, - FID_DBMT_PASS, - FID_DBMT_ARNIADB_PASS, - FID_CONN_LIST, - FID_AUTO_ADDVOLDB_CONF, - FID_AUTO_ADDVOLDB_LOG, - FID_AUTO_BACKUPDB_CONF, - FID_AUTO_HISTORY_CONF, - FID_AUTO_EXECQUERY_CONF, - FID_PSVR_DBINFO_TEMP, - FID_LOCK_CONN_LIST, - FID_LOCK_PSVR_DBINFO, - FID_LOCK_SVR_LOG, - FID_LOCK_DBMT_PASS, - FID_DIAG_ACTIVITY_LOG, - FID_DIAG_STATUS_TEMPLATE, - FID_DIAG_ACTIVITY_TEMPLATE, - FID_DIAG_SERVER_PID, - FID_CMSERVER_PID, - FID_CMS_LOG, - FID_CMS_ERROR_LOG, - FID_AUTO_JOBS_CONF, - FID_SHARD_CONF, -} T_DBMT_FILE_ID; - -typedef struct -{ - T_DBMT_FILE_ID fid; - char dir_name[PATH_MAX]; - char file_name[32]; -} T_DBMT_FILE_INFO; - -typedef struct -{ - /* - * program name (either fserver or pserver) - */ - char *szProgname; - - /* - * ARNIADB environment variables - */ - char *szArniadb; /* ARNIADB */ - char *szArniadb_databases; /* ARNIADB_DATABASES */ - - char *dbmt_tmp_dir; - - int iMonitorInterval; - char sMonStatDataPath[PATH_MAX]; - char szCWMPath[PATH_MAX]; - char szSSLKey[PATH_MAX]; - char szSSLCertificate[PATH_MAX]; - int iAllow_AdminMultiCon; - int iAutoJobTimeout; - int iCMS_port; - int iSupportWebManager; - int iSupportMonStat; - int iHttpTimeout; - char szAutoUpdateURL[PATH_MAX]; - char szCMSVersion[PATH_MAX]; - char szTokenActiveTime[PATH_MAX]; - int hmtab1, hmtab2, hmtab3, hmtab4; - char szAccessLog[PATH_MAX]; - char szErrorLog[PATH_MAX]; - int iMaxLogFileSize; - int iMaxLogFiles; -} sys_config; - -void sys_config_init (void); -int uReadEnvVariables (char *progname); -int uCheckSystemConfig (char *progname); -int uReadSystemConfig (void); - -char *conf_get_dbmt_file (T_DBMT_FILE_ID dbmt_fid, char *buf); -char *conf_get_dbmt_file2 (T_DBMT_FILE_ID dbmt_fid, char *buf); - -extern sys_config sco; -extern const char *autobackup_conf_entry[AUTOBACKUP_CONF_ENTRY_NUM]; -extern const char *autoaddvol_conf_entry[AUTOADDVOL_CONF_ENTRY_NUM]; -extern const char *autohistory_conf_entry[AUTOHISTORY_CONF_ENTRY_NUM]; -extern const char *autounicas_conf_entry[AUTOUNICAS_CONF_ENTRY_NUM]; -extern const char *autobackup_period_type[AUTOBACKUP_PERIOD_TYPE_NUM]; -extern const char *autobackup_period_week[AUTOBACKUP_PERIOD_WEEK_NUM]; - -extern int arniadb_version_major; -extern int arniadb_version_minor; -void find_and_parse_arn_admin_version (int &major_version, int &minor_version); -#define IS_INVALID_ARNIADB_VERS_MAJOR(major) (major <= 0) - -extern int auto_conf_delete (T_DBMT_FILE_ID fid, char *dbname); -extern int auto_conf_rename (T_DBMT_FILE_ID fid, char *src_dbname, - char *dest_dbname); -extern int auto_conf_execquery_update_dbuser (const char *src_db_uid, - const char *dest_db_uid, - const char *dest_db_passwd); -extern int auto_conf_execquery_delete_by_dbuser (const char *db_uid); - -#endif /* _CM_CONFIG_H_ */ diff --git a/server/src/cm_connect_info.cpp b/server/src/cm_connect_info.cpp deleted file mode 100644 index d26bb8a..0000000 --- a/server/src/cm_connect_info.cpp +++ /dev/null @@ -1,547 +0,0 @@ -/* - * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. - * - * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/* - * cm_connect_info.cpp - - */ - -#include -#include -#include -#include - -#if defined(WINDOWS) -#include -#else -#include -#endif - -#include "cm_porting.h" -#include "cm_server_util.h" -#include "cm_config.h" -#include "cm_connect_info.h" - -int -dbmt_con_search (const char *ip, const char *port, char *cli_ver) -{ - FILE *infile; - int lfd, retval; - int get_len, buf_len; - char *strbuf; - char sbuf[512]; - char ip_t[20], port_t[10]; - - /* check if ip is an existing ip */ - retval = 0; - lfd = uCreateLockFile (conf_get_dbmt_file (FID_LOCK_CONN_LIST, sbuf)); - if (lfd < 0) - { - return ERR_TMPFILE_OPEN_FAIL; - } - - infile = fopen (conf_get_dbmt_file (FID_CONN_LIST, sbuf), "r"); - if (infile != NULL) - { - strbuf = NULL; - buf_len = get_len = 0; - while ((get_len = ut_getline (&strbuf, &buf_len, infile)) != -1) - { - /* remove character '\n' */ - strbuf[strlen (strbuf) - 1] = '\0'; - - if (sscanf (strbuf, "%19s %9s", ip_t, port_t) == 2 - && uStringEqual (ip, ip_t) && uStringEqual (port, port_t)) - { - retval = 1; - sscanf (strbuf, "%*s %*s %*s %*s %14s", cli_ver); - break; - } - FREE_MEM (strbuf); - buf_len = 0; - } - fclose (infile); - - if (strbuf != NULL) - { - FREE_MEM (strbuf); - } - } - uRemoveLockFile (lfd); - - return retval; -} - -int -dbmt_con_add (const char *ip, const char *port, const char *cli_ver, - const char *user_name) -{ - FILE *outfile; - char strbuf[512]; - int lock_fd, retval; - - lock_fd = uCreateLockFile (conf_get_dbmt_file (FID_LOCK_CONN_LIST, strbuf)); - if (lock_fd < 0) - { - return -1; - } - - retval = -1; - outfile = fopen (conf_get_dbmt_file (FID_CONN_LIST, strbuf), "a"); - if (outfile != NULL) - { - time_to_str (time (NULL), "%04d/%02d/%02d %02d:%02d:%02d", strbuf, - TIME_STR_FMT_DATE_TIME); - fprintf (outfile, "%s %s %s %s %s\n", ip, port, strbuf, cli_ver, user_name); - fclose (outfile); - retval = 0; - } - uRemoveLockFile (lock_fd); - - return retval; -} - -int -dbmt_con_delete (const char *ip, const char *port) -{ - char ip_t[20]; - char port_t[10]; - char version[16]; - char c_date[16]; - char c_time[16]; - char *strbuf; - int buf_len, get_len; - FILE *infile, *outfile; - char tmpfile[512]; - char conn_list_file[512]; - int lock_fd, retval; - - lock_fd = - uCreateLockFile (conf_get_dbmt_file (FID_LOCK_CONN_LIST, tmpfile)); - if (lock_fd < 0) - { - return -1; - } - - conf_get_dbmt_file (FID_CONN_LIST, conn_list_file); - infile = fopen (conn_list_file, "r"); - sprintf (tmpfile, "%s/DBMT_util_014.%d", sco.dbmt_tmp_dir, (int) getpid ()); - outfile = fopen (tmpfile, "w"); - - if (infile == NULL || outfile == NULL) - { - if (infile != NULL) - { - fclose (infile); - } - if (outfile != NULL) - { - fclose (outfile); - } - retval = -1; - } - else - { - strbuf = NULL; - buf_len = get_len = 0; - while ((get_len = ut_getline (&strbuf, &buf_len, infile)) != -1) - { - ut_trim (strbuf); - sscanf (strbuf, "%19s %9s %15s %15s %15s", ip_t, port_t, c_date, - c_time, version); - - if (!uStringEqual (ip, ip_t) || !uStringEqual (port, port_t)) - { - fprintf (outfile, "%s\n", strbuf); - } - FREE_MEM (strbuf); - buf_len = 0; - } - fclose (outfile); - fclose (infile); - - if (strbuf != NULL) - { - FREE_MEM (strbuf); - } - - move_file (tmpfile, conn_list_file); - retval = 0; - } - uRemoveLockFile (lock_fd); - - return retval; -} - -int -dbmt_con_read_dbinfo (T_DBMT_CON_DBINFO *dbinfo, const char *ip, - const char *port, const char *dbname, char *_dbmt_error) -{ - FILE *infile; - int lfd, retval = -1; - char ip_t[20], port_t[10]; - char *prev, *next, *tok[2]; - char *strbuf = NULL; - char sbuf[512]; - int buf_len, get_len; - - lfd = uCreateLockFile (conf_get_dbmt_file (FID_LOCK_CONN_LIST, sbuf)); - if (lfd < 0) - { - strcpy (_dbmt_error, "Open conlist.lock fail"); - return retval; - } - - infile = fopen (conf_get_dbmt_file (FID_CONN_LIST, sbuf), "r"); - if (infile == NULL) - { - strcpy (_dbmt_error, "Open conlist fail"); - goto con_read_dbinfo_err; - } - - strbuf = NULL; - buf_len = get_len = 0; - while ((get_len = ut_getline (&strbuf, &buf_len, infile)) != -1) - { - /* remove character '\n' */ - strbuf[strlen (strbuf) - 1] = '\0'; - - if (sscanf (strbuf, "%19s %9s", ip_t, port_t) == 2 && - uStringEqual (ip, ip_t) && uStringEqual (port, port_t)) - { - /* locate dbinfo_list */ - int i = 0; - prev = strbuf; - while (*prev != '\0') - { - if (isspace (*prev)) - { - ++i; - } - ++prev; - if (i == 6) - { - break; - } - } - if (i == 5) - { - strcpy (_dbmt_error, "No db exists now"); - retval = 0; - goto con_read_dbinfo_err; - } - else if (i < 5) - { - strcpy (_dbmt_error, "Conlist format error"); - goto con_read_dbinfo_err; - } - - /* parse every dbinfo */ - while (prev != NULL) - { - next = strchr (prev, ';'); - if (next != NULL) - { - *next = '\0'; - next++; - } - - if (string_tokenize2 (prev, tok, 2, ':') < 0) - { - strcpy (_dbmt_error, "Conlist format error"); - goto con_read_dbinfo_err; - } - - if (uStringEqual (dbname, tok[0])) - { - strcpy_limit (dbinfo->dbname, tok[0], - sizeof (dbinfo->dbname)); - prev = tok[1]; - if (string_tokenize2 (prev, tok, 2, ',') < 0) - { - strcpy (_dbmt_error, "Conlist format error"); - goto con_read_dbinfo_err; - } - strcpy_limit (dbinfo->uid, tok[0], sizeof (dbinfo->uid)); - strcpy_limit (dbinfo->passwd, tok[1], - sizeof (dbinfo->passwd)); - - retval = 1; - break; - } - - /* parse the next dbinfo */ - prev = next; - } - break; - } - FREE_MEM (strbuf); - buf_len = 0; - } - - if (retval == -1 && strlen (_dbmt_error) == 0) - { - retval = 0; - strcpy (_dbmt_error, "Database not found"); - } - -con_read_dbinfo_err: - if (infile) - { - fclose (infile); - } - if (strbuf != NULL) - { - FREE_MEM (strbuf); - } - - uRemoveLockFile (lfd); - - return retval; -} - -int -dbmt_con_write_dbinfo (T_DBMT_CON_DBINFO *dbinfo, const char *ip, - const char *port, const char *dbname, int creat_flag, - char *_dbmt_error) -{ - FILE *infile, *outfile; - int lfd, retval = -1; - char tmpfile[512], conn_list_file[512]; - char date[15], time[10]; - char *prev, *next, *tok[2]; - char *strbuf = NULL; - char sbuf[512]; - int buf_len, get_len; - - T_DBMT_CON_INFO con_info; - memset (&con_info, 0, sizeof (T_DBMT_CON_INFO)); - - lfd = uCreateLockFile (conf_get_dbmt_file (FID_LOCK_CONN_LIST, sbuf)); - if (lfd < 0) - { - strcpy (_dbmt_error, "Open conlist.lock fail"); - return retval; - } - - conf_get_dbmt_file (FID_CONN_LIST, conn_list_file); - sprintf (tmpfile, "%s/DBMT_util_014.%d", sco.dbmt_tmp_dir, (int) getpid ()); - - infile = fopen (conf_get_dbmt_file (FID_CONN_LIST, sbuf), "r"); - outfile = fopen (tmpfile, "w"); - if (infile == NULL || outfile == NULL) - { - if (infile != NULL) - { - fclose (infile); - infile = NULL; - } - if (outfile != NULL) - { - fclose (outfile); - outfile = NULL; - } - - strcpy (_dbmt_error, "Open conlist fail"); - goto con_write_dbinfo_err; - } - - strbuf = NULL; - buf_len = get_len = 0; - while ((get_len = ut_getline (&strbuf, &buf_len, infile)) != -1) - { - /* remove character '\next' */ - strbuf[strlen (strbuf) - 1] = '\0'; - if (con_info.con_dbinfo != NULL) - { - FREE_MEM (con_info.con_dbinfo); - } - memset (&con_info, 0, sizeof (con_info)); - - if (sscanf - (strbuf, "%19s %9s %10s %8s %15s %64s", con_info.cli_ip, - con_info.cli_port, date, time, con_info.cli_ver, - con_info.user_name) == 6 - && uStringEqual (ip, con_info.cli_ip) - && uStringEqual (port, con_info.cli_port)) - { - /* locate dbinfo_list */ - int i = 0; - T_DBMT_CON_DBINFO tmp_dbinfo; - prev = strbuf; - while (*prev != '\0') - { - if (isspace (*prev)) - { - ++i; - } - ++prev; - if (i == 6) - { - break; - } - } - if (i < 6 && creat_flag == 0) - { - strcpy (_dbmt_error, "Conlist format error"); - goto con_write_dbinfo_err; - } - - /* parse every dbinfo */ - while (prev != NULL) - { - next = strchr (prev, ';'); - if (next != NULL) - { - *next = '\0'; - next++; - } - - memset (&tmp_dbinfo, 0, sizeof (T_DBMT_CON_DBINFO)); - - if (string_tokenize2 (prev, tok, 2, ':') < 0) - { - if (creat_flag == 0) - { - strcpy (_dbmt_error, "Conlist format error"); - goto con_write_dbinfo_err; - } - else - { - creat_flag = 0; - /* no db exists, add dbinfo */ - tmp_dbinfo = *dbinfo; - } - } - else - { - if (uStringEqual (dbname, tok[0])) - { - /* db exists, update dbinfo */ - creat_flag = 0; - tmp_dbinfo = *dbinfo; - } - else - { - /* just record dbinfo */ - strcpy_limit (tmp_dbinfo.dbname, tok[0], - sizeof (tmp_dbinfo.dbname) - 1); - prev = tok[1]; - if (string_tokenize2 (prev, tok, 2, ',') < 0) - { - strcpy (_dbmt_error, "Conlist format error"); - goto con_write_dbinfo_err; - } - strcpy_limit (tmp_dbinfo.uid, tok[0], - sizeof (tmp_dbinfo.uid)); - strcpy_limit (tmp_dbinfo.passwd, tok[1], - sizeof (tmp_dbinfo.passwd)); - } - } - - con_info.con_dbinfo = - (T_DBMT_CON_DBINFO *) increase_capacity (con_info.con_dbinfo, - sizeof (T_DBMT_CON_DBINFO), - con_info.num_con_dbinfo, - con_info.num_con_dbinfo + 1); - if (con_info.con_dbinfo == NULL) - { - strcpy (_dbmt_error, "Malloc fail"); - goto con_write_dbinfo_err; - } - con_info.num_con_dbinfo++; - con_info.con_dbinfo[con_info.num_con_dbinfo - 1] = tmp_dbinfo; - - /* parse the next dbinfo */ - prev = next; - } - /* db not found, create it */ - if (creat_flag == 1) - { - con_info.con_dbinfo = - (T_DBMT_CON_DBINFO *) increase_capacity (con_info.con_dbinfo, - sizeof (T_DBMT_CON_DBINFO), - con_info.num_con_dbinfo, - con_info.num_con_dbinfo + 1); - if (con_info.con_dbinfo == NULL) - { - strcpy (_dbmt_error, "Malloc fail"); - goto con_write_dbinfo_err; - } - con_info.num_con_dbinfo++; - con_info.con_dbinfo[con_info.num_con_dbinfo - 1] = *dbinfo; - } - - /* update conlist file content */ - fprintf (outfile, "%s %s %s %s %s %s ", con_info.cli_ip, - con_info.cli_port, date, time, con_info.cli_ver, - con_info.user_name); - for (i = 0; i < con_info.num_con_dbinfo; i++) - { - fprintf (outfile, "%s:%s,%s", con_info.con_dbinfo[i].dbname, - con_info.con_dbinfo[i].uid, con_info.con_dbinfo[i].passwd); - if (i != (con_info.num_con_dbinfo - 1)) - { - fprintf (outfile, ";"); - } - } - fprintf (outfile, "\n"); - - retval = 0; - } - else - { - fprintf (outfile, "%s\n", strbuf); - } - FREE_MEM (strbuf); - buf_len = 0; - } - -con_write_dbinfo_err: - if (infile) - { - fclose (infile); - } - if (outfile) - { - fclose (outfile); - } - if (strbuf != NULL) - { - FREE_MEM (strbuf); - } - if (con_info.con_dbinfo != NULL) - { - FREE_MEM (con_info.con_dbinfo); - } - move_file (tmpfile, conn_list_file); - - uRemoveLockFile (lfd); - - return retval; -} - -void -dbmt_con_set_dbinfo (T_DBMT_CON_DBINFO *dbinfo, const char *dbname, - const char *uid, const char *passwd) -{ - strcpy_limit (dbinfo->dbname, dbname, sizeof (dbinfo->dbname)); - strcpy_limit (dbinfo->uid, uid, sizeof (dbinfo->uid)); - strcpy_limit (dbinfo->passwd, passwd, sizeof (dbinfo->passwd)); -} diff --git a/server/src/cm_connect_info.h b/server/src/cm_connect_info.h deleted file mode 100644 index f5a909a..0000000 --- a/server/src/cm_connect_info.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. - * - * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/* - * cm_connect_info.h - - */ - -#ifndef _CM_CONNECT_INFO_H_ -#define _CM_CONNECT_INFO_H_ - -#define DBMT_USER_NAME_LEN 64 - -/* conlist */ -typedef struct -{ - char dbname[DBMT_USER_NAME_LEN]; - char uid[32]; - char passwd[80]; -} T_DBMT_CON_DBINFO; - -typedef struct -{ - char user_name[DBMT_USER_NAME_LEN]; - char cli_ip[20]; - char cli_port[10]; - char cli_ver[15]; - int num_con_dbinfo; - T_DBMT_CON_DBINFO *con_dbinfo; -} T_DBMT_CON_INFO; - -int dbmt_con_search (const char *ip, const char *port, char *cli_ver); -int dbmt_con_add (const char *ip, const char *port, const char *cli_ver, - const char *user_name); -int dbmt_con_delete (const char *ip, const char *port); - -int dbmt_con_read_dbinfo (T_DBMT_CON_DBINFO *dbinfo, const char *ip, - const char *port, const char *dbname, - char *_dbmt_error); -int dbmt_con_write_dbinfo (T_DBMT_CON_DBINFO *dbinfo, const char *ip, - const char *port, const char *dbname, - int creat_flag, char *_dbmt_error); -void dbmt_con_set_dbinfo (T_DBMT_CON_DBINFO *dbinfo, const char *dbname, - const char *uid, const char *passwd); - -#endif /* _CM_CONNECT_INFO_H_ */ diff --git a/server/src/cm_http_server.cpp b/server/src/cm_http_server.cpp deleted file mode 100644 index 71f795b..0000000 --- a/server/src/cm_http_server.cpp +++ /dev/null @@ -1,664 +0,0 @@ -/* - * Copyright (C) 2013 Search Solution Corporation. All rights reserved by Search Solution. - * - * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - -/* -* cm_http_server.cpp - -*/ - -#include -#include -#include -#include -#include - -#include "cm_http_server.h" -#include "cm_log.h" - -using namespace std; - -static void http_error_404 (struct evhttp_request *req, int fd); -static void server_setup_certs (SSL_CTX *ctx, const char *certificate_chain,const char *private_key); -static void web_error_404 (struct evhttp_request *req); -static void locking_callback (int mode, int type, const char *file, int line); - -#if !defined(WINDOWS) && !defined(__BEOS__) -static void thread_id_callback (CRYPTO_THREADID *tid); -#endif - -static char uri_root[512] = "/"; -static char *userAgent = NULL; -static MUTEX_T *lock_array = NULL; - -/* - * This struct is used to get type of the files to browser. - * if git contains ico etc. web browser will loading them one by one. - */ -typedef const struct -{ - const char *extension; - const char *content_type; -} table_entry; - -table_entry content_type_table[] = -{ - { "txt", "text/plain" }, - { "c", "text/plain" }, - { "h", "text/plain" }, - { "properties", "text/plain" }, - { "html", "text/html" }, - { "htm", "text/htm" }, - { "css", "text/css" }, - { "gif", "image/gif" }, - { "jpg", "image/jpeg" }, - { "jpeg", "image/jpeg" }, - { "png", "image/png" }, - { "ico", "image/x-icon" }, - { "js", "application/x-javascript" }, - { NULL, NULL }, -}; - -/** - * @brief guess_content_type - * This is a magic function, Try to guess a good content-type for 'path' - * @param path - * Full path - * @return - * Return the type of file that in content_type_table[], - * Other return application/misc to browser. - */ -static const char *guess_content_type (const char *path) -{ - const char *last_period = NULL; - const char *extension = NULL; - table_entry *ent = NULL; - - last_period = strrchr (path, '.'); - - if (!last_period || strchr (last_period, '/')) - { - return "application/misc"; /* no exension */ - } - - extension = last_period + 1; - if (extension == NULL) - { - return "application/misc"; /* no exension */ - } - - for (ent = &content_type_table[0]; ent->extension; ++ent) - { - if (!evutil_ascii_strcasecmp (ent->extension, extension)) - { - return ent->content_type; - } - } - - return "application/misc"; -} - -#ifdef WINDOWS -/** - * @brief isDirectory - * To check the path is file or path in windows OS. - * @param path - * Full path - * @return - * If file:0, - * else: 1 - */ -int isDirectory (char *path) -{ - DWORD fileAttributes = GetFileAttributes (path); - - if (fileAttributes != INVALID_FILE_ATTRIBUTES) - { - return (fileAttributes & FILE_ATTRIBUTE_DIRECTORY); - } - else - { - return 0; - } -} -#endif - -/** - * @brief load_webfiles_cb - * This callback gets invoked when we get any http request that doesn't match - * any other callback. Like any evhttp server callback, it has a simple job: - * it must eventually call evhttp_send_error() or evhttp_send_reply(). - * It is a real http server,if want add SSL connection. must be called after: - * create_sslconn_cb and init_SSL - * @param req - * http reuqest - * See also: struct evhttp_request - * @param arg - * The path or the files that need to be called. - * @return - */ -void load_webfiles_cb (struct evhttp_request *req, void *arg) -{ - struct evbuffer *evb = NULL; - const char *docroot = (char *)arg; - const char *uri = NULL; - struct evhttp_uri *decoded = NULL; - const char *path = NULL; - const char *default_path = "/index.html"; - char *decoded_path = NULL; - char *whole_path = NULL; - size_t len; - int fd = -1; - struct stat st; - int disable_directrory_listing = 1; - const char *get_query = NULL; - const char *type = "application/misc"; - -#ifdef WINDOWS - WIN32_FIND_DATA FileData; - HANDLE handle; -#endif - - /* This is be debug print */ - struct evkeyvalq *headers = NULL; - struct evkeyval *header = NULL; - - if (sco.iSupportWebManager == FALSE) - { - web_error_404 (req); - LOG_WARN ("-- Web server: Not config support_web_manager"); - goto done; - } - - headers = evhttp_request_get_input_headers (req); - for (header = headers->tqh_first; header; - header = header->next.tqe_next) - { - if (string (header->key).compare ("User-Agent") == 0) - { - userAgent = header->value; - } - } - - /* Decode the URI */ - uri = evhttp_request_get_uri (req); - decoded = evhttp_uri_parse (uri); - if (!decoded) - { - evhttp_send_error (req, HTTP_BADREQUEST, 0); - LOG_WARN ("-- %s -- %s -- Web server: bad request for [%s]", req->remote_host, userAgent, uri); - return; - } - - get_query = evhttp_uri_get_query (decoded); - /* Basic path routing. */ - path = evhttp_uri_get_path (decoded); - - if (!path) - { - path = default_path; - } - if (strcmp (path, "/") == 0) - { - path = default_path; - } - /* We need to decode it, to see what path the user really wanted. */ - decoded_path = evhttp_uridecode (path, 0, NULL); - - if (decoded_path == NULL) - { - http_error_404 (req, fd); - LOG_WARN ("-- %s -- %s -- Web server: bad request for [%s]", req->remote_host, userAgent, uri); - goto done; - } - - /* Don't allow any ".."s in the path, to avoid exposing stuff outside - * of the docroot. This test is both overzealous and underzealous: - * it forbids aceptable paths like "/this/one..here", but it doesn't - * do anything to prevent symlink following." - */ - if (strstr (decoded_path, "..")) - { - http_error_404 (req, fd); - goto done; - } - - len = strlen (decoded_path) + strlen (docroot) + 2; - - if (! (whole_path = (char *)malloc (len))) - { - http_error_404 (req, fd); - LOG_WARN ("-- %s -- %s -- Web server: bad request for [%s]", req->remote_host, userAgent, uri); - goto done; - } - evutil_snprintf (whole_path, len, "%s%s", docroot, decoded_path); - if (stat (whole_path, &st) < 0 ) - { - http_error_404 (req, fd); - LOG_WARN ("-- %s -- %s -- Web server: bad request for [%s]", req->remote_host, userAgent, uri); - goto done; - } - - /* This holds the content we're sending. */ - evb = evbuffer_new (); -#ifdef WINDOWS - const char *name = "unknown"; - handle = FindFirstFile (whole_path, &FileData); - if (handle == INVALID_HANDLE_VALUE) - { - goto done; - } - - if (isDirectory (whole_path)) - { - const char *trailing_slash = ""; - if (!strlen (path) || path[strlen (path)-1] != '/') - { - trailing_slash = "/"; - } - - evbuffer_add_printf (evb, "\n \n" - " %s\n" - " \n" - " \n" - " \n" - "

%s

\n" - "
    \n", - decoded_path, /* XXX html-escape this. */ - uri_root, path, /* XXX html-escape this? */ - trailing_slash, - decoded_path /* XXX html-escape this */); - - while (FindNextFile (handle, &FileData)) - { - name = FileData.cFileName; - evbuffer_add_printf (evb, - "
  • %s\n", - name, name);/* XXX escape this */ - } - FindClose (handle); - evbuffer_add_printf (evb, "
\n"); - evhttp_add_header (evhttp_request_get_output_headers (req), - "Content-Type", "text/html"); - } -#else - // directory listing security - if (S_ISDIR (st.st_mode) && disable_directrory_listing) - { - http_error_404 (req, fd); - LOG_WARN ("-- %s -- %s -- Web server: bad request for [%s]", req->remote_host, userAgent, uri); - goto done; - } - - if (S_ISDIR (st.st_mode)) - { - /* If it's a directory, read the comments and make a little - * index page - */ - DIR *d; - struct dirent *ent; - const char *trailing_slash = ""; - if (!strlen (path) || path[strlen (path)-1] != '/') - { - trailing_slash = "/"; - } - - if (! (d = opendir (whole_path))) - { - http_error_404 (req, fd); - LOG_WARN ("-- %s -- %s -- Web server: bad request for [%s]", req->remote_host, userAgent, uri); - goto done; - } - - evbuffer_add_printf (evb, "\n \n" - " %s\n" - " \n" - " \n" - " \n" - "

%s

\n" - "
    \n", - decoded_path, /* XXX html-escape this. */ - uri_root, path, /* XXX html-escape this? */ - trailing_slash, - decoded_path /* XXX html-escape this */); - - while ((ent = readdir (d))) - { - const char *name = ent->d_name; - evbuffer_add_printf (evb, - "
  • %s\n", - name, name);/* XXX escape this */ - } - evbuffer_add_printf (evb, "
\n"); - closedir (d); - evhttp_add_header (evhttp_request_get_output_headers (req), - "Content-Type", "text/html"); - } -#endif - else - { - /* Otherwise it's a file; add it to the buffer to get - * sent via sendfile - */ - type = guess_content_type (decoded_path); - /* O_BINARY is used to open the files that - * contains unicode. otherwise,open files will be failed. - */ - if ((fd = open (whole_path, O_RDONLY|O_BINARY)) < 0) - { - http_error_404 (req, fd); - LOG_WARN ("-- %s -- %s -- Web server: bad request for [%s]", req->remote_host, userAgent, uri); - goto done; - } - - if (fstat (fd, &st) < 0) - { - /* Make sure the length still matches, now that we - * opened the file :/ - */ - http_error_404 (req, fd); - LOG_WARN ("-- %s -- %s -- Web server: bad request for [%s]", req->remote_host, userAgent, uri); - goto done; - } - evhttp_add_header (evhttp_request_get_output_headers (req), - "Content-Type", type); - evbuffer_add_file (evb, fd, 0, st.st_size); - } - - evhttp_send_reply (req, 200, "OK", evb); - -done: - if (decoded) - { - evhttp_uri_free (decoded); - } - if (decoded_path) - { - free (decoded_path); - } - if (whole_path) - { - free (whole_path); - } - if (evb) - { - evbuffer_free (evb); - } -} - -/** - * @brief create_sslconn_cb - * This callback is responsible for creating a new SSL connection - * and wrapping it in an OpenSSL bufferevent. This is the way - * we implement an https server instead of a plain old http server. - * @param base - * See also: struct event_base and bufferevent_openssl_socket_new - * @param arg - * It must be struct SSL_CTX, - * See also: SSL_CTX - * @return bufferevent - */ -struct bufferevent *create_sslconn_cb (struct event_base *base, void *arg) -{ - struct bufferevent *r = NULL; - SSL_CTX *ctx = (SSL_CTX *) arg; - - r = bufferevent_openssl_socket_new (base, - -1, - SSL_new (ctx), - BUFFEREVENT_SSL_ACCEPTING, - BEV_OPT_CLOSE_ON_FREE); - if (r == NULL) - { - LOG_ERROR ("-- Web server: Failed to create SSL connection."); - return NULL; - } - - bufferevent_openssl_set_allow_dirty_shutdown(r, 1); - return r; -} - -/** - * @brief server_setup_certs - * Used to init SSL certificate and private key. - * @param ctx - * Used to generate SSL_CTX - * @param certificate_chain - * certificate chain file. It can be full path,also can be the name of file. - * @param private_key - * private key file. It can be full path,also can be the name of file. - * @return - */ -static void server_setup_certs (SSL_CTX *ctx, - const char *certificate_chain, - const char *private_key) -{ - if (1 != SSL_CTX_use_certificate_chain_file (ctx, certificate_chain)) - { - LOG_ERROR ("-- Web server: OpenSSL error: Cannot initialize certificate file."); - exit (-1); - } - if (1 != SSL_CTX_use_PrivateKey_file (ctx, private_key, SSL_FILETYPE_PEM)) - { - LOG_ERROR ("-- Web server: OpenSSL error: Cannot initialize private key file."); - exit (-1); - } - if (1 != SSL_CTX_check_private_key (ctx)) - { - LOG_ERROR ("-- Web server: OpenSSL error: Invalid CTX private key."); - exit (-1); - } -} - -/** - * @brief thread_setup_SSL - * Setup the necessary resources to ensure that OpenSSL can safely - * be used in multi-threaded environment. - * @return - */ -void thread_setup_SSL (void) -{ - int total_locks, i; - - total_locks = CRYPTO_num_locks (); - - lock_array = (MUTEX_T *) OPENSSL_malloc (total_locks * sizeof (MUTEX_T)); - - for (i = 0; i < total_locks; i++) - { - MUTEX_INIT (lock_array[i]); - } - -#if !defined(WINDOWS) && !defined(__BEOS__) - /* It's unnecessary to define or set the thread-id callback functions for - * WINDOWS and BEOS platform, since they have been defined in OpenSSL kernel. - * Please refer to the source code implemented CRYPTO_THREADID_current() - * function in crypto/cryptlib.c from OpenSSL. - */ - CRYPTO_THREADID_set_callback (thread_id_callback); -#endif - - CRYPTO_set_locking_callback (locking_callback); -} - -#if !defined(WINDOWS) && !defined(__BEOS__) -/** - * @brief thread_id_callback - * Callback function to get thread id for OpenSSL thread safety. - * @param tid - * The thread id to be set. - * @return - */ -static void thread_id_callback (CRYPTO_THREADID *tid) -{ - CRYPTO_THREADID_set_numeric (tid, (unsigned long) pthread_self ()); -} -#endif - -/** - * @brief locking_callback - * Callback function to get lock for OpenSSL thread safety. - * @param mode - * The lock mode (lock or unlock) as required by OpenSSL. - * @param type - * The lock type as required and internally used by OpenSSL. - * @param file - * The source code file name as required and internally used by OpenSSL. - * @param line - * The source code line number as required and internally used by OpenSSL. - * @return - */ -static void locking_callback (int mode, int type, const char *file, int line) -{ - if (mode & CRYPTO_LOCK) - { - MUTEX_LOCK (lock_array[type]); - } - else - { - MUTEX_UNLOCK (lock_array[type]); - } -} - -/** - * @brief thread_cleanup_SSL - * Cleanup the allocated resources which is used for OpenSSL thread safety. - * @return - */ -void thread_cleanup_SSL (void) -{ - int total_locks, i; - - CRYPTO_set_locking_callback (NULL); - - if (lock_array != NULL) - { - total_locks = CRYPTO_num_locks (); - - for (i = 0; i < total_locks; i++) - { - MUTEX_DESTROY (lock_array[i]); - } - - OPENSSL_free (lock_array); - lock_array = NULL; - } -} - -/** - * @brief init_SSL - * init the ssl methods,loading key and crt files, - * return ctx that used to create ssl connections. - * See also: create_sslconn_cb - * @param certificate_chain - * certificate chain file. It can be full path,also can be the name of file. - * @param private_key - * private key file. It can be full path,also can be the name of file. - * @return SSL_CTX - */ -SSL_CTX *init_SSL (const char *certificate_chain,const char *private_key) -{ - - SSL_CTX *ctx = NULL; - /* init SSL libray is must. */ - SSL_library_init (); - /* We just use SSLv3,do not support SSLv2. */ - - ctx = SSL_CTX_new (TLSv1_server_method ()); - if (!ctx) - { - LOG_ERROR ("-- Web server: Fail to generate CTX for openSSL."); - } - SSL_CTX_set_options (ctx, - SSL_OP_SINGLE_DH_USE | - SSL_OP_SINGLE_ECDH_USE | - SSL_OP_NO_SSLv3 | - SSL_OP_NO_SSLv2); - - /* Find and set up our server certificate. */ - server_setup_certs (ctx, certificate_chain, private_key); - return ctx; -} - -/** - * @brief http_error_404 - * Used to report 404 error to browser using libevent.and close fd - * @param req - * http request - * See also: struct evhttp_request - * @param fd - * if fd >= 0, close it. - * @return - * See also: evhttp_send_error - */ - -static void http_error_404 (struct evhttp_request *req, int fd) -{ - const char *uri = evhttp_request_get_uri (req); -#define ERROR_FORMAT "" \ - "404 Not Found" \ - "" \ - "

404 Not Found

" \ - "

Request: %s not found

"\ - "
"\ - "
Arniadb Manager Server
"\ - "\n" - - struct evbuffer *buf = evbuffer_new (); - if (buf == NULL) - { - /* if we cannot allocate memory; we just drop the connection */ - LOG_WARN ("-- Web server: http_error_404 cannot create a buffer."); - return; - } - evbuffer_add_printf (buf, ERROR_FORMAT, uri); - evhttp_send_reply (req, 404, "404 Not Found", buf); - evbuffer_free (buf); -#undef ERROR_FORMAT - if (fd >= 0) - { - close (fd); - } -} - -/** - * @brief web_error_404 - * Used to report 404 error to browser when use did not start web server: in cm.conf - * @param - * @return - * See also: evhttp_send_error - */ - -static void web_error_404 (struct evhttp_request *req) -{ - -#define ERROR_FORMAT "" \ - "404 Not Found" \ - "" \ - "

404 Not Found

" \ - "

Web Manager was not started, please configure it rightly

"\ - "
"\ - "
Arniadb Manager Server
"\ - "\n" - - struct evbuffer *buf = evbuffer_new (); - - evbuffer_add_printf (buf, ERROR_FORMAT); - evhttp_send_reply (req, 404, "Not Found", buf); - evbuffer_free (buf); -#undef ERROR_FORMAT -} diff --git a/server/src/cm_http_server.h b/server/src/cm_http_server.h deleted file mode 100644 index 72a800f..0000000 --- a/server/src/cm_http_server.h +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (C) 2013 Search Solution Corporation. All rights reserved by Search Solution. - * - * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - -/* -* cm_http_server.h -*/ - -#include - -#ifdef WINDOWS -#ifndef S_ISDIR -# define S_ISDIR(m) (((m) & (_S_IFMT)) == (_S_IFDIR)) -#endif -#include -#include -#include -#include -#include -#else -#include -#include -#include -#include -#endif - -#include -#include - -#ifdef _EVENT_HAVE_NETINET_IN_H -#include -# ifdef _XOPEN_SOURCE_EXTENDED -# include -# endif -#endif -#ifndef O_BINARY -#define O_BINARY 0x8000 //used for open files that contains some unicodes -#endif - - -/** - * @brief load_webfiles_cb - * This callback gets invoked when we get any http request that doesn't match - * any other callback. Like any evhttp server callback, it has a simple job: - * it must eventually call evhttp_send_error() or evhttp_send_reply(). - * It is a real http server,if want add SSL connection. must be called after: - * create_sslconn_cb and init_SSL - * @param req - * http reuqest - * See also: struct evhttp_request - * @param arg - * The path or the files that need to be called. - * @return - */ -void load_webfiles_cb (struct evhttp_request *req, void *arg); - -/** - * @brief create_sslconn_cb - * This callback is responsible for creating a new SSL connection - * and wrapping it in an OpenSSL bufferevent. This is the way - * we implement an https server instead of a plain old http server. - * @param base - * See also: struct event_base and bufferevent_openssl_socket_new - * @param arg - * It must be struct SSL_CTX, - * See also: SSL_CTX - * @return bufferevent - */ -struct bufferevent *create_sslconn_cb (struct event_base *base, void *arg); - -/** - * @brief init_SSL - * init the ssl methods,loading key and crt files, - * return ctx that used to create ssl connections. - * See also: create_sslconn_cb - * @param certificate_chain - * certificate chain file. It can be full path,also can be the name of file. - * @param private_key - * private key file. It can be full path,also can be the name of file. - * @return SSL_CTX - */ -SSL_CTX *init_SSL (const char *certificate_chain,const char *private_key); - -/** - * @brief thread_setup_SSL - * Setup the necessary resources to ensure that OpenSSL can safely - * be used in multi-threaded environment. - * @return - */ -void thread_setup_SSL (void); - -/** - * @brief thread_cleanup_SSL - * Cleanup the allocated resources which is used for OpenSSL thread safety. - * @return - */ -void thread_cleanup_SSL (void); diff --git a/server/src/cm_httpd.cpp b/server/src/cm_httpd.cpp deleted file mode 100644 index f07cd9d..0000000 --- a/server/src/cm_httpd.cpp +++ /dev/null @@ -1,921 +0,0 @@ -/* - * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. - * - * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - -/* -* cm_httpd.cpp -*/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef WINDOWS -#include -#include "cm_win_wsa.h" -#include -#include -#include -#else -#include -#include -#include -#include -#include -#include -#endif - -#include "cm_log.h" -#include "cm_server_util.h" -#include "cm_config.h" -#include "cm_autojob.h" -#include "cm_auto_task.h" -#include "cm_cci_interface.h" -#include "cm_server_interface.h" -#include "cm_server_stat.h" -#include "cm_server_extend_interface.h" -#include "cm_mon_stat.h" -#include "cm_http_server.h" - -//#include "cm_utf8.h" -using namespace std; - -#define DEFAULT_THRD_NUM 24 -#define DEFAULT_HTTP_TIMEOUT 6 * 60 //second -#define NUM_OF_FILES_IN_URL 3 -#define STAT_MONITOR_INTERVAL 1 // seconds - -static THREAD_FUNC automation_start (void *ud); -static THREAD_FUNC aj_thread_r (void *aj); -static void start_auto_thread (void); - -T_EMGR_VERSION CLIENT_VERSION = EMGR_MAKE_VER (8, 4); - -#ifdef WINDOWS -T_THREAD auto_task_tid = NULL; -#else -T_THREAD auto_task_tid = 0; -#endif - -typedef struct aj_thread_info_t -{ - T_THREAD thread_id; - time_t cur_time; - time_t prev_check_time; - ajob *ajob_list; - time_t stime; - int is_running; -} aj_thread_info; - -aj_thread_info aj_tinfo; - -MUTEX_T aj_thread_mutex; - -struct worker_context -{ - struct event_base *base; - struct evhttp *httpd; - struct event *timer; - bool first; -#ifdef WINDOWS - HANDLE ths; -#else - pthread_t ths; -#endif -}; - -int arniadb_version_major = -1; -int arniadb_version_minor = -1; - -int -bind_socket (int port) -{ - int r; - int nfd; - struct sockaddr_in addr; - int one = 1; - int flags = 1; - nfd = (int) socket (AF_INET, SOCK_STREAM, 0); - if (nfd < 0) - { - return -1; - } - - setsockopt (nfd, SOL_SOCKET, SO_REUSEADDR, (char *) &one, sizeof (int)); - - memset (&addr, 0, sizeof (addr)); - addr.sin_family = AF_INET; - addr.sin_port = htons (port); - r = bind (nfd, (struct sockaddr *) &addr, sizeof (addr)); - if (r < 0) - { - close (nfd); - return -1; - } - r = listen (nfd, 10240); - if (r < 0) - { - close (nfd); - return -1; - } -#ifdef WINDOWS - ioctlsocket (nfd, FIONBIO, (unsigned long *) &flags); -#else - if ((flags = fcntl (nfd, F_GETFL, 0)) != -1) - { - fcntl (nfd, F_SETFL, flags | O_NONBLOCK); - } -#endif - - return nfd; -} - -#ifdef WINDOWS -DWORD WINAPI -dispatch_thread (void *arg) -#else -void * -dispatch_thread (void *arg) -#endif -{ - struct worker_context *work_ctx = (struct worker_context *) arg; - event_base_dispatch ((struct event_base *) work_ctx->base); - - if (work_ctx->timer) - { - event_free (work_ctx->timer); - } - if (work_ctx->httpd) - { - evhttp_free (work_ctx->httpd); - } - if (work_ctx->base) - { - event_base_free (work_ctx->base); - } -#ifdef WINDOWS - return 0; -#else - return NULL; -#endif -} - -void -arn_add_private_param (struct evhttp_request *req, Json::Value &root) -{ - root["_CLIENTIP"] = req->remote_host; - root["_CLIENTPORT"] = req->remote_port; - root["_STAMP"] = 1; - root["_PROGNAME"] = CMS_NAME; -} - -void -arn_generic_request_handler (struct evhttp_request *req, void *arg) -{ - struct evbuffer *input; - struct evkeyvalq *headers; - char *body; - // char *inustr, *outustr; - string task_name; - int len; - struct evbuffer *evb; - Json::Value root, response; - Json::Reader reader; - Json::StyledWriter writer; - char *data = NULL; - - input = evhttp_request_get_input_buffer (req); - if (input == NULL) - { - evhttp_send_reply (req, HTTP_BADREQUEST, "", NULL); - return; - } - - len = (int) evbuffer_get_length (input); - if (len <= 0) - { - evhttp_send_reply (req, HTTP_BADREQUEST, "", NULL); - return; - } - - data = (char *) evbuffer_pullup(input, len); - if (data == NULL) - { - evhttp_send_reply (req, HTTP_BADREQUEST, "", NULL); - return; - } - - - body = (char *) malloc (len + 1); - if (body == NULL) - { - evhttp_send_reply (req, HTTP_BADREQUEST, "", NULL); - return; - } - - memset (body, 0x00, len+1); - memcpy (body, data, len); - - if (evbuffer_drain (input, len) < 0) - { - free (body); - evhttp_send_reply (req, HTTP_BADREQUEST, "", NULL); - return; - } - - if (!reader.parse (body, root)) - { - free (body); - //utf8_clean(inustr); - evhttp_send_reply (req, HTTP_BADREQUEST, "Error JSON format", NULL); - return; - } - - arn_add_private_param (req, root); - - if (!strcmp ((char *) arg, "cci")) - { - arn_cci_request_handler (root, response); - } - else if (!strcmp ((char *) arg, "cm_api")) - { - arn_cm_request_handler (root, response); - } - - //outustr = utf8_encode(writer.write(response).c_str()); - //printf("---------------------\n%s\n", outustr); - evb = evbuffer_new (); - if (NULL == evb) - { - free (body); - //utf8_clean(inustr); - //utf8_clean(outustr); - return evhttp_send_reply (req, HTTP_BADREQUEST, "", NULL); - } - - headers = evhttp_request_get_output_headers (req); - if (headers) - { - evhttp_add_header (headers, "Content-Type", "text/plain;charset=utf-8"); - } - - evbuffer_add_printf (evb, "%s", writer.write (response).c_str ()); - evhttp_send_reply (req, HTTP_OK, "OK", evb); - evbuffer_free (evb); - free (body); - //utf8_clean(inustr); - //utf8_clean(outustr); - - return; -} - -static int arn_loop_flag = 1; - -void -arn_ctrl_request_handler (struct evhttp_request *req, void *arg) -{ - evhttp_send_reply (req, HTTP_OK, "", NULL); - arn_loop_flag = 0; - return; -} - -void -arn_post_request_handler (struct evhttp_request *req, void *arg) -{ - string post_msg = "{ \"success\" : true }"; - string req_uri (req->uri); - char token[TOKEN_ENC_LENGTH]; - size_t token_pos; - int code; - string reason; - size_t fname_pos = 0; - size_t tmp_pos = 0; - struct evbuffer *evb = evbuffer_new(); - - code = HTTP_OK; - reason = "OK"; - token[0] = '\0'; - token_pos = 0; - - string cookie (evhttp_find_header (req->input_headers, "COOKIE")); - token_pos = cookie.find ("token="); - if (token_pos == string::npos) - { - goto send_nok_reply; - } - - cookie.copy (token, TOKEN_ENC_LENGTH - 1, token_pos + strlen ("token=")); - token[TOKEN_ENC_LENGTH - 1] = '\0'; - if (ext_ut_validate_token (token)) - { - goto send_reply; - } - - for (int index = 0; index < NUM_OF_FILES_IN_URL; ++index) - { - char fname[PATH_MAX]; - string fname_path = string (sco.dbmt_tmp_dir) + "/"; - fname[0] = '\0'; - fname_pos = req_uri.find ("fname=", tmp_pos); - if (fname_pos == string::npos && index == 0) - { - goto send_nok_reply; - } - else if (fname_pos == string::npos) - { - goto send_reply; - } - - fname_pos += strlen ("fname="); - tmp_pos = req_uri.find ("&", fname_pos); - if (tmp_pos == string::npos) - { - tmp_pos = req_uri.length(); - } - req_uri.copy (fname, tmp_pos - fname_pos + 1, fname_pos); - fname[tmp_pos - fname_pos] = '\0'; - if (strcmp (fname, "") != 0 || strcmp (fname, "&") != 0) - { - if (strstr (fname, "..") || strstr (fname, "\\") || strstr (fname, "/")) - { - continue; - } - fname_path += fname; - unlink (fname_path.c_str()); - } - } - -send_nok_reply: - post_msg = "{ \"failure\" : true }"; - code = HTTP_NOTFOUND; - reason = "NOK"; - -send_reply: - if (evb) - { - evbuffer_add_printf (evb, "%s", post_msg.c_str()); - } - evhttp_send_reply (req, code, reason.c_str(), evb); - if (evb) - { - evbuffer_free (evb); - } - return; -} - -void -arn_timeout_cb (evutil_socket_t fd, short event, void *arg) -{ - struct worker_context *work_ctx = (struct worker_context *) arg; - if (!arn_loop_flag) - { - event_base_loopexit (work_ctx->base, NULL); - } -} - - -/** - * @brief callback function to gather monitoring data - */ -void -start_monitor_stat_cb (evutil_socket_t fd, short event, void *arg) -{ - struct timeval stat_tv = { STAT_MONITOR_INTERVAL, 0 }; - - struct worker_context *work_ctx = (struct worker_context *) arg; - if (!arn_loop_flag) - { - event_base_loopexit (work_ctx->base, NULL); - return; - } - - // [CUBRIDSUS-11917]sleep the thread for a while when the ARNIADB is starting - if (work_ctx->first) - { - SLEEP_SEC (MIN_INTERVAL - 1); - work_ctx->first = false; - } - - if (sco.iSupportMonStat == TRUE) - { - (cm_mon_stat::get_instance())->gather_mon_data(); - } - - evtimer_add (work_ctx->timer, &stat_tv); -} - -void -start_monitor_auto_jobs_cb (evutil_socket_t fd, short event, void *arg) -{ - struct timeval auto_task_tv = { sco.iMonitorInterval, 0 }; - struct worker_context *work_ctx = (struct worker_context *) arg; - if (!arn_loop_flag) - { - event_base_loopexit (work_ctx->base, NULL); - return; - } -#ifdef WINDOWS - unsigned long thread_status; - GetExitCodeThread ((HANDLE) auto_task_tid, &thread_status); - - if (thread_status != STILL_ACTIVE) - { - auto_task_tid = NULL; - LOG_WARN ("Restart auto jobs thread when exit abnormally."); - start_auto_thread (); - } -#else - int pthread_kill_err = ESRCH; - /* ESRCH - Thread is not exist. - EINVAL - Signal is invalid. - */ - pthread_kill_err = pthread_kill (auto_task_tid, 0); - if (pthread_kill_err == ESRCH) - { - auto_task_tid = 0; - LOG_WARN ("Restart auto jobs thread when exit abnormally."); - start_auto_thread (); - } -#endif - - evtimer_add (work_ctx->timer, &auto_task_tv); -} - -int -start_service () -{ - struct worker_context *start_ctx[DEFAULT_THRD_NUM]; - char tmpstrbuf[DBMT_ERROR_MSG_SIZE]; - struct timeval tv = { sco.iMonitorInterval, 0 }; - int nfd, err, i = 0; - - tmpstrbuf[0] = '\0'; -#ifdef WINDOWS - wsa_initialize (); -#endif - - thread_setup_SSL (); - - SSL_CTX *ctx = init_SSL (sco.szSSLCertificate, sco.szSSLKey); - - nfd = bind_socket (sco.iCMS_port); - - if (nfd < 0) - { - snprintf (tmpstrbuf, DBMT_ERROR_MSG_SIZE, - "ARNIADB Manager Server : The port %d is still used by other process.\n", - sco.iCMS_port); - ut_record_arniadb_utility_log_stderr (tmpstrbuf); - return -1; - } - - for (i = 0; i < DEFAULT_THRD_NUM; i++) - { - start_ctx[i] = (struct worker_context *) malloc (sizeof (struct worker_context)); - if (start_ctx[i] == NULL) - { - continue; - } - - start_ctx[i]->base = event_base_new (); - if (start_ctx[i]->base == NULL) - { - continue; - } - - start_ctx[i]->first = true; -#ifndef WINDOWS - start_ctx[i]->ths = 0; -#endif - - if (i > 1) /* DEFAULT_THRD_NUM - 1 for request handler */ - { - start_ctx[i]->timer = event_new (start_ctx[i]->base, -1, EV_PERSIST, arn_timeout_cb, (void *) start_ctx[i]); - if (start_ctx[i]->timer == NULL) - { - continue; - } - - start_ctx[i]->httpd = evhttp_new (start_ctx[i]->base); - if (start_ctx[i]->httpd == NULL) - { - continue; - } - - err = evhttp_accept_socket (start_ctx[i]->httpd, nfd); - if (err != 0) - { - continue; - } - - evhttp_set_timeout (start_ctx[i]->httpd, DEFAULT_HTTP_TIMEOUT); - /* This is the magic that lets evhttp use SSL. */ - evhttp_set_bevcb (start_ctx[i]->httpd, create_sslconn_cb, ctx); - evhttp_set_cb (start_ctx[i]->httpd, "/cci", - arn_generic_request_handler, (void *) "cci"); - evhttp_set_cb (start_ctx[i]->httpd, "/cm_api", arn_generic_request_handler, (void *) "cm_api"); - evhttp_set_cb (start_ctx[i]->httpd, "/ctrl", arn_ctrl_request_handler, NULL); - evhttp_set_cb (start_ctx[i]->httpd, "/upload", arn_post_request_handler, NULL); - /* Start web server*/ - evhttp_set_gencb (start_ctx[i]->httpd, load_webfiles_cb, (void *) sco.szCWMPath); - } - else if (i == 1) - { - /* index 1 for starting monitor of auto jobs */ - start_ctx[i]->timer = event_new (start_ctx[i]->base, -1, EV_TIMEOUT, start_monitor_auto_jobs_cb, - (void *) start_ctx[i]); - if (start_ctx[i]->timer == NULL) - { - ut_record_arniadb_utility_log_stderr ("ARNIADB Manager Server : Failed to start monitor of auto job.\n"); - return -1; - } - start_ctx[i]->httpd = NULL; - } - else - { - /* index 0 for monitoring status job */ - start_ctx[i]->timer = event_new (start_ctx[i]->base, -1, EV_TIMEOUT, start_monitor_stat_cb, - (void *) start_ctx[i]); - if (start_ctx[i]->timer == NULL) - { - ut_record_arniadb_utility_log_stderr ( - "ARNIADB Manager Server : Failed to start monitoring state job.\n"); - return -1; /* Start monitor status job failed */ - } - start_ctx[i]->httpd = NULL; - } - if (i == 0) - { - struct timeval stat_tv = { 1, 0 }; - evtimer_add (start_ctx[i]->timer, &stat_tv); - } - else if (i == 1) - { - struct timeval auto_task_tv = { sco.iMonitorInterval, 0 }; - evtimer_add (start_ctx[i]->timer, &auto_task_tv); - } - else - { - evtimer_add (start_ctx[i]->timer, &tv); - } -#ifdef WINDOWS - start_ctx[i]->ths = - CreateThread (NULL, 0, dispatch_thread, start_ctx[i], 0, NULL); -#else - pthread_create (& (start_ctx[i]->ths), NULL, dispatch_thread, - (void *) start_ctx[i]); -#endif - } - - for (i = 0; i < DEFAULT_THRD_NUM; i++) - { -#ifdef WINDOWS - if (start_ctx[i]->ths != INVALID_HANDLE_VALUE) - { - WaitForSingleObject (start_ctx[i]->ths, INFINITE); - } -#else - if (start_ctx[i]->ths != 0) - { - pthread_join (start_ctx[i]->ths, NULL); - } -#endif - if (start_ctx[i] != NULL) - { - free (start_ctx[i]); - } - } - - thread_cleanup_SSL (); - -#ifdef WINDOWS - WSACleanup (); -#endif - - return 0; -} - -void -stop_service () -{ - FILE *pidfile = NULL; - int pidnum = -1; - char arn_manager_pid_file[PATH_MAX]; - char connect_list_file[PATH_MAX]; - - arn_manager_pid_file[0] = '\0'; - connect_list_file[0] = '\0'; - - conf_get_dbmt_file (FID_CMSERVER_PID, arn_manager_pid_file); - if (access (arn_manager_pid_file, F_OK) < 0) - { - ut_record_arniadb_utility_log_stderr ("ARNIADB Manager Server : The server is not running.\n"); - } - else - { - pidfile = fopen (arn_manager_pid_file, "rt"); - if (pidfile != NULL) - { - fscanf (pidfile, "%d", &pidnum); - fclose (pidfile); - } - - if ((pidfile == NULL) || ((kill (pidnum, SIGTERM)) < 0)) - { - ut_record_arniadb_utility_log_stderr ("ARNIADB Manager Server : Failed to stop the server.\n"); - } - else - { - unlink (conf_get_dbmt_file (FID_CMSERVER_PID, arn_manager_pid_file)); - unlink (conf_get_dbmt_file (FID_CONN_LIST, connect_list_file)); - } - } - - return; -} - -static int -get_processid () -{ - FILE *pidfile = NULL; - int pidnum = -1; - char pid_file_name[512]; - - conf_get_dbmt_file (FID_CMSERVER_PID, pid_file_name); - - if (access (pid_file_name, F_OK) < 0) - { - return 0; - } - - pidfile = fopen (pid_file_name, "rt"); - if (pidfile != NULL) - { - fscanf (pidfile, "%d", &pidnum); - fclose (pidfile); - } - if (pidfile == NULL || ((kill (pidnum, 0) < 0) && (errno == ESRCH)) - || (is_cmserver_process (pidnum, UTIL_CM_SERVER) == 0)) - { - unlink (pid_file_name); - return 0; - } - - return pidnum; -} - -static void -print_usage (char *pname) -{ - printf ("Usage: %s [command]\n", pname); - printf ("commands are :\n"); - printf (" start - start the server.\n"); - printf (" stop - stop the server.\n"); -} - -static void -init_files () -{ - char strbuf[PATH_MAX]; - strbuf[0] = '\0'; - - /* remove any temporary files from previous run */ - unlink (conf_get_dbmt_file (FID_CONN_LIST, strbuf)); - unlink (conf_get_dbmt_file (FID_PSVR_DBINFO_TEMP, strbuf)); - unlink (conf_get_dbmt_file (FID_CMSERVER_PID, strbuf)); -} - -static THREAD_FUNC -automation_start (void *ud) -{ - ajob ajob_list[AUTOJOB_SIZE]; - int i; - time_t prev_check_time, cur_time; - char strbuf[512]; - - strbuf[0] = '\0'; - - aj_tinfo.is_running = 0; - MUTEX_INIT (aj_thread_mutex); - - /* set up automation list */ - aj_initialize (ajob_list, ud); - for (i = 0; i < AUTOJOB_SIZE; ++i) - { - if (ajob_list[i].ajob_loader) - { - ajob_list[i].ajob_loader (& (ajob_list[i])); - } - } - - prev_check_time = time (NULL); - for (;;) - { - SLEEP_SEC (sco.iMonitorInterval); - cur_time = time (NULL); - - MUTEX_LOCK (aj_thread_mutex); - if (0 != aj_tinfo.is_running) - { - if (cur_time - aj_tinfo.stime > sco.iAutoJobTimeout) - { - THREAD_CANCEL (aj_tinfo.thread_id); - snprintf (strbuf, sizeof (strbuf), "%s - - -", ACCESS_LOG); - write_manager_access_log (strbuf, - "Auto jobs execute too long, Cancel the thread"); - aj_tinfo.is_running = 0; - } - } - if (0 == aj_tinfo.is_running) - { - T_THREAD tid; - aj_thread_info *ptr_aj_tinfo; - aj_tinfo.ajob_list = ajob_list; - aj_tinfo.cur_time = cur_time; - aj_tinfo.prev_check_time = prev_check_time; - ptr_aj_tinfo = &aj_tinfo; - THREAD_BEGIN (tid, aj_thread_r, ptr_aj_tinfo); - aj_tinfo.is_running = 1; - aj_tinfo.thread_id = tid; - aj_tinfo.stime = cur_time; - prev_check_time = cur_time; - } - MUTEX_UNLOCK (aj_thread_mutex); - } - -#if defined(WINDOWS) - return; -#else - return NULL; -#endif -} - -static THREAD_FUNC -aj_thread_r (void *aj) -{ - struct stat statbuf; - aj_thread_info *aj_tinfo_local = (aj_thread_info *) aj; - ajob *ajob_list = aj_tinfo_local->ajob_list; - time_t cur_time = aj_tinfo_local->cur_time; - time_t prev_check_time = aj_tinfo_local->prev_check_time; - int i; - - for (i = 0; i < AUTOJOB_SIZE; ++i) - { - /* check automation configure file and see if it has changed since last access */ - stat (ajob_list[i].config_file, &statbuf); - if (ajob_list[i].last_modi != statbuf.st_mtime) - { - ajob_list[i].last_modi = statbuf.st_mtime; - if (ajob_list[i].ajob_loader) - { - ajob_list[i].ajob_loader (& (ajob_list[i])); - } - } - - /* if unchanged, go ahead and check value */ - if (ajob_list[i].is_on && ajob_list[i].ajob_handler) - { - ajob_list[i].ajob_handler (ajob_list[i].hd, prev_check_time, cur_time); - } - } - - MUTEX_LOCK (aj_thread_mutex); - if (aj_tinfo_local->stime == cur_time) - { - aj_tinfo_local->is_running = 0; - } - MUTEX_UNLOCK (aj_thread_mutex); - -#if defined(WINDOWS) - return; -#else - return NULL; -#endif -} - -static void -start_auto_thread (void) -{ - int i = 0; - userdata *ud = NULL; - - if ((ud = (userdata *) calloc (1, sizeof (userdata))) == NULL) - { - exit (1); - } - /* initialize memory for active databases information */ - for (i = 0; i < MAX_INSTALLED_DB; ++i) - { - ud->dbvect[i] = 0; - } - - THREAD_BEGIN (auto_task_tid, automation_start, ud); -} - -int -main (int argc, char **argv) -{ - char dbmt_file[PATH_MAX]; - char tmpstrbuf[DBMT_ERROR_MSG_SIZE]; - int pidnum = 0; - - tmpstrbuf[0] = '\0'; - - arn_cm_init_env (); - if (argc >= 2) - { - if (strcmp (argv[1], "stop") == 0) - { - stop_service (); - exit (0); - } - else if (strcmp (argv[1], "--version") == 0) - { - fprintf (stdout, "ARNIADB Manager Server ver : %s\n", - makestring (BUILD_NUMBER)); - exit (0); - } - else if (strcmp (argv[1], "getpid") == 0) - { - pidnum = get_processid (); - if (pidnum > 0) - { - fprintf (stdout, "%d\n", pidnum); - } - exit (0); - } - else if (strcmp (argv[1], PRINT_CMD_START) != 0) - { - snprintf (tmpstrbuf, DBMT_ERROR_MSG_SIZE, "ARNIADB Manager Server : Invalid command - %s\n", argv[1]); - ut_record_arniadb_utility_log_stderr (tmpstrbuf); - print_usage (argv[0]); - exit (1); - } - } - - if ((pidnum = get_processid ()) > 0) - { - snprintf (tmpstrbuf, DBMT_ERROR_MSG_SIZE, - "ARNIADB Manager Server : The [pid=%d] process has been running.\n", pidnum); - ut_record_arniadb_utility_log_stderr (tmpstrbuf); - return 0; - } - - ut_daemon_start (); - - init_files (); - -#ifndef WINDOWS - signal (SIGPIPE, SIG_IGN); -#endif - - if (ut_write_pid (conf_get_dbmt_file (FID_CMSERVER_PID, dbmt_file)) < 0) - { - snprintf (tmpstrbuf, DBMT_ERROR_MSG_SIZE, - "ARNIADB Manager Server : Fail to store the pid file in (%s).\n", dbmt_file); - ut_record_arniadb_utility_log_stderr (tmpstrbuf); - exit (1); - } - - start_auto_thread (); - - find_and_parse_arn_admin_version (arniadb_version_major, arniadb_version_minor); - LOG_INFO ("started '%s' with Engine Version: %d.%d", argv[0], arniadb_version_major, arniadb_version_minor); - - start_service (); - - return 0; -} diff --git a/server/src/cm_job_task.cpp b/server/src/cm_job_task.cpp deleted file mode 100644 index 858356f..0000000 --- a/server/src/cm_job_task.cpp +++ /dev/null @@ -1,16143 +0,0 @@ -/* - * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. - * - * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/* - * cm_job_task.cpp - - */ - -#include -#include -#include -#include -#include -#include /* isalpha(), isspace() */ -#include -#include - -#if defined(WINDOWS) -#include -#include -#include -#include -#include -#else -#include /* umask() */ -#include /* umask(), stat() */ -#include -#include /* strfind() */ -#include -#include -#include /* wait() */ -#include /* opendir() ... */ -#include /* getpwuid_r() */ -#include -#include -#include -#include -#if !defined(HPUX) -#include -#endif -#endif - -#include "cm_log.h" -#include "cm_stat.h" -#include "cm_porting.h" -#include "cm_server_util.h" -#include "cm_job_task.h" -#include "cm_auto_task.h" -#include "cm_dep.h" -#include "cm_config.h" -#include "cm_cmd_exec.h" -#include "cm_user.h" -#include "cm_text_encryption.h" -#include "cm_connect_info.h" -#include "cm_server_autoupdate.h" - -#include "openssl/pem.h" -#include "openssl/conf.h" -#include "openssl/x509v3.h" -#include "openssl/md5.h" -#ifndef OPENSSL_NO_ENGINE -#include "openssl/engine.h" -#endif - -#include -#include - -#include - -using namespace std; - -#define PATTERN_LOG 1 -#define PATTERN_VOL 2 - -#define MAX_MSG_LINE 10000 - -#define DBMT_ERR_MSG_SET(ERR_BUF, MSG) \ - strncpy(ERR_BUF, MSG, DBMT_ERROR_MSG_SIZE - 1) -#define ARNIADB_ERR_MSG_SET(ERR_BUF) \ - DBMT_ERR_MSG_SET(ERR_BUF, db_error_string(1)) - -#define MAX_BROKER_NAMELENGTH 128 -#define MAX_AS_COUNT 200 -#define SET_LONGLONG_STR(STR, LL_VALUE) sprintf(STR, "%lld", (long long) LL_VALUE); - -#define QUERY_BUFFER_MAX 4096 - -#if !defined(WINDOWS) -#define STRING_APPEND(buffer_p, avail_size_holder, ...) \ - do { \ - if (avail_size_holder > 0) { \ - int n = snprintf (buffer_p, avail_size_holder, __VA_ARGS__); \ - if (n > 0) { \ - if ((size_t) n < avail_size_holder) { \ - buffer_p += n; avail_size_holder -= n; \ - } else { \ - buffer_p += (avail_size_holder - 1); \ - avail_size_holder = 0; \ - } \ - } \ - } \ - } while (0) -#else /* !WINDOWS */ -#define STRING_APPEND(buffer_p, avail_size_holder, ...) \ - do { \ - if (avail_size_holder > 0) { \ - int n = _snprintf (buffer_p, avail_size_holder, __VA_ARGS__); \ - if (n < 0 || (size_t) n >= avail_size_holder) { \ - buffer_p += (avail_size_holder - 1); \ - avail_size_holder = 0; \ - *buffer_p = '\0'; \ - } else { \ - buffer_p += n; avail_size_holder -= n; \ - } \ - } \ - } while (0) -#endif /* !WINDOWS */ - -extern T_EMGR_VERSION CLIENT_VERSION; -extern T_USER_TOKEN_INFO *user_token_info; - -typedef struct -{ - char dbname[DB_NAME_LEN]; - char server_mode[64]; - char server_msg[1024]; -} T_DB_MODE_INFO; - -typedef struct -{ - char hostname[MAXHOSTNAMELEN]; - char dbname[DB_NAME_LEN]; - char logpath[PATH_MAX]; - char state[64]; - int pid; - char mode[16]; /* mode of copylogdb proc. */ -} T_HA_LOG_PROC_INFO; - -typedef struct -{ - char dbname[DB_NAME_LEN]; - int pid; - char state[64]; -} T_HA_DB_PROC_INFO; - -typedef struct -{ - char dbname[DB_NAME_LEN]; - int num_ap; - int num_cp; - T_DB_MODE_INFO *dbmode_info; - T_HA_DB_PROC_INFO *dbproc_info; - T_HA_LOG_PROC_INFO *applylogdb_info; - T_HA_LOG_PROC_INFO *copylogdb_info; -} T_HA_DBSERVER_INFO; - -typedef struct -{ - char hostname[MAXHOSTNAMELEN]; - char ip[64]; - char state[64]; - int priority; -} T_HA_NODE_INFO; - -typedef struct -{ - int num_dbinfo; - int num_nodeinfo; - T_HA_DBSERVER_INFO *db_info; - T_HA_NODE_INFO *node_info; - char current_node[MAXHOSTNAMELEN]; - char current_node_state[64]; -} T_HA_SERVER_INFO_ALL; - -typedef struct -{ - INT64 delay_time; - INT64 insert_counter; - INT64 update_counter; - INT64 delete_counter; - INT64 commit_counter; - INT64 fail_counter; -} T_STANDBY_SERVER_STAT; - -typedef struct -{ - INT64 num_req; - INT64 num_query; - INT64 num_tran; - INT64 num_long_query; - INT64 num_long_tran; - INT64 num_error_query; - int num_busy_count; - int num_session; -} T_BROKER_DIAGDATA; - -#define MAX_STATDUMP_PROC 16 - typedef struct - { - int pid; - char dbname [DB_NAME_LEN]; - int status; - } T_STATDUMP_STAT; - - static T_STATDUMP_STAT *statdump_daemon = NULL; - - #define STATD_IDLE 0 - #define STATD_RUNNING 1 - - -#if defined(WINDOWS) -static void replace_colon (char *path); -#endif - -static char *to_upper_str (char *str, char *buf); -static char *to_lower_str (char *str, char *buf); -static int uca_conf_write (T_CM_BROKER_CONF *uc_conf, char *del_broekr, - char *_dbmt_error); -static char *get_user_name (int uid, char *name_buf); -static const char *_op_get_port_from_config (T_CM_BROKER_CONF *uc_conf, - char *broker_name); - -static int _tsParseSpacedb (nvplist *req, nvplist *res, char *dbname, - char *_dbmt_error, GeneralSpacedbResult *cmd_res); -static void _ts_gen_spaceinfo (nvplist *res, const char *filename, - const char *dbinstalldir, const char *type, int pagesize); - -static void _tsAppendDBMTUserList (nvplist *res, T_DBMT_USER *dbmt_user, - int return_dbmt_pwd, char *_dbmt_error); -static int _ts_lockdb_parse_us (nvplist *res, FILE *infile); - -static int get_dbitemdir (char *item_dir, size_t item_dir_size, char *dbname, - char *err_buf, int itemtype); -static int get_dblogdir (char *log_dir, size_t log_dir_size, char *dbname, - char *err_buf); -static int get_dbvoldir (char *vol_dir, size_t vol_dir_size, char *dbname, - char *err_buf); -static int op_make_triggerinput_file_add (nvplist *req, char *input_filename); -static int op_make_triggerinput_file_drop (nvplist *req, char *input_filename); -static int op_make_triggerinput_file_alter (nvplist *req, char *input_filename); - -static int get_broker_info_from_filename (char *path, char *br_name, int *as_id); -static char *_ts_get_error_log_param (char *dbname); - -static char *cm_get_abs_file_path (const char *filename, char *buf); -static int check_dbpath (char *dir, char *_dbmt_error); - -static int file_to_nvpairs (char *filepath, nvplist *res); -static int file_to_nvp_by_separator (FILE *fp, nvplist *res, char separator); -static int obsolete_version_autoexecquery_conf (const char *conf_line); -static int alter_dblocation (const char *dbname, const char *new_dbpath); -static void print_db_stat_to_res (T_CM_DB_PROC_STAT *db_stat, nvplist *res); -static int record_ha_topology_to_struct (FILE *infile, int get_all_dbmode, - char *dblist, char *_dbmt_error, T_HA_SERVER_INFO_ALL **all_info_out); -static char *get_mode_from_output_file (char *mode, int buf_len, - FILE *outputfile, char *_dbmt_error); -static void dbinfo_list_free (T_HA_SERVER_INFO_ALL *all_info); -static void print_dbinfo_list_to_res (T_HA_SERVER_INFO_ALL *all_info, - nvplist *res); -static void print_ha_proc_info (T_HA_LOG_PROC_INFO *ha_log_proc, - int elem_num, int is_copylogdb, nvplist *res); -static int dbname_exist_in_dbinfo_list (int nitem, char *dbname, - T_HA_SERVER_INFO_ALL *all_info); -static char *get_ip_from_hostname (char *hostname, char *ipaddr, int ip_len); -static int parse_standby_server_stat (T_STANDBY_SERVER_STAT *stat, - FILE *outfile, char *_dbmt_error); -static int analyze_heartbeat_cmd_outfile (FILE *infile, char *_dbmt_error); -static char *arn_admin_cmd_name (char *cmd_name, int buf_len); -static int cmd_get_db_mode (T_DB_MODE_INFO *dbmode, char *dbname, - char *dbmt_error); -static int fill_dbmode_into_dbinfo_list (T_HA_SERVER_INFO_ALL **all_info, - char *_dbmt_error); -static int parse_ha_proc_msg_to_all_info_array (char *buf, char *_dbmt_error, - T_HA_SERVER_INFO_ALL **all_info, int *nitem, - int *nalloc, int *nproc_alloc, int get_all_dbmode, - char *dblist); -static int parse_ha_node_to_all_info_array (char *buf, T_HA_SERVER_INFO_ALL **all_info, - int *node_alloc, char *_dbmt_error); -static int is_name_in_list (char *dbname, char *dblist); -static int cmd_heartbeat_list (T_HA_SERVER_INFO_ALL **all_info, - int get_all_dbmode, char *dblist, char *_dbmt_error); -static int cmd_heartbeat_act (char *_dbmt_error); -static int cmd_heartbeat_deact (char *_dbmt_error); -static int cmd_changemode (char *dbname, char *modify, char *force, - char *server_mode_out, int mode_len, char *_dbmt_error); -static int run_asql_statement (const char *sql_stat, char *dbname, - char *dbuser, char *dbpasswd, char *outfilepath, char *_dbmt_error); - -static void set_copylogdb_mode (T_HA_LOG_PROC_INFO *copylogdb); - -static int _op_get_session_from_broker (char *broker_list, - T_CM_CAS_INFO_ALL *cas_info_all); -static void _op_print_br_diagdata_to_res (nvplist *res, - T_BROKER_DIAGDATA br_diagdata); -static int _write_conf_to_file (nvplist *req, char *conf_path); -static int _get_folders_with_keyword (char *search_folder_path, - const char *keyword, nvplist *res, char *_dbmt_error); -static int _get_block_from_log (FILE *fp, char *block_buf, int len); -static int -_update_nvplist_name (nvplist *ref, const char *name, const char *value); -static int -_get_confpath_by_name (const char *conf_name, char *conf_path, int buflen); - -static void _write_auto_update_log (char *line_buf, int is_success); -static char *_get_format_time (); -static void read_stdout_stderr_as_err (char *tmp_out_file, char *tmp_err_file, - char *_dbmt_error); -static int _run_child (const char *const argv[], int wait_flag, - char *task_name, char *stdout_file, char *_dbmt_error); -static int _check_backup_info (const char *conf_item[], int check_backupid, - char *_dbmt_error); -static int _verify_user_passwd (char *dbname, char *dbuser, char *dbpasswd, - char *_dbmt_error); -static int _add_extensions (X509 *cert, int nid, char *value); -static void _add_issuer_info (X509_NAME *name, const char *item_name, - char *item_value); -static int _make_cert (nvplist *req, X509 **x509p, EVP_PKEY **pkeyp, - int bits, char *_dbmt_error); -static int _hash_cert (char *hash_value, char *file_path); -static int _is_default_cert (char *_dbmt_error); -static int _is_exist_default_backup_cert (char *_dbmt_error); -static int _backup_cert (char *_dbmt_error); -static int _recover_cert (char *_dbmt_error); - -static int find_statdumpd_info (char *dbname); -static int find_new_statdumpd_info (); - -static int -_verify_user_passwd (char *dbname, char *dbuser, char *dbpasswd, - char *_dbmt_error) -{ - int retval = ERR_NO_ERROR; - - /* every user can access db_user table. */ - const char *sql_stat = "select 1 from db_root"; - - if (dbname == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "dbname"); - return ERR_PARAM_MISSING; - } - - if (dbuser == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "dbuser"); - return ERR_PARAM_MISSING; - } - - /* - * using asql to verify the user's password. - */ - retval = run_asql_statement (sql_stat, dbname, dbuser, dbpasswd, NULL, _dbmt_error); /* asql */ - - return retval; -} - -static int -_run_child (const char *const argv[], int wait_flag, char *task_name, - char *stdout_file, char *_dbmt_error) -{ - char tmp_out_file[PATH_MAX]; - char tmp_err_file[PATH_MAX]; - - int exit_code = 0; - int ret_val = ERR_NO_ERROR; - - tmp_out_file[0] = '\0'; - tmp_err_file[0] = '\0'; - - if (stdout_file == NULL) - { - snprintf (tmp_out_file, PATH_MAX, "%s/%s.%u.out.tmp", - sco.dbmt_tmp_dir, task_name, getpid ()); - } - else - { - snprintf (tmp_out_file, PATH_MAX, stdout_file); - } - snprintf (tmp_err_file, PATH_MAX, "%s/%s.%u.err.tmp", - sco.dbmt_tmp_dir, task_name, getpid ()); - - if (run_child - (argv, wait_flag, NULL, tmp_out_file, tmp_err_file, &exit_code) < 0) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", argv[0]); - ret_val = ERR_SYSTEM_CALL; - goto rm_return; - } - - if (read_error_file (tmp_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) - { - ret_val = ERR_WITH_MSG; - goto rm_return; - } - - if (exit_code != EXIT_SUCCESS) - { - read_stdout_stderr_as_err (tmp_out_file, NULL, _dbmt_error); - ret_val = ERR_WITH_MSG; - goto rm_return; - } - -rm_return: - if (stdout_file == NULL) - { - unlink (tmp_out_file); - } - unlink (tmp_err_file); - return ret_val; -} - -int -ts_add_nvp_time (nvplist *ref, const char *name, time_t t, const char *fmt, - int type) -{ - char strbuf[64]; - if (t == 0) - { - return (nv_add_nvp (ref, name, "")); - } - else - { - time_to_str (t, fmt, strbuf, type); - return (nv_add_nvp (ref, name, strbuf)); - } -} - -/* if arniadb.conf's error_log is null, construct it by default value if existing */ -static char * -_ts_get_error_log_param (char *dbname) -{ - char *tok[2]; - FILE *infile; - char buf[PATH_MAX], dbdir[PATH_MAX]; - - if ((uRetrieveDBDirectory (dbname, dbdir)) != ERR_NO_ERROR) - { - return NULL; - } - -#if !defined (DO_NOT_USE_ARNIADBENV) - snprintf (buf, PATH_MAX - 1, "%s/conf/%s", sco.szArniadb, ARNIADB_ARNIADB_CONF); -#else - snprintf (buf, PATH_MAX - 1, "%s/%s", ARNIADB_CONFDIR, ARNIADB_ARNIADB_CONF); -#endif - - if ((infile = fopen (buf, "r")) == NULL) - { - return NULL; - } - - while (fgets (buf, sizeof (buf), infile)) - { - ut_trim (buf); - if (isalpha ((int) buf[0])) - { - if (string_tokenize2 (buf, tok, 2, '=') < 0) - { - continue; - } - if (uStringEqual (tok[0], "error_log")) - { - fclose (infile); - if (tok[1][0] == '\0') - { - return NULL; - } -#if defined(WINDOWS) - unix_style_path (tok[1]); -#endif - return (strdup (tok[1])); - } - } - } - fclose (infile); - return NULL; -} - -int -ts_get_broker_diagdata (nvplist *cli_request, nvplist *cli_response, - char *_dbmt_error) -{ - int i; - char *broker_list = NULL; - T_CM_BROKER_INFO_ALL uc_info; - T_CM_BROKER_INFO *br_info = NULL; - T_BROKER_DIAGDATA br_diagdata; - T_CM_ERROR error; - int get_all_diagdata = 0; - - memset (&br_diagdata, 0, sizeof (T_BROKER_DIAGDATA)); - - /* get broker info, if broker name is NULL then get all of them, - else get specified broker diagdata. */ - broker_list = nv_get_val (cli_request, "bname"); - - if (broker_list == NULL) - { - get_all_diagdata = 1; - } - - if (cm_get_broker_info (&uc_info, &error) < 0) - { - strcpy (_dbmt_error, error.err_msg); - return ERR_NO_ERROR; - } - - ts_add_nvp_time (cli_response, "time", time (NULL), - "%04d/%02d/%02d %02d:%02d:%02d", TIME_STR_FMT_DATE_TIME); - - for (i = 0; i < uc_info.num_info; i++) - { - br_info = uc_info.br_info + i; - - if (strcmp (br_info->status, "OFF") == 0) - { - continue; - } - - if (get_all_diagdata || is_name_in_list (br_info->name, broker_list)) - { - int session = 0; - T_CM_CAS_INFO_ALL cas_info_all; - - session = _op_get_session_from_broker (br_info->name, &cas_info_all); - - if (session < 0) - { - strcpy_limit (_dbmt_error, "Couldn't get session from broker", DBMT_ERROR_MSG_SIZE); - return ERR_WITH_MSG; - } - - br_diagdata.num_req += br_info->num_req; - br_diagdata.num_query += br_info->num_query; - br_diagdata.num_tran += br_info->num_tran; - br_diagdata.num_long_query += br_info->num_long_query; - br_diagdata.num_long_tran += br_info->num_long_tran; - br_diagdata.num_error_query += br_info->num_error_query; - br_diagdata.num_busy_count += br_info->num_busy_count; - br_diagdata.num_session += session; - - /* if the bname_list is not NULL, then get each broker diagdata. */ - if (get_all_diagdata == 0) - { - nv_add_nvp (cli_response, "open", "broker"); - nv_add_nvp (cli_response, "bname", br_info->name); - _op_print_br_diagdata_to_res (cli_response, br_diagdata); - nv_add_nvp (cli_response, "close", "broker"); - - /* init br_diagdata to get the next broker diagdata. */ - memset (&br_diagdata, 0, sizeof (T_BROKER_DIAGDATA)); - } - - /* free spaces that malloced in cm_cas_info_free */ - cm_cas_info_free (&cas_info_all, NULL); - } - } - - /* free spaces that malloced in cm_broker_info_free */ - cm_broker_info_free (&uc_info); - - /* return the sum of the diagdata to res, when bname token is NULL. */ - if (get_all_diagdata) - { - _op_print_br_diagdata_to_res (cli_response, br_diagdata); - } - - return ERR_NO_ERROR; -} - -static int -_op_get_session_from_broker (char *broker_list, - T_CM_CAS_INFO_ALL *cas_info_all) -{ - int i; - int session_t = 0; - T_CM_CAS_INFO *as_info = NULL; - T_CM_ERROR error; - - if (cm_get_cas_info (broker_list, cas_info_all, NULL, &error) < 0) - { - return -1; - } - - for (i = 0; i < cas_info_all->num_info; i++) - { - as_info = cas_info_all->as_info + i; - if (uStringEqual (as_info->status, "BUSY")) - { - session_t += 1; - } - } - return session_t; -} - -static void -_op_print_br_diagdata_to_res (nvplist *res, T_BROKER_DIAGDATA br_diagdata) -{ -#ifdef JSON_SUPPORT - nv_add_nvp (res, "open", "cas_mon"); -#else - nv_add_nvp (res, "cas_mon", "start"); -#endif - - /* - * "cas_mon_act_session" is left for campatibility, from version 8.3.1 - * the "cas_mon_session" is used instead of "cas_mon_act_session" - */ - nv_add_nvp_int (res, "cas_mon_act_session", br_diagdata.num_busy_count); - - nv_add_nvp_int (res, "cas_mon_session", br_diagdata.num_busy_count); - nv_add_nvp_int (res, "cas_mon_active", br_diagdata.num_session); - nv_add_nvp_int64 (res, "cas_mon_req", br_diagdata.num_req); - nv_add_nvp_int64 (res, "cas_mon_query", br_diagdata.num_query); - nv_add_nvp_int64 (res, "cas_mon_tran", br_diagdata.num_tran); - nv_add_nvp_int64 (res, "cas_mon_long_query", br_diagdata.num_long_query); - nv_add_nvp_int64 (res, "cas_mon_long_tran", br_diagdata.num_long_tran); - nv_add_nvp_int64 (res, "cas_mon_error_query", br_diagdata.num_error_query); - -#ifdef JSON_SUPPORT - nv_add_nvp (res, "close", "cas_mon"); -#else - nv_add_nvp (res, "cas_mon", "end"); -#endif -} - -int -ts_get_diagdata (nvplist *cli_request, nvplist *cli_response, - char *_dbmt_error) -{ - int i; - /*T_CM_DIAG_MONITOR_DB_VALUE server_result; */ - char *db_name, *broker_name; - char *mon_db, *mon_cas; - T_CM_BROKER_INFO_ALL uc_info; - T_CM_BROKER_INFO *br_info; - int num_busy_count = 0; - INT64 num_req, num_query, num_tran, num_long_query, num_long_tran, - num_error_query; - T_CM_ERROR error; - - db_name = nv_get_val (cli_request, "db_name"); - mon_db = nv_get_val (cli_request, "mon_db"); - mon_cas = nv_get_val (cli_request, "mon_cas"); - - /* - if (cm_get_diag_data (&server_result, db_name, mon_db) == 0) - { - #ifdef JSON_SUPPORT - nv_add_nvp (cli_response, "open", "db_mon"); - #else - nv_add_nvp (cli_response, "db_mon", "start"); - #endif - nv_add_nvp_int64 (cli_response, "mon_arn_query_open_page", - server_result.query_open_page); - nv_add_nvp_int64 (cli_response, "mon_arn_query_opened_page", - server_result.query_opened_page); - nv_add_nvp_int64 (cli_response, "mon_arn_query_slow_query", - server_result.query_slow_query); - nv_add_nvp_int64 (cli_response, "mon_arn_query_full_scan", - server_result.query_full_scan); - nv_add_nvp_int64 (cli_response, "mon_arn_lock_deadlock", - server_result.lock_deadlock); - nv_add_nvp_int64 (cli_response, "mon_arn_lock_request", - server_result.lock_request); - nv_add_nvp_int64 (cli_response, "mon_arn_conn_cli_request", - server_result.conn_cli_request); - nv_add_nvp_int64 (cli_response, "mon_arn_conn_aborted_clients", - server_result.conn_aborted_clients); - nv_add_nvp_int64 (cli_response, "mon_arn_conn_conn_req", - server_result.conn_conn_req); - nv_add_nvp_int64 (cli_response, "mon_arn_conn_conn_reject", - server_result.conn_conn_reject); - nv_add_nvp_int64 (cli_response, "mon_arn_buffer_page_write", - server_result.buffer_page_write); - nv_add_nvp_int64 (cli_response, "mon_arn_buffer_page_read", - server_result.buffer_page_read); - #ifdef JSON_SUPPORT - nv_add_nvp (cli_response, "close", "db_mon"); - #else - nv_add_nvp (cli_response, "db_mon", "end"); - #endif - } - */ - - if (mon_cas != NULL && strcmp (mon_cas, "yes") == 0) - { - num_req = num_query = num_tran = num_long_query = num_long_tran = - num_error_query = 0; - - broker_name = nv_get_val (cli_request, "broker_name"); - - if (cm_get_broker_info (&uc_info, &error) < 0) - { - strcpy (_dbmt_error, error.err_msg); - return ERR_NO_ERROR; - } - - for (i = 0; i < uc_info.num_info; i++) - { - br_info = uc_info.br_info + i; - - if (strcmp (br_info->status, "OFF") != 0 && - (broker_name == NULL || strcasecmp (broker_name, br_info->name) == 0)) - { - num_req += br_info->num_req; - num_query += br_info->num_query; - num_tran += br_info->num_tran; - num_long_query += br_info->num_long_query; - num_long_tran += br_info->num_long_tran; - num_error_query += br_info->num_error_query; - num_busy_count += br_info->num_busy_count; - } - } -#ifdef JSON_SUPPORT - nv_add_nvp (cli_response, "open", "cas_mon"); -#else - nv_add_nvp (cli_response, "cas_mon", "start"); -#endif - nv_add_nvp_int (cli_response, "cas_mon_act_session", num_busy_count); - nv_add_nvp_int64 (cli_response, "cas_mon_req", num_req); - nv_add_nvp_int64 (cli_response, "cas_mon_query", num_query); - nv_add_nvp_int64 (cli_response, "cas_mon_tran", num_tran); - nv_add_nvp_int64 (cli_response, "cas_mon_long_query", num_long_query); - nv_add_nvp_int64 (cli_response, "cas_mon_long_tran", num_long_tran); - nv_add_nvp_int64 (cli_response, "cas_mon_error_query", num_error_query); - -#ifdef JSON_SUPPORT - nv_add_nvp (cli_response, "close", "cas_mon"); -#else - nv_add_nvp (cli_response, "cas_mon", "end"); -#endif - } - - return ERR_NO_ERROR; -} - -int -ts_userinfo (nvplist *req, nvplist *res, char *_dbmt_error) -{ - int retval; - - retval = cm_ts_userinfo (req, res, _dbmt_error); - - if (retval != ERR_NO_ERROR) - { - return retval; - } - - _update_nvplist_name (res, "name", ENCRYPT_ARG ("name")); - _update_nvplist_name (res, "id", ENCRYPT_ARG ("id")); - - return ERR_NO_ERROR; -} - -int -ts_create_user (nvplist *req, nvplist *res, char *_dbmt_error) -{ - return cm_ts_create_user (req, res, _dbmt_error); -} - -int -ts_delete_user (nvplist *req, nvplist *res, char *_dbmt_error) -{ - int retval; - char *db_uid = nv_get_val (req, "username"); - - if ((retval = cm_ts_delete_user (req, res, _dbmt_error)) == ERR_NO_ERROR) - { - auto_conf_execquery_delete_by_dbuser (db_uid); - } - - return retval; -} - -int -ts_update_user (nvplist *req, nvplist *res, char *_dbmt_error) -{ - T_DBMT_USER dbmt_user; - const char *new_db_user_name; - const char *new_db_user_pass; - char *db_name; - int i, ret; - - new_db_user_name = nv_get_val (req, "username"); - new_db_user_pass = nv_get_val (req, "userpass"); - db_name = nv_get_val (req, "_DBNAME"); - - if (new_db_user_pass) - { - if (uStringEqual (new_db_user_pass, "__NULL__") - || uStringEqual (new_db_user_pass, "")) - { - sprintf (_dbmt_error, "%s", "user password is empty!"); - return ERR_WITH_MSG; - } - } - - ret = cm_ts_update_user (req, res, _dbmt_error); - if (ret != ERR_NO_ERROR) - { - return ret; - } - -#ifndef PK_AUTHENTICAITON - if (new_db_user_pass) - { - char hexacoded[PASSWD_ENC_LENGTH]; - /* update cmdb.pass dbinfo */ - if (dbmt_user_read (&dbmt_user, _dbmt_error) == ERR_NO_ERROR) - { - int src_dbinfo; - - for (i = 0; i < dbmt_user.num_dbmt_user; i++) - { - src_dbinfo = - dbmt_user_search (& (dbmt_user.user_info[i]), db_name); - if (src_dbinfo < 0) - { - continue; - } - if (strcmp - (dbmt_user.user_info[i].dbinfo[src_dbinfo].uid, new_db_user_name) != 0) - { - continue; - } - } - dbmt_user_write_auth (&dbmt_user, _dbmt_error); - dbmt_user_free (&dbmt_user); - } - - /* update db_user's passwd in autoexecquery.conf */ - uEncrypt (PASSWD_LENGTH, new_db_user_pass, hexacoded); - auto_conf_execquery_update_dbuser (new_db_user_name, new_db_user_name, hexacoded); - } -#endif - return ERR_NO_ERROR; -} - - -int -ts_class_info (nvplist *req, nvplist *res, char *_dbmt_error) -{ - return cm_ts_class_info (req, res, _dbmt_error); -} - -int -ts_class (nvplist *req, nvplist *res, char *_dbmt_error) -{ - return cm_ts_class (req, res, _dbmt_error); -} - -#if defined(WINDOWS) -static void -replace_colon (char *path) -{ - char *p; - for (p = path; *p; p++) - { - if (*p == '|') - { - *p = ':'; - } - } -} -#endif - -int -ts_update_attribute (nvplist *req, nvplist *res, char *_dbmt_error) -{ - return cm_ts_update_attribute (req, res, _dbmt_error); -} - -int -ts2_get_unicas_info (nvplist *in, nvplist *out, char *_dbmt_error) -{ - T_CM_BROKER_INFO_ALL uc_info; - int i; - T_CM_BROKER_CONF uc_conf; - T_CM_ERROR error; - char *broker_name; - - broker_name = nv_get_val (in, "bname"); - memset (&uc_info, 0, sizeof (T_CM_BROKER_INFO_ALL)); - if (cm_get_broker_conf (&uc_conf, NULL, &error) < 0) - { - strcpy (_dbmt_error, error.err_msg); - return ERR_WITH_MSG; - } - if (cm_get_broker_info (&uc_info, &error) < 0) - { - char *p; - int tmp_val; - - strcpy (_dbmt_error, error.err_msg); - nv_add_nvp (out, "open", "brokersinfo"); - for (i = 0; i < uc_conf.num_broker; i++) - { - /* - *add broker info to response according to the requested - * dbname.if dbname is null, then print all the brokers. - */ - if ((broker_name != NULL) && - (uc_info.br_info != NULL) && - (strcmp (uc_info.br_info[i].name, broker_name) != 0)) - { - continue; - } - nv_add_nvp (out, "open", "broker"); - nv_add_nvp (out, "name", - cm_br_conf_get_value (& (uc_conf.br_conf[i]), "%")); - nv_add_nvp (out, "port", - cm_br_conf_get_value (& (uc_conf.br_conf[i]), "BROKER_PORT")); - nv_add_nvp (out, "appl_server_shm_id", - cm_br_conf_get_value (& (uc_conf.br_conf[i]), "APPL_SERVER_SHM_ID")); - p = cm_br_conf_get_value (& (uc_conf.br_conf[i]), "SOURCE_ENV"); - tmp_val = 1; - if (p == NULL || *p == '\0') - { - tmp_val = 0; - } - nv_add_nvp_int (out, "source_env", tmp_val); - p = cm_br_conf_get_value (& (uc_conf.br_conf[i]), "ACCESS_LIST"); - tmp_val = 1; - if (p == NULL || *p == '\0') - { - tmp_val = 0; - } - nv_add_nvp_int (out, "access_list", tmp_val); - nv_add_nvp (out, "close", "broker"); - } - nv_add_nvp (out, "close", "brokersinfo"); - nv_add_nvp (out, "brokerstatus", "OFF"); - } - else - { - char *shmid; - nv_add_nvp (out, "open", "brokersinfo"); - for (i = 0; i < uc_info.num_info; i++) - { - /* - *add broker info to response according to the requested - * dbname.if dbname is null, then print all the brokers. - */ - if ((broker_name != NULL) && - (uc_info.br_info != NULL) && - (strcmp (uc_info.br_info[i].name, broker_name) != 0)) - { - continue; - } - nv_add_nvp (out, "open", "broker"); - nv_add_nvp (out, "name", uc_info.br_info[i].name); - nv_add_nvp (out, "type", uc_info.br_info[i].as_type); - if (strcmp (uc_info.br_info[i].status, "OFF") != 0) - { - nv_add_nvp_int (out, "pid", uc_info.br_info[i].pid); - nv_add_nvp_int (out, "port", uc_info.br_info[i].port); - nv_add_nvp_int (out, "as", uc_info.br_info[i].num_as); - nv_add_nvp_int (out, "jq", uc_info.br_info[i].num_job_q); -#ifdef GET_PSINFO - nv_add_nvp_int (out, "thr", uc_info.br_info[i].num_thr); - nv_add_nvp_float (out, "cpu", uc_info.br_info[i].pcpu, "%.2f"); - nv_add_nvp_int (out, "time", uc_info.br_info[i].cpu_time); -#endif - nv_add_nvp_int (out, "req", uc_info.br_info[i].num_req); - nv_add_nvp_int64 (out, "tran", uc_info.br_info[i].num_tran); - nv_add_nvp_int64 (out, "query", uc_info.br_info[i].num_query); - nv_add_nvp_int64 (out, "long_tran", uc_info.br_info[i].num_long_tran); - nv_add_nvp_int64 (out, "long_query", uc_info.br_info[i].num_long_query); - nv_add_nvp_int64 (out, "error_query", uc_info.br_info[i].num_error_query); - nv_add_nvp_float (out, "long_tran_time", - uc_info.br_info[i].long_transaction_time / 1000.0f, "%.2f"); - nv_add_nvp_float (out, "long_query_time", - uc_info.br_info[i].long_query_time / 1000.0f, "%.2f"); - - nv_add_nvp (out, "keep_conn", uc_info.br_info[i].keep_connection); - - nv_add_nvp (out, "auto", uc_info.br_info[i].auto_add); - nv_add_nvp (out, "ses", uc_info.br_info[i].session_timeout); - nv_add_nvp (out, "sqll", uc_info.br_info[i].sql_log_mode); - nv_add_nvp (out, "log", uc_info.br_info[i].log_dir); - nv_add_nvp (out, "access_mode", uc_info.br_info[i].access_mode); - } - else - { - nv_add_nvp (out, "port", _op_get_port_from_config (&uc_conf, uc_info.br_info[i].name)); - } - nv_add_nvp (out, "state", uc_info.br_info[i].status); - nv_add_nvp_int (out, "source_env", - uc_info.br_info[i].source_env_flag); - nv_add_nvp_int (out, "access_list", - uc_info.br_info[i].access_list_flag); - shmid = - cm_br_conf_get_value (cm_conf_find_broker (&uc_conf, uc_info.br_info[i].name), - "APPL_SERVER_SHM_ID"); - nv_add_nvp (out, "appl_server_shm_id", shmid); - nv_add_nvp (out, "close", "broker"); - } - nv_add_nvp (out, "close", "brokersinfo"); - nv_add_nvp (out, "brokerstatus", "ON"); - cm_broker_info_free (&uc_info); - } - - cm_broker_conf_free (&uc_conf); - return ERR_NO_ERROR; -} - - -int -ts2_start_unicas (nvplist *in, nvplist *out, char *_dbmt_error) -{ - T_CM_ERROR error; - if (cm_broker_env_start (&error) < 0) - { - strcpy (_dbmt_error, error.err_msg); - return ERR_WITH_MSG; - } - - return ERR_NO_ERROR; -} - -int -ts2_stop_unicas (nvplist *in, nvplist *out, char *_dbmt_error) -{ - T_CM_ERROR error; - if (cm_broker_env_stop (&error) < 0) - { - strcpy (_dbmt_error, error.err_msg); - return ERR_WITH_MSG; - } - - return ERR_NO_ERROR; -} - -int -ts2_get_admin_log_info (nvplist *in, nvplist *out, char *_dbmt_error) -{ - char buf[PATH_MAX]; - struct stat statbuf; - - cm_get_broker_file (UC_FID_ADMIN_LOG, buf); - - if (stat (buf, &statbuf) != 0) - { - return ERR_STAT; - } - nv_add_nvp (out, "open", "adminloginfo"); - nv_add_nvp (out, "path", buf); - nv_add_nvp (out, "owner", get_user_name (statbuf.st_uid, buf)); - nv_add_nvp_int (out, "size", statbuf.st_size); - ts_add_nvp_time (out, "lastupdate", statbuf.st_mtime, "%04d.%02d.%02d", NV_ADD_DATE); - nv_add_nvp (out, "close", "adminloginfo"); - - return ERR_NO_ERROR; -} - -int -ts2_get_logfile_info (nvplist *in, nvplist *out, char *_dbmt_error) -{ -#if defined(WINDOWS) - HANDLE handle; - WIN32_FIND_DATA data; - char find_file[PATH_MAX]; - int found; -#else - DIR *dp; - struct dirent *dirp; -#endif - struct stat statbuf; - T_CM_BROKER_CONF uc_conf; - char logdir[PATH_MAX], err_logdir[PATH_MAX], access_logdir[PATH_MAX]; - const char *v; - char *bname, *from, buf[1024], scriptdir[PATH_MAX]; - char *cur_file; - T_CM_ERROR error; - - bname = nv_get_val (in, "broker"); - from = nv_get_val (in, "from"); - nv_add_nvp (out, "broker", bname); - nv_add_nvp (out, "from", from); - nv_add_nvp (out, "open", "logfileinfo"); - - if (bname == NULL) - { - strcpy (_dbmt_error, "broker"); - return ERR_PARAM_MISSING; - } - chdir (sco.szArniadb); - if (cm_get_broker_conf (&uc_conf, NULL, &error) < 0) - { - strcpy (_dbmt_error, error.err_msg); - return ERR_WITH_MSG; - } - v = cm_br_conf_get_value (cm_conf_find_broker (&uc_conf, bname), "ERROR_LOG_DIR"); - if (v == NULL) - { - v = BROKER_LOG_DIR "/error_log"; - } - cm_get_abs_file_path (v, err_logdir); - - v = cm_br_conf_get_value (cm_conf_find_broker (&uc_conf, bname), "LOG_DIR"); - if (v == NULL) - { - v = BROKER_LOG_DIR "/sql_log"; - } - cm_get_abs_file_path (v, logdir); - - cm_get_abs_file_path (BROKER_LOG_DIR, access_logdir); - - cm_broker_conf_free (&uc_conf); - -#if defined(WINDOWS) - snprintf (find_file, PATH_MAX - 1, "%s/*", access_logdir); - handle = FindFirstFile (find_file, &data); - if (handle != INVALID_HANDLE_VALUE) -#else - dp = opendir (access_logdir); - if (dp != NULL) -#endif - { -#if defined(WINDOWS) - for (found = 1; found; found = FindNextFile (handle, &data)) -#else - while ((dirp = readdir (dp)) != NULL) -#endif - { -#if defined(WINDOWS) - cur_file = data.cFileName; -#else - cur_file = dirp->d_name; -#endif - if (strstr (cur_file, bname) != NULL) - { - nv_add_nvp (out, "open", "logfile"); - if (strstr (cur_file, "access") != NULL) - { - nv_add_nvp (out, "type", "access"); - } - snprintf (buf, sizeof (buf) - 1, "%s/%s", access_logdir, cur_file); - nv_add_nvp (out, "path", buf); - stat (buf, &statbuf); - nv_add_nvp (out, "owner", get_user_name (statbuf.st_uid, buf)); - nv_add_nvp_int (out, "size", statbuf.st_size); - ts_add_nvp_time (out, "lastupdate", statbuf.st_mtime, "%04d.%02d.%02d", NV_ADD_DATE); - nv_add_nvp (out, "close", "logfile"); - } - } -#if defined(WINDOWS) - FindClose (handle); -#else - closedir (dp); -#endif - } -#if defined(WINDOWS) - snprintf (find_file, PATH_MAX - 1, "%s/*", err_logdir); - handle = FindFirstFile (find_file, &data); - if (handle != INVALID_HANDLE_VALUE) -#else - dp = opendir (err_logdir); - if (dp != NULL) -#endif - { -#if defined(WINDOWS) - for (found = 1; found; found = FindNextFile (handle, &data)) -#else - while ((dirp = readdir (dp)) != NULL) -#endif - { -#if defined(WINDOWS) - cur_file = data.cFileName; -#else - cur_file = dirp->d_name; -#endif - if (strstr (cur_file, bname) != NULL) - { - nv_add_nvp (out, "open", "logfile"); - if (strstr (cur_file, "access") != NULL) - { - nv_add_nvp (out, "type", "access"); - } - else if (strstr (cur_file, "err") != NULL) - { - nv_add_nvp (out, "type", "error"); - } - snprintf (buf, sizeof (buf) - 1, "%s/%s", err_logdir, cur_file); - nv_add_nvp (out, "path", buf); - stat (buf, &statbuf); - nv_add_nvp (out, "owner", get_user_name (statbuf.st_uid, buf)); - nv_add_nvp_int (out, "size", statbuf.st_size); - ts_add_nvp_time (out, "lastupdate", statbuf.st_mtime, "%04d.%02d.%02d", NV_ADD_DATE); - nv_add_nvp (out, "close", "logfile"); - } - } -#if defined(WINDOWS) - FindClose (handle); -#else - closedir (dp); -#endif - } -#if defined(WINDOWS) - snprintf (find_file, PATH_MAX - 1, "%s/*", logdir); - handle = FindFirstFile (find_file, &data); - if (handle != INVALID_HANDLE_VALUE) -#else - dp = opendir (logdir); - if (dp != NULL) -#endif - { -#if defined(WINDOWS) - for (found = 1; found; found = FindNextFile (handle, &data)) -#else - while ((dirp = readdir (dp)) != NULL) -#endif - { -#if defined(WINDOWS) - cur_file = data.cFileName; -#else - cur_file = dirp->d_name; -#endif - if (strstr (cur_file, bname) != NULL) - { - nv_add_nvp (out, "open", "logfile"); - if (strstr (cur_file, "access") != NULL) - { - nv_add_nvp (out, "type", "access"); - } - snprintf (buf, sizeof (buf) - 1, "%s/%s", logdir, cur_file); - nv_add_nvp (out, "path", buf); - stat (buf, &statbuf); - nv_add_nvp (out, "owner", get_user_name (statbuf.st_uid, buf)); - nv_add_nvp_int (out, "size", statbuf.st_size); - ts_add_nvp_time (out, "lastupdate", statbuf.st_mtime, "%04d.%02d.%02d", NV_ADD_DATE); - nv_add_nvp (out, "close", "logfile"); - } - } -#if defined(WINDOWS) - FindClose (handle); -#else - closedir (dp); -#endif - } - snprintf (scriptdir, PATH_MAX - 1, "%s", logdir); -#if defined(WINDOWS) - snprintf (find_file, PATH_MAX - 1, "%s/*", scriptdir); - handle = FindFirstFile (find_file, &data); - if (handle != INVALID_HANDLE_VALUE) -#else - dp = opendir (scriptdir); - if (dp != NULL) -#endif - { - - sprintf (bname, "%s_", bname); -#if defined(WINDOWS) - for (found = 1; found; found = FindNextFile (handle, &data)) -#else - while ((dirp = readdir (dp)) != NULL) -#endif - { -#if defined(WINDOWS) - cur_file = data.cFileName; -#else - cur_file = dirp->d_name; -#endif - - if (strstr (cur_file, bname) != NULL) - { - nv_add_nvp (out, "open", "logfile"); - nv_add_nvp (out, "type", "script"); - snprintf (buf, sizeof (buf) - 1, "%s/%s", scriptdir, cur_file); - nv_add_nvp (out, "path", buf); - stat (buf, &statbuf); - nv_add_nvp (out, "owner", get_user_name (statbuf.st_uid, buf)); - nv_add_nvp_int (out, "size", statbuf.st_size); - ts_add_nvp_time (out, "lastupdate", statbuf.st_mtime, "%04d.%02d.%02d", NV_ADD_DATE); - nv_add_nvp (out, "close", "logfile"); - } - } -#if defined(WINDOWS) - FindClose (handle); -#else - closedir (dp); -#endif - } - nv_add_nvp (out, "close", "logfileinfo"); - - return ERR_NO_ERROR; -} - -int -ts2_get_add_broker_info (nvplist *in, nvplist *out, char *_dbmt_error) -{ - FILE *infile; - char broker_conf_path[PATH_MAX], strbuf[1024]; - - cm_get_broker_file (UC_FID_ARNIADB_BROKER_CONF, broker_conf_path); - - if (access (broker_conf_path, F_OK) < 0) - { - return ERR_FILE_OPEN_FAIL; - } - - infile = fopen (broker_conf_path, "r"); - if (infile == NULL) - { - strcpy (_dbmt_error, broker_conf_path); - return ERR_FILE_OPEN_FAIL; - } - - nv_add_nvp (out, "confname", "broker"); - nv_add_nvp (out, "open", "conflist"); - - while (fgets (strbuf, sizeof (strbuf), infile) != NULL) - { - uRemoveCRLF (strbuf); - nv_add_nvp (out, "confdata", strbuf); - } - nv_add_nvp (out, "close", "conflist"); - fclose (infile); - - return ERR_NO_ERROR; -} - -int -ts2_delete_broker (nvplist *in, nvplist *out, char *_dbmt_error) -{ - char *bname; - int retval = ERR_NO_ERROR; - T_CM_BROKER_CONF uc_conf; - T_CM_ERROR error; - - if ((bname = nv_get_val (in, "bname")) == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "bname"); - return ERR_PARAM_MISSING; - } - - if (cm_get_broker_conf (&uc_conf, NULL, &error) < 0) - { - strcpy (_dbmt_error, error.err_msg); - return ERR_WITH_MSG; - } - - retval = uca_conf_write (&uc_conf, bname, _dbmt_error); - - cm_broker_conf_free (&uc_conf); - - return retval; -} - - -int -ts2_get_broker_status (nvplist *in, nvplist *out, char *_dbmt_error) -{ - T_CM_CAS_INFO_ALL as_info_set; - T_CM_JOB_INFO_ALL job_info_set; - T_CM_ERROR error; - char *bname, buf[1024]; - char *blist; - int more_than_one_broker = 0; - int i; - - if ((blist = nv_get_val (in, "bname")) == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "bname"); - return ERR_PARAM_MISSING; - } - - /* if there is more than one brokers, there should be more than one ',' separator. */ - if (strstr (blist, ",") != NULL) - { - more_than_one_broker = 1; - } - - while (blist != NULL) - { - bname = blist; - - if ((blist = strchr (blist, ',')) != NULL) - { - blist[0] = '\0'; - blist++; - } - - ut_trim (bname); - - if (more_than_one_broker != 0) - { - nv_add_nvp (out, "open", "broker"); - } - - nv_add_nvp (out, "bname", bname); - ts_add_nvp_time (out, "time", time (NULL), - "%04d/%02d/%02d %02d:%02d:%02d", TIME_STR_FMT_DATE_TIME); - if (cm_get_cas_info (bname, &as_info_set, &job_info_set, &error) >= 0) - { - for (i = 0; i < as_info_set.num_info; i++) - { - if (strcmp (as_info_set.as_info[i].service_flag, "ON") != 0) - { - continue; - } - - nv_add_nvp (out, "open", "asinfo"); - - nv_add_nvp_int (out, "as_id", as_info_set.as_info[i].id); - nv_add_nvp_int (out, "as_pid", as_info_set.as_info[i].pid); - nv_add_nvp_int (out, "as_c", - as_info_set.as_info[i].num_request); - /* add "as_port" nvp in windows: - as_port only shows up on windows platform. */ -#if defined(WINDOWS) - nv_add_nvp_int (out, "as_port", as_info_set.as_info[i].as_port); -#endif - nv_add_nvp_int (out, "as_psize", as_info_set.as_info[i].psize); - nv_add_nvp (out, "as_status", as_info_set.as_info[i].status); - nv_add_nvp_float (out, "as_cpu", as_info_set.as_info[i].pcpu, "%.2f"); - cm_cpu_time_str (as_info_set.as_info[i].cpu_time, buf); - nv_add_nvp (out, "as_ctime", buf); - ts_add_nvp_time (out, "as_lat", - as_info_set.as_info[i].last_access_time, - "%02d/%02d/%02d %02d:%02d:%02d", NV_ADD_DATE_TIME); - nv_add_nvp (out, "as_cur", as_info_set.as_info[i].log_msg); - nv_add_nvp_int64 (out, "as_num_query", as_info_set.as_info[i].num_queries_processed); - nv_add_nvp_int64 (out, "as_num_tran", as_info_set.as_info[i].num_transactions_processed); - nv_add_nvp_int64 (out, "as_long_query", as_info_set.as_info[i].num_long_queries); - nv_add_nvp_int64 (out, "as_long_tran", as_info_set.as_info[i].num_long_transactions); - nv_add_nvp_int64 (out, "as_error_query", as_info_set.as_info[i].num_error_queries); - nv_add_nvp (out, "as_dbname", as_info_set.as_info[i].database_name); - nv_add_nvp (out, "as_dbhost", as_info_set.as_info[i].database_host); - ts_add_nvp_time (out, "as_lct", as_info_set.as_info[i].last_connect_time, - "%02d/%02d/%02d %02d:%02d:%02d", NV_ADD_DATE_TIME); - /* add "as_client_ip" nvp. */ - nv_add_nvp (out, "as_client_ip", as_info_set.as_info[i].clt_ip_addr); - nv_add_nvp (out, "close", "asinfo"); - } - for (i = 0; i < job_info_set.num_info; i++) - { - nv_add_nvp (out, "open", "jobinfo"); - nv_add_nvp_int (out, "job_id", job_info_set.job_info[i].id); - nv_add_nvp_int (out, "job_priority", - job_info_set.job_info[i].priority); - nv_add_nvp (out, "job_ip", job_info_set.job_info[i].ipstr); - ts_add_nvp_time (out, "job_time", - job_info_set.job_info[i].recv_time, "%02d:%02d:%02d", NV_ADD_TIME); - snprintf (buf, sizeof (buf) - 1, "%s:%s", - job_info_set.job_info[i].script, job_info_set.job_info[i].prgname); - nv_add_nvp (out, "job_request", buf); - nv_add_nvp (out, "close", "jobinfo"); - } - cm_cas_info_free (&as_info_set, &job_info_set); - } - if (more_than_one_broker != 0) - { - nv_add_nvp (out, "close", "broker"); - } - } - - return ERR_NO_ERROR; -} - - - -int -ts2_set_broker_conf (nvplist *in, nvplist *out, char *_dbmt_error) -{ - FILE *outfile; - char broker_conf_path[PATH_MAX]; - char *conf, *confdata; - int nv_len, i; - - cm_get_broker_file (UC_FID_ARNIADB_BROKER_CONF, broker_conf_path); - - if ((outfile = fopen (broker_conf_path, "w")) == NULL) - { - return ERR_TMPFILE_OPEN_FAIL; - } - - nv_len = in->nvplist_leng; - for (i = 1; i < nv_len; i++) - { - nv_lookup (in, i, &conf, &confdata); - if ((conf != NULL) && (strcmp (conf, "confdata") == 0)) - { - if (confdata == NULL) - { - fprintf (outfile, "\n"); - } - else - { - fprintf (outfile, "%s\n", confdata); - } - } - } - - fclose (outfile); - - return ERR_NO_ERROR; -} - - -int -ts2_start_broker (nvplist *in, nvplist *out, char *_dbmt_error) -{ - char *bname; - T_CM_ERROR error; - - if ((bname = nv_get_val (in, "bname")) == NULL) - { - strcpy (_dbmt_error, "broker name"); - return ERR_PARAM_MISSING; - } - - if (cm_broker_on (bname, &error) < 0) - { - strcpy (_dbmt_error, error.err_msg); - return ERR_WITH_MSG; - } - return ERR_NO_ERROR; -} - -int -ts2_stop_broker (nvplist *in, nvplist *out, char *_dbmt_error) -{ - char *bname; - T_CM_ERROR error; - - if ((bname = nv_get_val (in, "bname")) == NULL) - { - strcpy (_dbmt_error, "broker name"); - return ERR_PARAM_MISSING; - } - - if (cm_broker_off (bname, &error) < 0) - { - strcpy (_dbmt_error, error.err_msg); - return ERR_WITH_MSG; - } - return ERR_NO_ERROR; -} - -int -ts2_restart_broker_as (nvplist *in, nvplist *out, char *_dbmt_error) -{ - char *bname, *asnum; - T_CM_ERROR error; - T_CM_BROKER_INFO_ALL uc_info; - - int num_as = 0; - - bname = nv_get_val (in, "bname"); - asnum = nv_get_val (in, "asnum"); - - if (bname == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "bname"); - return ERR_PARAM_MISSING; - } - - if (asnum == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "asnum"); - return ERR_PARAM_MISSING; - } - - if (cm_get_broker_info (&uc_info, &error) < 0) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", error.err_msg); - return ERR_WITH_MSG; - } - - num_as = atoi (asnum); - if ((num_as <= 0) || (num_as > uc_info.br_info->num_as)) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, - "Broker query id(%d) is not exist.", num_as); - return ERR_WITH_MSG; - } - - if (cm_broker_as_restart (bname, num_as, &error) < 0) - { - strcpy (_dbmt_error, error.err_msg); - return ERR_WITH_MSG; - } - return ERR_NO_ERROR; -} - -int -ts_set_sysparam (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char conf_path[PATH_MAX]; - char *conf_name; - - conf_name = nv_get_val (req, "confname"); - if (conf_name == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "confname"); - return ERR_PARAM_MISSING; - } - - if (_get_confpath_by_name (conf_name, conf_path, sizeof (conf_path)) < 0) - { - strcpy (_dbmt_error, "confname error"); - return ERR_WITH_MSG; - } - - if (_write_conf_to_file (req, conf_path) < 0) - { - return ERR_TMPFILE_OPEN_FAIL; - } - - return ERR_NO_ERROR; -} - -int -ts_get_all_sysparam (nvplist *req, nvplist *res, char *_dbmt_error) -{ - FILE *infile; - char conf_path[PATH_MAX], strbuf[1024 * 200]; - char *conf_name; - - conf_name = nv_get_val (req, "confname"); - if (conf_name == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "confname"); - return ERR_PARAM_MISSING; - } - - if (_get_confpath_by_name (conf_name, conf_path, sizeof (conf_path)) < 0) - { - strcpy (_dbmt_error, "confname error"); - return ERR_WITH_MSG; - } - - if (access (conf_path, F_OK) < 0) - { - return ERR_FILE_OPEN_FAIL; - } - - infile = fopen (conf_path, "r"); - if (infile == NULL) - { - strcpy (_dbmt_error, conf_path); - return ERR_FILE_OPEN_FAIL; - } - - nv_add_nvp (res, "confname", conf_name); - nv_add_nvp (res, "open", "conflist"); - - while (fgets (strbuf, sizeof (strbuf), infile) != NULL) - { - uRemoveCRLF (strbuf); - nv_add_nvp (res, "confdata", strbuf); - } - nv_add_nvp (res, "close", "conflist"); - fclose (infile); - - return ERR_NO_ERROR; -} - -static int -_get_confpath_by_name (const char *conf_name, char *conf_path, int buflen) -{ - int retval = 0; - - if (uStringEqual (conf_name, "arniadbconf")) - { - snprintf (conf_path, buflen - 1, "%s/conf/%s", sco.szArniadb, - ARNIADB_ARNIADB_CONF); - } - else if (uStringEqual (conf_name, "cmconf")) - { - snprintf (conf_path, buflen - 1, "%s/conf/%s", sco.szArniadb, - ARNIADB_DBMT_CONF); - } - else if (uStringEqual (conf_name, "haconf")) - { - snprintf (conf_path, buflen - 1, "%s/conf/%s", sco.szArniadb, - ARNIADB_HA_CONF); - } - else if (uStringEqual (conf_name, "databases")) - { - snprintf (conf_path, buflen - 1, "%s/%s", sco.szArniadb_databases, - ARNIADB_DATABASE_TXT); - } - else - { - snprintf (conf_path, buflen - 1, "%s/conf/%s", sco.szArniadb, conf_name); - } - - return retval; -} - -static int -_write_conf_to_file (nvplist *req, char *conf_path) -{ - char *conf, *conf_data; - int nv_len, i; - FILE *outfile = NULL; - - if ((outfile = fopen (conf_path, "w")) == NULL) - { - return -1; - } - - nv_len = req->nvplist_leng; - for (i = 1; i < nv_len; i++) - { - nv_lookup (req, i, &conf, &conf_data); - if ((conf != NULL) && (strcmp (conf, "confdata") == 0)) - { - if (conf_data == NULL) - { - fprintf (outfile, "\n"); - } - else - { - fprintf (outfile, "%s\n", conf_data); - } - } - } - - fclose (outfile); - - return 0; -} - -int -tsCreateDBMTUser (nvplist *req, nvplist *res, char *_dbmt_error) -{ - int num_authinfo = 0, num_dbmt_user; - char *dbmt_id, *passwd_p; - int i, retval; - char dbmt_passwd[PASSWD_ENC_LENGTH]; - T_DBMT_USER dbmt_user; - T_DBMT_USER_AUTHINFO *authinfo = NULL; - - const char *casauth, *dbcreate, *status_monitor; - - memset (&dbmt_user, 0, sizeof (T_DBMT_USER)); - - if ((dbmt_id = nv_get_val (req, "targetid")) == NULL) - { - sprintf (_dbmt_error, "%s", "target id"); - return ERR_PARAM_MISSING; - } - if ((passwd_p = nv_get_val (req, "password")) == NULL) - { - sprintf (_dbmt_error, "%s", "password"); - return ERR_PARAM_MISSING; - } - - if (0 != IsValidUserName (dbmt_id)) - { - sprintf (_dbmt_error, - "Invalid user name!User name should begin with a letter,and can only contain letters, digits, or underscore."); - return ERR_WITH_MSG; - } - - if (strlen (passwd_p) > PASSWD_LENGTH) - { - sprintf (_dbmt_error, "invalid password!"); - return ERR_WITH_MSG; - } - - uEncrypt (PASSWD_LENGTH, passwd_p, dbmt_passwd); - - if ((retval = dbmt_user_read (&dbmt_user, _dbmt_error)) != ERR_NO_ERROR) - { - return retval; - } - num_dbmt_user = dbmt_user.num_dbmt_user; - for (i = 0; i < num_dbmt_user; i++) - { - if (strcmp (dbmt_user.user_info[i].user_name, dbmt_id) == 0) - { - dbmt_user_free (&dbmt_user); - sprintf (_dbmt_error, "%s", dbmt_id); - return ERR_DBMTUSER_EXIST; - } - } - - /* set authority info */ - if ((casauth = nv_get_val (req, "casauth")) == NULL) - { - casauth = ""; - } - authinfo = - (T_DBMT_USER_AUTHINFO *) increase_capacity (authinfo, - sizeof (T_DBMT_USER_AUTHINFO), - num_authinfo, num_authinfo + 1); - if (authinfo == NULL) - { - dbmt_user_free (&dbmt_user); - return ERR_MEM_ALLOC; - } - num_authinfo++; - dbmt_user_set_authinfo (& (authinfo[num_authinfo - 1]), "unicas", casauth); - - if ((dbcreate = nv_get_val (req, "dbcreate")) == NULL) - { - dbcreate = ""; - } - authinfo = - (T_DBMT_USER_AUTHINFO *) increase_capacity (authinfo, - sizeof (T_DBMT_USER_AUTHINFO), - num_authinfo, num_authinfo + 1); - if (authinfo == NULL) - { - dbmt_user_free (&dbmt_user); - return ERR_MEM_ALLOC; - } - num_authinfo++; - dbmt_user_set_authinfo (& (authinfo[num_authinfo - 1]), "dbcreate", dbcreate); - - if ((status_monitor = nv_get_val (req, "statusmonitorauth")) == NULL) - { - status_monitor = ""; - } - authinfo = - (T_DBMT_USER_AUTHINFO *) increase_capacity (authinfo, - sizeof (T_DBMT_USER_AUTHINFO), - num_authinfo, num_authinfo + 1); - if (authinfo == NULL) - { - dbmt_user_free (&dbmt_user); - return ERR_MEM_ALLOC; - } - num_authinfo++; - dbmt_user_set_authinfo (& (authinfo[num_authinfo - 1]), "statusmonitorauth", status_monitor); - - /* set user info */ - dbmt_user.user_info = - (T_DBMT_USER_INFO *) increase_capacity (dbmt_user.user_info, - sizeof (T_DBMT_USER_INFO), - num_dbmt_user, num_dbmt_user + 1); - if (dbmt_user.user_info == NULL) - { - dbmt_user_free (&dbmt_user); - if (authinfo != NULL) - { - free (authinfo); - } - return ERR_MEM_ALLOC; - } - num_dbmt_user++; - dbmt_user_set_userinfo (& (dbmt_user.user_info[num_dbmt_user - 1]), dbmt_id, - dbmt_passwd, num_authinfo, authinfo, 0, NULL); - dbmt_user.num_dbmt_user = num_dbmt_user; - - retval = dbmt_user_write_auth (&dbmt_user, _dbmt_error); - if (retval != ERR_NO_ERROR) - { - dbmt_user_free (&dbmt_user); - return retval; - } - dbmt_user_write_pass (&dbmt_user, _dbmt_error); - - /* add dblist */ - retval = ut_get_dblist (res, 0); - if (retval != ERR_NO_ERROR) - { - ut_error_log (req, "error while adding database lists to response"); - return retval; - } - - _tsAppendDBMTUserList (res, &dbmt_user, 0, _dbmt_error); - dbmt_user_free (&dbmt_user); - - return tsUpdateDBMTUser (req, res, _dbmt_error); -} - - -int -tsDeleteDBMTUser (nvplist *req, nvplist *res, char *_dbmt_error) -{ - T_DBMT_USER dbmt_user; - char *dbmt_id; - int i, retval, usr_index; - char file[PATH_MAX]; - - if ((dbmt_id = nv_get_val (req, "targetid")) == NULL) - { - sprintf (_dbmt_error, "%s", "target id"); - return ERR_PARAM_MISSING; - } - - if ((retval = dbmt_user_read (&dbmt_user, _dbmt_error)) != ERR_NO_ERROR) - { - return retval; - } - - usr_index = -1; - for (i = 0; i < dbmt_user.num_dbmt_user; i++) - { - if (strcmp (dbmt_user.user_info[i].user_name, dbmt_id) == 0) - { - dbmt_user.user_info[i].user_name[0] = '\0'; - usr_index = i; - break; - } - } - if (usr_index < 0) - { - strcpy (_dbmt_error, conf_get_dbmt_file2 (FID_DBMT_ARNIADB_PASS, file)); - dbmt_user_free (&dbmt_user); - return ERR_FILE_INTEGRITY; - } - - retval = dbmt_user_write_auth (&dbmt_user, _dbmt_error); - if (retval != ERR_NO_ERROR) - { - dbmt_user_free (&dbmt_user); - return retval; - } - dbmt_user_write_pass (&dbmt_user, _dbmt_error); - - /* add dblist */ - retval = ut_get_dblist (res, 0); - if (retval != ERR_NO_ERROR) - { - return retval; - } - - _tsAppendDBMTUserList (res, &dbmt_user, 0, _dbmt_error); - dbmt_user_free (&dbmt_user); - - return ERR_NO_ERROR; -} - -int -tsUpdateDBMTUser (nvplist *req, nvplist *res, char *_dbmt_error) -{ - int i, j, usr_index, retval; - int cas_idx = -1, dbcreate_idx = -1, status_monitor_idx = -1; - char *dbmt_id; - char file[PATH_MAX]; - T_DBMT_USER dbmt_user; - T_DBMT_USER_DBINFO *usr_dbinfo = NULL; - T_DBMT_USER_AUTHINFO *usr_authinfo = NULL; - int num_dbinfo = 0, num_authinfo = 0; - char *z_name, *z_value; - char *dbname, *dbid, *dbpassword, *casauth, *dbcreate, *status_monitor; - char *broker_address; - - int is_update_auth = 0; - - memset (&dbmt_user, 0, sizeof (T_DBMT_USER)); - - if ((dbmt_id = nv_get_val (req, "targetid")) == NULL) - { - sprintf (_dbmt_error, "%s", "target id"); - return ERR_PARAM_MISSING; - } - - for (i = 0; i < req->nvplist_leng; ++i) - { - dbname = dbid = dbpassword = NULL; - broker_address = NULL; - - nv_lookup (req, i, &z_name, &z_value); - - if (uStringEqual (z_name, "open") - && uStringEqual (z_value, "authoritylist")) - { - is_update_auth = 1; - continue; - } - - if (uStringEqual (z_name, "open") && uStringEqual (z_value, "dbauth")) - { - nv_lookup (req, ++i, &z_name, &z_value); - while (!uStringEqual (z_name, "close")) - { - if (uStringEqual (z_name, "dbname")) - { - dbname = z_value; - } - else if (uStringEqual (z_name, "dbid")) - { - dbid = z_value; - } - else if (uStringEqual (z_name, "dbpassword")) - { - dbpassword = z_value; - } - else if (uStringEqual (z_name, "dbbrokeraddress")) - { - broker_address = z_value; - } - else - { - if (usr_dbinfo != NULL) - { - free (usr_dbinfo); - } - return ERR_REQUEST_FORMAT; - } - nv_lookup (req, ++i, &z_name, &z_value); - if (i >= req->nvplist_leng) - { - break; - } - } - } - if (dbname == NULL || dbid == NULL) - { - continue; - } - usr_dbinfo = - (T_DBMT_USER_DBINFO *) increase_capacity (usr_dbinfo, - sizeof (T_DBMT_USER_DBINFO), - num_dbinfo, num_dbinfo + 1); - if (usr_dbinfo == NULL) - { - return ERR_MEM_ALLOC; - } - num_dbinfo++; - dbmt_user_set_dbinfo (& (usr_dbinfo[num_dbinfo - 1]), dbname, "admin", - dbid, broker_address); - } - - if ((casauth = nv_get_val (req, "casauth")) != NULL) - { - cas_idx = num_authinfo; - - } - if ((dbcreate = nv_get_val (req, "dbcreate")) != NULL) - { - dbcreate_idx = num_authinfo + 1; - - } - if ((status_monitor = nv_get_val (req, "statusmonitorauth")) != NULL) - { - status_monitor_idx = num_authinfo + 2; - - } - - if ((casauth != NULL) || (dbcreate != NULL)) - { - usr_authinfo = - (T_DBMT_USER_AUTHINFO *) increase_capacity (usr_authinfo, - sizeof (T_DBMT_USER_AUTHINFO), - num_authinfo, num_authinfo + 3); - if (usr_authinfo == NULL) - { - free (usr_dbinfo); - return ERR_MEM_ALLOC; - } - num_authinfo += 3; - } - - if (casauth != NULL && cas_idx >= 0) - { - dbmt_user_set_authinfo (& (usr_authinfo[cas_idx]), "unicas", casauth); - } - if (dbcreate != NULL && dbcreate_idx >= 0) - { - dbmt_user_set_authinfo (& (usr_authinfo[dbcreate_idx]), "dbcreate", dbcreate); - } - if (status_monitor != NULL && status_monitor_idx >= 0) - { - dbmt_user_set_authinfo (& (usr_authinfo[status_monitor_idx]), - "statusmonitorauth", status_monitor); - } - - if ((retval = dbmt_user_read (&dbmt_user, _dbmt_error)) != ERR_NO_ERROR) - { - if (usr_dbinfo != NULL) - { - free (usr_dbinfo); - } - if (usr_authinfo != NULL) - { - free (usr_authinfo); - } - return retval; - } - - usr_index = -1; - for (i = 0; i < dbmt_user.num_dbmt_user; i++) - { - if (strcmp (dbmt_user.user_info[i].user_name, dbmt_id) == 0) - { - usr_index = i; - break; - } - } - if (usr_index < 0) - { - strcpy (_dbmt_error, conf_get_dbmt_file2 (FID_DBMT_ARNIADB_PASS, file)); - dbmt_user_free (&dbmt_user); - if (usr_dbinfo != NULL) - { - free (usr_dbinfo); - } - if (usr_authinfo != NULL) - { - free (usr_authinfo); - } - return ERR_FILE_INTEGRITY; - } - - /* auth info */ - if (dbmt_user.user_info[usr_index].authinfo == NULL) - { - dbmt_user.user_info[usr_index].num_authinfo = num_authinfo; - dbmt_user.user_info[usr_index].authinfo = usr_authinfo; - usr_authinfo = NULL; - - } - else if (usr_authinfo != NULL) - { - T_DBMT_USER_INFO *current_user_info = - (T_DBMT_USER_INFO *) & (dbmt_user.user_info[usr_index]); - - for (j = 0; j < num_authinfo; j++) - { - int find_idx = -1; - for (i = 0; i < current_user_info->num_authinfo; i++) - { - if (strcmp (current_user_info->authinfo[i].domain, usr_authinfo[j].domain) == 0) - { - find_idx = i; - break; - } - } - if (find_idx == -1) - { - current_user_info->authinfo = - (T_DBMT_USER_AUTHINFO *) increase_capacity (current_user_info->authinfo, - sizeof (T_DBMT_USER_AUTHINFO), - current_user_info->num_authinfo, - current_user_info->num_authinfo + 1); - if (current_user_info->authinfo == NULL) - { - if (usr_dbinfo) - { - free (usr_dbinfo); - } - if (usr_authinfo) - { - free (usr_authinfo); - } - return ERR_MEM_ALLOC; - } - current_user_info->num_authinfo++; - find_idx = current_user_info->num_authinfo - 1; - } - dbmt_user_set_authinfo (& (current_user_info->authinfo[find_idx]), - usr_authinfo[j].domain, usr_authinfo[j].auth); - } - } - - /* db info */ - if (dbmt_user.user_info[usr_index].dbinfo == NULL) - { - dbmt_user.user_info[usr_index].num_dbinfo = num_dbinfo; - dbmt_user.user_info[usr_index].dbinfo = usr_dbinfo; - usr_dbinfo = NULL; - - } - else if (usr_dbinfo != NULL) - { - T_DBMT_USER_INFO *current_user_info = - (T_DBMT_USER_INFO *) & (dbmt_user.user_info[usr_index]); - - for (j = 0; j < num_dbinfo; j++) - { - int find_idx = -1; - for (i = 0; i < current_user_info->num_dbinfo; i++) - { - if (strcmp (current_user_info->dbinfo[i].dbname, usr_dbinfo[j].dbname) == 0) - { - find_idx = i; - break; - } - } - if (find_idx == -1) - { - current_user_info->dbinfo = - (T_DBMT_USER_DBINFO *) increase_capacity (current_user_info->dbinfo, - sizeof (T_DBMT_USER_DBINFO), - current_user_info->num_dbinfo, - current_user_info->num_dbinfo + 1); - if (current_user_info->dbinfo == NULL) - { - FREE_MEM (usr_dbinfo); - FREE_MEM (usr_authinfo); - return ERR_MEM_ALLOC; - } - current_user_info->num_dbinfo++; - find_idx = current_user_info->num_dbinfo - 1; - } - dbmt_user_set_dbinfo (& (current_user_info->dbinfo[find_idx]), - usr_dbinfo[j].dbname, usr_dbinfo[j].auth, - usr_dbinfo[j].uid, usr_dbinfo[j].broker_address); - } - } - - retval = dbmt_user_write_auth (&dbmt_user, _dbmt_error); - if (retval != ERR_NO_ERROR) - { - dbmt_user_free (&dbmt_user); - if (usr_dbinfo) - { - free (usr_dbinfo); - } - if (usr_authinfo) - { - free (usr_authinfo); - } - return retval; - } - - /* add dblist */ - retval = ut_get_dblist (res, 0); - if (retval != ERR_NO_ERROR) - { - return retval; - } - - _tsAppendDBMTUserList (res, &dbmt_user, 0, _dbmt_error); - dbmt_user_free (&dbmt_user); - if (usr_dbinfo) - { - free (usr_dbinfo); - } - if (usr_authinfo) - { - free (usr_authinfo); - } - return ERR_NO_ERROR; -} - -int -tsChangeDBMTUserPasswd (nvplist *req, nvplist *res, char *_dbmt_error) -{ - T_DBMT_USER dbmt_user; - int i, retval, usr_index; - char *dbmt_id, *new_passwd; - char file[PATH_MAX]; - - if ((dbmt_id = nv_get_val (req, "targetid")) == NULL) - { - sprintf (_dbmt_error, "%s", "target id"); - return ERR_PARAM_MISSING; - } - if ((new_passwd = nv_get_val (req, "newpassword")) == NULL) - { - sprintf (_dbmt_error, "%s", "new password"); - return ERR_PARAM_MISSING; - } - - if (!strcmp (new_passwd, "")) - { - sprintf (_dbmt_error, "%s", "NULL password"); - return ERR_WITH_MSG; - } - - if ((retval = dbmt_user_read (&dbmt_user, _dbmt_error)) != ERR_NO_ERROR) - { - return retval; - } - usr_index = -1; - for (i = 0; i < dbmt_user.num_dbmt_user; i++) - { - if (strcmp (dbmt_user.user_info[i].user_name, dbmt_id) == 0) - { - if (new_passwd == NULL) - { - dbmt_user.user_info[i].user_passwd[0] = '\0'; - } - else - { - char hexacoded[PASSWD_ENC_LENGTH]; - - uEncrypt (PASSWD_LENGTH, new_passwd, hexacoded); - strcpy (dbmt_user.user_info[i].user_passwd, hexacoded); - } - usr_index = i; - break; - } - } - if (usr_index < 0) - { - strcpy (_dbmt_error, conf_get_dbmt_file2 (FID_DBMT_ARNIADB_PASS, file)); - dbmt_user_free (&dbmt_user); - return ERR_FILE_INTEGRITY; - } - - retval = dbmt_user_write_pass (&dbmt_user, _dbmt_error); - if (retval != ERR_NO_ERROR) - { - dbmt_user_free (&dbmt_user); - return retval; - } - - /* add dblist */ - retval = ut_get_dblist (res, 0); - if (retval != ERR_NO_ERROR) - { - return retval; - } - - _tsAppendDBMTUserList (res, &dbmt_user, 0, _dbmt_error); - dbmt_user_free (&dbmt_user); - - return ERR_NO_ERROR; -} - - -int -tsGetDBMTUserInfo (nvplist *req, nvplist *res, char *_dbmt_error) -{ - T_DBMT_USER dbmt_user; - int retval; - - retval = ut_get_dblist (res, 0); - if (retval != ERR_NO_ERROR) - { - return retval; - } - retval = dbmt_user_read (&dbmt_user, _dbmt_error); - if (retval != ERR_NO_ERROR) - { - return retval; - } - _tsAppendDBMTUserList (res, &dbmt_user, 1, _dbmt_error); - dbmt_user_free (&dbmt_user); - - return ERR_NO_ERROR; -} - -int -tsCreateDB (nvplist *req, nvplist *res, char *_dbmt_error) -{ - int retval = ERR_NO_ERROR; - char *dbname = NULL; - char *dbmt_user_name = NULL; - char *charset = NULL; - - char *dbpagenum = NULL; - char *dbpagesize = NULL; - char *logpagenum = NULL; - char *logpagesize = NULL; - char dbvolsize[512]; - char logvolsize[512]; - - char *genvolpath = NULL; - char *logvolpath = NULL; -#if defined(WINDOWS) - char logvolpath_buf[1024]; -#endif - char *overwrite_config_file = NULL; - char targetdir[PATH_MAX]; - char extvolfile[PATH_MAX]; - char createdb_err_file[PATH_MAX]; - char *ip, *port; - T_DBMT_USER dbmt_user; - T_DBMT_CON_DBINFO con_dbinfo; - char cmd_name[ARNIADB_CMD_NAME_LEN]; - const char *argv[20]; - int argc = 0; - int gen_dir_created, log_dir_created, ext_dir_created; - - targetdir[0] = '\0'; - extvolfile[0] = '\0'; - createdb_err_file[0] = '\0'; - - gen_dir_created = log_dir_created = ext_dir_created = 0; - - if ((dbname = nv_get_val (req, "dbname")) == NULL) - { - strcpy (_dbmt_error, "database name"); - return ERR_PARAM_MISSING; - } - - if ((dbpagenum = nv_get_val (req, "numpage")) == NULL) - { - strcpy (_dbmt_error, "numpage"); - return ERR_PARAM_MISSING; - } - - if ((dbpagesize = nv_get_val (req, "pagesize")) == NULL) - { - strcpy (_dbmt_error, "pagesize"); - return ERR_PARAM_MISSING; - } - - if ((logpagenum = nv_get_val (req, "logsize")) == NULL) - { - strcpy (_dbmt_error, "logsize"); - return ERR_PARAM_MISSING; - } - - if ((logpagesize = nv_get_val (req, "logpagesize")) == NULL) - { - strcpy (_dbmt_error, "logpagesize"); - return ERR_PARAM_MISSING; - } - - if ((dbmt_user_name = nv_get_val (req, "_ID")) == NULL) - { - strcpy (_dbmt_error, "_ID"); - return ERR_PARAM_MISSING; - } - - if ((charset = nv_get_val (req, "charset")) == NULL) - { - strcpy (_dbmt_error, "charset"); - return ERR_PARAM_MISSING; - } - - genvolpath = nv_get_val (req, "genvolpath"); - logvolpath = nv_get_val (req, "logvolpath"); - overwrite_config_file = nv_get_val (req, "overwrite_config_file"); - - if (genvolpath == NULL) - { - strcpy (_dbmt_error, "volumn path"); - return ERR_PARAM_MISSING; - } - - if ((retval = check_dbpath (genvolpath, _dbmt_error)) != ERR_NO_ERROR) - { - return retval; - } - - if (logvolpath != NULL && logvolpath[0] == '\0') - { - logvolpath = NULL; - } - - if (logvolpath != NULL - && (retval = check_dbpath (logvolpath, _dbmt_error)) != ERR_NO_ERROR) - { - return retval; - } - - /* caculate dbvolsize & logvolsize */ - snprintf (dbvolsize, sizeof (dbvolsize) - 1, "%lldB", - ((long long) atoi (dbpagesize) * (long long) atoi (dbpagenum))); - snprintf (logvolsize, sizeof (logvolsize) - 1, "%lldB", - ((long long) atoi (logpagesize) * (long long) atoi (logpagenum))); - - /* create directory */ - strcpy (targetdir, genvolpath); - if (access (genvolpath, F_OK) < 0) - { - retval = uCreateDir (genvolpath); - if (retval != ERR_NO_ERROR) - { - return retval; - } - else - { - gen_dir_created = 1; - } - } - - if (logvolpath != NULL && access (logvolpath, F_OK) < 0) - { - retval = uCreateDir (logvolpath); - if (retval != ERR_NO_ERROR) - { - return retval; - } - else - { - log_dir_created = 1; - } - } - - if (access (genvolpath, W_OK) < 0) - { - sprintf (_dbmt_error, "%s: %s\n", genvolpath, strerror (errno)); - return ERR_WITH_MSG; - } - - if (logvolpath != NULL && access (logvolpath, W_OK) < 0) - { - sprintf (_dbmt_error, "%s: %s\n", genvolpath, strerror (errno)); - return ERR_WITH_MSG; - } - - /* copy config file to the directory and update config file */ - if ((overwrite_config_file == NULL) /* for backword compatibility */ - || (strcasecmp (overwrite_config_file, "NO") != 0)) - { - char strbuf[1024]; - FILE *infile = NULL; - FILE *outfile = NULL; - char dstrbuf[PATH_MAX]; - -#if !defined (DO_NOT_USE_ARNIADBENV) - snprintf (dstrbuf, PATH_MAX - 1, "%s/conf/%s", sco.szArniadb, - ARNIADB_ARNIADB_CONF); -#else - snprintf (dstrbuf, PATH_MAX - 1, "%s/%s", ARNIADB_CONFDIR, - ARNIADB_ARNIADB_CONF); -#endif - infile = fopen (dstrbuf, "r"); - if (infile == NULL) - { - strcpy (_dbmt_error, dstrbuf); - return ERR_FILE_OPEN_FAIL; - } - - snprintf (dstrbuf, PATH_MAX - 1, "%s/%s", targetdir, ARNIADB_ARNIADB_CONF); - outfile = fopen (dstrbuf, "w"); - if (outfile == NULL) - { - fclose (infile); - strcpy (_dbmt_error, dstrbuf); - return ERR_FILE_OPEN_FAIL; - } - - while (fgets (strbuf, sizeof (strbuf), infile)) - { - const char *param; - - param = "data_buffer_pages"; - if (!strncmp (strbuf, param, strlen (param)) - && nv_get_val (req, param)) - { - fprintf (outfile, "%s=%s\n", param, nv_get_val (req, param)); - continue; - } - - param = "media_failure_support"; - if (!strncmp (strbuf, param, strlen (param)) - && nv_get_val (req, param)) - { - fprintf (outfile, "%s=%s\n", param, nv_get_val (req, param)); - continue; - } - - param = "max_clients"; - if (!strncmp (strbuf, param, strlen (param)) - && nv_get_val (req, param)) - { - fprintf (outfile, "%s=%s\n", param, nv_get_val (req, param)); - continue; - } - - fputs (strbuf, outfile); - } - fclose (infile); - fclose (outfile); - } - - /* remove warning out of space message. - * judge creation failed if created page size is smaller then - * 343 page, write message with volumn expend to error file. - */ - if (0) - { - FILE *infile = NULL; - FILE *outfile = NULL; - char oldfilename[PATH_MAX]; - char newfilename[PATH_MAX]; - memset (oldfilename, '\0', sizeof (oldfilename)); - memset (newfilename, '\0', sizeof (newfilename)); - - snprintf (oldfilename, PATH_MAX - 1, "%s/%s", targetdir, - ARNIADB_ARNIADB_CONF); - infile = fopen (oldfilename, "r"); - if (infile == NULL) - { - strcpy (_dbmt_error, oldfilename); - return ERR_FILE_OPEN_FAIL; - } - - snprintf (newfilename, PATH_MAX - 1, "%s/temparniadb.conf", targetdir); - outfile = fopen (newfilename, "w"); - if (outfile == NULL) - { - fclose (infile); - strcpy (_dbmt_error, newfilename); - return ERR_FILE_OPEN_FAIL; - } - - fclose (infile); - fclose (outfile); - - unlink (oldfilename); - rename (newfilename, oldfilename); - } - - /* construct spec file */ - if (1) - { - int pos, len, i; - char *tn, *tv; - FILE *outfile; - char buf[1024], *val[3]; -#if defined(WINDOWS) - char val2_buf[1024]; -#endif - - snprintf (extvolfile, PATH_MAX - 1, "%s/extvol.spec", targetdir); - outfile = fopen (extvolfile, "w"); - if (outfile == NULL) - { - strcpy (_dbmt_error, extvolfile); - return ERR_FILE_OPEN_FAIL; - } - - nv_locate (req, "exvol", &pos, &len); - for (i = pos; i < len + pos; ++i) - { - nv_lookup (req, i, &tn, &tv); - if (tv == NULL) - { - continue; - } - strcpy (buf, tv); - if (string_tokenize2 (buf, val, 3, ';') < 0) - { - continue; - } - -#if defined(WINDOWS) - val[2] = nt_style_path (val[2], val2_buf); -#endif - fprintf (outfile, "NAME %s PATH %s PURPOSE %s NPAGES %s\n\n", - tn, val[2], val[0], val[1]); - /* create directory, if needed */ - if (access (val[2], F_OK) < 0) - { - retval = uCreateDir (val[2]); - if (retval != ERR_NO_ERROR) - { - fclose (outfile); - return retval; - } - else - { - ext_dir_created = 1; - } - } - } - fclose (outfile); - } - - /* construct command */ - arniadb_cmd_name (cmd_name); -#if defined(WINDOWS) - nt_style_path (targetdir, targetdir); -#endif - argv[argc++] = cmd_name; - argv[argc++] = UTIL_OPTION_CREATEDB; - - argv[argc++] = "--" CREATE_FILE_PATH_L; - argv[argc++] = targetdir; - - argv[argc++] = "--" CREATE_DB_VOLUMN_SIZE_L; - argv[argc++] = dbvolsize; - - argv[argc++] = "--" CREATE_LOG_VOLUMN_SIZE_L; - argv[argc++] = logvolsize; - - if (dbpagesize) - { - argv[argc++] = "--" CREATE_DB_PAGE_SIZE_L; - argv[argc++] = dbpagesize; - } - if (logpagesize) - { - argv[argc++] = "--" CREATE_LOG_PAGE_SIZE_L; - argv[argc++] = logpagesize; - } - if (logvolpath) - { -#if defined(WINDOWS) - logvolpath = nt_style_path (logvolpath, logvolpath_buf); - /* - remove_end_of_dir_ch(logvolpath); - */ -#endif - argv[argc++] = "--" CREATE_LOG_PATH_L; - argv[argc++] = logvolpath; - } - if (extvolfile[0] != '\0') - { - argv[argc++] = "--" CREATE_MORE_VOLUME_FILE_L; - argv[argc++] = extvolfile; - } - - argv[argc++] = dbname; - argv[argc++] = charset; - argv[argc++] = NULL; - - snprintf (createdb_err_file, PATH_MAX, "%s/createdb_err_file.%d.tmp", - sco.dbmt_tmp_dir, (int) getpid ()); - - retval = run_child (argv, 1, NULL, NULL, createdb_err_file, NULL); /* createdb */ - - if (read_error_file (createdb_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) - { - int pos, len, i; - char *tn, *tv; - char buf[1024], *val[3]; - - if ((access (genvolpath, F_OK) == 0) && (gen_dir_created)) - { - uRemoveDir (genvolpath, REMOVE_DIR_FORCED); - } - if ((logvolpath != NULL) && (access (logvolpath, F_OK) == 0) - && (log_dir_created)) - { - uRemoveDir (logvolpath, REMOVE_DIR_FORCED); - } - - nv_locate (req, "exvol", &pos, &len); - for (i = pos; i < len + pos; ++i) - { - nv_lookup (req, i, &tn, &tv); - if (tv == NULL) - { - continue; - } - strcpy (buf, tv); - if (string_tokenize2 (buf, val, 3, ';') < 0) - { - continue; - } - if ((access (val[2], F_OK) == 0) && (ext_dir_created)) - { - uRemoveDir (val[2], REMOVE_DIR_FORCED); /* ext vol path */ - } - } - unlink (createdb_err_file); - return ERR_WITH_MSG; - } - unlink (createdb_err_file); - - if (retval < 0) - { - int pos, len, i; - char *tn, *tv; - char buf[1024], *val[3]; - - if (access (genvolpath, F_OK) == 0) - { - uRemoveDir (genvolpath, REMOVE_DIR_FORCED); - } - if (logvolpath != NULL && access (logvolpath, F_OK) == 0) - { - uRemoveDir (logvolpath, REMOVE_DIR_FORCED); - } - - nv_locate (req, "exvol", &pos, &len); - for (i = pos; i < len + pos; ++i) - { - nv_lookup (req, i, &tn, &tv); - if (tv == NULL) - { - continue; - } - strcpy (buf, tv); - if (string_tokenize2 (buf, val, 3, ';') < 0) - { - continue; - } - if (access (val[2], F_OK) == 0) - { - uRemoveDir (val[2], REMOVE_DIR_FORCED); /* ext vol path */ - } - } - - sprintf (_dbmt_error, "%s", argv[0]); - return ERR_SYSTEM_CALL; - } - - /* add dbinfo to cmdb.pass */ - if (dbmt_user_read (&dbmt_user, _dbmt_error) == ERR_NO_ERROR) - { - int i; - T_DBMT_USER_DBINFO tmp_dbinfo; - - memset (&tmp_dbinfo, 0, sizeof (tmp_dbinfo)); - dbmt_user_set_dbinfo (&tmp_dbinfo, dbname, dbmt_user_name, "dba", ""); - - dbmt_user_db_delete (&dbmt_user, dbname); - for (i = 0; i < dbmt_user.num_dbmt_user; i++) - { - if (strcmp (dbmt_user.user_info[i].user_name, dbmt_user_name) == 0) - { - if (dbmt_user_add_dbinfo - (& (dbmt_user.user_info[i]), &tmp_dbinfo) == ERR_NO_ERROR) - { - dbmt_user_write_auth (&dbmt_user, _dbmt_error); - } - break; - } - } - dbmt_user_free (&dbmt_user); - } - - /* add dbinfo to conlist */ - memset (&con_dbinfo, 0, sizeof (con_dbinfo)); - dbmt_con_set_dbinfo (&con_dbinfo, dbname, "dba", ""); - ip = nv_get_val (req, "_IP"); - port = nv_get_val (req, "_PORT"); - dbmt_con_write_dbinfo (&con_dbinfo, ip, port, dbname, 1, _dbmt_error); - - /* restore warn out of space value */ - if (0) - { - char strbuf[1024]; - FILE *infile = NULL; - FILE *outfile = NULL; - char oldfilename[PATH_MAX]; - char newfilename[PATH_MAX]; - memset (oldfilename, '\0', sizeof (oldfilename)); - memset (newfilename, '\0', sizeof (newfilename)); - - snprintf (oldfilename, PATH_MAX - 1, "%s/%s", targetdir, - ARNIADB_ARNIADB_CONF); - infile = fopen (oldfilename, "r"); - if (infile == NULL) - { - strcpy (_dbmt_error, oldfilename); - return ERR_FILE_OPEN_FAIL; - } - - snprintf (newfilename, PATH_MAX - 1, "%s/temparniadb.conf", targetdir); - outfile = fopen (newfilename, "w"); - if (outfile == NULL) - { - fclose (infile); - strcpy (_dbmt_error, newfilename); - return ERR_FILE_OPEN_FAIL; - } - - while (fgets (strbuf, sizeof (strbuf), infile)) - { - const char *p; - p = "warn_outofspace_factor"; - if (!strncmp (strbuf, p, strlen (p))) - { - fprintf (outfile, "%s", p); - continue; - } - - fputs (strbuf, outfile); - } - fclose (infile); - fclose (outfile); - - unlink (oldfilename); - rename (newfilename, oldfilename); - } - - if ((overwrite_config_file == NULL) /* for backward compatibility */ - || (strcasecmp (overwrite_config_file, "NO") != 0)) - { - char strbuf[PATH_MAX]; - - snprintf (strbuf, PATH_MAX - 1, "%s/%s", targetdir, ARNIADB_ARNIADB_CONF); - unlink (strbuf); - } - - if (extvolfile[0] != '\0') - { - unlink (extvolfile); - } - return ERR_NO_ERROR; -} - -int -tsDeleteDB (nvplist *req, nvplist *res, char *_dbmt_error) -{ - T_DBMT_USER dbmt_user; - int retval = ERR_NO_ERROR; - char *dbname = NULL, *delbackup; - char arniadb_err_file[PATH_MAX]; - char cmd_name[ARNIADB_CMD_NAME_LEN]; - const char *argv[6]; - int argc = 0; - - /*dbvol path & db log path. */ - char dbvolpath[PATH_MAX]; - char dblogpath[PATH_MAX]; - - arniadb_err_file[0] = '\0'; - - if ((dbname = nv_get_val (req, "_DBNAME")) == NULL) - { - sprintf (_dbmt_error, "%s", "database name"); - return ERR_PARAM_MISSING; - } - - if (_isRegisteredDB (dbname) == 0) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", dbname); - return ERR_DB_NONEXISTANT; - } - - delbackup = nv_get_val (req, "delbackup"); - - arniadb_cmd_name (cmd_name); - argv[argc++] = cmd_name; - argv[argc++] = UTIL_OPTION_DELETEDB; - if (uStringEqual (delbackup, "y")) - { - argv[argc++] = "--" DELETE_DELETE_BACKUP_L; - } - argv[argc++] = dbname; - argv[argc++] = NULL; - - snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", - sco.dbmt_tmp_dir, "deletedb", getpid ()); - - /*get dbvolpath and dblogpath. */ - get_dbvoldir (dbvolpath, sizeof (dbvolpath), dbname, arniadb_err_file); - get_dblogdir (dblogpath, sizeof (dblogpath), dbname, arniadb_err_file); - - retval = run_child (argv, 1, NULL, NULL, arniadb_err_file, NULL); /* deletedb */ - - if (read_error_file (arniadb_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) - { - if (access (arniadb_err_file, F_OK) == 0) - { - unlink (arniadb_err_file); - } - return ERR_WITH_MSG; - } - if (access (arniadb_err_file, F_OK) == 0) - { - unlink (arniadb_err_file); - } - if (retval < 0) - { - strcpy (_dbmt_error, argv[0]); - return ERR_SYSTEM_CALL; - } - - auto_conf_addvol_delete (FID_AUTO_ADDVOLDB_CONF, dbname); - auto_conf_backup_delete (FID_AUTO_BACKUPDB_CONF, dbname); - auto_conf_history_delete (FID_AUTO_HISTORY_CONF, dbname); - auto_conf_execquery_delete (FID_AUTO_EXECQUERY_CONF, dbname); - - if (dbmt_user_read (&dbmt_user, _dbmt_error) == ERR_NO_ERROR) - { - dbmt_user_db_delete (&dbmt_user, dbname); - dbmt_user_write_auth (&dbmt_user, _dbmt_error); - dbmt_user_free (&dbmt_user); - } - - /* The following delete sequence can delete folder hierarchy like : - * / - * and /. - */ - rmdir (dbvolpath); - rmdir (dblogpath); - rmdir (dbvolpath); - - return ERR_NO_ERROR; -} - -int -tsRenameDB (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char *dbname = NULL; - char *newdbname = NULL; - char *exvolpath = NULL; - char *advanced = NULL; - char *forcedel = NULL; - char task_name[TASKNAME_LEN]; - - const char *argv[10]; - - int argc = 0; - int retval = 0; - T_DB_SERVICE_MODE db_mode; - T_DBMT_USER dbmt_user; - - char cmd_name[ARNIADB_CMD_NAME_LEN]; - char tmpfile[PATH_MAX]; - - cmd_name[0] = '\0'; - tmpfile[0] = '\0'; - task_name[0] = '\0'; - - if ((dbname = nv_get_val (req, "_DBNAME")) == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "dbname"); - return ERR_PARAM_MISSING; - } - if ((newdbname = nv_get_val (req, "rename")) == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "rename"); - return ERR_PARAM_MISSING; - } - if ((exvolpath = nv_get_val (req, "exvolpath")) == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "exvolpath"); - return ERR_PARAM_MISSING; - } - if ((advanced = nv_get_val (req, "advanced")) == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "advanced"); - return ERR_PARAM_MISSING; - } - if ((forcedel = nv_get_val (req, "forcedel")) == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "forcedel"); - return ERR_PARAM_MISSING; - } - - db_mode = uDatabaseMode (dbname, NULL); - if (db_mode == DB_SERVICE_MODE_SA) - { - sprintf (_dbmt_error, "%s", dbname); - return ERR_STANDALONE_MODE; - } - else if (db_mode == DB_SERVICE_MODE_CS) - { - sprintf (_dbmt_error, "%s", dbname); - return ERR_DB_ACTIVE; - } - - arniadb_cmd_name (cmd_name); - argv[argc++] = cmd_name; - argv[argc++] = UTIL_OPTION_RENAMEDB; - - if (uStringEqual (advanced, "on")) - { - FILE *outfile; - int i, flag = 0, line = 0; - char *n, *v; -#if defined(WINDOWS) - char n_buf[1024], v_buf[1024]; -#endif - char *p; - - snprintf (tmpfile, PATH_MAX - 1, "%s/DBMT_task_%d.%d", sco.dbmt_tmp_dir, - TS_RENAMEDB, (int) getpid ()); - if ((outfile = fopen (tmpfile, "w")) == NULL) - { - return ERR_TMPFILE_OPEN_FAIL; - } - for (i = 0; i < req->nvplist_leng; i++) - { - nv_lookup (req, i, &n, &v); - if (n == NULL || v == NULL) - { - fclose (outfile); - if (v != NULL) - { - strcpy (_dbmt_error, v); - return ERR_DIR_CREATE_FAIL; - } - else - { - strcpy (_dbmt_error, "Lost all parameters."); - return ERR_WITH_MSG; - } - } - - if (!strcmp (n, "open") && !strcmp (v, "volume")) - { - flag = 1; - } - else if (!strcmp (n, "close") && !strcmp (v, "volume")) - { - flag = 0; - break; - } - else if (flag == 1) - { -#if defined(WINDOWS) - replace_colon (n); - replace_colon (v); -#endif - p = strrchr (v, '/'); - if (p) - { - *p = '\0'; - } - if (uCreateDir (v) != ERR_NO_ERROR) - { - fclose (outfile); - strcpy (_dbmt_error, v); - return ERR_DIR_CREATE_FAIL; - } - if (p) - { - *p = '/'; - } -#if defined(WINDOWS) - n = nt_style_path (n, n_buf); - v = nt_style_path (v, v_buf); -#endif - fprintf (outfile, "%d %s %s\n", line++, n, v); - - } /* close "else if (flag == 1)" */ - } /* close "for" loop */ - fclose (outfile); - argv[argc++] = "--" RENAME_CONTROL_FILE_L; - argv[argc++] = tmpfile; - } /* close "if (adv_flag != NULL)" */ - else if (exvolpath != NULL && !uStringEqual (exvolpath, "none")) - { - if (uCreateDir (exvolpath) != ERR_NO_ERROR) - { - strcpy (_dbmt_error, exvolpath); - return ERR_DIR_CREATE_FAIL; - } - argv[argc++] = "--" RENAME_EXTENTED_VOLUME_PATH_L; - argv[argc++] = exvolpath; - } - - if (uStringEqual (forcedel, "y")) - { - argv[argc++] = "--" RENAME_DELETE_BACKUP_L; - } - - argv[argc++] = dbname; - argv[argc++] = newdbname; - argv[argc++] = NULL; - - strncpy (task_name, "renamedb", TASKNAME_LEN); - retval = _run_child (argv, 1, task_name, NULL, _dbmt_error); - if (retval != ERR_NO_ERROR) - { - return retval; - } - - auto_conf_addvol_rename (FID_AUTO_ADDVOLDB_CONF, dbname, newdbname); - auto_conf_backup_rename (FID_AUTO_BACKUPDB_CONF, dbname, newdbname); - auto_conf_history_rename (FID_AUTO_HISTORY_CONF, dbname, newdbname); - auto_conf_execquery_rename (FID_AUTO_EXECQUERY_CONF, dbname, newdbname); - - if (dbmt_user_read (&dbmt_user, _dbmt_error) == ERR_NO_ERROR) - { - int i, j; - for (i = 0; i < dbmt_user.num_dbmt_user; i++) - { - for (j = 0; j < dbmt_user.user_info[i].num_dbinfo; j++) - { - if (strcmp (dbmt_user.user_info[i].dbinfo[j].dbname, dbname) == 0) - { - strcpy (dbmt_user.user_info[i].dbinfo[j].dbname, newdbname); - } - } - } - dbmt_user_write_auth (&dbmt_user, _dbmt_error); - dbmt_user_free (&dbmt_user); - } - - return ERR_NO_ERROR; -} - -int -tsStartDB (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char *dbname; - char err_buf[ERR_MSG_SIZE]; - T_DB_SERVICE_MODE db_mode; - int retval; - - if ((dbname = nv_get_val (req, "_DBNAME")) == NULL) - { - sprintf (_dbmt_error, "%s", "database name"); - return ERR_PARAM_MISSING; - } - - db_mode = uDatabaseMode (dbname, NULL); - if (db_mode == DB_SERVICE_MODE_SA) - { - sprintf (_dbmt_error, "%s", dbname); - return ERR_STANDALONE_MODE; - } - if (db_mode == DB_SERVICE_MODE_CS) - { - return ERR_NO_ERROR; - } - - retval = cmd_start_server (dbname, err_buf, sizeof (err_buf)); - if (retval < 0) - { - DBMT_ERR_MSG_SET (_dbmt_error, err_buf); - return ERR_WITH_MSG; - } - else if (retval == 1) - { - DBMT_ERR_MSG_SET (_dbmt_error, err_buf); - } - - /* recount active db num and write to file */ - uWriteDBnfo (); - - return retval == 0 ? ERR_NO_ERROR : ERR_WARNING; -} - -int -tsStopDB (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char *dbname; - - if ((dbname = nv_get_val (req, "_DBNAME")) == NULL) - { - sprintf (_dbmt_error, "%s", "database name"); - return ERR_PARAM_MISSING; - } - - if (cmd_stop_server (dbname, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) - { - return ERR_WITH_MSG; - } - - /* recount active db num and write to file */ - uWriteDBnfo (); - - return ERR_NO_ERROR; -} - -int -tsDbspaceInfo (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char *dbname = NULL; - int retval = ERR_NO_ERROR; - const char *err_message; - char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; - int ha_mode = 0; - T_ARNIADB_MODE arniadb_mode; - GeneralSpacedbResult *cmd_res; - T_DB_SERVICE_MODE db_mode; - - /* get dbname */ - if ((dbname = nv_get_val (req, "_DBNAME")) == NULL) - { - sprintf (_dbmt_error, "%s", "database name"); - return ERR_PARAM_MISSING; - } - - db_mode = uDatabaseMode (dbname, &ha_mode); - if (db_mode == DB_SERVICE_MODE_SA) - { - sprintf (_dbmt_error, "%s", dbname); - return ERR_STANDALONE_MODE; - } - - nv_add_nvp (res, "dbname", dbname); - nv_add_nvp (res, "pagesize", "-1"); - nv_add_nvp (res, "logpagesize", "-1"); - - arniadb_mode = - (db_mode == DB_SERVICE_MODE_NONE) ? ARNIADB_MODE_SA : ARNIADB_MODE_CS; - - if (ha_mode != 0) - { - append_host_to_dbname (dbname_at_hostname, dbname, sizeof (dbname_at_hostname)); - cmd_res = cmd_spacedb (dbname_at_hostname, arniadb_mode); - } - else - { - cmd_res = cmd_spacedb (dbname, arniadb_mode); - } - - err_message = cmd_res->get_err_msg(); - - if (cmd_res == NULL) - { - sprintf (_dbmt_error, "spacedb %s", dbname); - retval = ERR_SYSTEM_CALL; - } - else if (cmd_res->has_error()) - { - strcpy (_dbmt_error, err_message); - retval = ERR_WITH_MSG; - } - else - { - retval = _tsParseSpacedb (req, res, dbname, _dbmt_error, cmd_res); - } - - delete cmd_res; - return retval; -} - -static int -nv_append_nvp (nvplist *dest, const nvplist *src) -{ - int i; - - if (dest == NULL || src == NULL) - { - return -1; - } - - for (i = 0; i < src->nvplist_size; ++i) - { - if (src->nvpairs[i] == NULL - || dst_buffer (src->nvpairs[i]->name) == NULL) - { - continue; - } - - nv_add_nvp (dest, dst_buffer (src->nvpairs[i]->name), - dst_buffer (src->nvpairs[i]->value)); - } - - return 1; -} - -int -ts_dbs_spaceInfo (nvplist *req, nvplist *res, char *_dbmt_error) -{ - int i, sect, sect_len; - char *tval; - nvplist *cli_request; - nvplist *cli_response; - - cli_request = nv_create (5, NULL, "\n", ":", "\n"); - cli_response = nv_create (5, NULL, "\n", ":", "\n"); - nv_add_nvp (cli_request, "_DBNAME", ""); - - nv_locate (req, "dblist", §, §_len); - if (sect >= 0) - { - for (i = 0; i < sect_len; ++i) - { - nv_lookup (req, sect + i, NULL, &tval); - nv_update_val (cli_request, "_DBNAME", tval); - nv_add_nvp (res, "open", tval); - if (tsDbspaceInfo (cli_request, cli_response, _dbmt_error) == ERR_NO_ERROR) - { - nv_append_nvp (res, cli_response); - } - nv_reset_nvp (cli_response); - nv_add_nvp (res, "close", tval); - } - } - nv_destroy (cli_request); - nv_destroy (cli_response); - return ERR_NO_ERROR; -} - -int -tsRunAddvoldb (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char *dbname = NULL; - char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; - int ha_mode = 0; - char *volpu = NULL; - char *volpath = NULL; - char *dbvolsize = NULL; - char dbvolsize_t[512]; -#if defined(WINDOWS) - char volpath_buf[PATH_MAX]; -#endif - char *volname = NULL; - char db_dir[PATH_MAX]; - T_DB_SERVICE_MODE db_mode; - char err_file[PATH_MAX]; - int ret; - char cmd_name[ARNIADB_CMD_NAME_LEN]; - const char *argv[15]; - int argc = 0; - int free_space_mb; - - err_file[0] = '\0'; - - if ((dbname = nv_get_val (req, "_DBNAME")) == NULL) - { - sprintf (_dbmt_error, "%s", "database name"); - return ERR_PARAM_MISSING; - } - - db_mode = uDatabaseMode (dbname, &ha_mode); - if (db_mode == DB_SERVICE_MODE_SA) - { - sprintf (_dbmt_error, "%s", dbname); - return ERR_STANDALONE_MODE; - } - - if ((volpu = nv_get_val (req, "purpose")) == NULL) - { - sprintf (_dbmt_error, "%s", "purpose"); - return ERR_PARAM_MISSING; - } - - volpath = nv_get_val (req, "path"); - volname = nv_get_val (req, "volname"); - - if ((dbvolsize = nv_get_val (req, "size_need_mb")) == NULL) - { - sprintf (_dbmt_error, "%s", "size_nee_mb"); - return ERR_PARAM_MISSING; - } - - if (uRetrieveDBDirectory (dbname, db_dir) != ERR_NO_ERROR) - { - strcpy (_dbmt_error, dbname); - return ERR_DBDIRNAME_NULL; - } - - /* check permission of the directory */ - if (access (db_dir, W_OK | X_OK | R_OK) < 0) - { - sprintf (_dbmt_error, "%s", db_dir); - return ERR_PERMISSION; - } - - if (volpath == NULL) - { - volpath = db_dir; - } - - if (access (volpath, F_OK) < 0) - { - if (uCreateDir (volpath) != ERR_NO_ERROR) - { - sprintf (_dbmt_error, "%s", volpath); - return ERR_DIR_CREATE_FAIL; - } - } - - free_space_mb = ut_disk_free_space (volpath); - if (dbvolsize && (free_space_mb < atoi (dbvolsize))) - { - sprintf (_dbmt_error, "Not enough free space in disk."); - return ERR_WITH_MSG; - } - - /* - * Get the dbvolsize, the format looks like: size_need_mb:2.047(MB) - */ - snprintf (dbvolsize_t, sizeof (dbvolsize_t) - 1, "%lldB", - (long long) (atof (dbvolsize) * BYTES_IN_M)); - - arniadb_cmd_name (cmd_name); - argv[argc++] = cmd_name; - argv[argc++] = UTIL_OPTION_ADDVOLDB; - - if (db_mode == DB_SERVICE_MODE_NONE) - { - argv[argc++] = "--" ADDVOL_SA_MODE_L; - } - -#if defined(WINDOWS) - volpath = nt_style_path (volpath, volpath_buf); -#endif - - argv[argc++] = "--" ADDVOL_FILE_PATH_L; - argv[argc++] = volpath; - - if (volname) - { - argv[argc++] = "--" ADDVOL_VOLUME_NAME_L; - argv[argc++] = volname; - } - - argv[argc++] = "--" ADDVOL_DB_VOLUMN_SIZE_L; - argv[argc++] = dbvolsize_t; - - argv[argc++] = "--" ADDVOL_PURPOSE_L; - argv[argc++] = volpu; - - if (ha_mode != 0) - { - append_host_to_dbname (dbname_at_hostname, dbname, sizeof (dbname_at_hostname)); - argv[argc++] = dbname_at_hostname; - } - else - { - argv[argc++] = dbname; - } - - argv[argc++] = NULL; - - snprintf (err_file, PATH_MAX, "%s/%s.%u.err.tmp", sco.dbmt_tmp_dir, "runaddvoldb", getpid ()); - - ret = run_child (argv, 1, NULL, NULL, err_file, NULL); /* addvoldb */ - if (read_error_file (err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) - { - if (access (err_file, F_OK) == 0) - { - unlink (err_file); - } - return ERR_WITH_MSG; - } - - if (access (err_file, F_OK) == 0) - { - unlink (err_file); - } - if (ret < 0) - { - sprintf (_dbmt_error, "%s", argv[0]); - return ERR_SYSTEM_CALL; - } - - nv_add_nvp (res, "dbname", dbname); - nv_add_nvp (res, "purpose", volpu); - - return ERR_NO_ERROR; -} - -int -ts_copydb (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char *srcdbname = NULL; - char *destdbname = NULL; - char *logpath = NULL; - char *destdbpath = NULL; - char *exvolpath = NULL; - int move_flag = 0; - int overwrite_flag = 0; - int adv_flag = 0; - char tmpfile[PATH_MAX], cmd_name[ARNIADB_CMD_NAME_LEN], - lob_base_path[PATH_MAX]; - char src_conf_file[PATH_MAX], dest_conf_file[PATH_MAX], conf_dir[PATH_MAX]; - int i = -1; - int retval = -1; - char arniadb_err_file[PATH_MAX]; - T_DBMT_USER dbmt_user; - T_DB_SERVICE_MODE db_mode; - const char *argv[15]; - int argc = 0; - - /* init var */ - tmpfile[0] = '\0'; - cmd_name[0] = '\0'; - lob_base_path[0] = '\0'; - src_conf_file[0] = '\0'; - dest_conf_file[0] = '\0'; - conf_dir[0] = '\0'; - arniadb_err_file[0] = '\0'; - - if ((srcdbname = nv_get_val (req, "srcdbname")) == NULL) - { - strcpy (_dbmt_error, "source database name"); - return ERR_PARAM_MISSING; - } - if ((destdbname = nv_get_val (req, "destdbname")) == NULL) - { - strcpy (_dbmt_error, "destination database name"); - return ERR_PARAM_MISSING; - } - - adv_flag = uStringEqual (nv_get_val (req, "advanced"), "on") ? 1 : 0; - overwrite_flag = uStringEqual (nv_get_val (req, "overwrite"), "y") ? 1 : 0; - move_flag = uStringEqual (nv_get_val (req, "move"), "y") ? 1 : 0; - - if ((logpath = nv_get_val (req, "logpath")) == NULL) - { - strcpy (_dbmt_error, "log path"); - return ERR_PARAM_MISSING; - } - if ((destdbpath = nv_get_val (req, "destdbpath")) == NULL && adv_flag == 0) - { - strcpy (_dbmt_error, "database directory path"); - return ERR_PARAM_MISSING; - } - if ((exvolpath = nv_get_val (req, "exvolpath")) == NULL && adv_flag == 0) - { - strcpy (_dbmt_error, "extended volume path"); - return ERR_PARAM_MISSING; - } - - db_mode = uDatabaseMode (srcdbname, NULL); - if (db_mode == DB_SERVICE_MODE_SA) - { - sprintf (_dbmt_error, "%s", srcdbname); - return ERR_STANDALONE_MODE; - } - else if (db_mode == DB_SERVICE_MODE_CS) - { - sprintf (_dbmt_error, "%s", srcdbname); - return ERR_DB_ACTIVE; - } - - /* create command */ - arniadb_cmd_name (cmd_name); - argv[argc++] = cmd_name; - argv[argc++] = UTIL_OPTION_COPYDB; - argv[argc++] = "--" COPY_LOG_PATH_L; - argv[argc++] = logpath; - - if (adv_flag) - { - FILE *outfile; - int flag = 0, line = 0; - char *n, *v; -#if defined(WINDOWS) - char n_buf[1024], v_buf[1024]; -#endif - char *p; - - snprintf (tmpfile, PATH_MAX - 1, "%s/DBMT_task_%d.%d", sco.dbmt_tmp_dir, TS_COPYDB, (int) getpid ()); - if ((outfile = fopen (tmpfile, "w")) == NULL) - { - return ERR_TMPFILE_OPEN_FAIL; - } - for (i = 0; i < req->nvplist_leng; i++) - { - nv_lookup (req, i, &n, &v); - if (n == NULL || v == NULL) - { - fclose (outfile); - if (v != NULL) - { - strcpy (_dbmt_error, v); - } - return ERR_DIR_CREATE_FAIL; - } - - if (!strcmp (n, "open") && !strcmp (v, "volume")) - { - flag = 1; - } - else if (!strcmp (n, "close") && !strcmp (v, "volume")) - { - flag = 0; - } - else if (flag == 1) - { -#if defined(WINDOWS) - replace_colon (n); - replace_colon (v); -#endif - p = strrchr (v, '/'); - if (p) - { - *p = '\0'; - } - snprintf (lob_base_path, PATH_MAX - 1, "%s/lob", v); - if (uCreateDir (lob_base_path) != ERR_NO_ERROR) - { - fclose (outfile); - strcpy (_dbmt_error, lob_base_path); - return ERR_DIR_CREATE_FAIL; - } - if (p) - { - *p = '/'; - } -#if defined(WINDOWS) - n = nt_style_path (n, n_buf); - v = nt_style_path (v, v_buf); -#endif - fprintf (outfile, "%d %s %s\n", line++, n, v); - } - } - fclose (outfile); - argv[argc++] = "--" COPY_CONTROL_FILE_L; - argv[argc++] = tmpfile; - } - else - { - /* adv_flag == 0 */ - snprintf (lob_base_path, PATH_MAX - 1, "%s/lob", destdbpath); - if (uCreateDir (lob_base_path) != ERR_NO_ERROR) - { - strcpy (_dbmt_error, lob_base_path); - return ERR_DIR_CREATE_FAIL; - } - if (uCreateDir (exvolpath) != ERR_NO_ERROR) - { - strcpy (_dbmt_error, exvolpath); - return ERR_DIR_CREATE_FAIL; - } - argv[argc++] = "--" COPY_FILE_PATH_L; - argv[argc++] = destdbpath; - argv[argc++] = "--" COPY_EXTENTED_VOLUME_PATH_L; - argv[argc++] = exvolpath; - } - if (overwrite_flag) - { - argv[argc++] = "--" COPY_REPLACE_L; - } - argv[argc++] = "-" COPY_LOB_BASE_PATH_S; - argv[argc++] = lob_base_path; - argv[argc++] = srcdbname; - argv[argc++] = destdbname; - argv[argc++] = NULL; - - if (uCreateDir (logpath) != ERR_NO_ERROR) - { - strcpy (_dbmt_error, logpath); - return ERR_DIR_CREATE_FAIL; - } - - snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", - sco.dbmt_tmp_dir, "copydb", getpid ()); - - retval = run_child (argv, 1, NULL, NULL, arniadb_err_file, NULL); /* copydb */ - if (adv_flag) - { - unlink (tmpfile); - } - if (read_error_file (arniadb_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) - { - if (access (arniadb_err_file, F_OK) == 0) - { - unlink (arniadb_err_file); - } - return ERR_WITH_MSG; - } - if (access (arniadb_err_file, F_OK) == 0) - { - unlink (arniadb_err_file); - } - if (retval < 0) - { - strcpy (_dbmt_error, argv[0]); - return ERR_SYSTEM_CALL; - } - - /* copy config file */ - if (uRetrieveDBDirectory (srcdbname, conf_dir) != ERR_NO_ERROR) - { - strcpy (_dbmt_error, srcdbname); - return ERR_DBDIRNAME_NULL; - } - snprintf (src_conf_file, sizeof (src_conf_file) - 1, "%s/%s", conf_dir, ARNIADB_ARNIADB_CONF); - - if (uRetrieveDBDirectory (destdbname, conf_dir) != ERR_NO_ERROR) - { - strcpy (_dbmt_error, destdbname); - return ERR_DBDIRNAME_NULL; - } - snprintf (dest_conf_file, sizeof (dest_conf_file) - 1, "%s/%s", conf_dir, ARNIADB_ARNIADB_CONF); - - /* Doesn't copy if src and desc is same */ - if (strcmp (src_conf_file, dest_conf_file) != 0) - { - file_copy (src_conf_file, dest_conf_file); - } - - /* if move, delete exist database */ - if (move_flag) - { - char cmd_name[ARNIADB_CMD_NAME_LEN]; - const char *argv[5]; - - arniadb_cmd_name (cmd_name); - argv[0] = cmd_name; - argv[1] = UTIL_OPTION_DELETEDB; - argv[2] = srcdbname; - argv[3] = NULL; - retval = run_child (argv, 1, NULL, NULL, NULL, NULL); /* deletedb */ - if (retval < 0) - { - strcpy (_dbmt_error, argv[0]); - return ERR_SYSTEM_CALL; - } - } - - /* cmdb.pass update after delete */ - if (dbmt_user_read (&dbmt_user, _dbmt_error) != ERR_NO_ERROR) - { - goto copydb_finale; - } - - dbmt_user_db_delete (&dbmt_user, destdbname); - for (i = 0; i < dbmt_user.num_dbmt_user; i++) - { - int dbinfo_idx; - T_DBMT_USER_DBINFO tmp_info; - - dbinfo_idx = dbmt_user_search (& (dbmt_user.user_info[i]), srcdbname); - if (dbinfo_idx < 0) - { - continue; - } - tmp_info = dbmt_user.user_info[i].dbinfo[dbinfo_idx]; - strcpy (tmp_info.dbname, destdbname); - if (dbmt_user_add_dbinfo (& (dbmt_user.user_info[i]), &tmp_info) != ERR_NO_ERROR) - { - dbmt_user_free (&dbmt_user); - goto copydb_finale; - } - } - if (move_flag) - { - dbmt_user_db_delete (&dbmt_user, srcdbname); - } - dbmt_user_write_auth (&dbmt_user, _dbmt_error); - dbmt_user_free (&dbmt_user); - -copydb_finale: - return ERR_NO_ERROR; -} - -int -ts_plandump (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char *dbname = NULL; - char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; - int ha_mode = 0; - T_DB_SERVICE_MODE db_mode; - char cmd_name[ARNIADB_CMD_NAME_LEN]; - char *plandrop = NULL; - const char *argv[10]; - int argc = 0; - char arniadb_err_file[PATH_MAX]; - char tmpfilepath[PATH_MAX]; - int retval = ERR_NO_ERROR; - - arniadb_err_file[0] = '\0'; - - if ((dbname = nv_get_val (req, "dbname")) == NULL) - { - strcpy (_dbmt_error, "database name"); - return ERR_PARAM_MISSING; - } - plandrop = nv_get_val (req, "plandrop"); - - /* - * check the running mode of current database, - * return error if it is DB_SERVICE_MODE_SA. - */ - db_mode = uDatabaseMode (dbname, &ha_mode); - if (db_mode == DB_SERVICE_MODE_SA) - { - sprintf (_dbmt_error, "%s", dbname); - return ERR_STANDALONE_MODE; - } - - arniadb_cmd_name (cmd_name); - argv[argc++] = cmd_name; - argv[argc++] = UTIL_OPTION_PLANDUMP; - if (uStringEqual (plandrop, "y")) - { - argv[argc++] = "--" PLANDUMP_DROP_L; - } - - if (ha_mode != 0) - { - append_host_to_dbname (dbname_at_hostname, dbname, - sizeof (dbname_at_hostname)); - argv[argc++] = dbname_at_hostname; - } - else - { - argv[argc++] = dbname; - } - - argv[argc++] = NULL; - - snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", - sco.dbmt_tmp_dir, "plandump", getpid ()); - - /* - * create a new tmp file to record the content - * that returned by plandump. - */ - snprintf (tmpfilepath, PATH_MAX - 1, "%s/DBMT_task_%d.%d", - sco.dbmt_tmp_dir, TS_PLANDUMP, (int) getpid ()); - - if (run_child (argv, 1, NULL, tmpfilepath, arniadb_err_file, NULL) < 0) /* plandump */ - { - strcpy (_dbmt_error, argv[0]); - retval = ERR_SYSTEM_CALL; - goto rm_tmpfile; - } - - if (read_error_file (arniadb_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) - { - retval = ERR_WITH_MSG; - goto rm_tmpfile; - } - - /* add file content to response line by line. */ - nv_add_nvp (res, "open", "log"); - if (file_to_nvpairs (tmpfilepath, res) < 0) - { - retval = ERR_TMPFILE_OPEN_FAIL; - } - nv_add_nvp (res, "close", "log"); - -rm_tmpfile: - unlink (tmpfilepath); - if (access (arniadb_err_file, F_OK) == 0) - { - unlink (arniadb_err_file); - } - return retval; -} - -int -ts_paramdump (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char *dbname = NULL; - char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; - int ha_mode = 0; - char *bothclientserver = NULL; - T_DB_SERVICE_MODE db_mode; - char cmd_name[ARNIADB_CMD_NAME_LEN]; - const char *argv[10]; - int argc = 0; - char arniadb_err_file[PATH_MAX]; - FILE *infile = NULL; - char tmpfilepath[PATH_MAX]; - int retval = ERR_NO_ERROR; - - arniadb_err_file[0] = '\0'; - - if ((dbname = nv_get_val (req, "dbname")) == NULL) - { - strcpy (_dbmt_error, "database name"); - return ERR_PARAM_MISSING; - } - - /* add both & SA & CS mode. */ - bothclientserver = nv_get_val (req, "both"); - - /* - * check the running mode of current database, - * return error if it is DB_SERVICE_MODE_SA. - */ - db_mode = uDatabaseMode (dbname, &ha_mode); - if (db_mode == DB_SERVICE_MODE_SA) - { - sprintf (_dbmt_error, "%s", dbname); - return ERR_STANDALONE_MODE; - } - - arniadb_cmd_name (cmd_name); - argv[argc++] = cmd_name; - argv[argc++] = UTIL_OPTION_PARAMDUMP; - if (db_mode == DB_SERVICE_MODE_NONE) - { - argv[argc++] = "--" PARAMDUMP_SA_MODE_L; - } - else - { - argv[argc++] = "--" PARAMDUMP_CS_MODE_L; - } - - if (uStringEqual (bothclientserver, "y")) - { - argv[argc++] = "--" PARAMDUMP_BOTH_L; - } - - if (ha_mode != 0) - { - append_host_to_dbname (dbname_at_hostname, dbname, sizeof (dbname_at_hostname)); - argv[argc++] = dbname_at_hostname; - } - else - { - argv[argc++] = dbname; - } - - argv[argc++] = NULL; - - snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", sco.dbmt_tmp_dir, "paramdump", getpid ()); - - /* - * create a new tmp file to record the content - * that returned by plandump. - */ - snprintf (tmpfilepath, PATH_MAX - 1, "%s/DBMT_task_%d.%d", sco.dbmt_tmp_dir, TS_PARAMDUMP, (int) getpid ()); - - if (run_child (argv, 1, NULL, tmpfilepath, arniadb_err_file, NULL) < 0) /* paramdump */ - { - strcpy (_dbmt_error, argv[0]); - retval = ERR_SYSTEM_CALL; - goto rm_tmpfile; - } - - if (read_error_file (arniadb_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) - { - retval = ERR_WITH_MSG; - goto rm_tmpfile; - } - - /* add dbname to response. */ - nv_add_nvp (res, "dbname", dbname); - - if ((infile = fopen (tmpfilepath, "r")) == NULL) - { - retval = ERR_TMPFILE_OPEN_FAIL; - goto rm_tmpfile; - } - - /* add file content to response line by line. */ - if (file_to_nvp_by_separator (infile, res, '=') < 0) - { - const char *tmperr = "Can't parse tmpfile of paramdump."; - strncpy (_dbmt_error, tmperr, strlen (tmperr)); - retval = ERR_WITH_MSG; - fclose (infile); - goto rm_tmpfile; - } - /* close tmp file. */ - fclose (infile); - -rm_tmpfile: - unlink (tmpfilepath); - if (access (arniadb_err_file, F_OK) == 0) - { - unlink (arniadb_err_file); - } - return retval; -} - -int -ts_optimizedb (nvplist *req, nvplist *res, char *_dbmt_error) -{ - return cm_ts_optimizedb (req, res, _dbmt_error); -} - -int -ts_checkdb (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; - char cmd_name[ARNIADB_CMD_NAME_LEN]; - char task_name[TASKNAME_LEN]; - const char *argv[7]; - T_DB_SERVICE_MODE db_mode; - - int ha_mode = 0; - int argc = 0; - int retval = 0; - - char *dbname = NULL; - char *repair_db = NULL; - - dbname_at_hostname[0] = '\0'; - cmd_name[0] = '\0'; - - if ((repair_db = nv_get_val (req, "repairdb")) == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "repairdb"); - return ERR_PARAM_MISSING; - } - - if ((dbname = nv_get_val (req, "dbname")) == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "dbname"); - return ERR_PARAM_MISSING; - } - if (_isRegisteredDB (dbname) == 0) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", dbname); - return ERR_DB_NONEXISTANT; - } - - db_mode = uDatabaseMode (dbname, &ha_mode); - if (db_mode == DB_SERVICE_MODE_SA) - { - sprintf (_dbmt_error, "%s", dbname); - return ERR_STANDALONE_MODE; - } - - arniadb_cmd_name (cmd_name); - argv[argc++] = cmd_name; - argv[argc++] = UTIL_OPTION_CHECKDB; - if (db_mode == DB_SERVICE_MODE_NONE) - { - argv[argc++] = "--" CHECK_SA_MODE_L; - } - else - { - argv[argc++] = "--" CHECK_CS_MODE_L; - } - - if (uStringEqual (repair_db, "y")) - { - argv[argc++] = "--" CHECK_REPAIR_L; - } - - if (ha_mode != 0) - { - append_host_to_dbname (dbname_at_hostname, dbname, - sizeof (dbname_at_hostname)); - argv[argc++] = dbname_at_hostname; - } - else - { - argv[argc++] = dbname; - } - - argv[argc++] = NULL; - - strncpy (task_name, "checkdb", TASKNAME_LEN); - retval = _run_child (argv, 1, task_name, NULL, _dbmt_error); - - return retval; -} - -int -ts_statdump (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char *dbname; - char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; - int ha_mode = 0; - T_CM_DB_EXEC_STAT exec_stat; - T_CM_ERROR err_buf; - int retval = -1; - T_DB_SERVICE_MODE db_mode; - - memset (&exec_stat, 0, sizeof (T_CM_DB_EXEC_STAT)); - memset (&err_buf, 0, sizeof (T_CM_ERROR)); - - /* check the parameters of input. */ - if ((dbname = nv_get_val (req, "dbname")) == NULL) - { - strcpy (_dbmt_error, "dbname"); - retval = ERR_PARAM_MISSING; - goto statdump_finale; - } - - /* check the database mode. */ - db_mode = uDatabaseMode (dbname, &ha_mode); - if (db_mode == DB_SERVICE_MODE_SA) - { - sprintf (_dbmt_error, "%s", dbname); - retval = ERR_STANDALONE_MODE; - goto statdump_finale; - } - - if (ha_mode != 0) - { - append_host_to_dbname (dbname_at_hostname, dbname, sizeof (dbname_at_hostname)); - retval = cm_get_db_exec_stat (dbname_at_hostname, &exec_stat, &err_buf); - } - else - { - retval = cm_get_db_exec_stat (dbname, &exec_stat, &err_buf); - } - - /* call cm_get_db_exec_stat to get stat infomation. */ - if (retval < 0) - { - /* return error with message if the operation is not success. */ - strcpy (_dbmt_error, err_buf.err_msg); - retval = ERR_WITH_MSG; - goto statdump_finale; - } - - /* set res with parameter in exec_stat. */ - nv_add_nvp (res, "dbname", dbname); - ts_add_nvp_time (res, "time", time (NULL), "%04d/%02d/%02d %02d:%02d:%02d", TIME_STR_FMT_DATE_TIME); - - /* Execution statistics for the file io */ - nv_add_nvp_int (res, "num_file_creates", exec_stat.file_num_creates); - nv_add_nvp_int (res, "num_file_removes", exec_stat.file_num_removes); - nv_add_nvp_int (res, "num_file_ioreads", exec_stat.file_num_ioreads); - nv_add_nvp_int (res, "num_file_iowrites", exec_stat.file_num_iowrites); - nv_add_nvp_int (res, "num_file_iosynches", exec_stat.file_num_iosynches); - nv_add_nvp_int (res, "num_file_page_allocs", exec_stat.file_num_page_allocs); - nv_add_nvp_int (res, "num_file_page_deallocs", exec_stat.file_num_page_deallocs); - - /* Execution statistics for the page buffer manager */ - nv_add_nvp_int (res, "num_data_page_fetches", exec_stat.pb_num_fetches); - nv_add_nvp_int (res, "num_data_page_dirties", exec_stat.pb_num_dirties); - nv_add_nvp_int (res, "num_data_page_ioreads", exec_stat.pb_num_ioreads); - nv_add_nvp_int (res, "num_data_page_iowrites", exec_stat.pb_num_iowrites); - - /* Execution statistics for the log manager */ - nv_add_nvp_int (res, "num_log_page_ioreads", exec_stat.log_num_ioreads); - nv_add_nvp_int (res, "num_log_page_iowrites", exec_stat.log_num_iowrites); - nv_add_nvp_int (res, "num_log_append_records", exec_stat.log_num_appendrecs); - nv_add_nvp_int (res, "num_log_archives", exec_stat.log_num_archives); -#if 0 //no use - nv_add_nvp_int (res, "num_log_start_checkpoints", exec_stat.log_num_start_checkpoints); - nv_add_nvp_int (res, "num_log_end_checkpoints", exec_stat.log_num_end_checkpoints); -#endif - nv_add_nvp_int (res, "num_log_wals", exec_stat.log_num_wals); - - /* Execution statistics for the lock manager */ - nv_add_nvp_int (res, "num_page_locks_acquired", exec_stat.lk_num_acquired_on_pages); - nv_add_nvp_int (res, "num_object_locks_acquired", exec_stat.lk_num_acquired_on_objects); - nv_add_nvp_int (res, "num_page_locks_converted", exec_stat.lk_num_converted_on_pages); - nv_add_nvp_int (res, "num_object_locks_converted", exec_stat.lk_num_converted_on_objects); - nv_add_nvp_int (res, "num_page_locks_re_requested", exec_stat.lk_num_re_requested_on_pages); - nv_add_nvp_int (res, "num_object_locks_re_requested", exec_stat.lk_num_re_requested_on_objects); - nv_add_nvp_int (res, "num_page_locks_waits", exec_stat.lk_num_waited_on_pages); - nv_add_nvp_int (res, "num_object_locks_waits", exec_stat.lk_num_waited_on_objects); - - /* Execution statistics for transactions */ - nv_add_nvp_int (res, "num_tran_commits", exec_stat.tran_num_commits); - nv_add_nvp_int (res, "num_tran_rollbacks", exec_stat.tran_num_rollbacks); - nv_add_nvp_int (res, "num_tran_savepoints", exec_stat.tran_num_savepoints); - nv_add_nvp_int (res, "num_tran_start_topops", exec_stat.tran_num_start_topops); - nv_add_nvp_int (res, "num_tran_end_topops", exec_stat.tran_num_end_topops); - nv_add_nvp_int (res, "num_tran_interrupts", exec_stat.tran_num_interrupts); - - /* Execution statistics for the btree manager */ - nv_add_nvp_int (res, "num_btree_inserts", exec_stat.bt_num_inserts); - nv_add_nvp_int (res, "num_btree_deletes", exec_stat.bt_num_deletes); - nv_add_nvp_int (res, "num_btree_updates", exec_stat.bt_num_updates); - nv_add_nvp_int (res, "num_btree_covered", exec_stat.bt_num_covered); - nv_add_nvp_int (res, "num_btree_noncovered", exec_stat.bt_num_noncovered); - nv_add_nvp_int (res, "num_btree_resumes", exec_stat.bt_num_resumes); - nv_add_nvp_int (res, "num_btree_multirange_optimization", exec_stat.bt_num_multi_range_opt); - nv_add_nvp_int (res, "num_btree_splits", exec_stat.bt_num_splits); - nv_add_nvp_int (res, "num_btree_merges", exec_stat.bt_num_merges); - nv_add_nvp_int (res, "num_btree_get_stats", exec_stat.bt_num_get_stats); - - /* Execution statistics for the query manager */ - nv_add_nvp_int (res, "num_query_selects", exec_stat.qm_num_selects); - nv_add_nvp_int (res, "num_query_inserts", exec_stat.qm_num_inserts); - nv_add_nvp_int (res, "num_query_deletes", exec_stat.qm_num_deletes); - nv_add_nvp_int (res, "num_query_updates", exec_stat.qm_num_updates); - nv_add_nvp_int (res, "num_query_sscans", exec_stat.qm_num_sscans); - nv_add_nvp_int (res, "num_query_iscans", exec_stat.qm_num_iscans); - nv_add_nvp_int (res, "num_query_lscans", exec_stat.qm_num_lscans); - nv_add_nvp_int (res, "num_query_setscans", exec_stat.qm_num_setscans); - nv_add_nvp_int (res, "num_query_methscans", exec_stat.qm_num_methscans); - nv_add_nvp_int (res, "num_query_nljoins", exec_stat.qm_num_nljoins); - nv_add_nvp_int (res, "num_query_mjoins", exec_stat.qm_num_mjoins); - nv_add_nvp_int (res, "num_query_objfetches", exec_stat.qm_num_objfetches); - nv_add_nvp_int (res, "num_query_holdable_cursors", exec_stat.qm_num_holdable_cursors); - - /* Execution statistics for external sort */ - nv_add_nvp_int (res, "num_sort_io_pages", exec_stat.sort_num_io_pages); - nv_add_nvp_int (res, "num_sort_data_pages", exec_stat.sort_num_data_pages); - - /* Execution statistics for network communication */ - nv_add_nvp_int (res, "num_network_requests", exec_stat.net_num_requests); - - /* flush control stat */ - nv_add_nvp_int (res, "num_adaptive_flush_pages", exec_stat.fc_num_pages); - nv_add_nvp_int (res, "num_adaptive_flush_log_pages", exec_stat.fc_num_log_pages); - nv_add_nvp_int (res, "num_adaptive_flush_max_pages", exec_stat.fc_tokens); - - /* prior lsa info */ - nv_add_nvp_int (res, "num_prior_lsa_list_size", exec_stat.prior_lsa_list_size); - nv_add_nvp_int (res, "num_prior_lsa_list_maxed", exec_stat.prior_lsa_list_maxed); - nv_add_nvp_int (res, "num_prior_lsa_list_removed", exec_stat.prior_lsa_list_removed); - - /* best space info */ - nv_add_nvp_int (res, "num_heap_stats_bestspace_entries", exec_stat.hf_stats_bestspace_entries); - nv_add_nvp_int (res, "num_heap_stats_bestspace_maxed", exec_stat.hf_stats_bestspace_maxed); - - /* HA replication delay */ - nv_add_nvp_int (res, "time_ha_replication_delay", exec_stat.ha_repl_delay); - - /* Execution statistics for Plan cache */ - nv_add_nvp_int (res, "num_plan_cache_add", exec_stat.pc_num_add); - nv_add_nvp_int (res, "num_plan_cache_lookup", exec_stat.pc_num_lookup); - nv_add_nvp_int (res, "num_plan_cache_hit", exec_stat.pc_num_hit); - nv_add_nvp_int (res, "num_plan_cache_miss", exec_stat.pc_num_miss); - nv_add_nvp_int (res, "num_plan_cache_full", exec_stat.pc_num_full); - nv_add_nvp_int (res, "num_plan_cache_delete", exec_stat.pc_num_delete); - nv_add_nvp_int (res, "num_plan_cache_invalid_xasl_id", exec_stat.pc_num_invalid_xasl_id); - nv_add_nvp_int (res, "num_plan_cache_query_string_hash_entries", exec_stat.pc_num_query_string_hash_entries); - nv_add_nvp_int (res, "num_plan_cache_xasl_id_hash_entries", exec_stat.pc_num_xasl_id_hash_entries); - nv_add_nvp_int (res, "num_plan_cache_class_oid_hash_entries", exec_stat.pc_num_class_oid_hash_entries); - - /* Other statistics */ - nv_add_nvp_int (res, "data_page_buffer_hit_ratio", exec_stat.pb_hit_ratio); - - retval = ERR_NO_ERROR; - -statdump_finale: - return retval; -} - -int -ts_compactdb (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char cmd_name[ARNIADB_CMD_NAME_LEN]; - char out_file[PATH_MAX]; - char err_file[PATH_MAX]; - - const char *argv[10]; - T_DB_SERVICE_MODE db_mode; - - int exit_code = 0; - int argc = 0; - int retval = ERR_NO_ERROR; - int createtmpfile = 0; - - char *dbname = NULL; - char *verbose = NULL; - - cmd_name[0] = '\0'; - out_file[0] = '\0'; - err_file[0] = '\0'; - - dbname = nv_get_val (req, "dbname"); - if (dbname == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "dbname"); - return ERR_PARAM_MISSING; - } - if (_isRegisteredDB (dbname) == 0) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", dbname); - return ERR_DB_NONEXISTANT; - } - - verbose = nv_get_val (req, "verbose"); - if (verbose == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "verbose"); - return ERR_PARAM_MISSING; - } - - db_mode = uDatabaseMode (dbname, NULL); - if (db_mode == DB_SERVICE_MODE_SA) - { - sprintf (_dbmt_error, "%s", dbname); - return ERR_STANDALONE_MODE; - } - - arniadb_cmd_name (cmd_name); - argv[argc++] = cmd_name; - argv[argc++] = UTIL_OPTION_COMPACTDB; - if (uStringEqual (verbose, "y")) - { - argv[argc++] = "--" COMPACT_VERBOSE_L; - createtmpfile = 1; - } - - if (db_mode == DB_SERVICE_MODE_CS) - { - argv[argc++] = "--" COMPACT_CS_MODE_L; - } - else if (db_mode == DB_SERVICE_MODE_NONE) - { - argv[argc++] = "--" COMPACT_SA_MODE_L; - } - - argv[argc++] = dbname; - argv[argc++] = NULL; - - if (createtmpfile != 0) - { - snprintf (out_file, PATH_MAX, "%s/DBMT_task_%d.%d", - sco.dbmt_tmp_dir, TS_COMPACTDB, (int) getpid ()); - } - else - { - snprintf (out_file, PATH_MAX, "%s/%s.%u.out.tmp", - sco.dbmt_tmp_dir, "compactdb", getpid ()); - } - - snprintf (err_file, PATH_MAX, "%s/%s.%u.err.tmp", - sco.dbmt_tmp_dir, "compactdb", getpid ()); - - if (run_child (argv, 1, NULL, out_file, err_file, &exit_code) < 0) - { - /* compactdb */ - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", argv[0]); - retval = ERR_SYSTEM_CALL; - goto rm_tmpfile; - } - - if (read_error_file (err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) - { - retval = ERR_WITH_MSG; - goto rm_tmpfile; - } - - if (exit_code != EXIT_SUCCESS) - { - read_stdout_stderr_as_err (out_file, NULL, _dbmt_error); - retval = ERR_WITH_MSG; - goto rm_tmpfile; - } - - if (createtmpfile != 0) - { - nv_add_nvp (res, "open", "log"); - /* add file content to response line by line. */ - if (file_to_nvpairs (out_file, res) < 0) - { - retval = ERR_TMPFILE_OPEN_FAIL; - } - nv_add_nvp (res, "close", "log"); - } - -rm_tmpfile: - unlink (out_file); - unlink (err_file); - return retval; -} - -int -ts_backupdb (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char *dbname, *level, *removelog, *volname, *backupdir, *check; - char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; - int ha_mode = 0; - char *mt, *zip, *safe_replication; - char backupfilepath[PATH_MAX]; - char inputfilepath[PATH_MAX]; - char cmd_name[ARNIADB_CMD_NAME_LEN]; - char sp_option[256]; - const char *argv[16]; - int argc = 0; - FILE *inputfile; - T_DB_SERVICE_MODE db_mode; - char arniadb_err_file[PATH_MAX]; - - arniadb_err_file[0] = '\0'; - - if ((dbname = nv_get_val (req, "dbname")) == NULL) - { - strcpy (_dbmt_error, "database name"); - return ERR_PARAM_MISSING; - } - - db_mode = uDatabaseMode (dbname, &ha_mode); - if (db_mode == DB_SERVICE_MODE_SA) - { - sprintf (_dbmt_error, "%s", dbname); - return ERR_STANDALONE_MODE; - } - level = nv_get_val (req, "level"); - volname = nv_get_val (req, "volname"); - backupdir = nv_get_val (req, "backupdir"); - removelog = nv_get_val (req, "removelog"); - check = nv_get_val (req, "check"); - mt = nv_get_val (req, "mt"); - zip = nv_get_val (req, "zip"); - safe_replication = nv_get_val (req, "safereplication"); - - if (backupdir == NULL) - { - strcpy (_dbmt_error, "backupdir"); - return ERR_PARAM_MISSING; - } - - snprintf (backupfilepath, PATH_MAX - 1, "%s/%s", backupdir, volname); - - /* create directory */ - if (access (backupfilepath, F_OK) < 0) - { - if (uCreateDir (backupfilepath) != ERR_NO_ERROR) - { - strcpy (_dbmt_error, backupfilepath); - return ERR_DIR_CREATE_FAIL; - } - } - - arniadb_cmd_name (cmd_name); - argv[argc++] = cmd_name; - argv[argc++] = UTIL_OPTION_BACKUPDB; - if (db_mode == DB_SERVICE_MODE_NONE) - { - argv[argc++] = "--" BACKUP_SA_MODE_L; - } - else - { - argv[argc++] = "--" BACKUP_CS_MODE_L; - } - argv[argc++] = "--" BACKUP_LEVEL_L; - argv[argc++] = level; - argv[argc++] = "--" BACKUP_DESTINATION_PATH_L; - argv[argc++] = backupfilepath; - if (uStringEqual (removelog, "y")) - { - argv[argc++] = "--" BACKUP_REMOVE_ARCHIVE_L; - } - if (uStringEqual (check, "n")) - { - argv[argc++] = "--" BACKUP_NO_CHECK_L; - } - if (mt != NULL) - { - argv[argc++] = "--" BACKUP_THREAD_COUNT_L; - argv[argc++] = mt; - } - if (zip != NULL && uStringEqual (zip, "y")) - { - argv[argc++] = "--" BACKUP_COMPRESS_L; - } - - if (safe_replication != NULL && uStringEqual (safe_replication, "y")) - { - snprintf (sp_option, sizeof (sp_option) - 1, - "--safe-page-id `repl_safe_page %s`", dbname); - argv[argc++] = sp_option; - } - - if (ha_mode != 0) - { - append_host_to_dbname (dbname_at_hostname, dbname, - sizeof (dbname_at_hostname)); - argv[argc++] = dbname_at_hostname; - } - else - { - argv[argc++] = dbname; - } - - argv[argc++] = NULL; - - snprintf (inputfilepath, PATH_MAX - 1, "%s/DBMT_task_%d.%d", - sco.dbmt_tmp_dir, TS_BACKUPDB, (int) getpid ()); - inputfile = fopen (inputfilepath, "w"); - if (inputfile) - { - fprintf (inputfile, "y"); - fclose (inputfile); - } - else - { - return ERR_FILE_OPEN_FAIL; - } - - snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", - sco.dbmt_tmp_dir, "backupdb", getpid ()); - - if (run_child (argv, 1, inputfilepath, NULL, arniadb_err_file, NULL) < 0) - { - /* backupdb */ - strcpy (_dbmt_error, argv[0]); - unlink (inputfilepath); - if (access (arniadb_err_file, F_OK) == 0) - { - unlink (arniadb_err_file); - } - return ERR_SYSTEM_CALL; - } - - unlink (inputfilepath); - - if (read_error_file (arniadb_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) - { - if (access (arniadb_err_file, F_OK) == 0) - { - unlink (arniadb_err_file); - } - return ERR_WITH_MSG; - } - - if (access (arniadb_err_file, F_OK) == 0) - { - unlink (arniadb_err_file); - } - return ERR_NO_ERROR; -} - -int -ts_unloaddb (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char *dbname, *targetdir, *usehash, *hashdir, *target, *s1, *s2, - *ref, *classonly, *delimit, *estimate, *prefix, *cach, *lofile, - buf[PATH_MAX], infofile[PATH_MAX], tmpfile[PATH_MAX], temp[PATH_MAX], - n[256], v[256], cname[256], p1[64], p2[8], p3[8]; - - char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; - int ha_mode = 0; - char cmd_name[ARNIADB_CMD_NAME_LEN]; - char arniadb_err_file[PATH_MAX]; - FILE *infile, *outfile; - int i, flag = 0, no_class = 0, index_exist = 0, trigger_exist = 0; - struct stat statbuf; - const char *argv[30]; - int argc = 0; - T_DB_SERVICE_MODE db_mode; - char fullpath[PATH_MAX]; - char dba_user[32] = "dba"; - char *dbuser = NULL; - char *dbpasswd = NULL; - - arniadb_err_file[0] = '\0'; - - dbname = nv_get_val (req, "dbname"); - if (dbname == NULL) - { - strcpy (_dbmt_error, "database name"); - return ERR_PARAM_MISSING; - } - - targetdir = nv_get_val (req, "targetdir"); - usehash = nv_get_val (req, "usehash"); - hashdir = nv_get_val (req, "hashdir"); - target = nv_get_val (req, "target"); - ref = nv_get_val (req, "ref"); - classonly = nv_get_val (req, "classonly"); - delimit = nv_get_val (req, "delimit"); - estimate = nv_get_val (req, "estimate"); - prefix = nv_get_val (req, "prefix"); - cach = nv_get_val (req, "cach"); - lofile = nv_get_val (req, "lofile"); - dbuser = nv_get_val (req, "dbuser"); - dbpasswd = nv_get_val (req, "dbpasswd"); - - if (target == NULL) - { - strcpy (_dbmt_error, "target"); - return ERR_PARAM_MISSING; - } - - db_mode = uDatabaseMode (dbname, &ha_mode); - if (db_mode == DB_SERVICE_MODE_SA) - { - sprintf (_dbmt_error, "%s", dbname); - return ERR_STANDALONE_MODE; - } - - if (targetdir == NULL) - { - strcpy (_dbmt_error, "targetdir"); - return ERR_PARAM_MISSING; - } - - if (strcmp (targetdir, "+D") == 0) - { - snprintf (fullpath, sizeof (fullpath) - 1, "%s/files/", sco.szCWMPath); - } - else - { - snprintf (fullpath, sizeof (fullpath) - 1, "%s", targetdir); - } - - if (access (fullpath, F_OK) < 0) - { - if (uCreateDir (fullpath) != ERR_NO_ERROR) - { - strcpy (_dbmt_error, targetdir); - return ERR_DIR_CREATE_FAIL; - } - } - - /* Verify password for dbuser */ - if (dbuser == NULL) - { - dbuser = dba_user; - } - if (_verify_user_passwd (dbname, dbuser, dbpasswd, _dbmt_error) != ERR_NO_ERROR) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, - "Invalid password or missing password for database(%s): dbuser(%s).", dbname, dbuser); - return ERR_WITH_MSG; - } - /* makeup upload class list file */ - snprintf (tmpfile, PATH_MAX - 1, "%s/DBMT_task_101.%d", sco.dbmt_tmp_dir, (int) getpid ()); - if ((outfile = fopen (tmpfile, "w")) == NULL) - { - return ERR_TMPFILE_OPEN_FAIL; - } - for (i = 0; i < req->nvplist_leng; i++) - { - nv_lookup (req, i, &s1, &s2); - if (s1 == NULL) - { - continue; - } - - if (!strcmp (s1, "open")) - { - flag = 1; - } - else if (!strcmp (s1, "close")) - { - flag = 0; - } - else if (flag == 1 && !strcmp (s1, "classname")) - { - snprintf (buf, sizeof (buf) - 1, "%s\n", s2); - fputs (buf, outfile); - no_class++; - } - } - fclose (outfile); - - /* makeup command and execute */ - arniadb_cmd_name (cmd_name); - argv[argc++] = cmd_name; - argv[argc++] = UTIL_OPTION_UNLOADDB; - if (db_mode == DB_SERVICE_MODE_NONE) - { - argv[argc++] = "--" UNLOAD_SA_MODE_L; - } - else - { - argv[argc++] = "--" UNLOAD_CS_MODE_L; - } - if (no_class > 0) - { - argv[argc++] = "--" UNLOAD_INPUT_CLASS_FILE_L; - argv[argc++] = tmpfile; - } - argv[argc++] = "--" UNLOAD_OUTPUT_PATH_L; - argv[argc++] = fullpath; - if ((usehash != NULL) && (strcmp (usehash, "yes") == 0)) - { - argv[argc++] = "--" UNLOAD_HASH_FILE_L; - argv[argc++] = hashdir; - } - - if (strcmp (target, "both") == 0) - { - argv[argc++] = "--" UNLOAD_SCHEMA_ONLY_L; - argv[argc++] = "--" UNLOAD_DATA_ONLY_L; - } - else if (strcmp (target, "schema") == 0) - { - argv[argc++] = "--" UNLOAD_SCHEMA_ONLY_L; - } - else if (strcmp (target, "object") == 0) - { - argv[argc++] = "--" UNLOAD_DATA_ONLY_L; - } - - if (uStringEqual (ref, "yes")) - { - argv[argc++] = "--" UNLOAD_INCLUDE_REFERENCE_L; - } - if (uStringEqual (classonly, "yes")) - { - argv[argc++] = "--" UNLOAD_INPUT_CLASS_ONLY_L; - } - if (uStringEqual (delimit, "yes")) - { - argv[argc++] = "--" UNLOAD_USE_DELIMITER_L; - } - if (estimate != NULL && !uStringEqual (estimate, "none")) - { - argv[argc++] = "--" UNLOAD_ESTIMATED_SIZE_L; - argv[argc++] = estimate; - } - if (prefix != NULL && !uStringEqual (prefix, "none")) - { - argv[argc++] = "--" UNLOAD_OUTPUT_PREFIX_L; - argv[argc++] = prefix; - } - if (cach != NULL && !uStringEqual (cach, "none")) - { - argv[argc++] = "--" UNLOAD_CACHED_PAGES_L; - argv[argc++] = cach; - } - if (lofile != NULL && !uStringEqual (lofile, "none")) - { - argv[argc++] = "--" UNLOAD_LO_COUNT_L; - argv[argc++] = lofile; - } - - if (ha_mode != 0) - { - append_host_to_dbname (dbname_at_hostname, dbname, - sizeof (dbname_at_hostname)); - argv[argc++] = dbname_at_hostname; - } - else - { - argv[argc++] = dbname; - } - - argv[argc++] = "--" UNLOAD_USER_L; - argv[argc++] = dbuser; - - if (dbpasswd != NULL) - { - argv[argc++] = "--" UNLOAD_PASSWORD_L; - argv[argc++] = dbpasswd; - } - - argv[argc++] = NULL; - - snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", - sco.dbmt_tmp_dir, "unloaddb", getpid ()); - - if (run_child (argv, 1, NULL, NULL, arniadb_err_file, NULL) < 0) - { - /* unloaddb */ - strcpy (_dbmt_error, argv[0]); - unlink (tmpfile); - if (access (arniadb_err_file, F_OK) == 0) - { - unlink (arniadb_err_file); - } - return ERR_SYSTEM_CALL; - } - - if (read_error_file (arniadb_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) - { - unlink (tmpfile); - if (access (arniadb_err_file, F_OK) == 0) - { - unlink (arniadb_err_file); - } - return ERR_WITH_MSG; - } - if (access (arniadb_err_file, F_OK) == 0) - { - unlink (arniadb_err_file); - } - unlink (tmpfile); - - /* makeup upload result information in unload.log file */ - snprintf (buf, sizeof (buf) - 1, "%s_unloaddb.log", dbname); - nv_add_nvp (res, "open", "result"); - if ((infile = fopen (buf, "rt")) != NULL) - { - flag = 0; - while (fgets (buf, sizeof (buf), infile)) - { - if (buf[0] == '-') - { - flag++; - } - else if (flag == 2 && - sscanf (buf, "%255s %*s %63s %7s %*s %7s", cname, p1, p2, p3) == 4) - { - snprintf (buf, sizeof (buf) - 1, "%s %s/%s", p1, p2, p3); - nv_add_nvp (res, cname, buf); - } - } - fclose (infile); - } - nv_add_nvp (res, "close", "result"); - unlink ("unload.log"); - - /* save uploaded result file to 'unloaddb.info' file */ - flag = 0; - snprintf (infofile, PATH_MAX - 1, "%s/unloaddb.info", - sco.szArniadb_databases); - if ((infile = fopen (infofile, "rt")) == NULL) - { - outfile = fopen (infofile, "w"); - if (outfile == NULL) - { - strcpy (_dbmt_error, infofile); - return ERR_FILE_OPEN_FAIL; - } - - snprintf (buf, sizeof (buf) - 1, "%% %s\n", dbname); - fputs (buf, outfile); - - if (!strcmp (target, "both")) - { - fprintf (outfile, "schema %s/%s%s\n", targetdir, dbname, - ARNIADB_UNLOAD_EXT_SCHEMA); - fprintf (outfile, "object %s/%s%s\n", targetdir, dbname, - ARNIADB_UNLOAD_EXT_OBJ); - } - else if (!strcmp (target, "schema")) - { - fprintf (outfile, "schema %s/%s%s\n", targetdir, dbname, - ARNIADB_UNLOAD_EXT_SCHEMA); - } - else if (!strcmp (target, "object")) - { - fprintf (outfile, "object %s/%s%s\n", targetdir, dbname, - ARNIADB_UNLOAD_EXT_OBJ); - } - - /* check index file and append if exist */ - snprintf (buf, sizeof (buf) - 1, "%s/%s%s", targetdir, dbname, - ARNIADB_UNLOAD_EXT_INDEX); - if (stat (buf, &statbuf) == 0) - { - fprintf (outfile, "index %s/%s%s\n", targetdir, dbname, - ARNIADB_UNLOAD_EXT_INDEX); - } - /* check trigger file and append if exist */ - snprintf (buf, sizeof (buf) - 1, "%s/%s%s", targetdir, dbname, - ARNIADB_UNLOAD_EXT_TRIGGER); - if (stat (buf, &statbuf) == 0) - { - fprintf (outfile, "trigger %s/%s%s\n", targetdir, dbname, - ARNIADB_UNLOAD_EXT_TRIGGER); - } - fclose (outfile); - } - else - { - snprintf (tmpfile, PATH_MAX - 1, "%s/DBMT_task_102.%d", - sco.dbmt_tmp_dir, (int) getpid ()); - outfile = fopen (tmpfile, "w"); - if (outfile == NULL) - { - fclose (infile); - strcpy (_dbmt_error, tmpfile); - return ERR_TMPFILE_OPEN_FAIL; - } - - while (fgets (buf, sizeof (buf), infile)) - { - if (sscanf (buf, "%255s %255s", n, v) != 2) - { - fputs (buf, outfile); - continue; - } - if (!strcmp (n, "%") && !strcmp (v, dbname)) - { - fputs (buf, outfile); - - if (!strcmp (target, "both")) - { - fprintf (outfile, "schema %s/%s%s\n", targetdir, dbname, - ARNIADB_UNLOAD_EXT_SCHEMA); - fprintf (outfile, "object %s/%s%s\n", targetdir, dbname, - ARNIADB_UNLOAD_EXT_OBJ); - } - else if (!strcmp (target, "schema")) - { - fprintf (outfile, "schema %s/%s%s\n", targetdir, dbname, - ARNIADB_UNLOAD_EXT_SCHEMA); - } - else if (!strcmp (target, "object")) - { - fprintf (outfile, "object %s/%s%s\n", targetdir, dbname, - ARNIADB_UNLOAD_EXT_OBJ); - } - - /* check index file and append if exist */ - snprintf (temp, PATH_MAX - 1, "%s/%s%s", targetdir, dbname, - ARNIADB_UNLOAD_EXT_INDEX); - if (stat (temp, &statbuf) == 0) - { - fprintf (outfile, "index %s/%s%s\n", targetdir, dbname, - ARNIADB_UNLOAD_EXT_INDEX); - index_exist = 1; - } - /* check trigger file and append if exist */ - snprintf (temp, PATH_MAX - 1, "%s/%s%s", targetdir, dbname, - ARNIADB_UNLOAD_EXT_TRIGGER); - if (stat (temp, &statbuf) == 0) - { - fprintf (outfile, "trigger %s/%s%s\n", targetdir, dbname, - ARNIADB_UNLOAD_EXT_TRIGGER); - trigger_exist = 1; - } - flag = 1; - continue; - } - if (!strcmp (target, "both") || !strcmp (target, "schema")) - { - snprintf (temp, PATH_MAX - 1, "%s/%s%s", targetdir, dbname, - ARNIADB_UNLOAD_EXT_SCHEMA); - if (!strcmp (n, "schema") && !strcmp (v, temp)) - { - continue; - } - } - if (!strcmp (target, "both") || !strcmp (target, "object")) - { - snprintf (temp, PATH_MAX - 1, "%s/%s%s", targetdir, dbname, - ARNIADB_UNLOAD_EXT_OBJ); - if (!strcmp (n, "object") && !strcmp (v, temp)) - { - continue; - } - } - if (index_exist) - { - snprintf (temp, PATH_MAX - 1, "%s/%s%s", targetdir, dbname, - ARNIADB_UNLOAD_EXT_INDEX); - if (!strcmp (n, "index") && !strcmp (v, temp)) - { - continue; - } - } - if (trigger_exist) - { - snprintf (temp, PATH_MAX - 1, "%s/%s%s", targetdir, dbname, - ARNIADB_UNLOAD_EXT_TRIGGER); - if (!strcmp (n, "trigger") && !strcmp (v, temp)) - { - continue; - } - } - fputs (buf, outfile); - } /* end of while(fgets()) */ - if (flag == 0) - { - fprintf (outfile, "%% %s\n", dbname); - if (!strcmp (target, "both")) - { - fprintf (outfile, "schema %s/%s%s\n", targetdir, dbname, - ARNIADB_UNLOAD_EXT_SCHEMA); - fprintf (outfile, "object %s/%s%s\n", targetdir, dbname, - ARNIADB_UNLOAD_EXT_OBJ); - } - else if (!strcmp (target, "schema")) - { - fprintf (outfile, "schema %s/%s%s\n", targetdir, dbname, - ARNIADB_UNLOAD_EXT_SCHEMA); - } - else if (!strcmp (target, "object")) - { - fprintf (outfile, "object %s/%s%s\n", targetdir, dbname, - ARNIADB_UNLOAD_EXT_OBJ); - } - /* check index file and append if exist */ - snprintf (temp, PATH_MAX - 1, "%s/%s%s", targetdir, dbname, - ARNIADB_UNLOAD_EXT_INDEX); - if (stat (temp, &statbuf) == 0) - { - fprintf (outfile, "index %s/%s%s\n", targetdir, dbname, - ARNIADB_UNLOAD_EXT_INDEX); - index_exist = 1; - } - /* check trigger file and append if exist */ - snprintf (temp, PATH_MAX - 1, "%s/%s%s", targetdir, dbname, - ARNIADB_UNLOAD_EXT_TRIGGER); - if (stat (temp, &statbuf) == 0) - { - fprintf (outfile, "trigger %s/%s%s\n", targetdir, dbname, - ARNIADB_UNLOAD_EXT_TRIGGER); - trigger_exist = 1; - } - } - fclose (infile); - fclose (outfile); - - /* copyback */ - infile = fopen (tmpfile, "rt"); - if (infile == NULL) - { - strcpy (_dbmt_error, tmpfile); - return ERR_TMPFILE_OPEN_FAIL; - } - - outfile = fopen (infofile, "w"); - if (outfile == NULL) - { - strcpy (_dbmt_error, infofile); - fclose (infile); - return ERR_FILE_OPEN_FAIL; - } - - while (fgets (buf, sizeof (buf), infile)) - { - fputs (buf, outfile); - } - fclose (infile); - fclose (outfile); - unlink (tmpfile); - } /* end of if */ - - return ERR_NO_ERROR; -} - -int -ts_loaddb (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char *dbname, *checkoption, *period, *user, *schema, *object, *index, - *error_control_file, *ignore_class_file, *estimated, *oiduse, *nolog, - *statisticsuse, tmpfile[PATH_MAX]; - - T_DB_SERVICE_MODE db_mode; - char *dbuser, *dbpasswd; - char arniadb_err_file[PATH_MAX]; - int retval; - char cmd_name[ARNIADB_CMD_NAME_LEN]; - const char *argv[32]; - int argc = 0; - - arniadb_err_file[0] = '\0'; - - if ((dbname = nv_get_val (req, "_DBNAME")) == NULL) - { - sprintf (_dbmt_error, "%s", "database name"); - return ERR_PARAM_MISSING; - } - - dbuser = nv_get_val (req, "_DBID"); - dbpasswd = nv_get_val (req, "_DBPASSWD"); - checkoption = nv_get_val (req, "checkoption"); - period = nv_get_val (req, "period"); - user = nv_get_val (req, "user"); - schema = nv_get_val (req, "schema"); - object = nv_get_val (req, "object"); - index = nv_get_val (req, "index"); - error_control_file = nv_get_val (req, "errorcontrolfile"); - ignore_class_file = nv_get_val (req, "ignoreclassfile"); -#if 0 /* will be added */ - trigger = nv_get_val (req, "trigger"); -#endif - estimated = nv_get_val (req, "estimated"); - oiduse = nv_get_val (req, "oiduse"); - nolog = nv_get_val (req, "nolog"); - statisticsuse = nv_get_val (req, "statisticsuse"); - - db_mode = uDatabaseMode (dbname, NULL); - if (db_mode == DB_SERVICE_MODE_SA) - { - sprintf (_dbmt_error, "%s", dbname); - return ERR_STANDALONE_MODE; - } - else if (db_mode == DB_SERVICE_MODE_CS) - { - sprintf (_dbmt_error, "%s", dbname); - return ERR_DB_ACTIVE; - } - - snprintf (tmpfile, PATH_MAX - 1, "%s/DBMT_task_%d.%d", sco.dbmt_tmp_dir, - TS_LOADDB, (int) getpid ()); - arniadb_cmd_name (cmd_name); - - argc = 0; - argv[argc++] = cmd_name; - argv[argc++] = UTIL_OPTION_LOADDB; - - if (checkoption != NULL) - { - if (strcmp (checkoption, "syntax") == 0) - { - argv[argc++] = "--" LOAD_CHECK_ONLY_L; - } - else if (strcmp (checkoption, "load") == 0) - { - argv[argc++] = "--" LOAD_LOAD_ONLY_L; - } - } - - if (dbuser) - { - argv[argc++] = "--" LOAD_USER_L; - argv[argc++] = dbuser; - if (dbpasswd) - { - argv[argc++] = "--" LOAD_PASSWORD_L; - argv[argc++] = dbpasswd; - } - } - - /* argv[argc++] = "-v"; */ - if (period != NULL && !uStringEqual (period, "none")) - { - argv[argc++] = "--" LOAD_PERIODIC_COMMIT_L; - argv[argc++] = period; - } - - if ((schema != NULL) && (strcmp (schema, "none") != 0)) - { - argv[argc++] = "--" LOAD_SCHEMA_FILE_L; - argv[argc++] = schema; - } - - if ((object != NULL) && (strcmp (object, "none") != 0)) - { - argv[argc++] = "--" LOAD_DATA_FILE_L; - argv[argc++] = object; - } - - if ((index != NULL) && (strcmp (index, "none") != 0)) - { - argv[argc++] = "--" LOAD_INDEX_FILE_L; - argv[argc++] = index; - } - -#if 0 /* will be added */ - if (trigger != NULL && !uStringEqual (trigger, "none")) - { - argv[argc++] = "-tf"; - argv[argc++] = trigger; - } -#endif - - if (estimated != NULL && !uStringEqual (estimated, "none")) - { - argv[argc++] = "--" LOAD_ESTIMATED_SIZE_L; - argv[argc++] = estimated; - } - - if (uStringEqual (oiduse, "no")) - { - argv[argc++] = "--" LOAD_NO_OID_L; - } - - if (uStringEqual (statisticsuse, "no")) - { - argv[argc++] = "--" LOAD_NO_STATISTICS_L; - } - - if (uStringEqual (nolog, "yes")) - { - argv[argc++] = "--" LOAD_IGNORE_LOGGING_L; - } - - if (error_control_file != NULL - && !uStringEqual (error_control_file, "none")) - { - argv[argc++] = "--" LOAD_ERROR_CONTROL_FILE_L; - argv[argc++] = error_control_file; - } - - if (ignore_class_file != NULL && !uStringEqual (ignore_class_file, "none")) - { - argv[argc++] = "--" LOAD_IGNORE_CLASS_L; - argv[argc++] = ignore_class_file; - } - argv[argc++] = dbname; - argv[argc++] = NULL; - - snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", - sco.dbmt_tmp_dir, "loaddb", getpid ()); - - retval = run_child (argv, 1, NULL, tmpfile, arniadb_err_file, NULL); /* loaddb */ - if (retval < 0) - { - if (access (arniadb_err_file, F_OK) == 0) - { - unlink (arniadb_err_file); - } - strcpy (_dbmt_error, argv[0]); - return ERR_SYSTEM_CALL; - } - - if (file_to_nvpairs (tmpfile, res) < 0) - { - if (access (arniadb_err_file, F_OK) == 0) - { - unlink (arniadb_err_file); - } - strcpy (_dbmt_error, tmpfile); - return ERR_TMPFILE_OPEN_FAIL; - } - unlink (tmpfile); - - /* the error file may not exist, don't check the error of it. */ - file_to_nvpairs (arniadb_err_file, res); - - if (access (arniadb_err_file, F_OK) == 0) - { - unlink (arniadb_err_file); - } - if (uStringEqualIgnoreCase (nv_get_val (req, "delete_orignal_files"), "y")) - { - if (schema) - { - unlink (schema); - } - if (object) - { - unlink (object); - } - if (index) - { - unlink (index); - } - } - - return ERR_NO_ERROR; -} - -int -ts_restoredb (nvplist *req, nvplist *res, char *_dbmt_error) -{ - int retval = ERR_NO_ERROR; - char *dbname, *date, *lv, *pathname, *partial, *recovery_path; - char cmd_name[ARNIADB_CMD_NAME_LEN]; - const char *argv[17]; - int argc = 0; - T_DB_SERVICE_MODE db_mode; - char arniadb_err_file[PATH_MAX]; - int status; - - arniadb_err_file[0] = '\0'; - - dbname = nv_get_val (req, "dbname"); - db_mode = uDatabaseMode (dbname, NULL); - if (db_mode == DB_SERVICE_MODE_SA) - { - sprintf (_dbmt_error, "%s", dbname); - return ERR_STANDALONE_MODE; - } - else if (db_mode == DB_SERVICE_MODE_CS) - { - sprintf (_dbmt_error, "%s", dbname); - return ERR_DB_ACTIVE; - } - - date = nv_get_val (req, "date"); - lv = nv_get_val (req, "level"); - pathname = nv_get_val (req, "pathname"); - partial = nv_get_val (req, "partial"); - recovery_path = nv_get_val (req, "recoverypath"); - - arniadb_cmd_name (cmd_name); - argv[argc++] = cmd_name; - argv[argc++] = UTIL_OPTION_RESTOREDB; - if ((date != NULL) && (strcmp (date, "none") != 0)) - { - argv[argc++] = "--" RESTORE_UP_TO_DATE_L; - argv[argc++] = date; - } - argv[argc++] = "--" RESTORE_LEVEL_L; - argv[argc++] = lv; - if (pathname != NULL && !uStringEqual (pathname, "none")) - { - argv[argc++] = "--" RESTORE_BACKUP_FILE_PATH_L; - argv[argc++] = pathname; - } - if (uStringEqual (partial, "y")) - { - argv[argc++] = "--" RESTORE_PARTIAL_RECOVERY_L; - } - - if (recovery_path != NULL && !uStringEqual (recovery_path, "") - && !uStringEqual (recovery_path, "none")) - { - /* use -u option to specify restore database path */ - argv[argc++] = "--" RESTORE_USE_DATABASE_LOCATION_PATH_L; - - if ((retval = - check_dbpath (recovery_path, _dbmt_error)) != ERR_NO_ERROR) - { - return retval; - } - if (access (recovery_path, F_OK) < 0) - { - retval = uCreateDir (recovery_path); - if (retval != ERR_NO_ERROR) - { - return retval; - } - } - - if ((retval = alter_dblocation (dbname, recovery_path)) != ERR_NO_ERROR) - { - return retval; - } - } - argv[argc++] = dbname; - argv[argc++] = NULL; - - snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", - sco.dbmt_tmp_dir, "restoredb", getpid ()); - - if (run_child (argv, 1, NULL, NULL, arniadb_err_file, &status) < 0) - { - strcpy_limit (_dbmt_error, argv[0], DBMT_ERROR_MSG_SIZE); - if (access (arniadb_err_file, F_OK) == 0) - { - unlink (arniadb_err_file); - } - return ERR_SYSTEM_CALL; - } - - if (status != 0 && read_error_file (arniadb_err_file, _dbmt_error, - DBMT_ERROR_MSG_SIZE) < 0) - { - if (access (arniadb_err_file, F_OK) == 0) - { - unlink (arniadb_err_file); - } - return ERR_WITH_MSG; - } - - if (access (arniadb_err_file, F_OK) == 0) - { - unlink (arniadb_err_file); - } - return ERR_NO_ERROR; -} - -int -ts_backup_vol_info (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char *dbname, *lv, *pathname, buf[1024], tmpfile[PATH_MAX]; - int ret; - FILE *infile; - char cmd_name[ARNIADB_CMD_NAME_LEN]; - const char *argv[10]; - int argc = 0; - - dbname = nv_get_val (req, "dbname"); - snprintf (tmpfile, PATH_MAX - 1, "%s/DBMT_task_%d.%d", sco.dbmt_tmp_dir, - TS_BACKUPVOLINFO, (int) getpid ()); - - if (uIsDatabaseActive (dbname)) - { - sprintf (_dbmt_error, "%s", dbname); - return ERR_DB_ACTIVE; - } - - if (uDatabaseMode (dbname, NULL) == DB_SERVICE_MODE_SA) - { - sprintf (_dbmt_error, "%s", dbname); - return ERR_STANDALONE_MODE; - } - - lv = nv_get_val (req, "level"); - pathname = nv_get_val (req, "pathname"); - - arniadb_cmd_name (cmd_name); - argv[argc++] = cmd_name; - argv[argc++] = UTIL_OPTION_RESTOREDB; - argv[argc++] = "--" RESTORE_LIST_L; - if (lv != NULL && - (uStringEqual (lv, "0") || uStringEqual (lv, "1") - || uStringEqual (lv, "2"))) - { - argv[argc++] = "--" RESTORE_LEVEL_L; - argv[argc++] = lv; - } - if (pathname != NULL && !uStringEqual (pathname, "none")) - { - argv[argc++] = "--" RESTORE_BACKUP_FILE_PATH_L; - argv[argc++] = pathname; - } - - argv[argc++] = dbname; - argv[argc++] = NULL; - -#if defined(WINDOWS) - ret = run_child (argv, 1, NULL, tmpfile, NULL, NULL); /* restoredb -t */ -#else - ret = run_child (argv, 1, "/dev/null", tmpfile, NULL, NULL); /* restoredb -t */ -#endif - if (ret < 0) - { - sprintf (_dbmt_error, "%s", argv[0]); - return ERR_SYSTEM_CALL; - } - - infile = fopen (tmpfile, "r"); - if (infile == NULL) - { - strcpy (_dbmt_error, tmpfile); - return ERR_TMPFILE_OPEN_FAIL; - } - - while (fgets (buf, sizeof (buf), infile)) - { - uRemoveCRLF (buf); - nv_add_nvp (res, "line", buf); - } - fclose (infile); - unlink (tmpfile); - - return ERR_NO_ERROR; -} - -int -ts_get_dbsize (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char *dbname; - char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; - int ha_mode = 0; - char strbuf[PATH_MAX], dbdir[PATH_MAX]; - int no_tpage = 0, log_size = 0, baselen; - struct stat statbuf; - GeneralSpacedbResult *cmd_res; - T_ARNIADB_MODE arniadb_mode; -#if defined(WINDOWS) - char find_file[PATH_MAX]; - WIN32_FIND_DATA data; - HANDLE handle; - int found; -#else - DIR *dirp; - struct dirent *dp; -#endif - char *cur_file; - - /* get dbname */ - if ((dbname = nv_get_val (req, "dbname")) == NULL) - { - sprintf (_dbmt_error, "%s", "database name"); - return ERR_PARAM_MISSING; - } - - if (uRetrieveDBDirectory (dbname, dbdir) != ERR_NO_ERROR) - { - strcpy (_dbmt_error, dbname); - return ERR_DBDIRNAME_NULL; - } - - arniadb_mode = - (uDatabaseMode (dbname, &ha_mode) == - DB_SERVICE_MODE_NONE) ? ARNIADB_MODE_SA : ARNIADB_MODE_CS; - - if (ha_mode != 0) - { - append_host_to_dbname (dbname_at_hostname, dbname, - sizeof (dbname_at_hostname)); - cmd_res = cmd_spacedb (dbname_at_hostname, arniadb_mode); - } - else - { - cmd_res = cmd_spacedb (dbname, arniadb_mode); - } - - if (cmd_res == NULL || cmd_res->has_error()) - { - sprintf (_dbmt_error, "spacedb %s", dbname); - delete cmd_res; - return ERR_SYSTEM_CALL; - } - - - /* get log volume info */ -#if defined(WINDOWS) - snprintf (find_file, PATH_MAX - 1, "%s/*", dbdir); - if ((handle = FindFirstFile (find_file, &data)) == INVALID_HANDLE_VALUE) -#else - if ((dirp = opendir (dbdir)) == NULL) -#endif - { - sprintf (_dbmt_error, "%s", dbdir); - return ERR_DIROPENFAIL; - } - - baselen = (int) strlen (dbname); -#if defined(WINDOWS) - for (found = 1; found; found = FindNextFile (handle, &data)) -#else - while ((dp = readdir (dirp)) != NULL) -#endif - { -#if defined(WINDOWS) - cur_file = data.cFileName; -#else - cur_file = dp->d_name; -#endif - if (!strncmp (cur_file + baselen, "_lginf", 6) - || !strcmp (cur_file + baselen, ARNIADB_ACT_LOG_EXT) - || !strncmp (cur_file + baselen, ARNIADB_ARC_LOG_EXT, ARNIADB_ARC_LOG_EXT_LEN)) - { - snprintf (strbuf, sizeof (strbuf) - 1, "%s/%s", dbdir, cur_file); - stat (strbuf, &statbuf); - log_size += statbuf.st_size; - } - } - -#if defined(WINDOWS) - FindClose (handle); -#else - closedir (dirp); -#endif - - snprintf (strbuf, sizeof (strbuf) - 1, "%d", - cmd_res->get_cnt_tpage() * cmd_res->get_page_size() + cmd_res->get_log_page_size()); - nv_add_nvp (res, "dbsize", strbuf); - - return ERR_NO_ERROR; -} - -int -tsGetEnvironment (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char tmpfile[PATH_MAX]; - char strbuf[1024]; - FILE *infile; - char cmd_name[ARNIADB_CMD_NAME_LEN]; - const char *argv[5]; - - nv_add_nvp (res, "ARNIADB", sco.szArniadb); - nv_add_nvp (res, "ARNIADB_DATABASES", sco.szArniadb_databases); - nv_add_nvp (res, "ARNIADB_DBMT", sco.szArniadb); - // nv_add_nvp (res, "ARNIADB_CHARSET", getenv ("ARNIADB_CHARSET")); - snprintf (tmpfile, PATH_MAX - 1, "%s/DBMT_task_015.%d", sco.dbmt_tmp_dir, - (int) getpid ()); - - cmd_name[0] = '\0'; - snprintf (cmd_name, sizeof (cmd_name) - 1, "%s/%s%s", sco.szArniadb, - ARNIADB_DIR_BIN, UTIL_ARNIADB_REL_NAME); - - argv[0] = cmd_name; - argv[1] = NULL; - - run_child (argv, 1, NULL, tmpfile, NULL, NULL); /* arniadb_rel */ - - if ((infile = fopen (tmpfile, "r")) != NULL) - { - fgets (strbuf, sizeof (strbuf), infile); - fgets (strbuf, sizeof (strbuf), infile); - uRemoveCRLF (strbuf); - fclose (infile); - unlink (tmpfile); - nv_add_nvp (res, "ARNIADBVER", strbuf); - } - else - { - nv_add_nvp (res, "ARNIADBVER", "version information not available"); - } - - snprintf (tmpfile, PATH_MAX - 1, "%s/DBMT_task_015.%d", sco.dbmt_tmp_dir, - (int) getpid ()); - snprintf (cmd_name, sizeof (cmd_name) - 1, "%s/bin/arniadb_broker%s", - sco.szArniadb, DBMT_EXE_EXT); - - argv[0] = cmd_name; - argv[1] = "--version"; - argv[2] = NULL; - - run_child (argv, 1, NULL, tmpfile, NULL, NULL); /* arniadb_broker --version */ - - if ((infile = fopen (tmpfile, "r")) != NULL) - { - fgets (strbuf, sizeof (strbuf), infile); - fclose (infile); - uRemoveCRLF (strbuf); - unlink (tmpfile); - nv_add_nvp (res, "BROKERVER", strbuf); - } - else - { - nv_add_nvp (res, "BROKERVER", "version information not available"); - } - - if (sco.hmtab1 == 1) - { - nv_add_nvp (res, "HOSTMONTAB0", "ON"); - } - else - { - nv_add_nvp (res, "HOSTMONTAB0", "OFF"); - } - if (sco.hmtab2 == 1) - { - nv_add_nvp (res, "HOSTMONTAB1", "ON"); - } - else - { - nv_add_nvp (res, "HOSTMONTAB1", "OFF"); - } - if (sco.hmtab3 == 1) - { - nv_add_nvp (res, "HOSTMONTAB2", "ON"); - } - else - { - nv_add_nvp (res, "HOSTMONTAB2", "OFF"); - } - if (sco.hmtab4 == 1) - { - nv_add_nvp (res, "HOSTMONTAB3", "ON"); - } - else - { - nv_add_nvp (res, "HOSTMONTAB3", "OFF"); - } - -#if defined(WINDOWS) - nv_add_nvp (res, "osinfo", "NT"); -#elif LINUX - nv_add_nvp (res, "osinfo", "LINUX"); -#elif AIX - nv_add_nvp (res, "osinfo", "AIX"); -#elif HPUX - nv_add_nvp (res, "osinfo", "HPUX"); -#elif UNIXWARE7 - nv_add_nvp (res, "osinfo", "UNIXWARE7"); -#elif SOLARIS - nv_add_nvp (res, "osinfo", "SOLARIS"); -#else - nv_add_nvp (res, "osinfo", "unknown"); -#endif - - return ERR_NO_ERROR; -} - -int -ts_startinfo (nvplist *req, nvplist *res, char *_dbmt_error) -{ - T_SERVER_STATUS_RESULT *cmd_res; - int retval; - - /* add dblist */ - retval = ut_get_dblist (res, 1); - if (retval != ERR_NO_ERROR) - { - return retval; - } - - nv_add_nvp (res, "open", "activelist"); - cmd_res = cmd_server_status (); - if (cmd_res != NULL) - { - T_SERVER_STATUS_INFO *info = (T_SERVER_STATUS_INFO *) cmd_res->result; - int i; - for (i = 0; i < cmd_res->num_result; i++) - { -#ifdef JSON_SUPPORT - nv_add_nvp (res, "open", "active"); -#endif - nv_add_nvp (res, "dbname", info[i].db_name); -#ifdef JSON_SUPPORT - nv_add_nvp (res, "close", "active"); -#endif - } - } - nv_add_nvp (res, "close", "activelist"); - - uWriteDBnfo2 (cmd_res); - cmd_servstat_result_free (cmd_res); - - return ERR_NO_ERROR; -} - -int -ts_kill_process (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char *pid_str; - int pid; - char *tgt_name; - - if ((pid_str = nv_get_val (req, "pid")) == NULL) - { - strcpy (_dbmt_error, "pid"); - return ERR_PARAM_MISSING; - } - tgt_name = nv_get_val (req, "name"); - - pid = atoi (pid_str); - if (pid > 0) - { - if (kill (pid, SIGTERM) < 0) - { - DBMT_ERR_MSG_SET (_dbmt_error, strerror (errno)); - return ERR_WITH_MSG; - } - } - - nv_add_nvp (res, "name", tgt_name); - uWriteDBnfo (); - return ERR_NO_ERROR; -} - -static int -ts_check_backup_id (const char *backupid) -{ - FILE *infile; - char strbuf[SIZE_BUFFER_MAX]; - char strbuf_tmp[SIZE_BUFFER_MAX]; - char *conf_item[AUTOBACKUP_CONF_ENTRY_NUM]; - - strbuf[0] = '\0'; - strbuf_tmp[0] = '\0'; - - infile = - fopen (conf_get_dbmt_file (FID_AUTO_BACKUPDB_CONF, strbuf_tmp), "r"); - if (infile == NULL) - { - return 0; - } - - while (fgets (strbuf, sizeof (strbuf), infile)) - { - ut_trim (strbuf); - if (strbuf[0] == '#') - { - continue; - } - if (string_tokenize (strbuf, conf_item, AUTOBACKUP_CONF_ENTRY_NUM) < 0) - { - continue; - } - if (strcmp (conf_item[1], backupid) == 0) - { - fclose (infile); - return 1; - } - } - fclose (infile); - - return 0; -} - -static int -_check_backup_info (const char *conf_item[], int check_backupid, - char *_dbmt_error) -{ - char time_item[5]; - char dbname[NAME_MAX]; - char path_item[PATH_MAX]; - char conf_value_item[NAME_MAX]; - - char *token = NULL; - - int i = 0; - int period_type_exist = 0; - int period_date_exist = 0; - int period_date = 0; - - time_item[0] = '\0'; - dbname[0] = '\0'; - path_item[0] = '\0'; - conf_value_item[0] = '\0'; - - /* check the validation of dbname */ - snprintf (dbname, NAME_MAX, "%s", conf_item[0]); - if (_isRegisteredDB (dbname) == 0) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", conf_item[0]); - return ERR_DB_NONEXISTANT; - } - /* check the validation of backupid */ - if (check_backupid == 1) - { - if (ts_check_backup_id (conf_item[1]) == 1) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, - "backupid(%s) already exist.", conf_item[1]); - return ERR_WITH_MSG; - } - } - /* check the validation of path */ - snprintf (path_item, PATH_MAX, "%s", conf_item[2]); - if (access (path_item, F_OK) < 0) - { - if (uCreateDir (path_item) == ERR_NO_ERROR) - { - uRemoveDir (path_item, REMOVE_DIR_FORCED); - } - else - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "Error : %s : %s", - conf_item[2], strerror (errno)); - return ERR_WITH_MSG; - } - } - else if (access (path_item, R_OK | W_OK) < 0) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "Error : %s : %s", - conf_item[2], strerror (errno)); - return ERR_WITH_MSG; - } - /* check the validation of period_type */ - for (i = 0; i < AUTOBACKUP_PERIOD_TYPE_NUM; i++) - { - if (strcmp (conf_item[3], autobackup_period_type[i]) == 0) - { - period_type_exist = 1; - break; - } - } - /* 0 is meaning period type is out of autobackup_period_type */ - if (period_type_exist == 0) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, - "(%s) is not allowed for parameter(%s).", conf_item[3], - autobackup_conf_entry[3]); - return ERR_WITH_MSG; - } - /* check the validation of period_date */ - /* period_date: Monthly */ - if ((strcmp (conf_item[3], AUTO_BACKUP_PERIOD_TYPE_MONTHLY) == 0)) - { - snprintf (conf_value_item, NAME_MAX, "%s", conf_item[4]); - token = strtok (conf_value_item, " ,"); - while (token != NULL) - { - period_date = atoi (token); - if ((period_date <= 0) || (period_date > 31)) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, - "(%s) is not allowed for parameter(%s).", token, - autobackup_conf_entry[4]); - return ERR_WITH_MSG; - } - - token = strtok (NULL, " ,"); - } - } - /* period_date: Weekly */ - else if (strcmp (conf_item[3], AUTO_BACKUP_PERIOD_TYPE_WEEKLY) == 0) - { - snprintf (conf_value_item, NAME_MAX, "%s", conf_item[4]); - token = strtok (conf_value_item, " ,"); - while (token != NULL) - { - for (i = 0; i < AUTOBACKUP_PERIOD_WEEK_NUM; i++) - { - if (strcmp (token, autobackup_period_week[i]) == 0) - { - period_date_exist = 1; - break; - } - } - /* 0 is meaning period type is out of autobackup_period_type */ - if (period_date_exist == 0) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, - "(%s) is not allowed for parameter(%s).", token, - autobackup_conf_entry[4]); - return ERR_WITH_MSG; - } - - period_date_exist = 0; - token = strtok (NULL, " ,"); - } - } - /* period_date: Daily */ - else if (strcmp (conf_item[3], AUTO_BACKUP_PERIOD_TYPE_DAILY) == 0) - { - /* do nothing */ - } - /* period_date: Hourly */ - else if (strcmp (conf_item[3], AUTO_BACKUP_PERIOD_TYPE_HOURLY) == 0) - { - period_date = atoi (conf_item[4]); - if ((period_date <= 0) || (period_date > 24)) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, - "(%s) is not allowed for parameter(%s).", conf_item[4], - autobackup_conf_entry[4]); - return ERR_WITH_MSG; - } - } - /* period_date: Special */ - else - { - snprintf (conf_value_item, NAME_MAX, "%s", conf_item[4]); - token = strtok (conf_value_item, " ,"); - while (token != NULL) - { - /* convert period_date from YYYY-MM-DD into YYYYMMDD */ - period_date = atoi (token) * 10000; /* convert year: YYYY0000 */ - period_date += atoi (token + 5) * 100; /* convert month: YYYYMM00 */ - period_date += atoi (token + 8); /* convert day: YYYYMMDD */ - - if (((period_date / 10000 - 1900) < 0) - || (((period_date % 10000) / 100) <= 0) - || (((period_date % 10000) / 100) > 12) - || ((period_date % 100) <= 0) || ((period_date % 100) > 31)) - { - /* tm_year : True year - 1900 */ - /* tm_mon : [0, 11] */ - /* tm_mday : [1, 31] */ - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, - "(%s) is not allowed for parameter(%s).", - conf_item[4], autobackup_conf_entry[4]); - return ERR_WITH_MSG; - } - token = strtok (NULL, " ,"); - } - } - /* check time */ - if (strlen (conf_item[5]) == 4) - { - snprintf (time_item, sizeof (time_item), "%s", conf_item[5]); - if ((time_item[0] < '0') || (time_item[0] >= '3')) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, - "(%s) is not valid time format for parameter(%s).", - conf_item[5], autobackup_conf_entry[5]); - return ERR_WITH_MSG; - } - if ((time_item[1] < '0') || (time_item[1] > '9')) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, - "(%s) is not valid time format for parameter(%s).", - conf_item[5], autobackup_conf_entry[5]); - return ERR_WITH_MSG; - } - if ((time_item[0] == '2') && (time_item[1] >= '4')) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, - "(%s) is not valid time format for parameter(%s).", - conf_item[5], autobackup_conf_entry[5]); - return ERR_WITH_MSG; - } - if ((time_item[2] < '0') || (time_item[2] >= '6')) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, - "(%s) is not valid time format for parameter(%s).", - conf_item[5], autobackup_conf_entry[5]); - return ERR_WITH_MSG; - } - if ((time_item[3] < '0') || (time_item[3] > '9')) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, - "(%s) is not valid time format for parameter(%s).", - conf_item[5], autobackup_conf_entry[5]); - return ERR_WITH_MSG; - } - } - else - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, - "(%s) is not valid time format for parameter(%s).", - conf_item[5], autobackup_conf_entry[5]); - return ERR_WITH_MSG; - } - /* check level: 0 (default ), 1, 2 */ - if ((conf_item[6][0] < '0') || (conf_item[6][0] >= '3')) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, - "(%c) is not allowed for parameter(%s).", conf_item[6][0], - autobackup_conf_entry[6]); - return ERR_WITH_MSG; - } - return ERR_NO_ERROR; -} - -int -ts_backupdb_info (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char db_dir[PATH_MAX], log_dir[PATH_MAX]; - char *tok[3], vinf[PATH_MAX], buf[LINE_MAX]; - char db_backup_dir[PATH_MAX]; - FILE *infile; - struct stat statbuf; - - char *dbname = NULL; - - db_dir[0] = '\0'; - log_dir[0] = '\0'; - vinf[0] = '\0'; - buf[0] = '\0'; - tok[0] = NULL; - db_backup_dir[0] = '\0'; /* Used for extension for backup path. */ - - dbname = nv_get_val (req, "dbname"); - if (dbname == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "dbname"); - return ERR_PARAM_MISSING; - } - - if (uDatabaseMode (dbname, NULL) == DB_SERVICE_MODE_SA) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", dbname); - return ERR_STANDALONE_MODE; - } - - if (uRetrieveDBDirectory (dbname, db_dir) != ERR_NO_ERROR) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", dbname); - return ERR_DBDIRNAME_NULL; - } - - if (uRetrieveDBLogDirectory (dbname, log_dir) != ERR_NO_ERROR) - { - strcpy (_dbmt_error, dbname); - return ERR_DBDIRNAME_NULL; - } - - snprintf (vinf, sizeof (vinf), "%s/%s%s", log_dir, dbname, - ARNIADB_BACKUP_INFO_EXT); - - if (access (vinf, F_OK) < 0) - { - goto exit_success; - } - - if ((infile = fopen (vinf, "rt")) != NULL) - { - while (fgets (buf, sizeof (buf), infile)) - { - ut_trim (buf); - if (string_tokenize (buf, tok, 3) < 0) - { - continue; - } - if (stat (tok[2], &statbuf) == 0) - { - snprintf (vinf, sizeof (vinf), "level%s", tok[0]); - nv_add_nvp (res, "open", vinf); - nv_add_nvp (res, "path", tok[2]); - nv_add_nvp_int (res, "size", statbuf.st_size); - ts_add_nvp_time (res, "data", statbuf.st_mtime, - "%04d.%02d.%02d.%02d.%02d", NV_ADD_DATE_TIME); - nv_add_nvp (res, "close", vinf); - } - } - fclose (infile); - } - else - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", vinf); - return ERR_PERMISSION; - } - -exit_success: - /* In ARNIADB Manager, $db_dir/backup is default path. */ - snprintf (db_backup_dir, sizeof (db_backup_dir), "%s/backup", db_dir); - nv_add_nvp (res, "dbdir", db_backup_dir); - - nv_add_nvp_int (res, "freespace", ut_disk_free_space (db_dir)); - - return ERR_NO_ERROR; -} - -int -ts_unloaddb_info (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char *n, *v, buf[1024]; - FILE *infile; - int flag = 0; - struct stat statbuf; - - snprintf (buf, sizeof (buf) - 1, "%s/unloaddb.info", - sco.szArniadb_databases); - if ((infile = fopen (buf, "rt")) == NULL) - { - return ERR_NO_ERROR; - } - - while (fgets (buf, sizeof (buf), infile)) - { - uRemoveCRLF (buf); - - if ((v = strchr (buf, ' ')) == NULL) - { - continue; - } - - *v = '\0'; - n = buf; - v++; - - while (*v == ' ') - { - v++; - } - - if (!strcmp (n, "%")) - { - if (flag == 1) - { - nv_add_nvp (res, "close", "database"); - } - else - { - flag = 1; - } - nv_add_nvp (res, "open", "database"); - nv_add_nvp (res, "dbname", v); - } - else - { - if (stat (v, &statbuf) == 0) - { - char timestr[64]; - char tmpbuf[1024]; - time_to_str (statbuf.st_mtime, "%04d.%02d.%02d %02d:%02d", - timestr, TIME_STR_FMT_DATE_TIME); - snprintf (tmpbuf, sizeof (tmpbuf) - 1, "%s;%s", v, timestr); - nv_add_nvp (res, n, tmpbuf); - } - } - } - if (flag == 1) - { - nv_add_nvp (res, "close", "database"); - } - fclose (infile); - - return ERR_NO_ERROR; -} - -/* backup automation */ - -int -ts_get_backup_info (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char *dbname; - FILE *infile; - char strbuf[1024]; - char *conf_item[AUTOBACKUP_CONF_ENTRY_NUM]; - int i; - - if ((dbname = nv_get_val (req, "_DBNAME")) == NULL) - { - strcpy (_dbmt_error, "database name"); - return ERR_PARAM_MISSING; - } - - nv_add_nvp (res, "dbname", dbname); - infile = fopen (conf_get_dbmt_file (FID_AUTO_BACKUPDB_CONF, strbuf), "r"); - if (infile == NULL) - { - return ERR_NO_ERROR; - } - - while (fgets (strbuf, sizeof (strbuf), infile)) - { - ut_trim (strbuf); - if (strbuf[0] == '#') - { - continue; - } - if (string_tokenize (strbuf, conf_item, AUTOBACKUP_CONF_ENTRY_NUM) < 0) - { - continue; - } - if (strcmp (conf_item[0], dbname) == 0) - { -#ifdef JSON_SUPPORT - nv_add_nvp (res, "open", dbname); -#endif - for (i = 0; i < AUTOBACKUP_CONF_ENTRY_NUM; i++) - { - nv_add_nvp (res, autobackup_conf_entry[i], conf_item[i]); - } -#ifdef JSON_SUPPORT - nv_add_nvp (res, "close", dbname); -#endif - } - } - fclose (infile); - - return ERR_NO_ERROR; -} - -int -ts_set_backup_info (nvplist *req, nvplist *res, char *_dbmt_error) -{ - FILE *infile, *outfile; - char line[LINE_MAX], tmpfile[PATH_MAX]; - char autofilepath[PATH_MAX]; - const char *conf_item[AUTOBACKUP_CONF_ENTRY_NUM]; - - int i = 0; - int retval = 0; - int no_auto_job = 1; /* 1 means there is no valid auto job */ - int backupid_exist = 0; - - autofilepath[0] = '\0'; - line[0] = '\0'; - tmpfile[0] = '\0'; - - for (i = 0; i < AUTOBACKUP_CONF_ENTRY_NUM - 1; i++) - { - conf_item[i] = nv_get_val (req, autobackup_conf_entry[i]); - if (conf_item[i] == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", - autobackup_conf_entry[i]); - return ERR_PARAM_MISSING; - } - } - - conf_item[AUTOBACKUP_CONF_ENTRY_NUM - 1] = - nv_get_val (req, autobackup_conf_entry[AUTOBACKUP_CONF_ENTRY_NUM - 1]); - if (conf_item[AUTOBACKUP_CONF_ENTRY_NUM - 1] == NULL) - { - conf_item[AUTOBACKUP_CONF_ENTRY_NUM - 1] = "1"; - } - - retval = _check_backup_info (conf_item, 0, _dbmt_error); - if (retval != ERR_NO_ERROR) - { - return retval; - } - - conf_get_dbmt_file (FID_AUTO_BACKUPDB_CONF, autofilepath); - if (access (autofilepath, F_OK) < 0) - { - outfile = fopen (autofilepath, "w"); - if (outfile == NULL) - { - strcpy (_dbmt_error, autofilepath); - return ERR_FILE_OPEN_FAIL; - } - for (i = 0; i < AUTOBACKUP_CONF_ENTRY_NUM; i++) - { - fprintf (outfile, "%s ", conf_item[i]); - } - fprintf (outfile, "\n"); - fclose (outfile); - return ERR_NO_ERROR; - } - - if ((infile = fopen (autofilepath, "r")) == NULL) - { - strcpy (_dbmt_error, autofilepath); - return ERR_FILE_OPEN_FAIL; - } - snprintf (tmpfile, PATH_MAX, "%s/DBMT_task_%d.%d", sco.dbmt_tmp_dir, - TS_SETBACKUPINFO, (int) getpid ()); - if ((outfile = fopen (tmpfile, "w")) == NULL) - { - fclose (infile); - return ERR_TMPFILE_OPEN_FAIL; - } - while (fgets (line, sizeof (line), infile)) - { - char conf_dbname[128], conf_backupid[128]; - - if (sscanf (line, "%127s %127s", conf_dbname, conf_backupid) < 2) - { - continue; - } - - no_auto_job = 0; /* 0 means there is some auto job in autobackupdb.conf */ - - if ((strcmp (conf_dbname, conf_item[0]) == 0) && - (strcmp (conf_backupid, conf_item[1]) == 0)) - { - for (i = 0; i < AUTOBACKUP_CONF_ENTRY_NUM; i++) - { - fprintf (outfile, "%s ", conf_item[i]); - } - fprintf (outfile, "\n"); - backupid_exist = 1; - } - else - { - fputs (line, outfile); - } - } - fclose (infile); - fclose (outfile); - - move_file (tmpfile, autofilepath); - /* if config file is valid but no auto job plan, create it. */ - if (no_auto_job == 1) - { - outfile = fopen (autofilepath, "w"); - if (outfile == NULL) - { - strcpy (_dbmt_error, autofilepath); - return ERR_FILE_OPEN_FAIL; - } - for (i = 0; i < AUTOBACKUP_CONF_ENTRY_NUM; i++) - { - fprintf (outfile, "%s ", conf_item[i]); - } - fprintf (outfile, "\n"); - fclose (outfile); - return ERR_NO_ERROR; - } - /* if config file is valid and there is some auto job plan, but no special backupid, throw exception */ - if (backupid_exist == 0) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, - "Backup plan does not exist. backupid is %s.", conf_item[1]); - return ERR_WITH_MSG; - } - return ERR_NO_ERROR; -} - -int -ts_add_backup_info (nvplist *req, nvplist *res, char *_dbmt_error) -{ - FILE *outfile; - char autofilepath[PATH_MAX]; - const char *conf_item[AUTOBACKUP_CONF_ENTRY_NUM]; - - int i = 0; - int retval = 0; - - autofilepath[0] = '\0'; - - for (i = 0; i < AUTOBACKUP_CONF_ENTRY_NUM - 1; i++) - { - conf_item[i] = nv_get_val (req, autobackup_conf_entry[i]); - if (conf_item[i] == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", - autobackup_conf_entry[i]); - return ERR_PARAM_MISSING; - } - } - - conf_item[AUTOBACKUP_CONF_ENTRY_NUM - 1] = - nv_get_val (req, autobackup_conf_entry[AUTOBACKUP_CONF_ENTRY_NUM - 1]); - if (conf_item[AUTOBACKUP_CONF_ENTRY_NUM - 1] == NULL) - { - conf_item[AUTOBACKUP_CONF_ENTRY_NUM - 1] = "1"; - } - - retval = _check_backup_info (conf_item, 1, _dbmt_error); - if (retval != ERR_NO_ERROR) - { - return retval; - } - - conf_get_dbmt_file (FID_AUTO_BACKUPDB_CONF, autofilepath); - if ((outfile = fopen (autofilepath, "a")) == NULL) - { - strcpy (_dbmt_error, autofilepath); - return ERR_FILE_OPEN_FAIL; - } - for (i = 0; i < AUTOBACKUP_CONF_ENTRY_NUM; i++) - { - fprintf (outfile, "%s ", conf_item[i]); - } - fprintf (outfile, "\n"); - - fclose (outfile); - - return ERR_NO_ERROR; -} - -int -ts_delete_backup_info (nvplist *req, nvplist *res, char *_dbmt_error) -{ - FILE *infile, *outfile; - char line[LINE_MAX], tmpfile[PATH_MAX]; - char autofilepath[PATH_MAX]; - - char *dbname = NULL; - char *backupid = NULL; - - line[0] = '\0'; - tmpfile[0] = '\0'; - autofilepath[0] = '\0'; - - dbname = nv_get_val (req, "dbname"); - if (dbname == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "dbname"); - return ERR_PARAM_MISSING; - } - - backupid = nv_get_val (req, "backupid"); - if (backupid == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "backupid"); - return ERR_PARAM_MISSING; - } - if (ts_check_backup_id (backupid) == 0) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, - "Backup plan does not exist. backupid is %s.", backupid); - return ERR_WITH_MSG; - } - - conf_get_dbmt_file (FID_AUTO_BACKUPDB_CONF, autofilepath); - if ((infile = fopen (autofilepath, "r")) == NULL) - { - strcpy (_dbmt_error, autofilepath); - return ERR_FILE_OPEN_FAIL; - } - snprintf (tmpfile, PATH_MAX - 1, "%s/DBMT_task_%d.%d", sco.dbmt_tmp_dir, - TS_DELETEBACKUPINFO, (int) getpid ()); - if ((outfile = fopen (tmpfile, "w")) == NULL) - { - fclose (infile); - return ERR_TMPFILE_OPEN_FAIL; - } - - while (fgets (line, sizeof (line), infile)) - { - char conf_dbname[128], conf_backupid[128]; - - if (sscanf (line, "%127s %127s", conf_dbname, conf_backupid) != 2) - { - continue; - } - if ((strcmp (conf_dbname, dbname) != 0) || - backupid == NULL || (strcmp (conf_backupid, backupid) != 0)) - { - fputs (line, outfile); - } - } - fclose (infile); - fclose (outfile); - move_file (tmpfile, autofilepath); - return ERR_NO_ERROR; -} - -int -ts_get_log_info (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char *dbname, log_dir[PATH_MAX], buf[PATH_MAX]; - char *error_log_param; - struct stat statbuf; - int fname_len = 0; -#if defined(WINDOWS) - WIN32_FIND_DATA data; - HANDLE handle; - int found; -#else - DIR *dirp = NULL; - struct dirent *dp = NULL; -#endif - char find_file[PATH_MAX]; - char *fname; - - dbname = nv_get_val (req, "_DBNAME"); - - if ((dbname == NULL) - || (uRetrieveDBDirectory (dbname, log_dir) != ERR_NO_ERROR)) - { - if (dbname != NULL) - { - strcpy (_dbmt_error, dbname); - } - return ERR_DBDIRNAME_NULL; - } - - nv_add_nvp (res, "dbname", dbname); - nv_add_nvp (res, "open", "loginfo"); - - if ((error_log_param = _ts_get_error_log_param (dbname)) == NULL) - { - snprintf (buf, sizeof (buf) - 1, "%s/%s.err", log_dir, dbname); - } - else if (error_log_param[0] == '/') - { - snprintf (buf, sizeof (buf) - 1, "%s", error_log_param); - } -#if defined(WINDOWS) - else if (error_log_param[2] == '/') - { - snprintf (buf, sizeof (buf) - 1, "%s", error_log_param); - } -#endif - else - { - snprintf (buf, sizeof (buf) - 1, "%s/%s", log_dir, error_log_param); - } - - if (stat (buf, &statbuf) == 0) - { - nv_add_nvp (res, "open", "log"); - nv_add_nvp (res, "path", buf); - nv_add_nvp (res, ENCRYPT_ARG ("owner"), - get_user_name (statbuf.st_uid, buf)); - nv_add_nvp_int (res, "size", statbuf.st_size); - ts_add_nvp_time (res, "lastupdate", statbuf.st_mtime, "%04d.%02d.%02d", - NV_ADD_DATE); - nv_add_nvp (res, "close", "log"); - } - FREE_MEM (error_log_param); - - snprintf (buf, sizeof (buf) - 1, "%s/arn_server.err", log_dir); - if (stat (buf, &statbuf) == 0) - { - nv_add_nvp (res, "open", "log"); - nv_add_nvp (res, "path", buf); - nv_add_nvp (res, ENCRYPT_ARG ("owner"), - get_user_name (statbuf.st_uid, buf)); - nv_add_nvp_int (res, "size", statbuf.st_size); - ts_add_nvp_time (res, "lastupdate", statbuf.st_mtime, "%04d.%02d.%02d", - NV_ADD_DATE); - nv_add_nvp (res, "close", "log"); - } - - snprintf (find_file, PATH_MAX - 1, "%s/%s", sco.szArniadb, - ARNIADB_ERROR_LOG_DIR); -#if defined(WINDOWS) - snprintf (&find_file[strlen (find_file)], PATH_MAX - strlen (find_file) - 1, - "/*"); - if ((handle = FindFirstFile (find_file, &data)) == INVALID_HANDLE_VALUE) -#else - if ((dirp = opendir (find_file)) == NULL) -#endif - { - nv_add_nvp (res, "close", "loginfo"); - return ERR_NO_ERROR; - } -#if defined(WINDOWS) - for (found = 1; found; found = FindNextFile (handle, &data)) -#else - while ((dp = readdir (dirp)) != NULL) -#endif - { -#if defined(WINDOWS) - fname = data.cFileName; -#else - fname = dp->d_name; -#endif - fname_len = (int) strlen (fname); - /* the "4" is the size of ".err" */ - if (fname_len < 4 || (strcmp (fname + fname_len - 4, ".err") != 0)) - { - continue; - } - if (memcmp (fname, dbname, strlen (dbname))) - { - continue; - } - if (isalnum (fname[strlen (dbname)])) - { - continue; - } - snprintf (buf, sizeof (buf) - 1, "%s/%s/%s", sco.szArniadb, - ARNIADB_ERROR_LOG_DIR, fname); - if (stat (buf, &statbuf) == 0) - { - nv_add_nvp (res, "open", "log"); - nv_add_nvp (res, "path", buf); - nv_add_nvp (res, ENCRYPT_ARG ("owner"), - get_user_name (statbuf.st_uid, buf)); - nv_add_nvp_int (res, "size", statbuf.st_size); - ts_add_nvp_time (res, "lastupdate", statbuf.st_mtime, - "%04d.%02d.%02d", NV_ADD_DATE); - nv_add_nvp (res, "close", "log"); - } - } -#if defined(WINDOWS) - FindClose (handle); -#else - closedir (dirp); -#endif - - nv_add_nvp (res, "close", "loginfo"); - return ERR_NO_ERROR; -} - -int -ts_view_log (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char *filepath, *startline, *endline, buf[1024]; - FILE *infile; - int no_line = 0, start, end; - - filepath = nv_get_val (req, "path"); - if (filepath == NULL) - { - strcpy (_dbmt_error, "filepath"); - return ERR_PARAM_MISSING; - } - - startline = nv_get_val (req, "start"); - endline = nv_get_val (req, "end"); - - start = (startline == NULL ? -1 : atoi (startline)); - end = (endline == NULL ? -1 : atoi (endline)); - - if ((infile = fopen (filepath, "rt")) == NULL) - { - sprintf (_dbmt_error, "%s", filepath); - return ERR_FILE_OPEN_FAIL; - } - - nv_add_nvp (res, "path", filepath); - nv_add_nvp (res, "open", "log"); - while (fgets (buf, sizeof (buf), infile)) - { - no_line++; - if (start != -1 && end != -1) - { - if (start > no_line || end < no_line) - { - continue; - } - } - - uRemoveCRLF (buf); - nv_add_nvp (res, "line", buf); - } - nv_add_nvp (res, "close", "log"); - fclose (infile); - - if (start != -1 && end != -1) - { - nv_add_nvp_int (res, "start", (start > no_line ? no_line : start)); - nv_add_nvp_int (res, "end", (end > no_line ? no_line : end)); - } - - nv_add_nvp_int (res, "total", no_line); - - return ERR_NO_ERROR; -} - -int -ts_reset_log (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char *path; - FILE *outfile; - - path = nv_get_val (req, "path"); - if (path == NULL) - { - strcpy (_dbmt_error, "filepath"); - return ERR_PARAM_MISSING; - } - - outfile = fopen (path, "w"); - if (outfile == NULL) - { - strcpy (_dbmt_error, path); - return ERR_FILE_OPEN_FAIL; - } - fclose (outfile); - - return ERR_NO_ERROR; -} - -int -ts_get_auto_add_vol (nvplist *req, nvplist *res, char *_dbmt_error) -{ - FILE *infile = NULL; - char *dbname; - char strbuf[1024], file[PATH_MAX]; - char *conf_item[AUTOADDVOL_CONF_ENTRY_NUM]; - int i; - - if ((dbname = nv_get_val (req, "_DBNAME")) == NULL) - { - sprintf (_dbmt_error, "%s", "database name"); - return ERR_PARAM_MISSING; - } - - nv_add_nvp (res, autoaddvol_conf_entry[1], "OFF"); - nv_add_nvp (res, autoaddvol_conf_entry[2], "0.0"); - nv_add_nvp (res, autoaddvol_conf_entry[3], "0"); - nv_add_nvp (res, autoaddvol_conf_entry[4], "OFF"); - nv_add_nvp (res, autoaddvol_conf_entry[5], "0.0"); - nv_add_nvp (res, autoaddvol_conf_entry[6], "0"); - - infile = fopen (conf_get_dbmt_file (FID_AUTO_ADDVOLDB_CONF, file), "r"); - if (infile == NULL) - { - return ERR_NO_ERROR; - } - - while (fgets (strbuf, sizeof (strbuf), infile)) - { - ut_trim (strbuf); - if (strbuf[0] == '#') - { - continue; - } - if (string_tokenize (strbuf, conf_item, AUTOADDVOL_CONF_ENTRY_NUM) < 0) - { - continue; - } - if (strcmp (conf_item[0], dbname) == 0) - { - for (i = 1; i < AUTOADDVOL_CONF_ENTRY_NUM; i++) - { - nv_update_val (res, autoaddvol_conf_entry[i], conf_item[i]); - } - break; - } - } - fclose (infile); - - return ERR_NO_ERROR; -} - -int -ts_set_auto_add_vol (nvplist *req, nvplist *res, char *_dbmt_error) -{ - FILE *infile, *outfile; - char line[1024], tmpfile[PATH_MAX]; - char auto_addvol_conf_file[PATH_MAX]; - char *conf_item[AUTOADDVOL_CONF_ENTRY_NUM]; - int i; - - if ((conf_item[0] = nv_get_val (req, "_DBNAME")) == NULL) - { - sprintf (_dbmt_error, "%s", "database name"); - return ERR_PARAM_MISSING; - } - - for (i = 1; i < AUTOADDVOL_CONF_ENTRY_NUM; i++) - { - conf_item[i] = nv_get_val (req, autoaddvol_conf_entry[i]); - if (conf_item[i] == NULL) - { - strcpy (_dbmt_error, autoaddvol_conf_entry[i]); - return ERR_PARAM_MISSING; - } - } - - conf_get_dbmt_file (FID_AUTO_ADDVOLDB_CONF, auto_addvol_conf_file); - if (access (auto_addvol_conf_file, F_OK) < 0) - { - outfile = fopen (auto_addvol_conf_file, "w"); - if (outfile == NULL) - { - strcpy (_dbmt_error, auto_addvol_conf_file); - return ERR_FILE_OPEN_FAIL; - } - for (i = 0; i < AUTOADDVOL_CONF_ENTRY_NUM; i++) - { - fprintf (outfile, "%s ", conf_item[i]); - } - fprintf (outfile, "\n"); - fclose (outfile); - return ERR_NO_ERROR; - } - - infile = fopen (auto_addvol_conf_file, "r"); - if (infile == NULL) - { - strcpy (_dbmt_error, auto_addvol_conf_file); - return ERR_FILE_OPEN_FAIL; - } - snprintf (tmpfile, PATH_MAX - 1, "%s/DBMT_task_045.%d", sco.dbmt_tmp_dir, - (int) getpid ()); - outfile = fopen (tmpfile, "w"); - if (outfile == NULL) - { - fclose (infile); - return ERR_TMPFILE_OPEN_FAIL; - } - - while (fgets (line, sizeof (line), infile)) - { - char conf_dbname[128]; - - if (sscanf (line, "%127s", conf_dbname) < 1) - { - continue; - } - - if (strcmp (conf_dbname, conf_item[0]) != 0) - { - fputs (line, outfile); - } - } - for (i = 0; i < AUTOADDVOL_CONF_ENTRY_NUM; i++) - { - fprintf (outfile, "%s ", conf_item[i]); - } - fprintf (outfile, "\n"); - fclose (infile); - fclose (outfile); - - move_file (tmpfile, auto_addvol_conf_file); - - return ERR_NO_ERROR; -} - -int -ts_get_addvol_status (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char *dbname = NULL; - char dbdir[PATH_MAX]; - - if ((dbname = nv_get_val (req, "_DBNAME")) == NULL) - { - sprintf (_dbmt_error, "%s", "database name"); - return ERR_PARAM_MISSING; - } - - if (uRetrieveDBDirectory (dbname, dbdir) != ERR_NO_ERROR) - { - strcpy (_dbmt_error, dbname); - return ERR_DBDIRNAME_NULL; - } - - nv_add_nvp_int (res, "freespace", ut_disk_free_space (dbdir)); - nv_add_nvp (res, "volpath", dbdir); - return ERR_NO_ERROR; -} - -int -ts_get_tran_info (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char *dbname = NULL; - char *dbpasswd = NULL; - char *user = NULL; - char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; - int ha_mode = 0; - char buf[1024]; - char tmpfile[PATH_MAX]; - char errfile[PATH_MAX]; - FILE *infile = NULL; - char *tok[9]; - char cmd_name[ARNIADB_CMD_NAME_LEN]; - const char *argv[10]; - int argc = 0; - int retval = 0; - int tmp = 0; - T_DB_SERVICE_MODE db_mode; - char *sqltext; - - cmd_name[0] = '\0'; - buf[0] = '\0'; - tmpfile[0] = '\0'; - errfile[0] = '\0'; - dbname_at_hostname[0] = '\0'; - - if ((dbname = nv_get_val (req, "dbname")) == NULL) - { - strncpy (_dbmt_error, "dbname", DBMT_ERROR_MSG_SIZE); - return ERR_PARAM_MISSING; - } - - /* get database mode. */ - db_mode = uDatabaseMode (dbname, &ha_mode); - if (db_mode == DB_SERVICE_MODE_SA) - { - strncpy (_dbmt_error, dbname, DBMT_ERROR_MSG_SIZE); - return ERR_STANDALONE_MODE; - } - - snprintf (tmpfile, PATH_MAX - 1, "%s/DBMT_task_%d.%d", sco.dbmt_tmp_dir, - TS_GETTRANINFO, (int) getpid ()); - snprintf (errfile, PATH_MAX - 1, "%s/DBMT_task_%d.stderr.%d", - sco.dbmt_tmp_dir, TS_GETTRANINFO, (int) getpid ()); - - arniadb_cmd_name (cmd_name); - argv[argc++] = cmd_name; - argv[argc++] = UTIL_OPTION_TRANLIST; - - argv[argc++] = "-f"; - - if (ha_mode != 0) - { - append_host_to_dbname (dbname_at_hostname, dbname, - sizeof (dbname_at_hostname)); - argv[argc++] = dbname_at_hostname; - } - else - { - argv[argc++] = dbname; - } - - argv[argc++] = NULL; - - retval = run_child (argv, 1, NULL, tmpfile, errfile, NULL); /* tranlist */ - if (retval < 0) - { - strncpy (_dbmt_error, argv[0], DBMT_ERROR_MSG_SIZE); - return ERR_SYSTEM_CALL; - } - - if ((infile = fopen (errfile, "r")) == NULL) - { - return ERR_TMPFILE_OPEN_FAIL; - } - - retval = ERR_NO_ERROR; - tmp = 0; - while (fgets (buf, sizeof (buf), infile)) - { - ut_trim (buf); - strncpy (_dbmt_error + tmp, buf, DBMT_ERROR_MSG_SIZE - tmp); - tmp += (int) strlen (buf); - retval = ERR_WITH_MSG; - } - - if (retval != ERR_NO_ERROR) - { - fclose (infile); - unlink (tmpfile); - unlink (errfile); - return retval; - } - - fclose (infile); - - if ((infile = fopen (tmpfile, "rt")) == NULL) - { - return ERR_TMPFILE_OPEN_FAIL; - } - nv_add_nvp (res, "dbname", dbname); - nv_add_nvp (res, "open", "transactioninfo"); - while (fgets (buf, sizeof (buf), infile)) - { - if (buf[0] == '-') - { - break; - } - } - while (fgets (buf, sizeof (buf), infile)) - { - ut_trim (buf); - if (buf[0] == '-') - { - break; - } - if (string_tokenize (buf, tok, 9) < 0) - { - continue; - } - nv_add_nvp (res, "open", "transaction"); - nv_add_nvp (res, "tranindex", tok[0]); - nv_add_nvp (res, ENCRYPT_ARG ("user"), tok[1]); - nv_add_nvp (res, "host", tok[2]); - nv_add_nvp (res, "pid", tok[3]); - nv_add_nvp (res, "program", tok[4]); - nv_add_nvp (res, "query_time", tok[5]); - nv_add_nvp (res, "tran_time", tok[6]); - nv_add_nvp (res, "wait_for_lock_holder", tok[7]); - if (strncmp (tok[8], "***", 3) == 0) - { - nv_add_nvp (res, "SQL_ID", "empty"); - } - else - { - nv_add_nvp (res, "SQL_ID", tok[8]); - - sqltext = tok[8] + strlen (tok[8]) + 1; - while (sqltext && *sqltext) - { - if (*sqltext == ' ') - { - sqltext++; - } - else - { - break; - } - } - nv_add_nvp (res, "SQL_Text", sqltext); - } - nv_add_nvp (res, "close", "transaction"); - } - nv_add_nvp (res, "close", "transactioninfo"); - fclose (infile); - unlink (tmpfile); - unlink (errfile); - - return ERR_NO_ERROR; -} - -/* - * read stdout and stderr files as error message. - * - */ -static void -read_stdout_stderr_as_err (char *stdout_file, char *stderr_file, - char *_dbmt_error) -{ - FILE *fp; - int len = 0; - int len_tmp = 0; - char buf[1024]; - - if (access (stderr_file, F_OK) == 0) - { - fp = fopen (stderr_file, "r"); - if (fp != NULL) - { - while (fgets (buf, sizeof (buf), fp) != NULL) - { - ut_trim (buf); - len_tmp = (int) strlen (buf); - - if (len_tmp < DBMT_ERROR_MSG_SIZE - len - 1) - { - strcpy (_dbmt_error, buf); - _dbmt_error += len_tmp; - len += len_tmp; - } - else - { - strcpy_limit (_dbmt_error, buf, DBMT_ERROR_MSG_SIZE - len); - strcpy_limit (_dbmt_error + DBMT_ERROR_MSG_SIZE - len - 4, - "...", 4); - break; - } - } - } - fclose (fp); - } - - if (access (stdout_file, F_OK) == 0) - { - fp = fopen (stdout_file, "r"); - if (fp != NULL) - { - while (fgets (buf, sizeof (buf), fp) != NULL) - { - ut_trim (buf); - len_tmp = (int) strlen (buf); - - if (len_tmp < DBMT_ERROR_MSG_SIZE - len - 1) - { - strcpy (_dbmt_error, buf); - _dbmt_error += len_tmp; - len += len_tmp; - } - else - { - strcpy_limit (_dbmt_error, buf, DBMT_ERROR_MSG_SIZE - len); - strcpy_limit (_dbmt_error + DBMT_ERROR_MSG_SIZE - len - 4, - "...", 4); - break; - } - } - } - fclose (fp); - } -} - -int -ts_killtran (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char *dbname = NULL; - char *dbpasswd = NULL; - char *type = NULL; - char *param = NULL; - char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; - char cmd_name[ARNIADB_CMD_NAME_LEN]; - char task_name[TASKNAME_LEN]; - const char *argv[10]; - int ha_mode = 0; - int argc = 0; - int is_need_param = 1; - int retval = 0; - T_DB_SERVICE_MODE db_mode; - - task_name[0] = '\0'; - dbname_at_hostname[0] = '\0'; - cmd_name[0] = '\0'; - - if ((dbname = nv_get_val (req, "dbname")) == NULL) - { - strcpy (_dbmt_error, "dbname"); - return ERR_PARAM_MISSING; - } - - dbpasswd = nv_get_val (req, "_DBPASSWD"); - - if ((type = nv_get_val (req, "type")) == NULL) - { - strcpy (_dbmt_error, "type"); - return ERR_PARAM_MISSING; - } - - param = nv_get_val (req, "parameter"); - - db_mode = uDatabaseMode (dbname, &ha_mode); - if (db_mode == DB_SERVICE_MODE_SA) - { - sprintf (_dbmt_error, "%s", dbname); - return ERR_STANDALONE_MODE; - } - - arniadb_cmd_name (cmd_name); - argv[argc++] = cmd_name; - argv[argc++] = UTIL_OPTION_KILLTRAN; - if (dbpasswd != NULL) - { - if (strcmp (type, "i") == 0 || strcmp (type, "u") == 0 || strcmp (type, "h") == 0 || strcmp (type, "p") == 0 - || strcmp (type, "s") == 0) - { - argv[argc++] = "--" KILLTRAN_DBA_PASSWORD_L; - argv[argc++] = dbpasswd; - } - } - - if (strcmp (type, "i") == 0) - { - /* remove (+) from formated string such as "1(+) | 1(-)" */ - /*char *p = strstr (param, "("); - if (p != NULL) - *p = '\0'; */ - - argv[argc++] = "--" KILLTRAN_KILL_TRANSACTION_INDEX_L; - } - else if (strcmp (type, "u") == 0) - { - argv[argc++] = "--" KILLTRAN_KILL_USER_NAME_L; - } - else if (strcmp (type, "h") == 0) - { - argv[argc++] = "--" KILLTRAN_KILL_HOST_NAME_L; - } - else if (strcmp (type, "p") == 0) - { - argv[argc++] = "--" KILLTRAN_KILL_PROGRAM_NAME_L; - } - else if (strcmp (type, "s") == 0) - { - argv[argc++] = "--" KILLTRAN_KILL_SQL_ID_L; - } - else if (strcmp (type, "q") == 0) - { - argv[argc++] = "--" KILLTRAN_KILL_QUERY_INFO_L; - is_need_param = 0; - } - else if (strcmp (type, "d") == 0) - { - argv[argc++] = "--" KILLTRAN_DISPLAY_INFORMATION_L; - is_need_param = 0; - } - else - { - strcpy (_dbmt_error, "invalid value in type."); - return ERR_WITH_MSG; - } - - if (is_need_param) - { - if (param == NULL) - { - strcpy (_dbmt_error, "parameter"); - return ERR_PARAM_MISSING; - } - argv[argc++] = param; - argv[argc++] = "--" KILLTRAN_FORCE_L; - } - if (ha_mode != 0) - { - append_host_to_dbname (dbname_at_hostname, dbname, - sizeof (dbname_at_hostname)); - argv[argc++] = dbname_at_hostname; - } - else - { - argv[argc++] = dbname; - } - - argv[argc++] = NULL; - - strncpy (task_name, "killtran", TASKNAME_LEN); - retval = _run_child (argv, 1, task_name, NULL, _dbmt_error); - if (retval != ERR_NO_ERROR) - { - return retval; - } - - ts_get_tran_info (req, res, _dbmt_error); - return ERR_NO_ERROR; -} - -int -ts_lockdb (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char buf[1024], tmpfile[PATH_MAX], tmpfile2[PATH_MAX], s[32]; - char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; - char cmd_name[ARNIADB_CMD_NAME_LEN]; - char task_name[TASKNAME_LEN]; - - const char *argv[10]; - int argc = 0; - int ha_mode = 0; - int retval = 0; - - char *dbname = NULL; - - T_DB_SERVICE_MODE db_mode; - FILE *infile, *outfile; - - buf[0] = '\0'; - tmpfile[0] = '\0'; - tmpfile2[0] = '\0'; - s[0] = '\0'; - dbname_at_hostname[0] = '\0'; - cmd_name[0] = '\0'; - task_name[0] = '\0'; - - if ((dbname = nv_get_val (req, "dbname")) == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "dbname"); - return ERR_PARAM_MISSING; - } - db_mode = uDatabaseMode (dbname, &ha_mode); - if (db_mode == DB_SERVICE_MODE_SA) - { - sprintf (_dbmt_error, "%s", dbname); - return ERR_STANDALONE_MODE; - } - - snprintf (tmpfile, PATH_MAX, "%s/DBMT_task_%d_1.%d.tmp", sco.dbmt_tmp_dir, - TS_LOCKDB, (int) getpid ()); - - arniadb_cmd_name (cmd_name); - argv[argc++] = cmd_name; - argv[argc++] = UTIL_OPTION_LOCKDB; - argv[argc++] = "--" LOCK_OUTPUT_FILE_L; - argv[argc++] = tmpfile; - - if (ha_mode != 0) - { - append_host_to_dbname (dbname_at_hostname, dbname, - sizeof (dbname_at_hostname)); - argv[argc++] = dbname_at_hostname; - } - else - { - argv[argc++] = dbname; - } - - argv[argc++] = NULL; - - strncpy (task_name, "lockdb", TASKNAME_LEN); - - retval = _run_child (argv, 1, task_name, NULL, _dbmt_error); - if (retval != ERR_NO_ERROR) - { - return retval; - } - - infile = fopen (tmpfile, "rt"); - if (infile == NULL) - { - return ERR_TMPFILE_OPEN_FAIL; - } - - /* create file that remove line feed at existed outputfile */ - snprintf (tmpfile2, PATH_MAX, "%s/DBMT_task_%d_2.%d.tmp", sco.dbmt_tmp_dir, - TS_LOCKDB, (int) getpid ()); - - outfile = fopen (tmpfile2, "w"); - if (outfile == NULL) - { - fclose (infile); - return ERR_TMPFILE_OPEN_FAIL; - } - - while (fgets (buf, sizeof (buf), infile)) - { - if (sscanf (buf, "%31s", s) == 1) - { - fputs (buf, outfile); - } - } - fclose (infile); - fclose (outfile); - unlink (tmpfile); - if ((infile = fopen (tmpfile2, "rt")) == NULL) - { - return ERR_TMPFILE_OPEN_FAIL; - } - - if (_ts_lockdb_parse_us (res, infile) < 0) - { - /* parshing error */ - strcpy (_dbmt_error, - "Lockdb operation has been failed(Unexpected state)."); - fclose (infile); - unlink (tmpfile2); - return ERR_WITH_MSG; - } - - fclose (infile); - unlink (tmpfile2); - - return ERR_NO_ERROR; -} - -int -ts_get_backup_list (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char buf[1024], file[PATH_MAX], s1[256], s2[256], *dbname, log_dir[512]; - FILE *infile; - int lv = -1; - - dbname = nv_get_val (req, "dbname"); - if (dbname == NULL) - { - strcpy (_dbmt_error, "database name"); - return ERR_PARAM_MISSING; - } - - if (uRetrieveDBLogDirectory (dbname, log_dir) != ERR_NO_ERROR) - { - strcpy (_dbmt_error, dbname); - return ERR_DBDIRNAME_NULL; - } - - snprintf (file, PATH_MAX - 1, "%s/%s%s", log_dir, dbname, - ARNIADB_BACKUP_INFO_EXT); - if ((infile = fopen (file, "rt")) != NULL) - { - while (fgets (buf, sizeof (buf), infile)) - { - sscanf (buf, "%255s %*s %255s", s1, s2); - lv = atoi (s1); - snprintf (buf, sizeof (buf) - 1, "level%d", lv); - nv_add_nvp (res, buf, s2); - } - fclose (infile); - } - for (lv++; lv <= 2; lv++) - { - snprintf (buf, sizeof (buf) - 1, "level%d", lv); - nv_add_nvp (res, buf, "none"); - } - - return ERR_NO_ERROR; -} - -static char * -remove_special_characters (char *str) -{ - char ret_old[MAX_LINE]; - char ret_new[MAX_LINE]; - unsigned int i = 0; - unsigned int j = 0; - - ret_new[0] = '\0'; - snprintf (ret_old, sizeof (ret_old), "%s", str); - - for (i = 0; i < sizeof (ret_old); i ++) - { - if ((ret_old[i] == '[') || (ret_old[i] == ']')) - { - continue; - } - ret_new[j] = ret_old[i]; - j++; - } - - snprintf (str, sizeof (ret_old), "%s", ret_new); - - return str; -} - -#if defined(WINDOWS) -static int -_get_dir_list (list < string > &files_list, const char *roor_dir, string special_key) -{ - HANDLE handle; - WIN32_FIND_DATA ffd; - char find_path[PATH_MAX]; - string cms_log_name; - - snprintf (find_path, PATH_MAX, "%s/*", roor_dir); - - handle = FindFirstFile (find_path, &ffd); - if (handle == INVALID_HANDLE_VALUE) - { - return -1; - } - while (FindNextFile (handle, &ffd)) - { - if (ffd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN - || ffd.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) - { - continue; - } - else if (! (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) - { - cms_log_name = ffd.cFileName; - if (special_key.length() == 0) - { - files_list.push_back (cms_log_name); - } - else - { - if (cms_log_name.find (special_key) < cms_log_name.length()) - { - files_list.push_back (cms_log_name); - } - } - } - } - FindClose (handle); - - return 0; -} - -#else - -static int -_get_dir_list (list < string > &files_list, const char *roor_dir, string special_key) -{ - DIR *dirptr = NULL; - struct dirent *entry; - string cms_log_name; - - if ((dirptr = opendir (roor_dir)) == NULL) - { - return -1; - } - while ((entry = readdir (dirptr)) != NULL) - { - if (strcmp (entry->d_name, ".") == 0 || strcmp (entry->d_name, "..") == 0) - { - continue; - } - - cms_log_name = entry->d_name; - - if (special_key.length() == 0) - { - files_list.push_back (cms_log_name); - } - else - { - if (cms_log_name.find (special_key) < cms_log_name.length()) - { - files_list.push_back (cms_log_name); - } - } - } - - closedir (dirptr); - return 0; -} -#endif - -static list < string > -_get_filtered_files_list (list < string > &files_list, string file_exp) -{ - list < string >::iterator itor; - list < string > ret_files_list; - - ret_files_list.clear(); - - if (files_list.empty() == true) - { - return ret_files_list; - } - - for (itor = files_list.begin(); itor != files_list.end(); itor++) - { - if ((*itor).find (file_exp) < (*itor).length()) - { - ret_files_list.push_back (*itor); - } - } - return ret_files_list; -} - -int -ts_load_access_log (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char buf[MAX_LINE], time[256]; - char root_dir[PATH_MAX]; - char log_full_dir[PATH_MAX]; - char err_full_dir[PATH_MAX]; - FILE *infile; - char *tok[10]; - unsigned int message_line = 0; - string log_exp = ".log"; - string err_exp = ".err"; - string cms_process_name = CMS_NAME; - list < string > all_files_list; - list < string > err_files_list; - list < string > log_files_list; - list < string >::iterator itor; - - buf[0] = '\0'; - time[0] = '\0'; - root_dir[0] = '\0'; - log_full_dir[0] = '\0'; - err_full_dir[0] = '\0'; - - snprintf (root_dir, PATH_MAX, "%s/%s/", sco.szArniadb, DBMT_LOG_DIR); - - _get_dir_list (all_files_list, root_dir, cms_process_name); - - log_files_list = _get_filtered_files_list (all_files_list, log_exp); - -#ifndef JSON_SUPPORT - nv_add_nvp (res, "open", "accesslog"); -#endif - for (itor = log_files_list.begin(); itor != log_files_list.end(); itor++) - { - snprintf (log_full_dir, PATH_MAX, "%s%s", root_dir, (*itor).c_str()); - if ((infile = fopen (log_full_dir, "rt")) != NULL) - { - while (fgets (buf, sizeof (buf), infile) != NULL) - { - remove_special_characters (buf); - ut_trim (buf); - - if (string_tokenize (buf, tok, 9) < 0) - { - continue; - } - - if (strcmp (tok[5], ACCESS_LOG) != 0) - { - continue; - } - - if (message_line > MAX_MSG_LINE) - { - nv_add_nvp (res, "full_line", - "The message is too much, please go to the log path and get the left."); -#ifndef JSON_SUPPORT - nv_add_nvp (res, "close", "errorlog"); -#endif - fclose (infile); - return ERR_NO_ERROR; - } -#ifdef JSON_SUPPORT - nv_add_nvp (res, "open", "accesslog"); -#endif - nv_add_nvp (res, ENCRYPT_ARG ("user"), tok[6]); - nv_add_nvp (res, "taskname", tok[8]); - snprintf (time, sizeof (time) - 1, "%s %s", tok[0], tok[1]); - nv_add_nvp (res, "time", time); - -#ifdef JSON_SUPPORT - nv_add_nvp (res, "close", "accesslog"); -#endif - - message_line++; - } - fclose (infile); - } - } - -#ifndef JSON_SUPPORT - nv_add_nvp (res, "close", "accesslog"); -#endif - - err_files_list = _get_filtered_files_list (all_files_list, err_exp); -#ifndef JSON_SUPPORT - nv_add_nvp (res, "open", "errorlog"); -#endif - for (itor = err_files_list.begin(); itor != err_files_list.end(); itor++) - { - snprintf (err_full_dir, PATH_MAX, "%s%s", root_dir, (*itor).c_str()); - if ((infile = fopen (err_full_dir, "rt")) != NULL) - { - while (fgets (buf, sizeof (buf), infile) != NULL) - { - remove_special_characters (buf); - ut_trim (buf); - - if (string_tokenize (buf, tok, 9) < 0) - { - continue; - } - - if (strcmp (tok[5], ACCESS_ERR) != 0) - { - continue; - } - - if (message_line > MAX_MSG_LINE) - { - nv_add_nvp (res, "full_line", - "The message is too much, please go to the log path and get the left."); -#ifndef JSON_SUPPORT - nv_add_nvp (res, "close", "errorlog"); -#endif - fclose (infile); - return ERR_NO_ERROR; - } - -#ifdef JSON_SUPPORT - nv_add_nvp (res, "open", "errorlog"); -#endif - nv_add_nvp (res, ENCRYPT_ARG ("user"), tok[6]); - nv_add_nvp (res, "taskname", tok[8]); - snprintf (time, sizeof (time) - 1, "%s %s", tok[0], tok[1]); - nv_add_nvp (res, "time", time); - nv_add_nvp (res, "errornote", tok[8] + strlen (tok[8]) + 1); -#ifdef JSON_SUPPORT - nv_add_nvp (res, "close", "errorlog"); -#endif - - message_line++; - } - fclose (infile); - } - } -#ifndef JSON_SUPPORT - nv_add_nvp (res, "close", "errorlog"); -#endif - return ERR_NO_ERROR; -} - -static void -_get_error_access_log_files (nvplist *req, nvplist *res, bool is_access_log) -{ - char log_full_dir[PATH_MAX]; - char root_dir[PATH_MAX]; - list < string > log_files_list; - list < string > all_files_list; - list < string >::iterator itor; - - string cms_process_name = CMS_NAME; - string log_exp = ".log"; - if (is_access_log == false) - { - log_exp = ".err"; - } - - log_full_dir[0] = '\0'; - - snprintf (root_dir, PATH_MAX, "%s/%s/", sco.szArniadb, DBMT_LOG_DIR); - - _get_dir_list (all_files_list, root_dir, cms_process_name); - log_files_list = _get_filtered_files_list (all_files_list, log_exp); - - if (log_files_list.empty() == true) - { - nv_add_nvp (res, "open", "logfileslist"); - - snprintf (log_full_dir, PATH_MAX, "%s%s%s", root_dir, cms_process_name.c_str(), log_exp.c_str()); - nv_add_nvp (res, "logfile", log_full_dir); - - nv_add_nvp (res, "close", "logfileslist"); - } - - for (itor = log_files_list.begin(); itor != log_files_list.end(); itor++) - { - nv_add_nvp (res, "open", "logfileslist"); - - snprintf (log_full_dir, PATH_MAX, "%s%s", root_dir, (*itor).c_str()); - nv_add_nvp (res, "logfile", log_full_dir); - - nv_add_nvp (res, "close", "logfileslist"); - } -} - - -int -ts_get_access_log_files (nvplist *req, nvplist *res, char *_dbmt_error) -{ - _get_error_access_log_files (req, res, true); - - return ERR_NO_ERROR; -} - -int -ts_get_error_log_files (nvplist *req, nvplist *res, char *_dbmt_error) -{ - _get_error_access_log_files (req, res, false); - - return ERR_NO_ERROR; -} - -int -tsGetAutoaddvolLog (nvplist *req, nvplist *res, char *_dbmt_error) -{ - FILE *infile; - char strbuf[1024]; - char dbname[512]; - char volname[512]; - char purpose[512]; - char page[512]; - char time[512]; - char outcome[512]; - char file[PATH_MAX]; - char *start_time, *end_time; - - start_time = nv_get_val (req, "start_time"); - end_time = nv_get_val (req, "end_time"); - - infile = fopen (conf_get_dbmt_file (FID_AUTO_ADDVOLDB_LOG, file), "r"); - if (infile != NULL) - { - while (fgets (strbuf, sizeof (strbuf), infile)) - { - uRemoveCRLF (strbuf); - /*testdb testdb_x002 data 1024 2012-11-16,10:4:57 success */ - sscanf (strbuf, "%511s %511s %511s %511s %511s %511s", dbname, - volname, purpose, page, time, outcome); - if (start_time != NULL && strcmp (time, start_time) < 0) - { - continue; - } - if (end_time != NULL && strcmp (time, end_time) > 0) - { - continue; - } - nv_add_nvp (res, "open", "log"); - nv_add_nvp (res, "dbname", dbname); - nv_add_nvp (res, "volname", volname); - nv_add_nvp (res, "purpose", purpose); - nv_add_nvp (res, "page", page); - nv_add_nvp (res, "time", time); - nv_add_nvp (res, "outcome", outcome); - nv_add_nvp (res, "close", "log"); - } - fclose (infile); - } - return ERR_NO_ERROR; -} - -int -ts_check_dir (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char *n, *v; - int i; - for (i = 0; i < req->nvplist_leng; i++) - { - nv_lookup (req, i, &n, &v); - if ((n != NULL) && (strcmp (n, "dir") == 0)) - { - if ((v == NULL) || (access (v, F_OK) < 0)) - { - nv_add_nvp (res, "noexist", v); - } - } - } - - return ERR_NO_ERROR; -} - -int -ts_check_file (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char *n, *v; - int i; - for (i = 0; i < req->nvplist_leng; i++) - { - nv_lookup (req, i, &n, &v); - if ((n != NULL) && (strcmp (n, "file") == 0)) - { - if ((v != NULL) && (access (v, F_OK) == 0)) - { - nv_add_nvp (res, "existfile", v); - } - } - } - - return ERR_NO_ERROR; -} - -int -ts_get_autobackupdb_error_log (nvplist *req, nvplist *res, - char *_dbmt_error) -{ - char buf[1024], logfile[PATH_MAX], s1[256], s2[256], time[512], dbname[256], - backupid[256]; - char *start_time, *end_time; - FILE *infile; - - start_time = nv_get_val (req, "start_time"); - end_time = nv_get_val (req, "end_time"); - - snprintf (logfile, PATH_MAX - 1, "%s/log/manager/auto_backupdb.log", - sco.szArniadb); - if ((infile = fopen (logfile, "r")) == NULL) - { - return ERR_NO_ERROR; - } - - while (fgets (buf, sizeof (buf), infile)) - { - if (sscanf (buf, "%255s %255s", s1, s2) != 2) - { - continue; - } - if (!strncmp (s1, "DATE:", 5)) - { - snprintf (time, sizeof (time) - 1, "%s %s", s1 + 5, s2 + 5); - if (start_time != NULL && strcmp (time, start_time) < 0) - { - continue; - } - if (end_time != NULL && strcmp (time, end_time) > 0) - { - continue; - } - if (fgets (buf, sizeof (buf), infile) == NULL) - { - break; - } - sscanf (buf, "%255s %255s", s1, s2); - snprintf (dbname, sizeof (dbname) - 1, "%s", s1 + 7); - snprintf (backupid, sizeof (backupid) - 1, "%s", s2 + 9); - if (fgets (buf, sizeof (buf), infile) == NULL) - { - break; - } - uRemoveCRLF (buf); - nv_add_nvp (res, "open", "error"); - nv_add_nvp (res, "dbname", dbname); - nv_add_nvp (res, "backupid", backupid); - nv_add_nvp (res, "error_time", time); - nv_add_nvp (res, "error_desc", buf + 3); - nv_add_nvp (res, "close", "error"); - } - } - fclose (infile); - - return ERR_NO_ERROR; -} - -int -ts_get_autoexecquery_error_log (nvplist *req, nvplist *res, - char *_dbmt_error) -{ - char buf[1024], logfile[PATH_MAX], s1[256], s2[256], s3[256], s4[256], - time[512], dbname[256], username[256], query_id[256], error_code[256]; - char *start_time, *end_time; - FILE *infile; - - start_time = nv_get_val (req, "start_time"); - end_time = nv_get_val (req, "end_time"); - - snprintf (logfile, PATH_MAX - 1, "%s/log/manager/auto_execquery.log", - sco.szArniadb); - if ((infile = fopen (logfile, "r")) == NULL) - { - return ERR_NO_ERROR; - } - - while (fgets (buf, sizeof (buf), infile)) - { - if (sscanf (buf, "%255s %255s", s1, s2) != 2) - { - continue; - } - if (!strncmp (s1, "DATE:", 5)) - { - snprintf (time, sizeof (time) - 1, "%s %s", s1 + 5, s2 + 5); /* 5 = strlen("DATE:"); 5 = strlen("TIME:"); */ - if (start_time != NULL && strcmp (time, start_time) < 0) - { - continue; - } - if (end_time != NULL && strcmp (time, end_time) > 0) - { - continue; - } - if (fgets (buf, sizeof (buf), infile) == NULL) - { - break; - } - - s3[0] = 0; - sscanf (buf, "%255s %255s %255s %255s", s1, s2, s3, s4); - snprintf (dbname, sizeof (dbname) - 1, "%s", s1 + 7); /* 7 = strlen("DBNAME:") */ - snprintf (username, sizeof (username) - 1, "%s", s2 + 14); /* 14 = strlen("EMGR-USERNAME:") */ - snprintf (query_id, sizeof (query_id) - 1, "%s", s3 + 9); /* 9 = strlen("QUERY-ID:") */ - snprintf (error_code, sizeof (error_code) - 1, "%s", s4 + 11); /* 11 = strlen("ERROR-CODE:") */ - if (fgets (buf, sizeof (buf), infile) == NULL) - { - break; - } - - uRemoveCRLF (buf); - nv_add_nvp (res, "open", "error"); - nv_add_nvp (res, "dbname", dbname); - nv_add_nvp (res, ENCRYPT_ARG ("username"), username); - nv_add_nvp (res, "query_id", query_id); - nv_add_nvp (res, "error_time", time); - nv_add_nvp (res, "error_code", error_code); - nv_add_nvp (res, "error_desc", buf + 3); - nv_add_nvp (res, "close", "error"); - } - } - fclose (infile); - return ERR_NO_ERROR; -} - -int -ts_trigger_operation (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char *task, *dbname, *dbuser, *dbpasswd; - char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; - int ha_mode = 0; - char cmd_name[ARNIADB_CMD_NAME_LEN]; - const char *argv[11]; - char input_file[PATH_MAX]; - char arniadb_err_file[PATH_MAX]; - int retval, argc; - T_DB_SERVICE_MODE db_mode; - - input_file[0] = '\0'; - arniadb_err_file[0] = '\0'; - - task = nv_get_val (req, "task"); - if (task != NULL) - { - if (strcmp (task, "addtrigger") == 0) - { - snprintf (input_file, PATH_MAX - 1, "%s/dbmt_task_%d_%d", - sco.dbmt_tmp_dir, TS_ADDNEWTRIGGER, (int) getpid ()); - } - else if (strcmp (task, "droptrigger") == 0) - { - snprintf (input_file, PATH_MAX - 1, "%s/dbmt_task_%d_%d", - sco.dbmt_tmp_dir, TS_DROPTRIGGER, (int) getpid ()); - } - else if (strcmp (task, "altertrigger") == 0) - { - snprintf (input_file, PATH_MAX - 1, "%s/dbmt_task_%d_%d", - sco.dbmt_tmp_dir, TS_ALTERTRIGGER, (int) getpid ()); - } - } - - dbname = nv_get_val (req, "_DBNAME"); - dbuser = nv_get_val (req, "_DBID"); - dbpasswd = nv_get_val (req, "_DBPASSWD"); - - cmd_name[0] = '\0'; - snprintf (cmd_name, sizeof (cmd_name) - 1, "%s/%s%s", sco.szArniadb, - ARNIADB_DIR_BIN, UTIL_ASQL_NAME); - argc = 0; - argv[argc++] = cmd_name; - - db_mode = uDatabaseMode (dbname, &ha_mode); - if (ha_mode != 0) - { - append_host_to_dbname (dbname_at_hostname, dbname, - sizeof (dbname_at_hostname)); - argv[argc++] = dbname_at_hostname; - } - else - { - argv[argc++] = dbname; - } - - argv[argc++] = NULL; - argv[argc++] = "--" ASQL_INPUT_FILE_L; - argv[argc++] = input_file; - if (dbuser) - { - argv[argc++] = "--" ASQL_USER_L; - argv[argc++] = dbuser; - if (dbpasswd) - { - argv[argc++] = "--" ASQL_PASSWORD_L; - argv[argc++] = dbpasswd; - } - } - - argv[argc++] = "--" ASQL_NO_AUTO_COMMIT_L; - - for (; argc < 11; argc++) - { - argv[argc] = NULL; - } - - if (!_isRegisteredDB (dbname)) - { - return ERR_DB_NONEXISTANT; - } - - if (db_mode == DB_SERVICE_MODE_SA) - { - sprintf (_dbmt_error, "%s", dbname); - return ERR_STANDALONE_MODE; - } - - if (db_mode == DB_SERVICE_MODE_CS) - { - /* run asql command with -cs option */ - argv[2] = "--" ASQL_CS_MODE_L; - } - - if (db_mode == DB_SERVICE_MODE_NONE) - { - /* run asql command with -sa option */ - argv[2] = "--" ASQL_SA_MODE_L; - } - - /* asql -sa -i input_file dbname */ - if (task != NULL) - { - if (strcmp (task, "addtrigger") == 0) - { - if (op_make_triggerinput_file_add (req, input_file) == 0) - { - strcpy (_dbmt_error, argv[0]); - return ERR_TMPFILE_OPEN_FAIL; - } - } - else if (strcmp (task, "droptrigger") == 0) - { - if (op_make_triggerinput_file_drop (req, input_file) == 0) - { - strcpy (_dbmt_error, argv[0]); - return ERR_TMPFILE_OPEN_FAIL; - } - } - else if (strcmp (task, "altertrigger") == 0) - { - if (op_make_triggerinput_file_alter (req, input_file) == 0) - { - strcpy (_dbmt_error, argv[0]); - return ERR_TMPFILE_OPEN_FAIL; - } - } - } - - snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", - sco.dbmt_tmp_dir, "trigger_operation", getpid ()); - SET_TRANSACTION_NO_WAIT_MODE_ENV (); - - retval = run_child (argv, 1, NULL, NULL, arniadb_err_file, NULL); /* asql - trigger */ - if (strlen (input_file) > 0) - { - unlink (input_file); - } - - if (read_asql_error_file (arniadb_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) - { - if (access (arniadb_err_file, F_OK) == 0) - { - unlink (arniadb_err_file); - } - return ERR_WITH_MSG; - } - if (access (arniadb_err_file, F_OK) == 0) - { - unlink (arniadb_err_file); - } - if (retval < 0) - { - strcpy (_dbmt_error, argv[0]); - return ERR_SYSTEM_CALL; - } - - nv_add_nvp (res, "dbname", dbname); - - return ERR_NO_ERROR; -} - -int -ts_get_triggerinfo (nvplist *req, nvplist *res, char *_dbmt_error) -{ - return cm_ts_get_triggerinfo (req, res, _dbmt_error); -} - -int -ts_set_autoexec_query (nvplist *req, nvplist *res, char *_dbmt_error) -{ - FILE *conf_file, *temp_file; - char autoexecquery_conf_file[PATH_MAX]; - char tmpfile[PATH_MAX]; - char db_uid[64]; - char db_name[DB_NAME_LEN]; - char dbmt_uid[DBMT_USER_NAME_LEN]; - char enc_dbpasswd[PASSWD_ENC_LENGTH]; - nvplist *db_user_info; - char line_buf[MAX_JOB_CONFIG_FILE_LINE_LENGTH]; - char *conf_item[AUTOEXECQUERY_CONF_ENTRY_NUM]; - int i, nvlist_index, nvlist_section_len; - char *name, *value; - - if ((conf_item[0] = nv_get_val (req, "_DBNAME")) == NULL) - { - sprintf (_dbmt_error, "%s", "database name"); - return ERR_PARAM_MISSING; - } - - if ((conf_item[4] = nv_get_val (req, "_ID")) == NULL) - { - sprintf (_dbmt_error, "%s", "database user"); - return ERR_PARAM_MISSING; - } - - conf_get_dbmt_file (FID_AUTO_EXECQUERY_CONF, autoexecquery_conf_file); - if (access (autoexecquery_conf_file, F_OK) == 0) - { - conf_file = fopen (autoexecquery_conf_file, "r"); - } - else - { - conf_file = fopen (autoexecquery_conf_file, "w+"); - } - if (conf_file == NULL) - { - return ERR_FILE_OPEN_FAIL; - } - - snprintf (tmpfile, PATH_MAX - 1, "%s/DBMT_task_045.%d", sco.dbmt_tmp_dir, - (int) getpid ()); - if ((temp_file = fopen (tmpfile, "w")) == NULL) - { - fclose (conf_file); - return ERR_TMPFILE_OPEN_FAIL; - } - - db_user_info = nv_create (5, NULL, "\n", ":", "\n"); - while (fgets (line_buf, sizeof (line_buf), conf_file) != NULL) - { - if (obsolete_version_autoexecquery_conf (line_buf)) - { - if (sscanf (line_buf, "%64s %*s %64s", db_name, dbmt_uid) < 2) - { - continue; - } - - if ((strcmp (dbmt_uid, conf_item[4]) != 0) - || (strcmp (db_name, conf_item[0]) != 0)) - { - /* configure item not set by current dbmt_user, - * or it has no relation with current database */ - fputs (line_buf, temp_file); - } - } - else - { - if (sscanf - (line_buf, "%64s %*s %64s %80s %64s", db_name, db_uid, - enc_dbpasswd, dbmt_uid) < 4) - { - continue; - } - - if ((strcmp (dbmt_uid, conf_item[4]) != 0) - || (strcmp (db_name, conf_item[0]) != 0)) - { - fputs (line_buf, temp_file); - } - else - { - nv_add_nvp (db_user_info, db_uid, enc_dbpasswd); - } - } - } - fclose (conf_file); - - nv_locate (req, "planlist", &nvlist_index, &nvlist_section_len); - if (nvlist_section_len == 0) - { - fclose (temp_file); - move_file (tmpfile, autoexecquery_conf_file); - - return ERR_NO_ERROR; - } - - name = value = NULL; - for (i = nvlist_index + 1; i < nvlist_index + nvlist_section_len; i += 8) - { - /* open:queryplan */ - if (value != NULL && strcasecmp (value, "planlist") == 0) - { - fclose (temp_file); - return ERR_NO_ERROR; - } - - /* query_id */ - nv_lookup (req, i, &name, &value); - conf_item[1] = value; - - /* db_uid */ - nv_lookup (req, i + 1, &name, &value); - conf_item[2] = value; - - /* db_passwd */ - nv_lookup (req, i + 2, &name, &value); - if (strcmp (value, "unknown") == 0) - { - if ((conf_item[3] = - nv_get_val (db_user_info, conf_item[2])) == NULL) - { - uEncrypt (PASSWD_LENGTH, "", enc_dbpasswd); - conf_item[3] = enc_dbpasswd; - } - } - else if (strcmp (value, "none") == 0) - { - uEncrypt (PASSWD_LENGTH, "", enc_dbpasswd); - conf_item[3] = enc_dbpasswd; - } - else - { - uEncrypt (PASSWD_LENGTH, value, enc_dbpasswd); - conf_item[3] = enc_dbpasswd; - } - - /* period */ - nv_lookup (req, i + 3, &name, &value); - conf_item[5] = value; - - /* time detail */ - nv_lookup (req, i + 4, &name, &value); - conf_item[6] = value; - - /* query string */ - nv_lookup (req, i + 5, &name, &value); - if ((value != NULL) && (strlen (value) > MAX_AUTOQUERY_SCRIPT_SIZE)) - { - sprintf (_dbmt_error, - "Query script too long. MAX_AUTOQUERY_SCRIPT_SIZE:%d.", - MAX_AUTOQUERY_SCRIPT_SIZE); - fclose (temp_file); - return ERR_WITH_MSG; - } - else - { - conf_item[7] = value; - } - - fprintf (temp_file, "%s %s %s %s %s %s %s %s\n", conf_item[0], - conf_item[1], conf_item[2], conf_item[3], conf_item[4], - conf_item[5], conf_item[6], conf_item[7]); - /* close:queryplan */ - } - fclose (temp_file); - move_file (tmpfile, autoexecquery_conf_file); - - nv_destroy (db_user_info); - - return ERR_NO_ERROR; -} - -int -ts_get_autoexec_query (nvplist *req, nvplist *res, char *_dbmt_error) -{ - int retval = ERR_NO_ERROR; - FILE *conf_file; - char autoexecquery_conf_file[PATH_MAX]; - int conf_item_num; - char *dbname, *dbmt_uid; - char line_buf[MAX_JOB_CONFIG_FILE_LINE_LENGTH]; - char *conf_item[AUTOEXECQUERY_CONF_ENTRY_NUM]; - char exectime_detail[256]; - - conf_get_dbmt_file (FID_AUTO_EXECQUERY_CONF, autoexecquery_conf_file); - if (access (autoexecquery_conf_file, F_OK) == 0) - { - conf_file = fopen (autoexecquery_conf_file, "r"); - if (!conf_file) - { - return ERR_FILE_OPEN_FAIL; - } - } - else - { - nv_add_nvp (res, "open", "planlist"); - nv_add_nvp (res, "close", "planlist"); - return ERR_NO_ERROR; - } - - nv_add_nvp (res, "open", "planlist"); - dbname = nv_get_val (req, "_DBNAME"); - dbmt_uid = nv_get_val (req, "_ID"); - if (dbname == NULL || dbmt_uid == NULL) - { - goto err_ts_get_autoexec_query; - } - nv_add_nvp (res, "dbname", dbname); - - while (fgets (line_buf, sizeof (line_buf), conf_file) != NULL) - { - ut_trim (line_buf); - - if (obsolete_version_autoexecquery_conf (line_buf)) - { - conf_item_num = AUTOEXECQUERY_CONF_ENTRY_NUM - 2; - } - else - { - conf_item_num = AUTOEXECQUERY_CONF_ENTRY_NUM; - } - - if (string_tokenize_accept_laststring_space - (line_buf, conf_item, conf_item_num) < 0) - { - strcpy_limit (_dbmt_error, - "autoexecquery.conf contains syntax error.", - DBMT_ERROR_MSG_SIZE); - retval = ERR_WITH_MSG; - goto err_ts_get_autoexec_query; - } - - if (strcmp (dbname, conf_item[0]) != 0 - || strcmp (dbmt_uid, conf_item[conf_item_num - 5]) != 0) - { - continue; - } - - nv_add_nvp (res, "open", "queryplan"); - nv_add_nvp (res, "query_id", conf_item[1]); - - if (conf_item_num == AUTOEXECQUERY_CONF_ENTRY_NUM) - { - nv_add_nvp (res, ENCRYPT_ARG ("username"), conf_item[2]); - } - else - { - nv_add_nvp (res, ENCRYPT_ARG ("username"), NULL); - } - - nv_add_nvp (res, "period", conf_item[conf_item_num - 4]); - snprintf (exectime_detail, sizeof (exectime_detail) - 1, "%s %s", - conf_item[conf_item_num - 3], conf_item[conf_item_num - 2]); - nv_add_nvp (res, "detail", exectime_detail); - nv_add_nvp (res, "query_string", conf_item[conf_item_num - 1]); - nv_add_nvp (res, "close", "queryplan"); - } - -err_ts_get_autoexec_query: - nv_add_nvp (res, "close", "planlist"); - fclose (conf_file); - - return retval; -} - -int -ts_addstatustemplate (nvplist *cli_request, nvplist *cli_response, - char *diag_error) -{ - FILE *templatefile, *tempfile; - char templatefilepath[PATH_MAX], tempfilepath[PATH_MAX]; - char buf[1024]; - char *templatename, *desc, *sampling_term, *dbname; - int ret_val = ERR_NO_ERROR; - - templatename = nv_get_val (cli_request, "name"); - desc = nv_get_val (cli_request, "desc"); - sampling_term = nv_get_val (cli_request, "sampling_term"); - dbname = nv_get_val (cli_request, "db_name"); - - if (templatename == NULL) - { - snprintf (diag_error, DBMT_ERROR_MSG_SIZE, "%s", "name"); - return ERR_PARAM_MISSING; - } - - /* write related information to template config file */ - conf_get_dbmt_file (FID_DIAG_STATUS_TEMPLATE, templatefilepath); - if (access (templatefilepath, F_OK) < 0) - { - templatefile = fopen (templatefilepath, "w"); - if (templatefile == NULL) - { - if (diag_error) - { - strcpy (diag_error, templatefilepath); - } - return ERR_FILE_OPEN_FAIL; - } - fclose (templatefile); - } - - if ((templatefile = fopen (templatefilepath, "r")) == NULL) - { - if (diag_error) - { - strcpy (diag_error, templatefilepath); - } - return ERR_FILE_OPEN_FAIL; - } - - snprintf (tempfilepath, PATH_MAX - 1, "%s/statustemplate_add.tmp", - sco.dbmt_tmp_dir); - if ((tempfile = fopen (tempfilepath, "w+")) == NULL) - { - if (diag_error) - { - strcpy (diag_error, tempfilepath); - } - fclose (templatefile); - return ERR_FILE_OPEN_FAIL; - } - - while (fgets (buf, sizeof (buf), templatefile)) - { - if (strncmp (buf, "<<<", 3) == 0) - { - fprintf (tempfile, "%s", buf); - - /* template name */ - if (! (fgets (buf, sizeof (buf), templatefile))) - { - break; - } - buf[strlen (buf) - 1] = '\0'; - if (strcmp (buf, templatename) == 0) - { - strcpy (diag_error, templatename); - ret_val = ERR_TEMPLATE_ALREADY_EXIST; - break; - } - - fprintf (tempfile, "%s\n", buf); - - /* copy others */ - while (fgets (buf, sizeof (buf), templatefile)) - { - fprintf (tempfile, "%s", buf); - if (strncmp (buf, ">>>", 3) == 0) - { - break; - } - } - } - } - - if (ret_val == ERR_NO_ERROR) - { - int i, config_index, config_length; - char *target_name, *target_value; - - /* add new template config */ - fprintf (tempfile, "<<<\n"); - fprintf (tempfile, "%s\n", templatename); - if (desc) - { - fprintf (tempfile, "%s\n", desc); - } - else - { - fprintf (tempfile, " \n"); - } - - if (dbname) - { - fprintf (tempfile, "%s\n", dbname); - } - else - { - fprintf (tempfile, " \n"); - } - - fprintf (tempfile, "%s\n", sampling_term); - - if (nv_locate - (cli_request, "target_config", &config_index, &config_length) != 1) - { - ret_val = ERR_REQUEST_FORMAT; - } - else - { - for (i = config_index; i < config_index + config_length; i++) - { - if (nv_lookup (cli_request, i, &target_name, &target_value) == 1) - { - fprintf (tempfile, "%s %s\n", target_name, target_value); - } - else - { - ret_val = ERR_REQUEST_FORMAT; - break; - } - } - fprintf (tempfile, ">>>\n"); - } - } - - fclose (tempfile); - fclose (templatefile); - - if (ret_val == ERR_NO_ERROR) - { - unlink (templatefilepath); - rename (tempfilepath, templatefilepath); - } - else - { - unlink (tempfilepath); - } - - return ret_val; -} - -int -ts_removestatustemplate (nvplist *cli_request, nvplist *cli_response, - char *diag_error) -{ - FILE *templatefile, *tempfile; - char templatefilepath[PATH_MAX], tempfilepath[PATH_MAX]; - char buf[1024]; - char *templatename; - int ret_val = ERR_NO_ERROR; - - templatename = nv_get_val (cli_request, "name"); - - if (templatename == NULL) - { - snprintf (diag_error, DBMT_ERROR_MSG_SIZE, "%s", "name"); - return ERR_PARAM_MISSING; - } - - /* write related information to template config file */ - conf_get_dbmt_file (FID_DIAG_STATUS_TEMPLATE, templatefilepath); - if ((templatefile = fopen (templatefilepath, "r")) == NULL) - { - if (diag_error) - { - strcpy (diag_error, templatefilepath); - } - return ERR_FILE_OPEN_FAIL; - } - - snprintf (tempfilepath, PATH_MAX - 1, "%s/statustemplate_remove.tmp", - sco.dbmt_tmp_dir); - if ((tempfile = fopen (tempfilepath, "w+")) == NULL) - { - if (diag_error) - { - strcpy (diag_error, tempfilepath); - } - fclose (templatefile); - return ERR_FILE_OPEN_FAIL; - } - - while (fgets (buf, sizeof (buf), templatefile)) - { - if (strncmp (buf, "<<<", 3) == 0) - { - /* template name */ - if (! (fgets (buf, sizeof (buf), templatefile))) - { - break; - } - buf[strlen (buf) - 1] = '\0'; - if (strcmp (buf, templatename) == 0) - { - continue; - } - - fprintf (tempfile, "<<<\n"); - fprintf (tempfile, "%s\n", buf); - - /* copy others */ - while (fgets (buf, sizeof (buf), templatefile)) - { - fprintf (tempfile, "%s", buf); - if (strncmp (buf, ">>>", 3) == 0) - { - break; - } - } - } - } - - fclose (tempfile); - fclose (templatefile); - - if (ret_val == ERR_NO_ERROR) - { - unlink (templatefilepath); - rename (tempfilepath, templatefilepath); - } - else - { - unlink (tempfilepath); - } - - return ret_val; -} - -int -ts_updatestatustemplate (nvplist *cli_request, nvplist *cli_response, - char *diag_error) -{ - FILE *templatefile, *tempfile; - char templatefilepath[PATH_MAX], tempfilepath[PATH_MAX]; - char buf[1024]; - char *templatename, *desc, *sampling_term, *dbname; - int ret_val = ERR_NO_ERROR; - - templatename = nv_get_val (cli_request, "name"); - desc = nv_get_val (cli_request, "desc"); - sampling_term = nv_get_val (cli_request, "sampling_term"); - dbname = nv_get_val (cli_request, "db_name"); - - if (templatename == NULL) - { - snprintf (diag_error, DBMT_ERROR_MSG_SIZE, "%s", "name"); - return ERR_PARAM_MISSING; - } - - /* write related information to template config file */ - conf_get_dbmt_file (FID_DIAG_STATUS_TEMPLATE, templatefilepath); - if ((templatefile = fopen (templatefilepath, "r")) == NULL) - { - if (diag_error) - { - strcpy (diag_error, templatefilepath); - } - return ERR_FILE_OPEN_FAIL; - } - - snprintf (tempfilepath, PATH_MAX - 1, "%s/statustemplate_update_%d.tmp", - sco.dbmt_tmp_dir, getpid ()); - if ((tempfile = fopen (tempfilepath, "w+")) == NULL) - { - if (diag_error) - { - strcpy (diag_error, tempfilepath); - } - fclose (templatefile); - return ERR_FILE_OPEN_FAIL; - } - - while (fgets (buf, sizeof (buf), templatefile)) - { - if (strncmp (buf, "<<<", 3) == 0) - { - fprintf (tempfile, "%s", buf); - - /* template name */ - if (! (fgets (buf, sizeof (buf), templatefile))) - { - break; - } - buf[strlen (buf) - 1] = '\0'; - if (strcmp (buf, templatename) == 0) - { - int i, config_index, config_length; - char *target_name, *target_value; - - /* add new configuration */ - fprintf (tempfile, "%s\n", templatename); - if (desc) - { - fprintf (tempfile, "%s\n", desc); - } - else - { - fprintf (tempfile, " \n"); - } - - if (dbname) - { - fprintf (tempfile, "%s\n", dbname); - } - else - { - fprintf (tempfile, " \n"); - } - - fprintf (tempfile, "%s\n", sampling_term); - - if (nv_locate - (cli_request, "target_config", &config_index, - &config_length) != 1) - { - ret_val = ERR_REQUEST_FORMAT; - break; - } - else - { - for (i = config_index; i < config_index + config_length; i++) - { - if (nv_lookup - (cli_request, i, &target_name, &target_value) == 1) - { - fprintf (tempfile, "%s %s\n", target_name, target_value); - } - else - { - ret_val = ERR_REQUEST_FORMAT; - break; - } - } - if (ret_val != ERR_NO_ERROR) - { - break; - } - fprintf (tempfile, ">>>\n"); - } - - continue; - } - - fprintf (tempfile, "%s\n", buf); - - /* copy others */ - while (fgets (buf, sizeof (buf), templatefile)) - { - fprintf (tempfile, "%s", buf); - if (strncmp (buf, ">>>", 3) == 0) - { - break; - } - } - } - } - - fclose (tempfile); - fclose (templatefile); - - if (ret_val == ERR_NO_ERROR) - { - unlink (templatefilepath); - rename (tempfilepath, templatefilepath); - } - else - { - unlink (tempfilepath); - } - - return ret_val; -} - -int -ts_getstatustemplate (nvplist *cli_request, nvplist *cli_response, - char *diag_error) -{ - FILE *templatefile; - char templatefilepath[PATH_MAX]; - char buf[1024]; - char *templatename; - char targetname[100], targetcolor[8], targetmag[32]; - int ret_val = ERR_NO_ERROR; - - templatename = nv_get_val (cli_request, "name"); - - /* write related information to template config file */ - conf_get_dbmt_file (FID_DIAG_STATUS_TEMPLATE, templatefilepath); - if ((templatefile = fopen (templatefilepath, "r")) == NULL) - { - return ERR_NO_ERROR; - } -#ifdef JSON_SUPPORT - nv_add_nvp (cli_response, "open", "templatelist"); -#else - nv_add_nvp (cli_response, "start", "templatelist"); -#endif - while (fgets (buf, sizeof (buf), templatefile)) - { - if (strncmp (buf, "<<<", 3) == 0) - { - /* template name */ - if (! (fgets (buf, sizeof (buf), templatefile))) - { - break; - } - buf[strlen (buf) - 1] = '\0'; - if (templatename) - { - if (strcmp (buf, templatename) != 0) - { - continue; - } - } -#ifdef JSON_SUPPORT - nv_add_nvp (cli_response, "open", "template"); -#else - nv_add_nvp (cli_response, "start", "template"); -#endif - nv_add_nvp (cli_response, "name", buf); - if (!fgets (buf, sizeof (buf), templatefile)) - { - ret_val = ERR_WITH_MSG; - if (diag_error) - { - strcpy (diag_error, "Invalid file format\n"); - strcat (diag_error, templatefilepath); - } - - break; - } - buf[strlen (buf) - 1] = '\0'; - nv_add_nvp (cli_response, "desc", buf); - - if (!fgets (buf, sizeof (buf), templatefile)) - { - ret_val = ERR_WITH_MSG; - if (diag_error) - { - strcpy (diag_error, "Invalid file format\n"); - strcat (diag_error, templatefilepath); - } - - break; - } - buf[strlen (buf) - 1] = '\0'; - nv_add_nvp (cli_response, "db_name", buf); - - if (!fgets (buf, sizeof (buf), templatefile)) - { - ret_val = ERR_WITH_MSG; - if (diag_error) - { - strcpy (diag_error, "Invalid file format\n"); - strcat (diag_error, templatefilepath); - } - - break; - } - buf[strlen (buf) - 1] = '\0'; - nv_add_nvp (cli_response, "sampling_term", buf); -#ifdef JSON_SUPPORT - nv_add_nvp (cli_response, "close", "target_config"); -#else - nv_add_nvp (cli_response, "start", "target_config"); -#endif - while (fgets (buf, sizeof (buf), templatefile)) - { - int matched; - if (strncmp (buf, ">>>", 3) == 0) - { - break; - } - matched = - sscanf (buf, "%99s %7s %31s", targetname, targetcolor, - targetmag); - if (matched != 3) - { - continue; /* error file format */ - } - nv_add_nvp (cli_response, targetname, targetcolor); - nv_add_nvp (cli_response, targetname, targetmag); - } - -#ifdef JSON_SUPPORT - nv_add_nvp (cli_response, "close", "target_config"); - nv_add_nvp (cli_response, "close", "template"); -#else - nv_add_nvp (cli_response, "end", "target_config"); - nv_add_nvp (cli_response, "end", "template"); -#endif - - } - } -#ifdef JSON_SUPPORT - nv_add_nvp (cli_response, "close", "templatelist"); -#else - nv_add_nvp (cli_response, "end", "templatelist"); -#endif - - fclose (templatefile); - - return ret_val; -} - - -int -ts_analyzecaslog (nvplist *cli_request, nvplist *cli_response, - char *diag_error) -{ - int retval, i, arg_index; - int matched, sect, sect_len; - char tmpfileQ[PATH_MAX], tmpfileRes[PATH_MAX], tmpfileT[PATH_MAX], - tmpfileanalyzeresult[PATH_MAX]; - char *logfile, *option_t; - char cmd_name[ARNIADB_CMD_NAME_LEN]; - char diag_err_file[PATH_MAX]; - const char *argv[256]; - char buf[1024], logbuf[2048]; - char qnum[16], max[32], min[32], avg[32], cnt[16], err[16]; - FILE *fdRes, *fdQ, *fdT, *fdAnalyzeResult; -#if defined(WINDOWS) - DWORD th_id; -#else - T_THREAD th_id; -#endif - diag_err_file[0] = '\0'; - - logfile = nv_get_val (cli_request, "logfile"); - option_t = nv_get_val (cli_request, "option_t"); - - /* set prarameter with logfile and execute broker_log_top */ - /* execute at current directory and copy result to $ARNIADB/tmp directory */ - snprintf (cmd_name, sizeof (cmd_name) - 1, "%s/bin/broker_log_top%s", - sco.szArniadb, DBMT_EXE_EXT); - arg_index = 0; - argv[arg_index++] = cmd_name; - if (option_t &&!strcmp (option_t, "yes")) - { - argv[arg_index++] = "-t"; - } - nv_locate (cli_request, "logfilelist", §, §_len); - if (sect == -1) - { - snprintf (diag_error, DBMT_ERROR_MSG_SIZE, "%s", "logfilelist"); - return ERR_PARAM_MISSING; - } - for (i = 0; i < sect_len; i++) - { - nv_lookup (cli_request, sect + i, NULL, &logfile); - if (logfile) - { - argv[arg_index++] = logfile; - } - } - argv[arg_index++] = NULL; - snprintf (diag_err_file, PATH_MAX, "%s/%s.%u.err.tmp", - sco.dbmt_tmp_dir, "analyzecaslog", getpid ()); - - retval = run_child (argv, 1, NULL, NULL, diag_err_file, NULL); /* broker_log_top */ - if (read_error_file (diag_err_file, diag_error, DBMT_ERROR_MSG_SIZE) < 0) - { - if (access (diag_err_file, F_OK) == 0) - { - unlink (diag_err_file); - } - return ERR_WITH_MSG; - } - - if (access (diag_err_file, F_OK) == 0) - { - unlink (diag_err_file); - } - - if (retval < 0) - { - if (diag_error) - { - strcpy (diag_error, argv[0]); - } - return ERR_SYSTEM_CALL; - } - - snprintf (tmpfileanalyzeresult, PATH_MAX - 1, "%s/analyzelog_%d.res", - sco.dbmt_tmp_dir, (int) getpid ()); - fdAnalyzeResult = fopen (tmpfileanalyzeresult, "w+"); - if (fdAnalyzeResult == NULL) - { - if (diag_error) - { - strcpy (diag_error, "Tmpfile"); - } - return ERR_FILE_OPEN_FAIL; - } - - if ((option_t != NULL) && (strcmp (option_t, "yes") == 0)) - { - int log_init_flag, log_index; - - snprintf (tmpfileT, PATH_MAX - 1, "%s/log_top_%d.t", sco.dbmt_tmp_dir, - (int) getpid ()); - rename ("./log_top.t", tmpfileT); - - fdT = fopen (tmpfileT, "r"); - if (fdT == NULL) - { - if (diag_error) - { - strcpy (diag_error, "log_top.t"); - } - fclose (fdAnalyzeResult); - return ERR_FILE_OPEN_FAIL; - } - - log_index = 1; - log_init_flag = 1; -#ifdef JSON_SUPPORT - nv_add_nvp (cli_response, "open", "resultlist"); -#else - nv_add_nvp (cli_response, "resultlist", "start"); -#endif - while (fgets (buf, sizeof (buf), fdT)) - { - char *time_str = NULL; - const char *exec_time_tag = "*** elapsed time"; - - if (strlen (buf) == 1) - { - continue; - } - - if (log_init_flag == 1) - { -#ifdef JSON_SUPPORT - nv_add_nvp (cli_response, "open", "result"); -#else - nv_add_nvp (cli_response, "result", "start"); -#endif - snprintf (qnum, sizeof (qnum) - 1, "[Q%d]", log_index); - fprintf (fdAnalyzeResult, "%s\n", qnum); - nv_add_nvp (cli_response, "qindex", qnum); - log_index++; - log_init_flag = 0; - } - - if ((time_str = strstr (buf, exec_time_tag)) != NULL) - { - time_str += strlen (exec_time_tag); - ut_trim (time_str); - - nv_add_nvp (cli_response, "exec_time", time_str); -#ifdef JSON_SUPPORT - nv_add_nvp (cli_response, "close", "result"); -#else - nv_add_nvp (cli_response, "result", "end"); -#endif - log_init_flag = 1; - } - else - { - fprintf (fdAnalyzeResult, "%s", buf); - } - } -#ifdef JSON_SUPPORT - nv_add_nvp (cli_response, "close", "resultlist"); -#else - nv_add_nvp (cli_response, "resultlist", "end"); -#endif - - fclose (fdT); - unlink (tmpfileT); - } - else - { -#if defined(WINDOWS) - th_id = GetCurrentThreadId (); -#else - th_id = getpid (); -#endif - snprintf (tmpfileQ, PATH_MAX - 1, "%s/log_top_%lu.q", sco.dbmt_tmp_dir, - th_id); - snprintf (tmpfileRes, PATH_MAX - 1, "%s/log_top_%lu.res", - sco.dbmt_tmp_dir, th_id); - - rename ("./log_top.q", tmpfileQ); - rename ("./log_top.res", tmpfileRes); - - fdQ = fopen (tmpfileQ, "r"); - if (fdQ == NULL) - { - if (diag_error) - { - strcpy (diag_error, "log_top.q"); - } - fclose (fdAnalyzeResult); - return ERR_FILE_OPEN_FAIL; - } - - fdRes = fopen (tmpfileRes, "r"); - if (fdRes == NULL) - { - if (diag_error) - { - strcpy (diag_error, "log_top.res"); - } - fclose (fdAnalyzeResult); - fclose (fdQ); - return ERR_FILE_OPEN_FAIL; - } - - memset (buf, '\0', sizeof (buf)); - memset (logbuf, '\0', sizeof (logbuf)); -#ifdef JSON_SUPPORT - nv_add_nvp (cli_response, "open", "resultlist"); -#else - nv_add_nvp (cli_response, "resultlist", "start"); -#endif - /* read result, log file and create msg with them */ - while (fgets (buf, sizeof (buf), fdRes)) - { - if (strlen (buf) == 1) - { - continue; - } - - if (!strncmp (buf, "[Q", 2)) - { -#ifdef JSON_SUPPORT - nv_add_nvp (cli_response, "open", "result"); -#else - nv_add_nvp (cli_response, "result", "start"); -#endif - matched = - sscanf (buf, "%15s %31s %31s %31s %15s %15s", qnum, max, min, - avg, cnt, err); - if (matched != 6) - { - continue; - } - nv_add_nvp (cli_response, "qindex", qnum); - nv_add_nvp (cli_response, "max", max); - nv_add_nvp (cli_response, "min", min); - nv_add_nvp (cli_response, "avg", avg); - nv_add_nvp (cli_response, "cnt", cnt); - if (strlen (err)) - { - err[strlen (err) - 1] = '\0'; - } - nv_add_nvp (cli_response, "err", err + 1); - - fprintf (fdAnalyzeResult, "%s\n", qnum); - - while (strncmp (logbuf, qnum, 4) != 0) - { - if (fgets (logbuf, sizeof (logbuf), fdQ) == NULL) - { - if (diag_error) - { - strcpy (diag_error, - "log_top.q file format is not valid"); - } - fclose (fdRes); - fclose (fdQ); - fclose (fdAnalyzeResult); - return ERR_WITH_MSG; - } - } - - while (fgets (logbuf, sizeof (logbuf), fdQ)) - { - if (!strncmp (logbuf, "[Q", 2)) - { - break; - } - fprintf (fdAnalyzeResult, "%s", logbuf); - } -#ifdef JSON_SUPPORT - nv_add_nvp (cli_response, "close", "result"); -#else - nv_add_nvp (cli_response, "result", "end"); -#endif - } - } -#ifdef JSON_SUPPORT - nv_add_nvp (cli_response, "close", "resultlist"); -#else - nv_add_nvp (cli_response, "resultlist", "end"); -#endif - - fclose (fdRes); - fclose (fdQ); - - unlink (tmpfileQ); - unlink (tmpfileRes); - } - - fclose (fdAnalyzeResult); - nv_add_nvp (cli_response, "resultfile", tmpfileanalyzeresult); - - return ERR_NO_ERROR; -} - -int -ts_executecasrunner (nvplist *cli_request, nvplist *cli_response, - char *diag_error) -{ - int i, sect, sect_len; - char *log_string, *brokername, *username, *passwd; - char *num_thread, *repeat_count, *show_queryresult; - char *dbname, *casrunnerwithFile, *logfilename; - char *show_queryplan; - char bport[6], buf[1024]; - FILE *flogfile, *fresfile2; - char tmplogfilename[PATH_MAX], resfile[PATH_MAX], resfile2[PATH_MAX]; - char log_converter_res[PATH_MAX]; - char cmd_name[ARNIADB_CMD_NAME_LEN]; - const char *argv[25]; - T_CM_BROKER_CONF uc_conf; - char out_msg_file_env[1024]; - T_CM_ERROR error; -#if defined(WINDOWS) - DWORD th_id; -#else - T_THREAD th_id; -#endif - char use_tmplogfile = FALSE; - - brokername = nv_get_val (cli_request, "brokername"); - dbname = nv_get_val (cli_request, "dbname"); - username = nv_get_val (cli_request, "username"); - passwd = nv_get_val (cli_request, "passwd"); - num_thread = nv_get_val (cli_request, "num_thread"); - repeat_count = nv_get_val (cli_request, "repeat_count"); - show_queryresult = nv_get_val (cli_request, "show_queryresult"); - show_queryplan = nv_get_val (cli_request, "show_queryplan"); - casrunnerwithFile = nv_get_val (cli_request, "executelogfile"); - logfilename = nv_get_val (cli_request, "logfile"); - - if (brokername == NULL) - { - snprintf (diag_error, DBMT_ERROR_MSG_SIZE, "%s", "brokername"); - return ERR_PARAM_MISSING; - } - - if (dbname == NULL) - { - snprintf (diag_error, DBMT_ERROR_MSG_SIZE, "%s", "dbname"); - return ERR_PARAM_MISSING; - } - - if (username == NULL) - { - snprintf (diag_error, DBMT_ERROR_MSG_SIZE, "%s", "username"); - return ERR_PARAM_MISSING; - } - -#if defined(WINDOWS) - th_id = GetCurrentThreadId (); -#else - th_id = getpid (); -#endif - - snprintf (resfile, PATH_MAX - 1, "%s/log_run_%lu.res", sco.dbmt_tmp_dir, - th_id); - snprintf (resfile2, PATH_MAX - 1, "%s/log_run_%lu.res2", sco.dbmt_tmp_dir, - th_id); - - /* get right port number with broker name */ - if (cm_get_broker_conf (&uc_conf, NULL, &error) < 0) - { - strcpy (diag_error, error.err_msg); - return ERR_WITH_MSG; - } - - memset (bport, 0x0, sizeof (bport)); - for (i = 0; i < uc_conf.num_broker; i++) - { - char *confvalue = cm_br_conf_get_value (& (uc_conf.br_conf[i]), "%"); - - if ((confvalue != NULL) && (strcmp (brokername, confvalue) == 0)) - { - confvalue = - cm_br_conf_get_value (& (uc_conf.br_conf[i]), "BROKER_PORT"); - if (confvalue != NULL) - { - snprintf (bport, sizeof (bport) - 1, "%s", confvalue); - } - break; - } - } - - cm_broker_conf_free (&uc_conf); - - if ((casrunnerwithFile != NULL) && (strcmp (casrunnerwithFile, "yes") == 0) - && (logfilename != NULL)) - { - snprintf (tmplogfilename, PATH_MAX - 1, "%s", logfilename); - } - else - { - use_tmplogfile = TRUE; - /* create logfile */ - snprintf (tmplogfilename, PATH_MAX - 1, "%s/cas_log_tmp_%lu.q", - sco.dbmt_tmp_dir, th_id); - - flogfile = fopen (tmplogfilename, "w+"); - if (!flogfile) - { - return ERR_FILE_OPEN_FAIL; - } - - nv_locate (cli_request, "logstring", §, §_len); - if (sect >= 0) - { - for (i = 0; i < sect_len; ++i) - { - nv_lookup (cli_request, sect + i, NULL, &log_string); - fprintf (flogfile, "%s\n", - (log_string == NULL) ? " " : log_string); - } - } - fclose (flogfile); - } - - /* execute broker_log_converter why logfile is created */ - snprintf (log_converter_res, PATH_MAX - 1, "%s/log_converted_%lu.q_res", - sco.dbmt_tmp_dir, th_id); - snprintf (cmd_name, sizeof (cmd_name) - 1, "%s/bin/broker_log_converter%s", - sco.szArniadb, DBMT_EXE_EXT); - - i = 0; - argv[i] = cmd_name; - argv[++i] = tmplogfilename; - argv[++i] = log_converter_res; - argv[++i] = NULL; - - if (run_child (argv, 1, NULL, NULL, NULL, NULL) < 0) - { - /* broker_log_converter */ - strcpy (diag_error, argv[0]); - return ERR_SYSTEM_CALL; - } - - /* execute broker_log_runner through logfile that converted */ - snprintf (cmd_name, sizeof (cmd_name) - 1, "%s/bin/broker_log_runner%s", - sco.szArniadb, DBMT_EXE_EXT); - i = 0; - argv[i] = cmd_name; - argv[++i] = "-I"; - argv[++i] = "localhost"; - argv[++i] = "-P"; - argv[++i] = bport; - argv[++i] = "-d"; - argv[++i] = dbname; - argv[++i] = "-u"; - argv[++i] = username; - if (passwd) - { - argv[++i] = "-p"; - argv[++i] = passwd; - } - argv[++i] = "-t"; - argv[++i] = num_thread; - argv[++i] = "-r"; - argv[++i] = repeat_count; - if (show_queryplan && !strcmp (show_queryplan, "yes")) - { - argv[++i] = "-Q"; - } - argv[++i] = "-o"; - argv[++i] = resfile; - argv[++i] = log_converter_res; - argv[++i] = NULL; - - snprintf (out_msg_file_env, sizeof (out_msg_file_env) - 1, - "ARNIADB_MANAGER_OUT_MSG_FILE=%s", resfile2); - putenv (out_msg_file_env); - - if (run_child (argv, 1, NULL, NULL, NULL, NULL) < 0) - { - /* broker_log_runner */ - return ERR_SYSTEM_CALL; - } - - /* create message with read file's content */ -#ifdef JSON_SUPPORT - nv_add_nvp (cli_response, "open", "result_list"); -#else - nv_add_nvp (cli_response, "result_list", "start"); -#endif - - fresfile2 = fopen (resfile2, "r"); - if (fresfile2) - { - while (fgets (buf, sizeof (buf), fresfile2)) - { - if (!strncmp (buf, "cas_ip", 6)) - { - continue; - } - if (!strncmp (buf, "cas_port", 8)) - { - continue; - } - if (!strncmp (buf, "num_thread", 10)) - { - continue; - } - if (!strncmp (buf, "repeat", 6)) - { - continue; - } - if (!strncmp (buf, "dbname", 6)) - { - continue; - } - if (!strncmp (buf, "dbuser", 6)) - { - continue; - } - if (!strncmp (buf, "dbpasswd", 6)) - { - continue; - } - if (!strncmp (buf, "result_file", 11)) - { - continue; - } - - buf[strlen (buf) - 1] = '\0'; /* remove new line ch */ - nv_add_nvp (cli_response, "result", buf); - } - fclose (fresfile2); - } -#ifdef JSON_SUPPORT - nv_add_nvp (cli_response, "close", "result_list"); -#else - nv_add_nvp (cli_response, "result_list", "end"); -#endif - nv_add_nvp (cli_response, "query_result_file", resfile); - nv_add_nvp (cli_response, "query_result_file_num", num_thread); - - if ((show_queryresult != NULL) && !strcmp (show_queryresult, "no")) - { - /* remove query result file - resfile */ - int i, n = 0; - char filename[PATH_MAX]; - if (num_thread != NULL) - { - n = atoi (num_thread); - } - - for (i = 0; i < n && i < MAX_SERVER_THREAD_COUNT; i++) - { - snprintf (filename, PATH_MAX - 1, "%s.%d", resfile, i); - unlink (filename); - } - } - - unlink (log_converter_res); /* broker_log_converter execute result */ - unlink (resfile2); /* cas log execute result */ - - if (use_tmplogfile == TRUE) - { - unlink (tmplogfilename); /* temp logfile */ - } - return ERR_NO_ERROR; -} - -int -ts_removecasrunnertmpfile (nvplist *cli_request, nvplist *cli_response, - char *diag_error) -{ - char command[PATH_MAX]; - char filename[PATH_MAX]; - char arniadb_tmp_path[PATH_MAX]; - char *fullpath_with_filename = NULL; - - const char *casrunnertmp_short[] = - { "log_converted", "cas_log_tmp", "log_run" }; - unsigned int casrunnertmp_short_num = - sizeof (casrunnertmp_short) / sizeof (casrunnertmp_short[0]); - unsigned int i = 0; - int valid_casrunnertmpfile = 0; - - command[0] = '\0'; - filename[0] = '\0'; - arniadb_tmp_path[0] = '\0'; - - fullpath_with_filename = nv_get_val (cli_request, "filename"); - if (fullpath_with_filename == NULL) - { - snprintf (diag_error, DBMT_ERROR_MSG_SIZE, "%s", "filename"); - return ERR_PARAM_MISSING; - } - - /* check permission : must under $ARNIADB/tmp/ */ -#if defined(WINDOWS) - snprintf (arniadb_tmp_path, PATH_MAX, "%s\\", sco.dbmt_tmp_dir); -#else - snprintf (arniadb_tmp_path, PATH_MAX, "%s/", sco.dbmt_tmp_dir); -#endif - - if (strstr (fullpath_with_filename, arniadb_tmp_path) == NULL) - { - snprintf (diag_error, DBMT_ERROR_MSG_SIZE, "%s", - fullpath_with_filename); - return ERR_PERMISSION; - } - - if (ut_get_filename (fullpath_with_filename, 1, filename) != 0) - { - snprintf (diag_error, DBMT_ERROR_MSG_SIZE, "%s", - fullpath_with_filename); - return ERR_PERMISSION; - } - - for (i = 0; i < casrunnertmp_short_num; i++) - { - if (strstr (filename, casrunnertmp_short[i]) != NULL) - { - valid_casrunnertmpfile = 1; - break; - } - } - - if (valid_casrunnertmpfile == 0) - { - snprintf (diag_error, DBMT_ERROR_MSG_SIZE, "%s", - fullpath_with_filename); - return ERR_PERMISSION; - } - -#if defined(WINDOWS) - snprintf (command, sizeof (command), "%s %s %s", DEL_FILE, - DEL_FILE_OPT, fullpath_with_filename); -#else - snprintf (command, sizeof (command), "%s %s %s", DEL_DIR, DEL_DIR_OPT, - fullpath_with_filename); -#endif - - if (system (command) == -1) - { - snprintf (diag_error, DBMT_ERROR_MSG_SIZE, "%s", - fullpath_with_filename); - return ERR_DIR_REMOVE_FAIL; - } - return ERR_NO_ERROR; -} - -int -ts_getcaslogtopresult (nvplist *cli_request, nvplist *cli_response, - char *diag_error) -{ - char *filename, *qindex; - FILE *fd; - char buf[1024]; - int find_flag; - - filename = nv_get_val (cli_request, "filename"); - if (filename == NULL) - { - snprintf (diag_error, DBMT_ERROR_MSG_SIZE, "%s", "filename"); - return ERR_PARAM_MISSING; - } - - qindex = nv_get_val (cli_request, "qindex"); - if (qindex == NULL) - { - snprintf (diag_error, DBMT_ERROR_MSG_SIZE, "%s", "qindex"); - return ERR_PARAM_MISSING; - } - - fd = fopen (filename, "r"); - if (!fd) - { - return ERR_FILE_OPEN_FAIL; - } - - find_flag = 0; -#ifndef JSON_SUPPORT - nv_add_nvp (cli_response, "logstringlist", "start"); -#endif - while (fgets (buf, sizeof (buf), fd)) - { - if (!strncmp (buf, "[Q", 2)) - { - if (find_flag == 1) - { - break; - } - if (!strncmp (buf, qindex, strlen (qindex))) - { - find_flag = 1; - continue; - } - } - - if (find_flag == 1) - { - buf[strlen (buf) - 1] = '\0'; -#ifdef JSON_SUPPORT - nv_add_nvp (cli_response, "open", "logstringlist"); -#endif - nv_add_nvp (cli_response, "logstring", buf); -#ifdef JSON_SUPPORT - nv_add_nvp (cli_response, "close", "logstringlist"); -#endif - } - } -#ifndef JSON_SUPPORT - nv_add_nvp (cli_response, "logstringlist", "end"); -#endif - fclose (fd); - return ERR_NO_ERROR; -} - -int -dbmt_user_is_dba (char *dbuser, const char *out_file) -{ - FILE *fp; - char buf[1024]; - int res_flag = 0; - int res = 0; - - buf[0] = '\0'; - - if (out_file == NULL || dbuser == NULL) - { - return 0; - } - - if (strcasecmp ("DBA", dbuser) == 0) - { - return 1; - } - - fp = fopen (out_file, "r"); - if (fp == NULL) - { - return 0; - } - - while (fgets (buf, sizeof (buf) - 1, fp)) - { - ut_trim (buf); - if (strncmp (buf, "=", 1) == 0) - { - continue; - } - - if (strstr (buf, "count(*)")) - { - res_flag = 1; - continue; - } - - if (res_flag) - { - if (strstr (buf, "0")) - { - res = 0; - break; - } - else - { - res = 1; - break; - } - } - } - fclose (fp); - - return res; -} - -int -cmd_dbmt_user_login (nvplist *in, nvplist *out, char *_dbmt_error) -{ - int errcode; - char *targetid, *dbname, *dbuser, *dbpasswd; - int isdba = 0; - char outfile[PATH_MAX]; - static int cmdid = 0; - const char *statement = - "SELECT COUNT( * ) FROM db_user d WHERE {'DBA'} SUBSETEQ (SELECT SET{CURRENT_USER}+COALESCE(SUM(SET{t.g.name}), SET{}) from db_user u, TABLE(groups) AS t( g ) WHERE u.name = d.name) AND d.name=CURRENT_USER;"; - - targetid = nv_get_val (in, "targetid"); - dbname = nv_get_val (in, "dbname"); - dbuser = nv_get_val (in, "dbuser"); - dbpasswd = nv_get_val (in, "dbpasswd"); - - if (dbname == NULL) - { - strcpy (_dbmt_error, "dbname"); - return ERR_PARAM_MISSING; - } - - if (dbuser == NULL) - { - strcpy (_dbmt_error, "dbuser"); - return ERR_PARAM_MISSING; - } - - nv_add_nvp (out, "targetid", targetid); - nv_add_nvp (out, "dbname", dbname); - - snprintf (outfile, sizeof (outfile) - 1, "%s/tmp/DBMT_user_login.%d", - sco.szArniadb, cmdid++); - errcode = - run_asql_statement (statement, dbname, dbuser, dbpasswd, outfile, _dbmt_error); - if (errcode != ERR_NO_ERROR) - { - return errcode; - } - - isdba = dbmt_user_is_dba (dbuser, outfile); - if (isdba) - { - nv_add_nvp (out, "authority", "isdba"); - } - else - { - nv_add_nvp (out, "authority", "isnotdba"); - } - _update_nvplist_name (out, "targetid", ENCRYPT_ARG ("targetid")); - unlink (outfile); - return ERR_NO_ERROR; -} - - - -int -tsDBMTUserLogin (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char hexacoded[PASSWD_ENC_LENGTH]; - int ret; - T_DBMT_CON_DBINFO con_dbinfo; - char *dbname, *dbpasswd, *dbuser; - char *ip, *port; - - ret = cmd_dbmt_user_login (req, res, _dbmt_error); - if (ret != ERR_NO_ERROR) - { - return ret; - } - - ip = nv_get_val (req, "_IP"); - port = nv_get_val (req, "_PORT"); - dbname = nv_get_val (req, "dbname"); - dbpasswd = nv_get_val (req, "dbpasswd"); - dbuser = nv_get_val (req, "dbuser"); - - if (dbpasswd != NULL && strlen (dbpasswd) > PASSWD_LENGTH) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, - "The input DB password is more than maximum password length %d.", - PASSWD_LENGTH); - return ERR_WITH_MSG; - } - - /* update dbinfo to conlist */ - uEncrypt (PASSWD_LENGTH, dbpasswd, hexacoded); - memset (&con_dbinfo, 0, sizeof (T_DBMT_CON_DBINFO)); - dbmt_con_set_dbinfo (&con_dbinfo, dbname, dbuser, hexacoded); - if (dbmt_con_write_dbinfo (&con_dbinfo, ip, port, dbname, 1, _dbmt_error) < 0) - { - return ERR_WITH_MSG; - } - - _update_nvplist_name (res, "targetid", ENCRYPT_ARG ("targetid")); - - return ERR_NO_ERROR; -} - - -int -ts_remove_log (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char *path = NULL; - FILE *output = NULL; - int i = 0; - int sect = -1; - int sect_len = 0; - int as_id = 0; - char broker_name[PATH_MAX]; - char command[PATH_MAX]; - char full_path_buf[PATH_MAX]; - char buf[PATH_MAX]; - T_CM_ERROR error = { 0, {0} }; - - broker_name[0] = '\0'; - command[0] = '\0'; - full_path_buf[0] = '\0'; - buf[0] = '\0'; - - nv_locate (req, "files", §, §_len); - if (sect < 0) - { - return ERR_REQUEST_FORMAT; - } - - for (i = 0; i < sect_len; ++i) - { - nv_lookup (req, sect + i, NULL, &path); -#if defined(WINDOWS) - path = nt_style_path (path, full_path_buf); -#endif - if (access (path, F_OK) != 0) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "No such file: %s", - path); - return ERR_WITH_MSG; - } - - snprintf (command, sizeof (command), "%s %s %s", DEL_FILE, - DEL_FILE_OPT, path); - - output = popen (command, "r"); - memset (buf, '\0', sizeof (buf)); - if (output != NULL) - { - if (fgets (buf, PATH_MAX, output) != NULL) - { -#if defined(WINDOWS) - pclose (output); - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "Cannot remove %s", - full_path_buf); - return ERR_WITH_MSG; -#endif - if (get_broker_info_from_filename (path, broker_name, &as_id) < 0 - || cm_del_cas_log (broker_name, as_id, &error) < 0) - { - pclose (output); - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", - error.err_msg); - return ERR_WITH_MSG; - } - } - } - pclose (output); - } /* end of for */ - - return ERR_NO_ERROR; -} - -int -ts_get_host_stat (nvplist *req, nvplist *res, char *_dbmt_error) -{ - int retval = ERR_NO_ERROR; - T_CMS_HOST_STAT stat; - - memset (&stat, 0, sizeof (T_CMS_HOST_STAT)); - - retval = ut_get_host_stat (&stat, _dbmt_error); - - nv_add_nvp_int64 (res, "cpu_user", stat.cpu_user); - nv_add_nvp_int64 (res, "cpu_kernel", stat.cpu_kernel); - nv_add_nvp_int64 (res, "cpu_idle", stat.cpu_idle); - nv_add_nvp_int64 (res, "cpu_iowait", stat.cpu_iowait); - nv_add_nvp_int64 (res, "mem_phy_total", stat.mem_physical_total); - nv_add_nvp_int64 (res, "mem_phy_free", stat.mem_physical_free); - nv_add_nvp_int64 (res, "mem_swap_total", stat.mem_swap_total); - nv_add_nvp_int64 (res, "mem_swap_free", stat.mem_swap_free); - - return retval; -} - -int -ts_get_dbproc_stat (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char *dbname = NULL; - T_CM_DB_PROC_STAT_ALL *db_stat_all = NULL; - T_CM_DB_PROC_STAT db_stat; - T_CM_ERROR error; - int retval; - int i = 0; - - memset (&db_stat, 0, sizeof (T_CM_DB_PROC_STAT)); - memset (&error, 0, sizeof (T_CM_ERROR)); - - if ((dbname = nv_get_val (req, "dbname")) == NULL) - { - if ((db_stat_all = cm_get_db_proc_stat_all (&error)) == NULL) - { - strcpy_limit (_dbmt_error, error.err_msg, DBMT_ERROR_MSG_SIZE); - retval = ERR_WITH_MSG; - goto error_return; - } - - for (i = 0; i < db_stat_all->num_stat; i++) - { - print_db_stat_to_res ((db_stat_all->db_stats + i), res); - } - - cm_db_proc_stat_all_free (db_stat_all); - retval = ERR_NO_ERROR; - } - else - { - if (cm_get_db_proc_stat (dbname, &db_stat, &error) < 0) - { - strcpy_limit (_dbmt_error, error.err_msg, DBMT_ERROR_MSG_SIZE); - retval = ERR_WITH_MSG; - goto error_return; - } - print_db_stat_to_res (&db_stat, res); - retval = ERR_NO_ERROR; - } - - return retval; - -error_return: - print_db_stat_to_res (&db_stat, res); - return retval; -} - -static int -analyze_heartbeat_cmd_outfile (FILE *infile, char *_dbmt_error) -{ - char buf[1024]; - const char *headtag = "++"; - const char *failtag = "not running"; - char *p; - - while (fgets (buf, sizeof (buf), infile)) - { - if (strncmp (buf, headtag, strlen (headtag)) == 0) - { - if (strstr (buf, failtag) != NULL) - { - p = strchr (buf, '\n'); - if (p) - { - *p = '\0'; - } - /* copy begins with the 3rd charactor, ignore the "++" tag. */ - strcpy_limit (_dbmt_error, &buf[2], DBMT_ERROR_MSG_SIZE); - return ERR_WITH_MSG; - } - } - } - - return ERR_NO_ERROR; -} - -static char * -arn_admin_cmd_name (char *cmd_name, int buf_len) -{ - cmd_name[0] = '\0'; -#if !defined (DO_NOT_USE_ARNIADBENV) - snprintf (cmd_name, buf_len, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, - UTIL_ADMIN_NAME); -#else - sprintf (cmd_name, buf_len, "%s/%s", ARNIADB_BINDIR, UTIL_ADMIN_NAME); -#endif - return cmd_name; -} - -static int -cmd_heartbeat_deact (char *_dbmt_error) -{ - int retval = ERR_NO_ERROR; - const char *argv[8]; - int argc = 0; - char cmd_name[ARNIADB_CMD_NAME_LEN]; - FILE *outputfile = NULL; - char outputfilepath[PATH_MAX]; - char arniadb_err_file[PATH_MAX]; - - arniadb_err_file[0] = '\0'; - outputfilepath[0] = '\0'; - - snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", - sco.dbmt_tmp_dir, "heartbeat_deact", getpid ()); - - arniadb_cmd_name (cmd_name); - argv[argc++] = cmd_name; - argv[argc++] = PRINT_CMD_HEARTBEAT; - argv[argc++] = PRINT_CMD_DEACT; - argv[argc++] = NULL; - - snprintf (outputfilepath, PATH_MAX - 1, "%s/DBMT_task_%d.%d", - sco.dbmt_tmp_dir, TS_HEARTBEAT_DEACT, (int) getpid ()); - - if (run_child (argv, 1, NULL, outputfilepath, arniadb_err_file, NULL) < 0) - { - /* heartbeat deact */ - strcpy (_dbmt_error, argv[0]); - retval = ERR_SYSTEM_CALL; - goto rm_outputfile; - } - - if (read_error_file (arniadb_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) - { - retval = ERR_WITH_MSG; - goto rm_outputfile; - } - - /* open tmp file. */ - outputfile = fopen (outputfilepath, "r"); - if (outputfile == NULL) - { - retval = ERR_TMPFILE_OPEN_FAIL; - goto rm_outputfile; - } - - if ((retval = - analyze_heartbeat_cmd_outfile (outputfile, _dbmt_error)) != ERR_NO_ERROR) - { - fclose (outputfile); - goto rm_outputfile; - } - - /* close tmp file. */ - fclose (outputfile); - -rm_outputfile: - unlink (outputfilepath); - if (access (arniadb_err_file, F_OK) == 0) - { - unlink (arniadb_err_file); - } - return retval; -} - -static int -cmd_heartbeat_act (char *_dbmt_error) -{ - int retval = ERR_NO_ERROR; - const char *argv[8]; - int argc = 0; - char cmd_name[ARNIADB_CMD_NAME_LEN]; - FILE *outputfile = NULL; - char outputfilepath[PATH_MAX]; - char arniadb_err_file[PATH_MAX]; - - outputfilepath[0] = '\0'; - arniadb_err_file[0] = '\0'; - - snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", - sco.dbmt_tmp_dir, "cmd_heartbeat_act", getpid ()); - - arniadb_cmd_name (cmd_name); - argv[argc++] = cmd_name; - argv[argc++] = PRINT_CMD_HEARTBEAT; - argv[argc++] = PRINT_CMD_ACT; - argv[argc++] = NULL; - - snprintf (outputfilepath, PATH_MAX - 1, "%s/DBMT_task_%d.%d", - sco.dbmt_tmp_dir, TS_HEARTBEAT_ACT, (int) getpid ()); - - if (run_child (argv, 1, NULL, outputfilepath, arniadb_err_file, NULL) < 0) - { - /* heartbeat act */ - strcpy (_dbmt_error, argv[0]); - retval = ERR_SYSTEM_CALL; - goto rm_outputfile; - } - - if (read_error_file (arniadb_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) - { - retval = ERR_WITH_MSG; - goto rm_outputfile; - } - - /* open tmp file. */ - outputfile = fopen (outputfilepath, "r"); - if (outputfile == NULL) - { - retval = ERR_TMPFILE_OPEN_FAIL; - goto rm_outputfile; - } - - if ((retval = - analyze_heartbeat_cmd_outfile (outputfile, _dbmt_error)) != ERR_NO_ERROR) - { - fclose (outputfile); - goto rm_outputfile; - } - - /* close tmp file. */ - fclose (outputfile); - -rm_outputfile: - unlink (outputfilepath); - if (access (arniadb_err_file, F_OK) == 0) - { - unlink (arniadb_err_file); - } - return retval; -} - -static int -run_asql_statement (const char *sql_stat, char *dbname, char *dbuser, - char *dbpasswd, char *outfilepath, char *_dbmt_error) -{ - char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; - char cmd_name[ARNIADB_CMD_NAME_LEN]; - char task_name[TASKNAME_LEN]; - const char *argv[15]; - - int argc = 0; - int retval = 0; - int ha_mode = 0; - - T_DB_SERVICE_MODE db_mode; - - task_name[0] = '\0'; - dbname_at_hostname[0] = '\0'; - cmd_name[0] = '\0'; - - snprintf (cmd_name, sizeof (cmd_name) - 1, "%s/%s%s", sco.szArniadb, - ARNIADB_DIR_BIN, UTIL_ASQL_NAME); - - if (!_isRegisteredDB (dbname)) - { - return ERR_DB_NONEXISTANT; - } - - db_mode = uDatabaseMode (dbname, &ha_mode); - - if (db_mode == DB_SERVICE_MODE_SA) - { - sprintf (_dbmt_error, "%s", dbname); - return ERR_STANDALONE_MODE; - } - - argv[argc++] = cmd_name; - - if (db_mode == DB_SERVICE_MODE_NONE) - { - argv[argc++] = "--" ASQL_SA_MODE_L; - } - else - { - argv[argc++] = "--" ASQL_CS_MODE_L; - } - - if (dbuser != NULL) - { - argv[argc++] = "--" ASQL_USER_L; - argv[argc++] = dbuser; - - argv[argc++] = "--" ASQL_PASSWORD_L; - if (dbpasswd != NULL) - { - argv[argc++] = dbpasswd; - } - else - { - argv[argc++] = ""; - } - } - else - { - strcpy (_dbmt_error, "dbuser"); - return ERR_PARAM_MISSING; - } - - argv[argc++] = "--" ASQL_COMMAND_L; - argv[argc++] = sql_stat; - - if (ha_mode != 0) - { - append_host_to_dbname (dbname_at_hostname, dbname, - sizeof (dbname_at_hostname)); - argv[argc++] = dbname_at_hostname; - } - else - { - argv[argc++] = dbname; - } - - argv[argc++] = NULL; - - SET_TRANSACTION_NO_WAIT_MODE_ENV (); - - strncpy (task_name, "asql", TASKNAME_LEN); - retval = _run_child (argv, 1, task_name, outfilepath, _dbmt_error); - - return retval; -} - -int -ts_user_verify (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char *dbname, *dbuser, *dbpasswd; - int retval = ERR_NO_ERROR; - - /* every user can access db_user table. */ - const char *sql_stat = "select 1 from db_root"; - - if ((dbname = nv_get_val (req, "dbname")) == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "dbname"); - return ERR_PARAM_MISSING; - } - - if ((dbuser = nv_get_val (req, "dbuser")) != NULL) - { - dbpasswd = nv_get_val (req, "dbpasswd"); - } - else - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "dbuser"); - return ERR_PARAM_MISSING; - } - - /* - * using asql to verify the user's password. - */ - retval = run_asql_statement (sql_stat, dbname, dbuser, dbpasswd, NULL, _dbmt_error); /* asql */ - - return retval; -} - -int -ts_get_standby_server_stat (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char *dbname, *dbuser, *dbpasswd; - char output_file[PATH_MAX] = { 0 }; - int retval; - T_STANDBY_SERVER_STAT stat; - FILE *outfile = NULL; - - /* - * get the record which contains the insert/delete/update/commit/fail counter, - * if there is more than one records, the one with largest last_access_time - * in db_ha_apply_info table is chosen. - */ - const char *sql_stat = - "select " - "insert_counter, update_counter, delete_counter, commit_counter, fail_counter, " - "(last_access_time - log_record_time) " - "from db_ha_apply_info " - "where (last_access_time IN (select max (last_access_time) from db_ha_apply_info))"; - - memset (&stat, 0, sizeof (stat)); - - snprintf (output_file, PATH_MAX - 1, "%s/dbmt_task_%d_%d", - sco.dbmt_tmp_dir, TS_GET_STANDBY_SERVER_STAT, (int) getpid ()); - - if ((dbname = nv_get_val (req, "dbname")) == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "dbname"); - retval = ERR_PARAM_MISSING; - goto func_return; - } - - nv_add_nvp (res, "dbname", dbname); - - if ((dbuser = nv_get_val (req, "dbid")) != NULL) - { - dbpasswd = nv_get_val (req, "dbpasswd"); - } - else - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "dbid"); - retval = ERR_PARAM_MISSING; - goto func_return; - } - - retval = run_asql_statement (sql_stat, dbname, dbuser, dbpasswd, output_file, _dbmt_error); /* asql */ - - if (retval != ERR_NO_ERROR) - { - goto func_return; - } - - if ((outfile = fopen (output_file, "r")) == NULL) - { - retval = ERR_TMPFILE_OPEN_FAIL; - goto func_return; - } - - if ((retval = - parse_standby_server_stat (&stat, outfile, _dbmt_error)) != ERR_NO_ERROR) - { - fclose (outfile); - goto func_return; - } - - fclose (outfile); - retval = ERR_NO_ERROR; - -func_return: - nv_add_nvp_int64 (res, "delay_time", stat.delay_time); - nv_add_nvp_int64 (res, "insert_counter", stat.insert_counter); - nv_add_nvp_int64 (res, "update_counter", stat.update_counter); - nv_add_nvp_int64 (res, "delete_counter", stat.delete_counter); - nv_add_nvp_int64 (res, "commit_counter", stat.commit_counter); - nv_add_nvp_int64 (res, "fail_counter", stat.fail_counter); - - unlink (output_file); - return retval; -} - -static int -parse_standby_server_stat (T_STANDBY_SERVER_STAT *stat, FILE *outfile, - char *_dbmt_error) -{ - char buf[1024]; - char prefix[64] = { 0 }; - long long delay_time = 0; - long long insert_counter = 0; - long long update_counter = 0; - long long delete_counter = 0; - long long commit_counter = 0; - long long fail_counter = 0; - - while (fgets (buf, sizeof (buf), outfile)) - { - sscanf (buf, "%63s", prefix); - - /* the first charactor is the num of insert_counter, it should be digit. */ - if (isdigit (prefix[0])) - { - /* break when found the result. */ - if (sscanf - (buf, "%lld %lld %lld %lld %lld %lld", - &insert_counter, &update_counter, &delete_counter, - &commit_counter, &fail_counter, &delay_time) == 6) - { - break; - } - } - } - - stat->delay_time = delay_time; - stat->insert_counter = insert_counter; - stat->update_counter = update_counter; - stat->delete_counter = delete_counter; - stat->commit_counter = commit_counter; - stat->fail_counter = fail_counter; - - return ERR_NO_ERROR; -} - -static char * -get_mode_from_output_file (char *mode, int buf_len, FILE *outputfile, - char *_dbmt_error) -{ - char buf[1024]; - char server_mode[64] = { 0 }; - int scan_matched = 0; - - while (fgets (buf, sizeof (buf), outputfile)) - { - if (strcmp (buf, "\n") == 0) - { - continue; - } - - scan_matched = - sscanf (buf, "%*s %*s %*s %*s %*s %*s %*s %*s %63s", server_mode); - - if (scan_matched != 1) - { - strcpy_limit (_dbmt_error, "error occur when parsing output file.", - DBMT_ERROR_MSG_SIZE); - return NULL; - } - - /* remove '.' */ - if (strlen (server_mode) != 0) - { - server_mode[strlen (server_mode) - 1] = '\0'; - } - break; - } - strcpy_limit (mode, server_mode, buf_len); - - return mode; -} - -static int -cmd_get_db_mode (T_DB_MODE_INFO *dbmodeinfo, char *dbname, char *_dbmt_error) -{ - int ha_mode = 0; - T_DB_SERVICE_MODE dbmode; - char server_mode[64] = ""; - char server_msg[1024] = "none"; - int retval; - - strcpy_limit (dbmodeinfo->dbname, dbname, sizeof (dbmodeinfo->dbname)); - - dbmode = uDatabaseMode (dbname, &ha_mode); - - if (ha_mode == 0) - { - /* To ARNIADB Client, the SA and NONE mode all means the database is stopped. */ - if (dbmode == DB_SERVICE_MODE_SA || dbmode == DB_SERVICE_MODE_NONE) - { - strcpy_limit (server_mode, "stopped", sizeof (server_mode)); - } - else - { - strcpy_limit (server_mode, "CS-mode", sizeof (server_mode)); - } - - retval = ERR_NO_ERROR; - } - else - { - /* - * The task is used for monitoring, the retval of changemode command is - * not checked. The error message will be appended to the server_msg. - */ - retval = - cmd_changemode (dbname, NULL, NULL, server_mode, sizeof (server_mode), - _dbmt_error); - /* changemode */ - } - - /* record the error message to server_msg */ - if (retval != ERR_NO_ERROR) - { - strcpy_limit (server_msg, _dbmt_error, sizeof (server_msg)); - } - - strcpy_limit (dbmodeinfo->server_msg, server_msg, - sizeof (dbmodeinfo->server_msg)); - strcpy_limit (dbmodeinfo->server_mode, server_mode, - sizeof (dbmodeinfo->server_mode)); - - return ERR_NO_ERROR; -} - -int -ts_get_db_mode (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char *dblist, *dbname; - char separator = ','; - T_DB_MODE_INFO dbmode; - - if ((dblist = nv_get_val (req, "dblist")) == NULL) - { - strcpy_limit (_dbmt_error, "dblist", DBMT_ERROR_MSG_SIZE); - return ERR_PARAM_MISSING; - } - - while (dblist != NULL) - { - dbname = dblist; - - if ((dblist = strchr (dblist, separator)) != NULL) - { - dblist[0] = '\0'; - dblist++; - } - - nv_add_nvp (res, "open", "dbserver"); - nv_add_nvp (res, "dbname", dbname); - - cmd_get_db_mode (&dbmode, dbname, _dbmt_error); - nv_add_nvp (res, "server_mode", (&dbmode)->server_mode); - nv_add_nvp (res, "server_msg", (&dbmode)->server_msg); - - nv_add_nvp (res, "close", "dbserver"); - } - - return ERR_NO_ERROR; -} - -int -ts_changemode (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char *dbname, *modify, *force; - char server_mode[64]; - int retval; - - if ((dbname = nv_get_val (req, "dbname")) == NULL) - { - strcpy_limit (_dbmt_error, "dbname", DBMT_ERROR_MSG_SIZE); - return ERR_PARAM_MISSING; - } - modify = nv_get_val (req, "modify"); - force = nv_get_val (req, "force"); - - /* changemode */ - retval = - cmd_changemode (dbname, modify, force, server_mode, sizeof (server_mode), - _dbmt_error); - - if (retval != ERR_NO_ERROR) - { - return retval; - } - - nv_add_nvp (res, "server_mode", server_mode); - - return ERR_NO_ERROR; -} - -static int -cmd_changemode (char *dbname, char *modify, char *force, - char *server_mode_out, int mode_len, char *_dbmt_error) -{ - char server_mode[64]; - const char *argv[10]; - int argc = 0; - int ha_mode = 0; - char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; - char cmd_name[ARNIADB_CMD_NAME_LEN]; - T_DB_SERVICE_MODE dbmode; - char arniadb_err_file[PATH_MAX]; - FILE *outputfile; - char tmpfilepath[PATH_MAX]; - int retval = ERR_NO_ERROR; - - arniadb_err_file[0] = '\0'; - - if (dbname == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "dbname"); - return ERR_PARAM_MISSING; - } - - dbmode = uDatabaseMode (dbname, &ha_mode); - if (dbmode == DB_SERVICE_MODE_SA) - { - strcpy_limit (_dbmt_error, dbname, DBMT_ERROR_MSG_SIZE); - return ERR_STANDALONE_MODE; - } - - snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", - sco.dbmt_tmp_dir, "changemode", getpid ()); - snprintf (tmpfilepath, PATH_MAX - 1, "%s/DBMT_task_%d.%d", - sco.dbmt_tmp_dir, TS_CHANGEMODE, (int) getpid ()); - - arniadb_cmd_name (cmd_name); - argv[argc++] = cmd_name; - argv[argc++] = UTIL_OPTION_CHANGEMODE; - - if (modify != NULL) - { - argv[argc++] = "--" CHANGEMODE_MODE_L; - argv[argc++] = modify; - - if (uStringEqual (force, "y")) - { - argv[argc++] = "--" CHANGEMODE_FORCE_L; - } - } - - if (ha_mode != 0) - { - append_host_to_dbname (dbname_at_hostname, dbname, - sizeof (dbname_at_hostname)); - argv[argc++] = dbname_at_hostname; - } - else - { - argv[argc++] = dbname; - } - - argv[argc++] = NULL; - - if (run_child (argv, 1, NULL, tmpfilepath, arniadb_err_file, NULL) < 0) /* changemode */ - { - strcpy_limit (_dbmt_error, argv[0], DBMT_ERROR_MSG_SIZE); - retval = ERR_SYSTEM_CALL; - goto error_return; - } - - if (read_error_file (arniadb_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) - { - retval = ERR_WITH_MSG; - goto error_return; - } - - if ((outputfile = fopen (tmpfilepath, "r")) == NULL) - { - retval = ERR_TMPFILE_OPEN_FAIL; - goto error_return; - } - - if ((get_mode_from_output_file - (server_mode, sizeof (server_mode), outputfile, _dbmt_error)) == NULL) - { - - fclose (outputfile); - strcpy_limit (server_mode_out, "", mode_len); - strcpy_limit (_dbmt_error, "unknown database mode.", - DBMT_ERROR_MSG_SIZE); - retval = ERR_WITH_MSG; - goto error_return; - } - - strcpy_limit (server_mode_out, server_mode, mode_len); - - fclose (outputfile); - unlink (tmpfilepath); - if (access (arniadb_err_file, F_OK) == 0) - { - unlink (arniadb_err_file); - } - return ERR_NO_ERROR; - -error_return: - unlink (tmpfilepath); - if (access (arniadb_err_file, F_OK) == 0) - { - unlink (arniadb_err_file); - } - return retval; -} - -int -ts_role_change (nvplist *req, nvplist *res, char *_dbmt_error) -{ - int i; - int retval = ERR_NO_ERROR; - char cmdfile[PATH_MAX]; - FILE *infile = NULL; - char *tok[8]; - const char *cmd_argv[8]; - char arn_admin_cmd[ARNIADB_CMD_NAME_LEN]; - char buf[2048] = { 0 }; - - const char *argv[] = - { - "/bin/ps", - "xo", - "cmd", - NULL, - }; - - snprintf (cmdfile, PATH_MAX - 1, "%s/DBMT_task_%d.%d", - sco.dbmt_tmp_dir, TS_ROLE_CHANGE, (int) getpid ()); - - /* save the process info before heartbeat deact operation. */ - if (run_child (argv, 1, NULL, cmdfile, NULL, NULL) < 0) - { - strcpy_limit (_dbmt_error, argv[0], DBMT_ERROR_MSG_SIZE); - return ERR_SYSTEM_CALL; - } - - /* - * use heartbeat deact command to deact the heartbeat in Master node, - * so that the slave node can change into a master node. - */ - if ((retval = cmd_heartbeat_deact (_dbmt_error)) != ERR_NO_ERROR) /* heartbeat deact */ - { - goto error_return; - } - - /* - * sleep 6s to wait for the slave node change into master node. - * the slave node needs about 4s to change itself into master node. - */ - SLEEP_SEC (6); - - /* restart the heartbeat after the slave node changed into master node. */ - if ((retval = cmd_heartbeat_act (_dbmt_error)) != ERR_NO_ERROR) /* heartbeat act */ - { - goto error_return; - } - - if ((infile = fopen (cmdfile, "r")) == NULL) - { - retval = ERR_TMPFILE_OPEN_FAIL; - goto error_return; - } - - /* restart the HA related processes recorded in cmdfile. */ - while (fgets (buf, sizeof (buf), infile)) - { - char buf_t[2048] = { 0 }; - - ut_trim (buf); - to_lower_str (buf, buf_t); - - for (i = 0; i < 8; i++) - { - tok[i] = NULL; - cmd_argv[i] = NULL; - } - - if ((strstr (buf_t, " copylogdb") != NULL) || - (strstr (buf_t, " applylogdb") != NULL)) - { - /* restart applylogdb & copylogdb processes. */ - string_tokenize2 (buf, tok, 8, ' '); - arn_admin_cmd_name (arn_admin_cmd, sizeof (arn_admin_cmd)); - - cmd_argv[0] = arn_admin_cmd; - - for (i = 1; tok[i] != NULL; i++) - { - cmd_argv[i] = tok[i]; - } - - if (run_child (cmd_argv, 0, NULL, NULL, NULL, NULL) < 0) - { - retval = ERR_SYSTEM_CALL; - goto error_return; - } - } - else if (strstr (buf, "arn_server") != NULL) - { - /* restart database server processes. */ - string_tokenize2 (buf, tok, 3, ' '); - - if (cmd_start_server (tok[1], _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) - { - retval = ERR_WITH_MSG; - goto error_return; - } - } - } - - retval = ERR_NO_ERROR; - -error_return: - if (infile) - { - fclose (infile); - } - unlink (cmdfile); - return retval; -} - -static void -print_db_stat_to_res (T_CM_DB_PROC_STAT *db_stat, nvplist *res) -{ - nv_add_nvp (res, "open", "dbstat"); - nv_add_nvp (res, "dbname", db_stat->name); - nv_add_nvp_int64 (res, "cpu_kernel", db_stat->stat.cpu_kernel); - nv_add_nvp_int64 (res, "cpu_user", db_stat->stat.cpu_user); - nv_add_nvp_int64 (res, "mem_physical", db_stat->stat.mem_physical); - nv_add_nvp_int64 (res, "mem_virtual", db_stat->stat.mem_virtual); - nv_add_nvp (res, "close", "dbstat"); -} - -int -ts_heartbeat_list (nvplist *req, nvplist *res, char *_dbmt_error) -{ - T_HA_SERVER_INFO_ALL *all_info = NULL; - char *dbmodeall = NULL; - char *dblist = NULL; - int get_all_dbmode = 0; - int retval = ERR_NO_ERROR; - - if ((dbmodeall = nv_get_val (req, "dbmodeall")) != NULL) - { - if (strcmp (dbmodeall, "y") == 0) - { - get_all_dbmode = 1; - } - else - { - get_all_dbmode = 0; - dblist = nv_get_val (req, "dblist"); - } - } - else - { - retval = ERR_PARAM_MISSING; - strcpy_limit (_dbmt_error, "dbmodeall", DBMT_ERROR_MSG_SIZE); - goto error_return; - } - - all_info = (T_HA_SERVER_INFO_ALL *) MALLOC (sizeof (T_HA_SERVER_INFO_ALL)); - if (all_info == NULL) - { - return ERR_MEM_ALLOC; - } - - memset (all_info, 0, sizeof (T_HA_SERVER_INFO_ALL)); - - if ((retval = - cmd_heartbeat_list (&all_info, get_all_dbmode, dblist, - _dbmt_error)) != ERR_NO_ERROR) - { - goto error_return; - } - - /* - * get dbmode for every dbserver in the dbinfo list, the allocated space will be - * freed in dbinfo_list_free function. - */ - if ((retval = - fill_dbmode_into_dbinfo_list (&all_info, _dbmt_error)) != ERR_NO_ERROR) - { - goto error_return; - } - - print_dbinfo_list_to_res (all_info, res); - -error_return: - dbinfo_list_free (all_info); - return retval; -} - -int -ts_get_envvar_by_name (nvplist *req, nvplist *res, char *_dbmt_error) -{ - int i; - char *n, *v; - - for (i = 0; i < req->nvplist_leng; i++) - { - nv_lookup (req, i, &n, &v); - if ((n != NULL) && (strcmp (n, "envvar") == 0)) - { - char *envvar_t = getenv (v); - - nv_add_nvp (res, v, (envvar_t == NULL ? "" : envvar_t)); - } - } - - return ERR_NO_ERROR; -} - -int -ts_copy_folder (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char *src_dir; - char *dest_dir; - - if ((src_dir = nv_get_val (req, "srcdir")) == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "srcdir"); - return ERR_PARAM_MISSING; - } - if ((dest_dir = nv_get_val (req, "destdir")) == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "destdir"); - return ERR_PARAM_MISSING; - } - - if (folder_copy (src_dir, dest_dir) < 0) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE - 1, - "Failed when copying %s to %s.", src_dir, dest_dir); - return ERR_WITH_MSG; - } - - return ERR_NO_ERROR; -} - -int -ts_delete_folder (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char *src_dir; - int force_flag; - - if ((src_dir = nv_get_val (req, "srcdir")) == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "srcdir"); - return ERR_PARAM_MISSING; - } - - force_flag = REMOVE_DIR_FORCED; - - if (uRemoveDir (src_dir, force_flag) != ERR_NO_ERROR) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE - 1, - "Can't' delete the folder: %s.", src_dir); - return ERR_WITH_MSG; - } - - return ERR_NO_ERROR; -} - -int -ts_write_and_save_conf (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char *conf_path; - char conf_backup_path[PATH_MAX]; - - if ((conf_path = nv_get_val (req, "confpath")) == NULL) - { - strcpy_limit (_dbmt_error, "confpath", DBMT_ERROR_MSG_SIZE); - return ERR_PARAM_MISSING; - } - - /* if conf_path exsit, backup it at the current path. */ - if (access (conf_path, F_OK) == 0) - { - snprintf (conf_backup_path, sizeof (conf_backup_path) - 1, - "%s.bak", conf_path); - - if (file_copy (conf_path, conf_backup_path) != 0) - { - strcpy_limit (_dbmt_error, "backup file error.", - DBMT_ERROR_MSG_SIZE); - return ERR_WITH_MSG; - } - } - - /* create a new conf file from request. */ - if (_write_conf_to_file (req, conf_path) < 0) - { - strcpy_limit (_dbmt_error, "write config file error.", - DBMT_ERROR_MSG_SIZE); - return ERR_WITH_MSG; - } - - return ERR_NO_ERROR; -} - -int -ts_run_sql_statement (nvplist *req, nvplist *res, char *_dbmt_error) -{ - T_ARNIADB_MODE mode; - T_ASQL_RESULT *asql_res = NULL; - int retval = ERR_NO_ERROR; - char *dbname, *uid, *passwd; - char *infile; - char *command; - char *error_continue; - - if ((dbname = nv_get_val (req, "dbname")) == NULL) - { - strcpy_limit (_dbmt_error, "dbname", DBMT_ERROR_MSG_SIZE); - return ERR_PARAM_MISSING; - } - - infile = nv_get_val (req, "infile"); - command = nv_get_val (req, "command"); - - uid = nv_get_val (req, "uid"); - passwd = nv_get_val (req, "passwd"); - error_continue = nv_get_val (req, "error_continue"); - - mode = - (uDatabaseMode (dbname, NULL) == - DB_SERVICE_MODE_NONE ? ARNIADB_MODE_SA : ARNIADB_MODE_CS); - - asql_res = cmd_asql (dbname, uid, passwd, mode, infile, command, error_continue); /* asql */ - - if (asql_res == NULL) - { - strcpy_limit (_dbmt_error, "Error occur when execurating asql.", - DBMT_ERROR_MSG_SIZE); - return ERR_WITH_MSG; - } - - if (strlen (asql_res->err_msg) != 0) - { - strcpy_limit (_dbmt_error, asql_res->err_msg, DBMT_ERROR_MSG_SIZE); - retval = ERR_WITH_MSG; - } - free (asql_res); - return retval; -} - -int -ts_get_folders_with_keyword (nvplist *req, nvplist *res, char *_dbmt_error) -{ - int retval; - char *search_folder; - char *keyword; - - if ((search_folder = nv_get_val (req, "search_folder")) == NULL) - { - strcpy_limit (_dbmt_error, "search_folder", DBMT_ERROR_MSG_SIZE); - return ERR_PARAM_MISSING; - } - - if ((keyword = nv_get_val (req, "keyword")) == NULL) - { - strcpy_limit (_dbmt_error, "keyword", DBMT_ERROR_MSG_SIZE); - return ERR_PARAM_MISSING; - } - - retval = - _get_folders_with_keyword (search_folder, keyword, res, _dbmt_error); - - return retval; -} - -int -ts_run_script (nvplist *req, nvplist *res, char *_dbmt_error) -{ - int argc = 0; - const char *argv[5]; - char *script_path; - char outfile[PATH_MAX]; - char errfile[PATH_MAX]; - char *n, *v; - int retval = ERR_NO_ERROR; - int i, pid; - - pid = (int) getpid (); - snprintf (outfile, sizeof (outfile) - 1, "%s/DBMT_task_%d_out.%d", - sco.dbmt_tmp_dir, TS_RUN_SCRIPT, pid); - snprintf (errfile, sizeof (errfile) - 1, "%s/DBMT_task_%d_err.%d", - sco.dbmt_tmp_dir, TS_RUN_SCRIPT, pid); - - /* set environment that the script need to run. */ - for (i = 0; i < req->nvplist_leng; i++) - { - nv_lookup (req, i, &n, &v); - if ((n != NULL) && (strcmp (n, "envvar") == 0)) - { - putenv (v); - } - } - - if ((script_path = nv_get_val (req, "script_path")) == NULL) - { - strcpy_limit (_dbmt_error, "script_path", DBMT_ERROR_MSG_SIZE); - return ERR_PARAM_MISSING; - } - - argv[argc++] = script_path; - argv[argc++] = NULL; - - /* run *.bat or *.sh. */ - if (run_child (argv, 1, NULL, outfile, errfile, NULL) < 0) - { - strcpy_limit (_dbmt_error, argv[0], DBMT_ERROR_MSG_SIZE); - retval = ERR_SYSTEM_CALL; - } - - unlink (outfile); - unlink (errfile); - - return retval; -} - -int -ts_get_file_total_line_num (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char *filepath; - FILE *fp = NULL; - char buf[LINE_MAX]; - int total_num = 0; - - if ((filepath = nv_get_val (req, "filepath")) == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "filepath"); - return ERR_PARAM_MISSING; - } - - if ((fp = fopen (filepath, "r")) == NULL) - { - return ERR_TMPFILE_OPEN_FAIL; - } - - while (fgets (buf, sizeof (buf), fp)) - { - total_num++; - } - fclose (fp); - - nv_add_nvp_int (res, "totalnum", total_num); - - return ERR_NO_ERROR; -} - -int -ts_error_trace (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char *err_log_path; - char *eid; - char *err_time; - FILE *fp; - char buf[10 * 1024]; - - if ((err_log_path = nv_get_val (req, "logpath")) == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "logpath"); - return ERR_PARAM_MISSING; - } - - if ((eid = nv_get_val (req, "eid")) == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "eid"); - return ERR_PARAM_MISSING; - } - - if ((err_time = nv_get_val (req, "errtime")) == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "errtime"); - return ERR_PARAM_MISSING; - } - - memset (buf, 0, sizeof (buf)); - - if ((fp = fopen (err_log_path, "r")) == NULL) - { - return ERR_FILE_OPEN_FAIL; - } - - nv_add_nvp (res, "open", "errbloc"); - - while (_get_block_from_log (fp, buf, sizeof (buf)) == 0) - { - char *line_start, *line_end; - char eid_tok[64]; - char err_time_tok[64]; - - snprintf (eid_tok, sizeof (eid_tok) - 1, "EID = %s", eid); - snprintf (err_time_tok, sizeof (err_time_tok) - 1, "%s (", err_time); - - line_start = buf; - if ((strstr (line_start, eid_tok) != NULL) - && (strstr (line_start, err_time_tok) != NULL)) - { - while ((line_end = strchr (line_start, '\n')) != NULL) - { - *line_end = '\0'; - nv_add_nvp (res, "line", line_start); - line_end++; - line_start = line_end; - } - } - } - - nv_add_nvp (res, "close", "errbloc"); - fclose (fp); - - return ERR_NO_ERROR; -} - -int -ts_remove_files (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char *path = NULL; - char fullpath[PATH_MAX]; - int i = 0; - int sect = -1; - int sect_len = -1; - int path_len = -1; - int found = -1; - - fullpath[0] = '\0'; - - nv_locate (req, "files", §, §_len); - if (sect >= 0) - { - for (i = 0; i < sect_len; ++i) - { - found = nv_lookup (req, sect + i, NULL, &path); - if (found == -1) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", - "The key [path] is missing or its value is not valid."); - return ERR_WITH_MSG; - } - if (path == NULL) - { - sprintf (_dbmt_error, - "Please inform file names to be deleted."); - return ERR_WITH_MSG; - } - path_len = (int) strlen (path); - if (path_len <= 2 || strstr (path, "..") || strstr (path, "/") - || strstr (path, "\\")) - { - sprintf (_dbmt_error, "Cannot be permitted to delete %s file", - path); - return ERR_WITH_MSG; - } - if (*path == '+' && * (path + 1) == 'T') // for ARNIADB/tmp - { - snprintf (fullpath, sizeof (fullpath) - 1, "%s/tmp/%s", - sco.szArniadb, (path + 2)); - } - else - { - sprintf (_dbmt_error, "Cannot be permitted to delete %s file", - path); - return ERR_WITH_MSG; - } - if ((unlink (fullpath) != 0) && (errno != ENOENT)) - { - sprintf (_dbmt_error, "Cannot remove file '%s' (%s)", path, - strerror (errno)); - return ERR_WITH_MSG; - } - } /* end of for */ - return ERR_NO_ERROR; - } - else - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", - "The key [files] is missing or its value is not valid."); - return ERR_WITH_MSG; - } -} - - -int -ts_login (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char *value = NULL; - int ret_val = ERR_NO_ERROR; - - if ((ret_val = ts_validate_user (req, res, _dbmt_error)) != ERR_NO_ERROR) - { - /* Authentication failed. Drop connection */ - /* because function ts_validate_user already add the err msg to res */ - return ret_val; - } - - if (ts_check_client_version (req, res) == 0) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "Version-mismatched"); - - /* because function ts_validate_user already add the err msg to res */ - return ERR_WITH_MSG; - } - - /* generate token and record new connection to file */ - value = nv_get_val (req, "id"); - /* set _ID token for ut_error_log & ut_access_log. */ - nv_add_nvp (req, "_ID", value); - - _accept_connection (req, res); - - ut_access_log (req, "connected"); - - return ERR_NO_ERROR; -} - -int -ts_logout (nvplist *req, nvplist *res, char *_dbmt_error) -{ - T_USER_TOKEN_INFO *removed_node = NULL; - - char *token = NULL; - - ut_access_log (req, "disconnected"); - - nv_update_val (res, "status", "success"); - nv_update_val (res, "note", ""); - - token = nv_get_val (req, "token"); - removed_node = dbmt_user_delete_token_info_by_token (token); - - if (removed_node == NULL) - { - return ERR_INVALID_TOKEN; - } - - FREE_MEM (removed_node); - - return ERR_NO_ERROR; -} - -int -ts_job_test (nvplist *req, nvplist *res, char *_dbmt_error) -{ - int i; - nvplist *cli_response; - const char *argvs[2]; - - cli_response = nv_create (5, NULL, "\n", ":", "\n"); - for (i = ERR_NO_ERROR; i <= ERR_WARNING; i++) - { - uGenerateStatus (req, cli_response, i, "test error"); - } - - nv_destroy (cli_response); - argvs[0] = "ping"; - argvs[1] = NULL; - - ut_run_child ("ping", argvs, 1, "infile.test", "outfile.test", - "errfile.test", &i); - unlink ("outfile.test"); - unlink ("errfile.test"); - return ERR_NO_ERROR; -} - -static const char * -get_processor_architecture () -{ -#ifdef WINDOWS - SYSTEM_INFO siSysInfo; - GetSystemInfo (&siSysInfo); - switch (siSysInfo.wProcessorArchitecture) - { - case PROCESSOR_ARCHITECTURE_AMD64: - case PROCESSOR_ARCHITECTURE_IA64: - return "x64"; - case PROCESSOR_ARCHITECTURE_INTEL: - return "x86"; - default: - break; - } - return "unknown"; -#else - struct utsname u_name; - if (uname (&u_name) < 0) - { - return "unknown"; - } - - if (!strcmp (u_name.machine, "x86_64")) - { - return "x64"; - } - else - { - return "x86"; - } -#endif -} - -int -ts_get_cms_env (nvplist *req, nvplist *res, char *_dbmt_error) -{ - int is_default_cert_file = 0; - - ts_get_server_version (req, res); - nv_add_nvp (res, "PLATFORM", get_processor_architecture ()); - nv_add_nvp (res, "CMS_VER", makestring (BUILD_NUMBER)); - - nv_add_nvp_int (res, "cm_port", sco.iCMS_port); - - is_default_cert_file = _is_default_cert (_dbmt_error); - if (is_default_cert_file < 0) - { - return ERR_WITH_MSG; - } - if (is_default_cert_file == 0) - { - nv_add_nvp (res, "is_default_cert", "no"); - } - else - { - nv_add_nvp (res, "is_default_cert", "yes"); - } - - return ERR_NO_ERROR; -} - -int -ts_keepalive (nvplist *req, nvplist *res, char *_dbmt_error) -{ - SLEEP_SEC (10); - nv_update_val (res, "status", "success"); - nv_update_val (res, "note", ""); - return ERR_NO_ERROR; -} - -static int -_get_block_from_log (FILE *fp, char *block_buf, int len) -{ - int retval = -1; - int space_left = len - 1; - char buf[2048]; - char *buf_t = block_buf; - - while (fgets (buf, sizeof (buf), fp)) - { - if (space_left <= 0) - { - return 0; - } - - if (strcmp (buf, "\n") == 0) - { - break; - } - - strcpy_limit (buf_t, buf, space_left); - space_left -= (int) strlen (buf); - buf_t += strlen (buf); - retval = 0; - } - - if (strlen (block_buf)) - { - block_buf[strlen (block_buf) - 1] = '\0'; - } - return retval; -} - -static int -cmd_heartbeat_list (T_HA_SERVER_INFO_ALL **all_info, int get_all_dbmode, - char *dblist, char *_dbmt_error) -{ - char cmd_name[ARNIADB_CMD_NAME_LEN]; - const char *argv[6]; - int argc = 0; - char arniadb_err_file[PATH_MAX]; - char outputfilepath[PATH_MAX]; - int retval = ERR_NO_ERROR; - FILE *tmpfile = NULL; - - arniadb_err_file[0] = '\0'; - - arniadb_cmd_name (cmd_name); - argv[argc++] = cmd_name; - argv[argc++] = PRINT_CMD_HEARTBEAT; - argv[argc++] = PRINT_CMD_LIST; - argv[argc++] = NULL; - - snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", - sco.dbmt_tmp_dir, "heartbeat_list", getpid ()); - - snprintf (outputfilepath, PATH_MAX - 1, "%s/DBMT_task_%d.%d", - sco.dbmt_tmp_dir, TS_HEARTBEAT_LIST, (int) getpid ()); - - if (run_child (argv, 1, NULL, outputfilepath, arniadb_err_file, NULL) < 0) - { - /* heartbeat list */ - strcpy (_dbmt_error, argv[0]); - retval = ERR_SYSTEM_CALL; - goto rm_tmpfile; - } - - if (read_error_file (arniadb_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) - { - retval = ERR_WITH_MSG; - goto rm_tmpfile; - } - - /* open tmp file. */ - tmpfile = fopen (outputfilepath, "r"); - if (tmpfile == NULL) - { - retval = ERR_TMPFILE_OPEN_FAIL; - goto rm_tmpfile; - } - - if ((retval = - record_ha_topology_to_struct (tmpfile, get_all_dbmode, dblist, - _dbmt_error, all_info)) != ERR_NO_ERROR) - { - fclose (tmpfile); - goto rm_tmpfile; - } - - /* close tmp file. */ - fclose (tmpfile); - -rm_tmpfile: - unlink (outputfilepath); - if (access (arniadb_err_file, F_OK) == 0) - { - unlink (arniadb_err_file); - } - return retval; -} - -static int -dbname_exist_in_dbinfo_list (int nitem, char *dbname, - T_HA_SERVER_INFO_ALL *all_info) -{ - int i; - T_HA_DBSERVER_INFO *db_info_t = NULL; - - for (i = 0; i < nitem; i++) - { - db_info_t = & (all_info->db_info[i]); - if (strcmp (dbname, db_info_t->dbname) == 0) - { - return i; - } - } - return -1; -} - -static void -print_ha_proc_info (T_HA_LOG_PROC_INFO *ha_log_proc, int elem_num, - int is_copylogdb, nvplist *res) -{ - int i; - - for (i = 0; i < elem_num; i++) - { - nv_add_nvp (res, "open", "element"); - nv_add_nvp (res, "hostname", ha_log_proc[i].hostname); - nv_add_nvp (res, "dbname", ha_log_proc[i].dbname); - nv_add_nvp (res, "state", ha_log_proc[i].state); - nv_add_nvp (res, "logpath", ha_log_proc[i].logpath); - nv_add_nvp_int (res, "pid", ha_log_proc[i].pid); - if (is_copylogdb != 0) - { - nv_add_nvp (res, "mode", ha_log_proc[i].mode); - } - nv_add_nvp (res, "close", "element"); - } -} - -static void -print_dbinfo_list_to_res (T_HA_SERVER_INFO_ALL *all_info, nvplist *res) -{ - int i; - T_DB_MODE_INFO *dbmode_info_t = NULL; - T_HA_DB_PROC_INFO *dbproc_info_t = NULL; - T_HA_LOG_PROC_INFO *applylogdb_info_t = NULL; - T_HA_LOG_PROC_INFO *copylogdb_info_t = NULL; - T_HA_NODE_INFO *node_info_t = NULL; - - nv_add_nvp (res, "currentnode", all_info->current_node); - nv_add_nvp (res, "currentnodestate", all_info->current_node_state); - - nv_add_nvp (res, "open", "hanodelist"); - - for (i = 0; i < all_info->num_nodeinfo; i++) - { - nv_add_nvp (res, "open", "node"); - if ((node_info_t = & (all_info->node_info[i])) != NULL) - { - nv_add_nvp (res, "hostname", node_info_t->hostname); - nv_add_nvp (res, "ip", node_info_t->ip); - nv_add_nvp_int (res, "priority", node_info_t->priority); - nv_add_nvp (res, "state", node_info_t->state); - } - nv_add_nvp (res, "close", "node"); - } - nv_add_nvp (res, "close", "hanodelist"); - - nv_add_nvp (res, "open", "hadbinfolist"); - - for (i = 0; i < all_info->num_dbinfo; i++) - { - nv_add_nvp (res, "open", "server"); - - /* add db mode info */ - nv_add_nvp (res, "open", "dbmode"); - if ((dbmode_info_t = all_info->db_info[i].dbmode_info) != NULL) - { - nv_add_nvp (res, "dbname", dbmode_info_t->dbname); - nv_add_nvp (res, "server_mode", dbmode_info_t->server_mode); - nv_add_nvp (res, "server_msg", dbmode_info_t->server_msg); - } - nv_add_nvp (res, "close", "dbmode"); - - nv_add_nvp (res, "open", "dbprocinfo"); - if ((dbproc_info_t = all_info->db_info[i].dbproc_info) != NULL) - { - nv_add_nvp (res, "dbname", dbproc_info_t->dbname); - nv_add_nvp_int (res, "pid", dbproc_info_t->pid); - nv_add_nvp (res, "state", dbproc_info_t->state); - } - nv_add_nvp (res, "close", "dbprocinfo"); - - nv_add_nvp (res, "open", "applylogdb"); - if ((applylogdb_info_t = all_info->db_info[i].applylogdb_info) != NULL) - { - print_ha_proc_info (applylogdb_info_t, all_info->db_info[i].num_ap, - 0, res); - } - nv_add_nvp (res, "close", "applylogdb"); - - nv_add_nvp (res, "open", "copylogdb"); - if ((copylogdb_info_t = all_info->db_info[i].copylogdb_info) != NULL) - { - print_ha_proc_info (copylogdb_info_t, all_info->db_info[i].num_cp, - 1, res); - } - nv_add_nvp (res, "close", "copylogdb"); - - nv_add_nvp (res, "close", "server"); - } - nv_add_nvp (res, "close", "hadbinfolist"); -} - -static void -dbinfo_list_free (T_HA_SERVER_INFO_ALL *all_info) -{ - int i; - - if (all_info == NULL) - { - return; - } - - for (i = 0; i < all_info->num_dbinfo; i++) - { - if (&all_info->db_info[i] == NULL) - { - continue; - } - - FREE_MEM ((&all_info->db_info[i])->dbmode_info); - FREE_MEM ((&all_info->db_info[i])->dbproc_info); - FREE_MEM ((&all_info->db_info[i])->applylogdb_info); - FREE_MEM ((&all_info->db_info[i])->copylogdb_info); - } - - FREE_MEM (all_info->db_info); - FREE_MEM (all_info->node_info); - FREE_MEM (all_info); -} - -static char * -get_ip_from_hostname (char *hostname, char *ipaddr, int ip_len) -{ - char *ip = NULL; - int i; - struct hostent *hostent_p = NULL; - - hostent_p = gethostbyname (hostname); - - if (hostent_p == NULL) - { - ipaddr = NULL; - } - else - { - for (i = 0; hostent_p->h_addr_list[i] != NULL; i++) - { - ip = inet_ntoa (* ((struct in_addr *) hostent_p->h_addr_list[i])); - - /* ignore the 127.0.0.1 */ - if (strcmp (ip, "127.0.0.1") == 0) - { - continue; - } - break; - } - if (ip) - { - strcpy_limit (ipaddr, ip, ip_len); - } - } - - return ipaddr; -} - -static int -is_name_in_list (char *name, char *list) -{ - int first_name_len = 0; - char *name_start_p = NULL; - char *name_end_p = NULL; - char name_t[1024] = { 0 }; - - name_start_p = list; - name_end_p = strchr (name_start_p, ','); - - while (name_end_p != NULL) - { - /* copy name from list and trim it. */ - first_name_len = (int) (name_end_p - name_start_p); - - if (first_name_len > (int) sizeof (name_t)) - { - return -1; - } - - strcpy_limit (name_t, name_start_p, first_name_len + 1); - - ut_trim (name_t); - - if (strcmp (name_t, name) == 0) - { - return 1; - } - - name_start_p = name_end_p + 1; - name_end_p = strchr (name_start_p, ','); - } - - /* - * when name_end_p is NULL, it indicates the end of list is met. - * check the last name in the list. - */ - - strcpy_limit (name_t, name_start_p, sizeof (name_t)); - ut_trim (name_t); - - if (strcmp (name_t, name) == 0) - { - return 1; - } - - return 0; -} - -static void -set_copylogdb_mode (T_HA_LOG_PROC_INFO *copylogdb) -{ - FILE *cmd_fp = NULL; - int cmd_len = 0; - char buf[2048] = { 0 }; - char cmd_file[PATH_MAX]; - char *buf_t = NULL; - - memset (buf, 0, sizeof (buf)); - - snprintf (cmd_file, PATH_MAX - 1, "/proc/%d/cmdline", copylogdb->pid); - cmd_fp = fopen (cmd_file, "r"); - - if (cmd_fp == NULL) - { - strcpy_limit (copylogdb->mode, "", sizeof (copylogdb->mode)); - return; - } - - cmd_len = (int) fread (buf, sizeof (char), sizeof (buf) - 1, cmd_fp); - buf_t = buf; - - while (buf_t[0] != 0 && ((int) (buf_t - buf)) < cmd_len) - { - int s_len = 0; - - s_len = (int) strlen (buf_t); - - if (uStringEqual (buf_t, "-m") || uStringEqual (buf_t, "--mode")) - { - /* if the arg is "-m" or "--mode", then the next arg is the mode. */ - buf_t = &buf_t[s_len + 1]; - break; - } - else if (strncmp (buf_t, "--mode=", strlen ("--mode=")) == 0) - { - /* if the arg is "--mode", the mode is right behind the '='. */ - buf_t += strlen ("--mode="); - break; - } - - buf_t = &buf_t[ (s_len + 1)]; - } - - /* if the "-m" & "--mode" args are not exist, the default "sync" mode is used. */ - if (buf_t[0] == 0) - { - strcpy_limit (copylogdb->mode, "sync", sizeof (copylogdb->mode)); - goto func_return; - } - else - { - if (uStringEqual (buf_t, "3") || uStringEqualIgnoreCase (buf_t, "sync")) - { - strcpy_limit (copylogdb->mode, "sync", sizeof (copylogdb->mode)); - } - else if (uStringEqual (buf_t, "2") || - uStringEqualIgnoreCase (buf_t, "semisync")) - { - strcpy_limit (copylogdb->mode, "semisync", - sizeof (copylogdb->mode)); - } - else if (uStringEqual (buf_t, "1") || - uStringEqualIgnoreCase (buf_t, "async")) - { - strcpy_limit (copylogdb->mode, "async", sizeof (copylogdb->mode)); - } - else - { - strcpy_limit (copylogdb->mode, "", - sizeof (copylogdb->mode)); - } - goto func_return; - } - -func_return: - fclose (cmd_fp); - return; -} - -static int -parse_ha_proc_msg_to_all_info_array (char *buf, char *_dbmt_error, - T_HA_SERVER_INFO_ALL **all_info, - int *nitem, int *nalloc, - int *nproc_alloc, int get_all_dbmode, - char *dblist) -{ - char tmpbuf[1280] = { 0 }; - char pid[32] = { 0 }; - char elem_name[64] = { 0 }; - char state[64] = { 0 }; - char dbname[DB_NAME_LEN] = { 0 }; - char logpath[PATH_MAX] = { 0 }; - char hostname[MAXHOSTNAMELEN] = { 0 }; - int dbinfo_index = 0; - int retval = ERR_NO_ERROR; - T_HA_LOG_PROC_INFO *applylogdb_info = NULL; - T_HA_LOG_PROC_INFO *copylogdb_info = NULL; - - if (sscanf (buf, "%63s %1279s %*s %31[^,] , %*s %63[^)]", - elem_name, tmpbuf, pid, state) != 4) - { - retval = ERR_NO_ERROR; - goto func_return; - } - else - { - T_HA_DBSERVER_INFO *db_info_t = NULL; - - if (strcmp (elem_name, "Server") == 0) - { - T_HA_DB_PROC_INFO *dbproc_info = NULL; - - if ((get_all_dbmode == 0) - && (is_name_in_list (tmpbuf, dblist) == 0)) - { - retval = ERR_NO_ERROR; - goto func_return; - } - - dbproc_info = - (T_HA_DB_PROC_INFO *) MALLOC (sizeof (T_HA_DB_PROC_INFO)); - - if (dbproc_info == NULL) - { - retval = ERR_MEM_ALLOC; - goto func_return; - } - - /* create a T_HA_DB_PROC_INFO element */ - strcpy_limit (dbproc_info->dbname, tmpbuf, - sizeof (dbproc_info->dbname)); - strcpy_limit (dbproc_info->state, state, - sizeof (dbproc_info->state)); - dbproc_info->pid = atoi (pid); - - /* - * if the dbname is already exist in dbinfo list, add the server proc - * info to the node with the dbname. - */ - if ((dbinfo_index = - dbname_exist_in_dbinfo_list ((*nitem), - dbproc_info->dbname, - *all_info)) >= 0) - { - (*all_info)->db_info[dbinfo_index].dbproc_info = dbproc_info; - } - else - { - /* - * Else add a new dbnode, and add the server proc info to the node. - */ - if ((*nitem) >= (*nalloc)) - { - (*nalloc) *= 2; - - (*all_info)->db_info = - (T_HA_DBSERVER_INFO *) realloc ((*all_info)->db_info, - (*nalloc) * sizeof (T_HA_DBSERVER_INFO)); - - if ((*all_info)->db_info == NULL) - { - retval = ERR_MEM_ALLOC; - goto func_return; - } - } - - /* create two node list for applylogdb and copylogdb process of the server. */ - copylogdb_info = - (T_HA_LOG_PROC_INFO *) MALLOC ((*nproc_alloc) * - sizeof (T_HA_LOG_PROC_INFO)); - applylogdb_info = - (T_HA_LOG_PROC_INFO *) MALLOC ((*nproc_alloc) * - sizeof (T_HA_LOG_PROC_INFO)); - - if (copylogdb_info == NULL || applylogdb_info == NULL) - { - FREE_MEM (copylogdb_info); - FREE_MEM (applylogdb_info); - retval = ERR_MEM_ALLOC; - goto func_return; - } - - db_info_t = & ((*all_info)->db_info[ (*nitem)]); - - strcpy_limit (db_info_t->dbname, - dbproc_info->dbname, sizeof (db_info_t->dbname)); - db_info_t->dbproc_info = dbproc_info; - db_info_t->applylogdb_info = applylogdb_info; - db_info_t->copylogdb_info = copylogdb_info; - db_info_t->num_ap = 0; - db_info_t->num_cp = 0; - (*nitem)++; - } - } - else - { - /* - * if the elem_name is 'Applylogdb' or 'Copylogdb'. - */ - - /* create a tmp T_HA_LOG_PROC_INFO element for later copy. */ - T_HA_DBSERVER_INFO *db_info_t = NULL; - T_HA_LOG_PROC_INFO p_proc_info; - memset (&p_proc_info, 0, sizeof (T_HA_LOG_PROC_INFO)); - if (sscanf (tmpbuf, "%63[^@] @ %128[^:] : %1023s", dbname, - hostname, logpath) != 3) - { - retval = ERR_NO_ERROR; - goto func_return; - } - - if ((get_all_dbmode == 0) - && (is_name_in_list (dbname, dblist) == 0)) - { - retval = ERR_NO_ERROR; - goto func_return; - } - - strcpy_limit (p_proc_info.dbname, dbname, - sizeof (p_proc_info.dbname)); - strcpy_limit (p_proc_info.hostname, hostname, - sizeof (p_proc_info.hostname)); - strcpy_limit (p_proc_info.logpath, logpath, - sizeof (p_proc_info.logpath)); - strcpy_limit (p_proc_info.state, state, sizeof (p_proc_info.state)); - p_proc_info.pid = atoi (pid); - - /* - * if the node already exist in the dbinfo list, then add - * the Applylogdb or Copylogdb proc info to the node with the - * dbname. - */ - if ((dbinfo_index = - dbname_exist_in_dbinfo_list ((*nitem), - p_proc_info.dbname, - *all_info)) >= 0) - { - db_info_t = & ((*all_info)->db_info[dbinfo_index]); - - if (db_info_t->num_ap >= (*nproc_alloc)) - { - (*nproc_alloc) *= 2; - db_info_t->applylogdb_info = - (T_HA_LOG_PROC_INFO *) realloc (db_info_t->applylogdb_info, - (*nproc_alloc) * sizeof (T_HA_LOG_PROC_INFO)); - db_info_t->copylogdb_info = - (T_HA_LOG_PROC_INFO *) realloc (db_info_t->copylogdb_info, - (*nproc_alloc) * sizeof (T_HA_LOG_PROC_INFO)); - - if ((db_info_t->applylogdb_info == NULL) || - (db_info_t->copylogdb_info == NULL)) - { - retval = ERR_MEM_ALLOC; - goto func_return; - } - } - - if (strcmp (elem_name, "Applylogdb") == 0) - { - memmove (& (db_info_t->applylogdb_info[db_info_t->num_ap]), - &p_proc_info, sizeof (T_HA_LOG_PROC_INFO)); - db_info_t->num_ap++; - } - else - { - /* set the copylogdb mode. */ - set_copylogdb_mode (&p_proc_info); - - memmove (& (db_info_t->copylogdb_info[db_info_t->num_cp]), - &p_proc_info, sizeof (T_HA_LOG_PROC_INFO)); - db_info_t->num_cp++; - } - } - else - { - /* - * if the node does not exist in the dbinfo list, - * add a new node with the dbname, and add Applylogdb and - * Copylogdb to the node. - */ - - if ((*nitem) >= (*nalloc)) - { - (*nalloc) *= 2; - - (*all_info)->db_info = - (T_HA_DBSERVER_INFO *) realloc ((*all_info)->db_info, - (*nalloc) * sizeof (T_HA_DBSERVER_INFO)); - if ((*all_info)->db_info == NULL) - { - retval = ERR_MEM_ALLOC; - goto func_return; - } - } - - /* create two node list for applylogdb and copylogdb process of the server. */ - copylogdb_info = - (T_HA_LOG_PROC_INFO *) MALLOC ((*nproc_alloc) * - sizeof (T_HA_LOG_PROC_INFO)); - applylogdb_info = - (T_HA_LOG_PROC_INFO *) MALLOC ((*nproc_alloc) * - sizeof (T_HA_LOG_PROC_INFO)); - - if (copylogdb_info == NULL || applylogdb_info == NULL) - { - FREE_MEM (copylogdb_info); - FREE_MEM (applylogdb_info); - retval = ERR_MEM_ALLOC; - goto func_return; - } - - db_info_t = & ((*all_info)->db_info[ (*nitem)]); - strcpy_limit (db_info_t->dbname, - p_proc_info.dbname, sizeof (db_info_t->dbname)); - db_info_t->dbproc_info = NULL; - db_info_t->copylogdb_info = copylogdb_info; - db_info_t->applylogdb_info = applylogdb_info; - db_info_t->num_ap = 0; - db_info_t->num_cp = 0; - - if (strcmp (elem_name, "Applylogdb") == 0) - { - memmove (& (db_info_t->applylogdb_info[db_info_t->num_ap]), - &p_proc_info, sizeof (T_HA_LOG_PROC_INFO)); - db_info_t->num_ap++; - } - if (strcmp (elem_name, "Copylogdb") == 0) - { - /* set the copylogdb mode. */ - set_copylogdb_mode (&p_proc_info); - - memmove (& (db_info_t->copylogdb_info[db_info_t->num_cp]), - &p_proc_info, sizeof (T_HA_LOG_PROC_INFO)); - db_info_t->num_cp++; - } - (*nitem)++; - } - } - } - -func_return: - return retval; -} - -static int -parse_ha_node_to_all_info_array (char *buf, T_HA_SERVER_INFO_ALL **all_info, - int *node_alloc, char *_dbmt_error) -{ - char tok[4][64] = { {0}, {0}, {0}, {0} }; - char ipaddr[64] = { 0 }; - T_HA_NODE_INFO *node_info_t = NULL; - - if (((*all_info)->num_nodeinfo) >= (*node_alloc)) - { - (*node_alloc) *= 2; - - (*all_info)->node_info = - (T_HA_NODE_INFO *) realloc ((*all_info)->node_info, - (*node_alloc) * sizeof (T_HA_NODE_INFO)); - - if ((*all_info)->node_info == NULL) - { - return ERR_MEM_ALLOC; - } - } - - node_info_t = & ((*all_info)->node_info[ (*all_info)->num_nodeinfo]); - - if (sscanf (buf, "%63s %63s %*s %63[^,] , %*s %63[^)]", - tok[0], tok[1], tok[2], tok[3]) != 4) - { - return ERR_NO_ERROR; - } - - strcpy_limit (node_info_t->hostname, tok[1], - sizeof (node_info_t->hostname)); - - get_ip_from_hostname (tok[1], ipaddr, sizeof (ipaddr)); - - if (ipaddr == NULL) - { - strcpy_limit (_dbmt_error, "can't get ip addr from hostname", - DBMT_ERROR_MSG_SIZE); - return ERR_WITH_MSG; - } - - strcpy_limit (node_info_t->ip, ipaddr, sizeof (node_info_t->ip)); - - node_info_t->priority = atoi (tok[2]); - - strcpy_limit (node_info_t->state, tok[3], sizeof (node_info_t->state)); - - (*all_info)->num_nodeinfo++; - return ERR_NO_ERROR; -} - -static int -record_ha_topology_to_struct (FILE *infile, int get_all_dbmode, char *dblist, - char *_dbmt_error, - T_HA_SERVER_INFO_ALL **all_info) -{ - char buf[2048] = { 0 }; - char ha_elem_name[64] = { 0 }; - T_HA_DBSERVER_INFO *dbserver_p = NULL; - T_HA_NODE_INFO *node_p = NULL; - - int nitem = 0; - int nalloc = 15; - int nproc_alloc = 20; - int node_alloc = 10; - int retval = ERR_NO_ERROR; - - /* Create a dbproc info list which contains all the info about the HA-Process. */ - dbserver_p = - (T_HA_DBSERVER_INFO *) MALLOC (nalloc * sizeof (T_HA_DBSERVER_INFO)); - node_p = (T_HA_NODE_INFO *) MALLOC (node_alloc * sizeof (T_HA_NODE_INFO)); - - if (dbserver_p == NULL || node_p == NULL) - { - FREE_MEM (dbserver_p); - FREE_MEM (node_p); - return ERR_MEM_ALLOC; - } - - (*all_info)->db_info = dbserver_p; - (*all_info)->node_info = node_p; - (*all_info)->num_dbinfo = 0; - (*all_info)->num_nodeinfo = 0; - - while (fgets (buf, sizeof (buf), infile)) - { - sscanf (buf, "%63s", ha_elem_name); - if (strcmp (ha_elem_name, "HA-Node") == 0) - { - char tok[4][64] = { {0}, {0}, {0}, {0} }; - - if (sscanf (buf, "%63s %63s %*s %63[^,] , %*s %63[^)]", - tok[0], tok[1], tok[2], tok[3]) != 4) - { - continue; - } - if (strcmp (tok[0], "HA-Node") == 0) - { - strcpy_limit ((*all_info)->current_node, tok[2], - sizeof ((*all_info)->current_node)); - strcpy_limit ((*all_info)->current_node_state, tok[3], - sizeof ((*all_info)->current_node_state)); - } - } - else if (strcmp (ha_elem_name, "Node") == 0) - { - parse_ha_node_to_all_info_array (buf, all_info, &node_alloc, - _dbmt_error); - } - else if (strcmp (ha_elem_name, "Applylogdb") == 0 || - strcmp (ha_elem_name, "Copylogdb") == 0 || - strcmp (ha_elem_name, "Server") == 0) - { - if (get_all_dbmode == 0 && dblist == NULL) - { - continue; - } - if ((retval = - parse_ha_proc_msg_to_all_info_array - (buf, _dbmt_error, all_info, &nitem, &nalloc, - &nproc_alloc, get_all_dbmode, dblist)) != ERR_NO_ERROR) - { - goto func_return; - } - } - else if ((strcmp (ha_elem_name, "++") == 0)) - { - /* delete the '\n' at the end of buf. */ - ut_trim (buf); - - /* ignore the "++" tag. */ - strcpy_limit (_dbmt_error, &buf[2], DBMT_ERROR_MSG_SIZE); - retval = ERR_WITH_MSG; - goto func_return; - } - } - - retval = ERR_NO_ERROR; - -func_return: - (*all_info)->num_dbinfo = nitem; - return retval; -} - -static int -fill_dbmode_into_dbinfo_list (T_HA_SERVER_INFO_ALL **all_info, - char *_dbmt_error) -{ - int i; - T_HA_DBSERVER_INFO *dbserver_info_t = NULL; - T_DB_MODE_INFO *dbmode_info_p = NULL; - - for (i = 0; i < (*all_info)->num_dbinfo; i++) - { - dbmode_info_p = (T_DB_MODE_INFO *) MALLOC (sizeof (T_DB_MODE_INFO)); - dbserver_info_t = & (*all_info)->db_info[i]; - - if (dbmode_info_p == NULL) - { - return ERR_MEM_ALLOC; - } - - cmd_get_db_mode (dbmode_info_p, dbserver_info_t->dbname, _dbmt_error); - dbserver_info_t->dbmode_info = dbmode_info_p; - } - - return ERR_NO_ERROR; -} - -/* - * get port info from brokers config, that located by - */ -static const char * -_op_get_port_from_config (T_CM_BROKER_CONF *uc_conf, char *broker_name) -{ - int pos; - char *name; - for (pos = 0; pos < uc_conf->num_broker; pos++) - { - name = cm_br_conf_get_value (& (uc_conf->br_conf[pos]), "%"); - if (name != NULL && strcasecmp (broker_name, name) == 0) - { - return cm_br_conf_get_value (& (uc_conf->br_conf[pos]), - "BROKER_PORT"); - } - } - - /* not found. in this case returns zero value, it is means unknown port. */ - return "0"; -} - -/* Read dbmt password file and append user information to nvplist */ -static void -_tsAppendDBMTUserList (nvplist *res, T_DBMT_USER *dbmt_user, - int return_dbmt_pwd, char *_dbmt_error) -{ - const char *unicas_auth, *dbcreate = NULL; - int i, j; - - nv_add_nvp (res, "open", "userlist"); - for (i = 0; i < dbmt_user->num_dbmt_user; i++) - { - if (dbmt_user->user_info[i].user_name[0] == '\0') - { - continue; - } - nv_add_nvp (res, "open", "user"); - nv_add_nvp (res, ENCRYPT_ARG ("id"), dbmt_user->user_info[i].user_name); - if (return_dbmt_pwd) - { - char decrypted[PASSWD_LENGTH + 1]; - - uDecrypt (PASSWD_LENGTH, dbmt_user->user_info[i].user_passwd, - decrypted); - nv_add_nvp (res, ENCRYPT_ARG ("passwd"), decrypted); - } - - nv_add_nvp (res, "open", "dbauth"); - unicas_auth = NULL; - /* add dbinfo */ - for (j = 0; j < dbmt_user->user_info[i].num_dbinfo; j++) - { - if (dbmt_user->user_info[i].dbinfo[j].dbname[0] == '\0') - { - continue; - } -#ifdef JSON_SUPPORT - nv_add_nvp (res, "open", "auth_info"); -#endif - nv_add_nvp (res, "dbname", - dbmt_user->user_info[i].dbinfo[j].dbname); - nv_add_nvp (res, ENCRYPT_ARG ("dbid"), - dbmt_user->user_info[i].dbinfo[j].uid); - nv_add_nvp (res, "dbbrokeraddress", - dbmt_user->user_info[i].dbinfo[j].broker_address); -#ifdef JSON_SUPPORT - nv_add_nvp (res, "close", "auth_info"); -#endif - } - nv_add_nvp (res, "close", "dbauth"); - - /* add auth info */ - for (j = 0; j < dbmt_user->user_info[i].num_authinfo; j++) - { - if (dbmt_user->user_info[i].authinfo[j].domain[0] == '\0') - { - continue; - } - if (strcmp (dbmt_user->user_info[i].authinfo[j].domain, "unicas") == 0) - { - unicas_auth = dbmt_user->user_info[i].authinfo[j].auth; - nv_add_nvp (res, "casauth", - dbmt_user->user_info[i].authinfo[j].auth); - continue; - } - else if (strcmp - (dbmt_user->user_info[i].authinfo[j].domain, "dbcreate") == 0) - { - dbcreate = dbmt_user->user_info[i].authinfo[j].auth; - nv_add_nvp (res, "dbcreate", - dbmt_user->user_info[i].authinfo[j].auth); - continue; - } - else if (strcmp (dbmt_user->user_info[i].authinfo[j].domain, - "statusmonitorauth") == 0) - { - nv_add_nvp (res, "statusmonitorauth", - dbmt_user->user_info[i].authinfo[j].auth); - continue; - } - } - if (unicas_auth == NULL) - { - nv_add_nvp (res, "casauth", "none"); - } - - if (dbcreate == NULL) - { - nv_add_nvp (res, "dbcreate", "none"); - } - nv_add_nvp (res, "close", "user"); - } - nv_add_nvp (res, "close", "userlist"); -} - -static char * -get_user_name (int uid, char *name_buf) -{ -#if defined(WINDOWS) - strcpy (name_buf, ""); -#else - struct passwd *pwd; - - pwd = getpwuid (uid); - if (pwd->pw_name) - { - strcpy (name_buf, pwd->pw_name); - } - else - { - name_buf[0] = '\0'; - } -#endif - - return name_buf; -} - -static int -uca_conf_write (T_CM_BROKER_CONF *uc_conf, char *del_broker, - char *_dbmt_error) -{ - char buf[512]; - FILE *fp; - int i, j; - struct stat statbuf; - - for (i = 0; i < uc_conf->num_header; i++) - { - if (uc_conf->header_conf[i].name == NULL || - uc_conf->header_conf[i].value == NULL) - { - return ERR_MEM_ALLOC; - } - } - for (i = 0; i < uc_conf->num_broker; i++) - { - for (j = 0; j < uc_conf->br_conf[i].num; j++) - { - if (uc_conf->br_conf[i].item[j].name == NULL || - uc_conf->br_conf[i].item[j].value == NULL) - { - return ERR_MEM_ALLOC; - } - } - } - - cm_get_broker_file (UC_FID_ARNIADB_BROKER_CONF, buf); - - if (stat (buf, &statbuf) < 0) - { - cm_get_broker_file (UC_FID_ARNIADB_CAS_CONF, buf); - if (stat (buf, &statbuf) < 0) - { - cm_get_broker_file (UC_FID_UNICAS_CONF, buf); - if (stat (buf, &statbuf) < 0) - { - cm_get_broker_file (UC_FID_ARNIADB_BROKER_CONF, buf); - } - } - } - - if ((fp = fopen (buf, "w")) == NULL) - { - strcpy (_dbmt_error, buf); - return ERR_FILE_OPEN_FAIL; - } - fprintf (fp, "[broker]\n"); - for (i = 0; i < uc_conf->num_header; i++) - { - fprintf (fp, "%-25s =%s\n", - uc_conf->header_conf[i].name, uc_conf->header_conf[i].value); - } - fprintf (fp, "\n"); - for (i = 0; i < uc_conf->num_broker; i++) - { - if ((del_broker != NULL) && - (strcmp (uc_conf->br_conf[i].item[0].value, del_broker) == 0)) - { - continue; - } - fprintf (fp, "[%s%s]\n", uc_conf->br_conf[i].item[0].name, - to_upper_str (uc_conf->br_conf[i].item[0].value, buf)); - for (j = 1; j < uc_conf->br_conf[i].num; j++) - { - if (uc_conf->br_conf[i].item[j].value[0] == '\0') - { - continue; - } - fprintf (fp, "%-25s =%s\n", uc_conf->br_conf[i].item[j].name, - uc_conf->br_conf[i].item[j].value); - } - fprintf (fp, "\n"); - } - fclose (fp); - return ERR_NO_ERROR; -} - -static int -_tsParseSpacedb (nvplist *req, nvplist *res, char *dbname, - char *_dbmt_error, GeneralSpacedbResult *cmd_res) -{ - int pagesize, logpagesize; - char dbdir[PATH_MAX]; -#if defined(WINDOWS) - WIN32_FIND_DATA data; - char find_file[PATH_MAX]; - HANDLE handle; - int found; -#else - DIR *dirp = NULL; - struct dirent *dp = NULL; -#endif - - cmd_res->create_result (res); - pagesize = cmd_res->get_page_size(); - logpagesize = cmd_res->get_log_page_size(); - - - if (uRetrieveDBLogDirectory (dbname, dbdir) != ERR_NO_ERROR) - { - strcpy (_dbmt_error, dbname); - return ERR_DBDIRNAME_NULL; - } - - /* read entries in the directory and generate result */ -#if defined(WINDOWS) - snprintf (find_file, PATH_MAX - 1, "%s/*", dbdir); - if ((handle = FindFirstFile (find_file, &data)) == INVALID_HANDLE_VALUE) -#else - if ((dirp = opendir (dbdir)) == NULL) -#endif - { - sprintf (_dbmt_error, "%s", dbdir); - return ERR_DIROPENFAIL; - } - -#if defined(WINDOWS) - for (found = 1; found; found = FindNextFile (handle, &data)) -#else - while ((dp = readdir (dirp)) != NULL) -#endif - { - int baselen; - char *fname; - -#if defined(WINDOWS) - fname = data.cFileName; -#else - fname = dp->d_name; -#endif - baselen = (int) strlen (dbname); - - if (strncmp (fname, dbname, baselen) == 0) - { - if (!strcmp (fname + baselen, ARNIADB_ACT_LOG_EXT)) - { - _ts_gen_spaceinfo (res, fname, dbdir, "Active_log", - logpagesize); - } - else if (!strncmp (fname + baselen, ARNIADB_ARC_LOG_EXT, - ARNIADB_ARC_LOG_EXT_LEN)) - { - _ts_gen_spaceinfo (res, fname, dbdir, "Archive_log", - logpagesize); - } -#if 0 - else if (strncmp (fname + baselen, "_lginf", 6) == 0) - { - _ts_gen_spaceinfo (res, fname, dbdir, "Generic_log", - logpagesize); - } -#endif - - } - } -#if defined(WINDOWS) - FindClose (handle); -#else - closedir (dirp); -#endif - - if (uRetrieveDBDirectory (dbname, dbdir) == ERR_NO_ERROR) - { - nv_add_nvp_int (res, "freespace", ut_disk_free_space (dbdir)); - } - else - { - nv_add_nvp_int (res, "freespace", -1); - } - - return ERR_NO_ERROR; -} - -static void -_ts_gen_spaceinfo (nvplist *res, const char *filename, - const char *dbinstalldir, const char *type, int pagesize) -{ - char volfile[PATH_MAX]; - struct stat statbuf; - - nv_add_nvp (res, "open", "spaceinfo"); - nv_add_nvp (res, "spacename", filename); - nv_add_nvp (res, "type", type); - nv_add_nvp (res, "location", dbinstalldir); - - snprintf (volfile, PATH_MAX - 1, "%s/%s", dbinstalldir, filename); - stat (volfile, &statbuf); - - nv_add_nvp_int (res, "totalpage", - pagesize ? statbuf.st_size / pagesize : 0); - nv_add_nvp (res, "freepage", " "); - - ts_add_nvp_time (res, "date", statbuf.st_mtime, "%04d%02d%02d", NV_ADD_DATE); - - nv_add_nvp (res, "close", "spaceinfo"); - return; -} - -static int -_ts_lockdb_parse_us (nvplist *res, FILE *infile) -{ - char buf[1024], s[256], s1[256], s2[256], s3[256], s4[256]; - char *temp, *temp2; - int scan_matched; - int flag = 0; - int flag_lot_tag = 0; - int has_index_name = 0; - - nv_add_nvp (res, "open", "lockinfo"); - while (fgets (buf, sizeof (buf), infile)) - { - sscanf (buf, "%255s", s); - - if (flag == 0 && !strcmp (s, "***")) - { - fgets (buf, sizeof (buf), infile); - scan_matched = - sscanf (buf, "%*s %*s %*s %*s %255s %*s %*s %*s %*s %255s", s1, s2); - - if (scan_matched != 2) - { - return -1; - } - if (strlen (s1) > 0) - { - s1[strlen (s1) - 1] = '\0'; - } - nv_add_nvp (res, "esc", s1); - nv_add_nvp (res, "dinterval", s2); - flag = 1; - } - else if (flag == 1) - { - if (strcmp (s, "Transaction") == 0) - { - scan_matched = - sscanf (buf, "%*s %*s %255s %255s %255s", s1, s2, s3); - - if (scan_matched != 3) - { - return -1; - } - - s1[strlen (s1) - 1] = '\0'; - s2[strlen (s2) - 1] = '\0'; - s3[strlen (s3) - 1] = '\0'; - - nv_add_nvp (res, "open", "transaction"); - nv_add_nvp (res, "index", s1); - nv_add_nvp (res, "pname", s2); - - temp = strchr (s3, '@'); - if (temp != NULL) - { - strncpy (buf, s3, (int) (temp - s3)); - buf[ (int) (temp - s3)] = '\0'; - nv_add_nvp (res, ENCRYPT_ARG ("uid"), buf); - } - - temp2 = strrchr (s3, '|'); - if (temp2 != NULL) - { - strncpy (buf, temp + 1, (int) (temp2 - temp - 1)); - buf[ (int) (temp2 - temp) - 1] = '\0'; - nv_add_nvp (res, "host", buf); - - nv_add_nvp (res, "pid", temp2 + 1); /* moved from below to avoid seg. fault */ - } - - fgets (buf, sizeof (buf), infile); - buf[strlen (buf) - 1] = '\0'; - nv_add_nvp (res, "isolevel", buf + strlen ("Isolation ")); - - fgets (buf, sizeof (buf), infile); - if (strncmp (buf, "State", strlen ("State")) == 0) - { - fgets (buf, sizeof (buf), infile); - } - - scan_matched = sscanf (buf, "%*s %255s", s1); - - if (scan_matched != 1) - { - return -1; - } - nv_add_nvp (res, "timeout", s1); - nv_add_nvp (res, "close", "transaction"); - } - else if (strcmp (s, "Object") == 0) - { - fgets (buf, sizeof (buf), infile); - scan_matched = - sscanf (buf, "%*s %*s %*s %*s %*s %*s %*s %*s %255s", s1); - if (scan_matched != 1) - { - return -1; - } - nv_add_nvp (res, "open", "lot"); - flag_lot_tag = 1; - nv_add_nvp (res, "numlocked", s1); - - fgets (buf, sizeof (buf), infile); - scan_matched = - sscanf (buf, "%*s %*s %*s %*s %*s %*s %*s %*s %*s %255s", s2); - if (scan_matched != 1) - { - return -1; - } - nv_add_nvp (res, "maxnumlock", s2); - flag = 2; - } - } /* end of if (flag == 1) */ - else if (flag == 2) - { - char value[1024]; - - while (!strcmp (s, "OID")) - { - int num_holders, num_b_holders, num_waiters, scan_matched; - - scan_matched = - sscanf (buf, "%*s %*s %[^|] %*[|] %[^|] %*[|] %255s", s1, s2, s3); - if (scan_matched != 3) - { - return -1; - } - - snprintf (value, sizeof (value) - 1, "%s|%s|%s", s1, s2, s3); - - nv_add_nvp (res, "open", "entry"); - nv_add_nvp (res, "oid", value); - - fgets (buf, sizeof (buf), infile); - sscanf (buf, "%*s %*s %255s", s); - - s1[0] = s2[0] = s3[0] = '\0'; - scan_matched = 0; - if ((strcmp (s, "Class") == 0) || (strcmp (s, "Instance") == 0) - || (strcmp (s, "Index") == 0)) - { - char *p; - p = strchr (buf, ':'); - if (strlen (buf) > 1) - { - buf[strlen (buf) - 1] = '\0'; - if (buf[strlen (buf) - 1] == '.') - { - buf[strlen (buf) - 1] = '\0'; - } - } - nv_add_nvp (res, "ob_type", p + 2); - if (strcmp (s, "Index") == 0) - { - has_index_name = 1; - } - fgets (buf, sizeof (buf), infile); - } - else if (strcmp (s, "Root") == 0) - { - nv_add_nvp (res, "ob_type", "Root class"); - fgets (buf, sizeof (buf), infile); - } - else - { - /* Current test is not 'OID = ...' and if 'Total mode of holders ...' then */ - if (has_index_name == 1) - { - fgets (buf, sizeof (buf), infile); - } - scan_matched = - sscanf (buf, - "%*s %*s %255s %*s %*s %255s %*s %*s %255s", s1, s2, s3); - if ((strncmp (s1, "of", 2) == 0) - && (strncmp (s3, "of", 2) == 0)) - { - nv_add_nvp (res, "ob_type", "None"); - } - else - { - return -1; - } - } - - if (has_index_name == 1) - { - fgets (buf, sizeof (buf), infile); - } - /* already get scan_matched value, don't sscanf */ - if (scan_matched == 0) - scan_matched = - sscanf (buf, "%*s %*s %255s %*s %*s %255s %*s %*s %255s", s1, s2, s3); - - if ((strncmp (s1, "of", 2) == 0) - && (strncmp (s3, "of", 2) == 0)) - { - /* ignore UnixWare's 'Total mode of ...' text */ - fgets (buf, sizeof (buf), infile); - scan_matched = - sscanf (buf, "%*s %*s %255s %*s %*s %255s %*s %*s %255s", s1, s2, s3); - } - - if (scan_matched != 3) - { - return -1; - } - s1[strlen (s1) - 1] = '\0'; - s2[strlen (s2) - 1] = '\0'; - - num_holders = atoi (s1); - num_b_holders = atoi (s2); - num_waiters = atoi (s3); - - if (num_waiters < 0 || num_waiters >= INT_MAX) - { - return -1; - } - - nv_add_nvp (res, "num_holders", s1); - nv_add_nvp (res, "num_b_holders", s2); - nv_add_nvp (res, "num_waiters", s3); - - while (fgets (buf, sizeof (buf), infile)) - { - sscanf (buf, "%255s", s); - if (strcmp (s, "NON_2PL_RELEASED:") == 0) - { - fgets (buf, sizeof (buf), infile); - while (sscanf (buf, "%255s", s)) - { - if (strcmp (s, "Tran_index") != 0) - { - break; - } - else - { - if (fgets (buf, sizeof (buf), infile) == NULL) - { - break; - } - } - } - break; - } /* ignore NON_2PL_RELEASED information */ - - sscanf (buf, "%*s %255s", s); - if (strcmp (s, "HOLDERS:") == 0) - { - int index; - - for (index = 0; index < num_holders; index++) - { - /* make lock holders information */ - - fgets (buf, sizeof (buf), infile); - scan_matched = - sscanf (buf, - "%*s %*s %255s %*s %*s %255s %*s %*s %255s %*s %*s %255s", - s1, s2, s3, s4); - - /* parshing error */ - if (scan_matched < 3) - { - return -1; - } - if (scan_matched == 4) - { - /* nsubgranules is existed */ - s3[strlen (s3) - 1] = '\0'; - } - - s1[strlen (s1) - 1] = '\0'; - s2[strlen (s2) - 1] = '\0'; - - nv_add_nvp (res, "open", "lock_holders"); - nv_add_nvp (res, "tran_index", s1); - nv_add_nvp (res, "granted_mode", s2); - nv_add_nvp (res, "count", s3); - if (scan_matched == 4) - { - nv_add_nvp (res, "nsubgranules", s4); - } - nv_add_nvp (res, "close", "lock_holders"); - } - - if ((num_b_holders == 0) && (num_waiters == 0)) - { - break; - } - } - else if (strcmp (s, "LOCK") == 0) - { - int index; - char *p; - - for (index = 0; index < num_b_holders; index++) - { - /* make blocked lock holders */ - int scan_matched; - fgets (buf, sizeof (buf), infile); - scan_matched = - sscanf (buf, - "%*s %*s %255s %*s %*s %255s %*s %*s %255s %*s %*s %255s", - s1, s2, s3, s4); - - /* parshing error */ - if (scan_matched < 3) - { - return -1; - } - if (scan_matched == 4) - { - /* nsubgranules is existed */ - s3[strlen (s3) - 1] = '\0'; - } - - s1[strlen (s1) - 1] = '\0'; - s2[strlen (s2) - 1] = '\0'; - - nv_add_nvp (res, "open", "b_holders"); - nv_add_nvp (res, "tran_index", s1); - nv_add_nvp (res, "granted_mode", s2); - nv_add_nvp (res, "count", s3); - - if (scan_matched == 4) - { - nv_add_nvp (res, "nsubgranules", s4); - } - fgets (buf, sizeof (buf), infile); - sscanf (buf, "%*s %*s %255s", s1); - nv_add_nvp (res, "b_mode", s1); - - fgets (buf, sizeof (buf), infile); - p = strchr (buf, '='); - buf[strlen (buf) - 1] = '\0'; - nv_add_nvp (res, "start_at", p + 2); - - fgets (buf, sizeof (buf), infile); - sscanf (buf, "%*s %*s %255s", s1); - nv_add_nvp (res, "waitfornsec", s1); - - nv_add_nvp (res, "close", "b_holders"); - } - - if (num_waiters == 0) - { - break; - } - } - else if (strcmp (s, "WAITERS:") == 0) - { - int index; - - for (index = 0; index < num_waiters; index++) - { - /* make lock waiters */ - char *p; - - fgets (buf, sizeof (buf), infile); - sscanf (buf, "%*s %*s %255s %*s %*s %255s", s1, s2); - s1[strlen (s1) - 1] = '\0'; - - nv_add_nvp (res, "open", "waiters"); - nv_add_nvp (res, "tran_index", s1); - nv_add_nvp (res, "b_mode", s2); - - fgets (buf, sizeof (buf), infile); - p = strchr (buf, '='); - buf[strlen (buf) - 1] = '\0'; - nv_add_nvp (res, "start_at", p + 2); - - fgets (buf, sizeof (buf), infile); - sscanf (buf, "%*s %*s %255s", s1); - nv_add_nvp (res, "waitfornsec", s1); - - nv_add_nvp (res, "close", "waiters"); - } - break; - } - } /* end of while - for just one object */ - nv_add_nvp (res, "close", "entry"); - } /* end of while(OID) */ - } - } - if (flag_lot_tag != 0) - { - nv_add_nvp (res, "close", "lot"); - } - nv_add_nvp (res, "close", "lockinfo"); - return 0; -} - -static char * -to_lower_str (char *str, char *buf) -{ - char *p; - - strcpy (buf, str); - for (p = buf; *p; p++) - { - if (*p >= 'A' && *p <= 'Z') - { - *p = *p - 'A' + 'a'; - } - } - return buf; -} - -static char * -to_upper_str (char *str, char *buf) -{ - char *p; - - strcpy (buf, str); - for (p = buf; *p; p++) - { - if (*p >= 'a' && *p <= 'z') - { - *p = *p - 'a' + 'A'; - } - } - return buf; -} - -static int -op_make_triggerinput_file_add (nvplist *req, char *input_filename) -{ - char *name, *status, *cond_source, *priority; - char *event_target, *event_type, *event_time, *actiontime, *action; - FILE *input_file; - - if (input_filename == NULL) - { - return 0; - } - - input_file = fopen (input_filename, "w+"); - if (input_file == NULL) - { - return 0; - } - - name = nv_get_val (req, "triggername"); - status = nv_get_val (req, "status"); - event_type = nv_get_val (req, "eventtype"); - event_target = nv_get_val (req, "eventtarget"); - event_time = nv_get_val (req, "conditiontime"); - cond_source = nv_get_val (req, "condition"); - actiontime = nv_get_val (req, "actiontime"); - action = nv_get_val (req, "action"); - priority = nv_get_val (req, "priority"); - /* fprintf(input_file, ";autocommit off\n"); */ - fprintf (input_file, "create trigger\t%s\n", name); - - if (status) - { - fprintf (input_file, "status\t%s\n", status); - } - if (priority) - { - fprintf (input_file, "priority\t%s\n", priority); - } - fprintf (input_file, "%s\t%s\t", event_time, event_type); - - if (event_target) - { - fprintf (input_file, "ON\t%s\n", event_target); - } - if (cond_source) - { - fprintf (input_file, "if\t%s\n", cond_source); - } - fprintf (input_file, "execute\t"); - - if (actiontime) - { - fprintf (input_file, "%s\t", actiontime); - } - fprintf (input_file, "%s\n", action); - fprintf (input_file, "\n\ncommit;\n\n"); - - fclose (input_file); - - return 1; -} - -static int -op_make_triggerinput_file_drop (nvplist *req, char *input_filename) -{ - char *trigger_name; - FILE *input_file; - - if (input_filename == NULL) - { - return 0; - } - - input_file = fopen (input_filename, "w+"); - if (input_file == NULL) - { - return 0; - } - - trigger_name = nv_get_val (req, "triggername"); - /* fprintf(input_file, ";autocommit off\n"); */ - fprintf (input_file, "drop trigger\t%s\n", trigger_name); - fprintf (input_file, "\n\n\ncommit;\n\n"); - - fclose (input_file); - - return 1; -} - -static int -op_make_triggerinput_file_alter (nvplist *req, char *input_filename) -{ - char *trigger_name, *status, *priority; - FILE *input_file; - - if (input_filename == NULL) - { - return 0; - } - - input_file = fopen (input_filename, "w+"); - if (input_file == NULL) - { - return 0; - } - - trigger_name = nv_get_val (req, "triggername"); - status = nv_get_val (req, "status"); - priority = nv_get_val (req, "priority"); - /* fprintf(input_file, ";autocommit off\n"); */ - if (status) - { - fprintf (input_file, "alter trigger\t%s\t", trigger_name); - fprintf (input_file, "status %s\t", status); - } - - if (priority) - { - fprintf (input_file, "alter trigger\t%s\t", trigger_name); - fprintf (input_file, "priority %s\t", priority); - } - - fprintf (input_file, "\n\n\ncommit;\n\n"); - fclose (input_file); - - return 1; -} - -static int -get_broker_info_from_filename (char *path, char *br_name, int *as_id) -{ -#if defined(WINDOWS) - const char *sql_log_ext = ".sql.log"; - int sql_log_ext_len = (int) strlen (sql_log_ext); - int path_len; - char *p; - - if (path == NULL) - { - return -1; - } - path_len = (int) strlen (path); - if (strncmp (path, sco.szArniadb, strlen (sco.szArniadb)) != 0 || - path_len <= sql_log_ext_len || - strcmp (path + (path_len - sql_log_ext_len), sql_log_ext) != 0) - { - return -1; - } - - for (p = path + path_len - 1; p >= path; p--) - { - if (*p == '/' || *p == '\\') - { - break; - } - } - path = p + 1; - path_len = (int) strlen (path); - - * (path + path_len - sql_log_ext_len) = '\0'; - p = strrchr (path, '_'); - - *as_id = atoi (p + 1); - if (*as_id <= 0) - { - return -1; - } - strncpy (br_name, path, p - path); - * (br_name + (p - path)) = '\0'; - - return 0; -#else - return -1; -#endif -} - -/* - * check if dir path contains white space character, - * and if path contains '\', substitute it with '/' - */ -static int -check_dbpath (char *dir, char *_dbmt_error) -{ - if (dir == NULL || *dir == '\0') - { - strcpy (_dbmt_error, "Path is NULL!"); - return ERR_WITH_MSG; - } - - while (*dir != '\0') - { - if (isspace (*dir)) - { - strcpy (_dbmt_error, "Path contains white space!"); - return ERR_WITH_MSG; - } - else if (*dir == '\\') - { - *dir = '/'; - } - dir++; - } - - return ERR_NO_ERROR; -} - -static int -get_dbitemdir (char *item_dir, size_t item_dir_size, char *dbname, - char *err_buf, int itemtype) -{ - FILE *databases_txt; - char *envpath; - char db_txt[PATH_MAX]; - char cbuf[2048]; - char itemname[1024]; - char scan_format[128]; - char pattern[64]; - const char *patternVol = "%%%lus %%%lus %%*s %%*s"; - const char *patternLog = "%%%lus %%*s %%*s %%%lus"; - - if (item_dir == NULL || dbname == NULL) - { - return -1; - } -#if !defined (DO_NOT_USE_ARNIADBENV) - envpath = sco.szArniadb_databases; -#else - envpath = ARNIADB_VARDIR; -#endif - if ((envpath == NULL) || (strlen (envpath) == 0)) - { - return -1; - } - snprintf (db_txt, sizeof (db_txt) - 1, "%s/%s", envpath, - ARNIADB_DATABASE_TXT); - databases_txt = fopen (db_txt, "r"); - - /*set the patten to get dir from databases.txt. */ - if (databases_txt == NULL) - { - return -1; - } - - if (itemtype == PATTERN_VOL) - { - strcpy_limit (pattern, patternVol, sizeof (pattern)); - } - else if (itemtype == PATTERN_LOG) - { - strcpy_limit (pattern, patternLog, sizeof (pattern)); - } - else - { - fclose (databases_txt); - return -1; - } - - snprintf (scan_format, sizeof (scan_format) - 1, pattern, - (unsigned long) sizeof (itemname) - 1, - (unsigned long) item_dir_size - 1); - - while (fgets (cbuf, sizeof (cbuf), databases_txt) != NULL) - { - if (sscanf (cbuf, scan_format, itemname, item_dir) < 2) - { - continue; - } - if (strcmp (itemname, dbname) == 0) - { - fclose (databases_txt); - return 1; - } - } - - fclose (databases_txt); - return 1; -} - -static int -get_dblogdir (char *log_dir, size_t log_dir_size, char *dbname, char *err_buf) -{ - int retVal = - get_dbitemdir (log_dir, log_dir_size, dbname, err_buf, PATTERN_LOG); - return retVal; -} - -static int -get_dbvoldir (char *vol_dir, size_t vol_dir_size, char *dbname, char *err_buf) -{ - int retVal = - get_dbitemdir (vol_dir, vol_dir_size, dbname, err_buf, PATTERN_VOL); - return retVal; -} - -static char * -cm_get_abs_file_path (const char *filename, char *buf) -{ - strcpy (buf, filename); - - if (buf[0] == '/') - { - return buf; - } -#if defined(WINDOWS) - if (buf[2] == '/' || buf[2] == '\\') - { - return buf; - } -#endif - sprintf (buf, "%s/%s", getenv ("ARNIADB"), filename); - return buf; -} - -static int -file_to_nvpairs (char *filepath, nvplist *res) -{ - FILE *infile; - char buf[1024]; - - /* return error if the input file is NULL. */ - if ((infile = fopen (filepath, "r")) == NULL) - { - return -1; - } - - /* get all file content into response. */ - while (fgets (buf, sizeof (buf), infile)) - { - uRemoveCRLF (buf); - nv_add_nvp (res, "line", buf); - } - - fclose (infile); - return 0; -} - -static int -file_to_nvp_by_separator (FILE *fp, nvplist *res, char separator) -{ - char buf[1024]; - char *p, *q, *next; - int clientexist = 0; - const char *comparestr = "System parameters"; - - while (fgets (buf, sizeof (buf), fp) != NULL) - { - if (strncmp (buf, comparestr, strlen (comparestr)) == 0) - { - /* check if the sentences contains "client" or "server" or "standalone". */ - if (strstr (buf, "client") != NULL) - { - clientexist = 1; - nv_add_nvp (res, "open", "client"); - } - else if (strstr (buf, "server") != NULL) - { - /* if it is "server" then check if there is need to close "client". */ - if (clientexist != 0) - { - nv_add_nvp (res, "close", "client"); - } - nv_add_nvp (res, "open", "server"); - } - else if (strstr (buf, "standalone") != NULL) - { - /* if it is "standalone" then there should return only server paramdump. */ - nv_add_nvp (res, "open", "server"); - } - else - { - return -1; - } - } - - /* - * ignore the lines that start with "#", empty lines, - * and lines with out separator. - */ - if ('#' == buf[0] || '\n' == buf[0] || strchr (buf, separator) == NULL) - { - continue; - } - p = buf; - next = strchr (p, '\n'); - if (next != NULL) - { - *next = '\0'; - } - q = strchr (p, '='); - if (q != NULL) - { - *q = '\0'; - q++; - } - nv_add_nvp (res, p, q); - } - nv_add_nvp (res, "close", "server"); - return 0; -} - -/* check if autoexecquery.conf version < 8.3.0 */ -static int -obsolete_version_autoexecquery_conf (const char *conf_line) -{ - char conf_item_buf[80]; - - if (conf_line == NULL) - { - return -1; - } - - sscanf (conf_line, "%*s %*s %*s %80s", conf_item_buf); - if (strcmp (conf_item_buf, "ONE") == 0 - || strcmp (conf_item_buf, "DAY") == 0 - || strcmp (conf_item_buf, "WEEK") == 0 - || strcmp (conf_item_buf, "MONTH") == 0) - { - return 1; - } - else - { - return 0; - } -} - -static int -alter_dblocation (const char *dbname, const char *new_dbpath) -{ - int retval = ERR_NO_ERROR; - FILE *dblocation_info, *tmpfile; - char dblocation_info_path[PATH_MAX]; - char tmpfile_path[PATH_MAX]; - char *strbuf; - int buf_len, get_len; - int db_existant = 0; - char *tok[4]; - - snprintf (dblocation_info_path, PATH_MAX - 1, "%s/%s", - sco.szArniadb_databases, ARNIADB_DATABASE_TXT); - snprintf (tmpfile_path, PATH_MAX - 1, "%s/DBMT_util_dblocation.%d", - sco.dbmt_tmp_dir, (int) getpid ()); - - dblocation_info = fopen (dblocation_info_path, "r"); - tmpfile = fopen (tmpfile_path, "w"); - if (dblocation_info == NULL || tmpfile == NULL) - { - if (dblocation_info != NULL) - { - fclose (dblocation_info); - } - if (tmpfile != NULL) - { - fclose (tmpfile); - } - retval = ERR_FILE_OPEN_FAIL; - } - else - { - strbuf = NULL; - buf_len = get_len = 0; - while ((get_len = - ut_getline (&strbuf, &buf_len, dblocation_info)) != -1) - { - ut_trim (strbuf); - if (strbuf[0] == '#') - { - fprintf (tmpfile, "%s\n", strbuf); - continue; - } - - string_tokenize (strbuf, tok, 4); - if (uStringEqual (dbname, tok[0])) - { - db_existant = 1; - fprintf (tmpfile, "%s\t\t%s\t%s\t%s\n", tok[0], new_dbpath, - tok[2], new_dbpath); - } - else - { - fprintf (tmpfile, "%s\t\t%s\t%s\t%s\n", tok[0], tok[1], - tok[2], tok[3]); - } - FREE_MEM (strbuf); - buf_len = 0; - } - - if (strbuf != NULL) - { - FREE_MEM (strbuf); - } - - fclose (dblocation_info); - fclose (tmpfile); - - move_file (tmpfile_path, dblocation_info_path); - } - - if (!db_existant) - { - retval = ERR_DB_NONEXISTANT; - } - - return retval; -} - -static int -_get_folders_with_keyword (char *search_folder_path, const char *keyword, - nvplist *res, char *_dbmt_error) -{ -#if defined(WINDOWS) - WIN32_FIND_DATA data; - char find_file[512]; - HANDLE handle; - int found; - - sprintf (find_file, "%s/%s", search_folder_path, keyword); - handle = FindFirstFile (find_file, &data); - if (handle == INVALID_HANDLE_VALUE) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE - 1, - "Folder with keyword: %s does not exist.", keyword); - return ERR_WITH_MSG; - } - - nv_add_nvp (res, "open", "folders"); - for (found = 1; found; found = FindNextFile (handle, &data)) - { - if (strcmp (data.cFileName, ".") == 0 - || strcmp (data.cFileName, "..") == 0) - { - continue; - } - - if (data.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY) - { - nv_add_nvp (res, "foldername", data.cFileName); - } - } /* end of while and for */ - nv_add_nvp (res, "close", "folders"); - - FindClose (handle); -#else - struct dirent *dirp; - struct stat statbuf; - DIR *dp; - - dp = opendir (search_folder_path); - if (dp == NULL) - { - strcpy_limit (_dbmt_error, "Could not open the search folder.", - DBMT_ERROR_MSG_SIZE); - return ERR_WITH_MSG; - } - - nv_add_nvp (res, "open", "folders"); - while ((dirp = readdir (dp)) != NULL) - { - char dir[PATH_MAX] = { 0 }; - - snprintf (dir, sizeof (dir) - 1, "%s/%s", search_folder_path, - dirp->d_name); - stat (dir, &statbuf); - - if (strcmp (dirp->d_name, ".") == 0 || strcmp (dirp->d_name, "..") == 0) - { - continue; - } - - if (S_ISDIR (statbuf.st_mode) && - (fnmatch (keyword, dirp->d_name, 0) == 0)) - { - nv_add_nvp (res, "foldername", dirp->d_name); - } - } /* end of while and for */ - nv_add_nvp (res, "close", "folders"); - - closedir (dp); -#endif - - return ERR_NO_ERROR; -} - -static int -_update_nvplist_name (nvplist *ref, const char *name, const char *value) -{ - int i; - char *name_buf; - nvpair *nvp; - - if ((ref == NULL) || (name == NULL) || (value == NULL)) - { - return -1; - } - - for (i = 0; i < ref->nvplist_leng; i++) - { - if ((nvp = ref->nvpairs[i]) == NULL) - { - return -1; - } - - name_buf = dst_buffer (nvp->name); - if (uStringEqual (name_buf, name)) - { - dst_reset (nvp->name); - dst_append (nvp->name, value, (int) strlen (value)); - } - } - - return 0; -} - -static int -read_shard_info_output (nvplist *res, char *stdout_file, char *stderr_file, - char *_dbmt_error) -{ - int num_shard = 0, rtn = ERR_NO_ERROR; - int len = 0; - char str_buf[512]; - char scan_buf[21][64]; - char *num[2] = { NULL, NULL }; - FILE *fp; - - if (access (stderr_file, F_OK) == 0) - { - fp = fopen (stderr_file, "r"); - if (fp != NULL) - { - while (fgets (str_buf, sizeof (str_buf), fp) != NULL) - { - ut_trim (str_buf); - if (strncmp (str_buf, "++", 2) == 0) - { - continue; - } - len += (int) strlen (str_buf); - if (len < (DBMT_ERROR_MSG_SIZE - 1)) - { - strcpy (_dbmt_error, str_buf); - _dbmt_error += len; - } - else - { - strcpy_limit (_dbmt_error, str_buf, DBMT_ERROR_MSG_SIZE); - strcpy_limit (_dbmt_error + DBMT_ERROR_MSG_SIZE - 4, "...", 4); - break; - } - } - fclose (fp); - if (len != 0) - { - return ERR_WITH_MSG; - } - } - } - - - fp = fopen (stdout_file, "r"); - if (fp == NULL) - { - strcpy (_dbmt_error, stdout_file); - return ERR_FILE_OPEN_FAIL; - } - - while (fgets (str_buf, sizeof (str_buf), fp)) - { - if (strstr (str_buf, "++") != NULL) - { - strcpy (_dbmt_error, str_buf); - rtn = ERR_WITH_MSG; - break; - } - - if (strstr (str_buf, "*") == NULL) - { - continue; - } - - /* * NAME PID PSIZE PORT Active-P Active-C REQ TPS QPS K-QPS (H-KEY H-ID H-ALL) NK-QPS LONG-T LONG-Q ERR-Q CANCELED ACCESS_MODE SQL_LOG */ - if (sscanf (str_buf, - "%63s %63s %63s %63s %63s %63s %63s %63s %63s %63s %63s %63s %63s %63s %63s %63s %63s %63s %63s %63s %63s ", - scan_buf[0], scan_buf[1], scan_buf[2], scan_buf[3], - scan_buf[4], scan_buf[5], scan_buf[6], scan_buf[7], - scan_buf[8], scan_buf[9], scan_buf[10], scan_buf[11], - scan_buf[12], scan_buf[13], scan_buf[14], scan_buf[15], - scan_buf[16], scan_buf[17], scan_buf[18], scan_buf[19], - scan_buf[20]) < 21) - { - continue; - } - - num_shard++; - nv_add_nvp (res, "open", "shard"); - nv_add_nvp (res, "name", scan_buf[1]); - nv_add_nvp (res, "pid", scan_buf[2]); - nv_add_nvp (res, "psize", scan_buf[3]); - nv_add_nvp (res, "port", scan_buf[4]); - nv_add_nvp (res, "active-p", scan_buf[5]); - nv_add_nvp (res, "active-c", scan_buf[6]); - nv_add_nvp (res, "req", scan_buf[7]); - - nv_add_nvp (res, "tps", scan_buf[8]); - nv_add_nvp (res, "qps", scan_buf[9]); - nv_add_nvp (res, "k-qps", scan_buf[10]); - nv_add_nvp (res, "h-key", scan_buf[11]); - nv_add_nvp (res, "h-id", scan_buf[12]); - nv_add_nvp (res, "h-all", scan_buf[13]); - nv_add_nvp (res, "nk-qps", scan_buf[14]); - - string_tokenize2 (scan_buf[15], num, 2, '/'); - nv_add_nvp (res, "long_tran", num[0]); - nv_add_nvp (res, "long_tran_time", num[1]); - - string_tokenize2 (scan_buf[16], num, 2, '/'); - nv_add_nvp (res, "long_query", num[0]); - nv_add_nvp (res, "long_query_time", num[1]); - - nv_add_nvp (res, "error_query", scan_buf[17]); - nv_add_nvp (res, "canceled", scan_buf[18]); - nv_add_nvp (res, "access_mode", scan_buf[19]); - nv_add_nvp (res, "sqll", scan_buf[20]); - nv_add_nvp (res, "state", "ON"); - nv_add_nvp (res, "close", "shard"); - } - fclose (fp); - return rtn; -} - -int -ts_get_shard_info (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char stdout_log_file[512]; - char stderr_log_file[512]; - int pid, argc = 0; - int ret_val; - char cmd_name[ARNIADB_CMD_NAME_LEN]; - const char *argv[6]; - static int reqid = 0; - - /* not thread safe :( */ - reqid++; - sprintf (stdout_log_file, "%s/cmshardinfo.%d.err", sco.dbmt_tmp_dir, reqid); - sprintf (stderr_log_file, "%s/cmshardinfo2.%d.err", sco.dbmt_tmp_dir, reqid); - - cmd_name[0] = '\0'; -#if !defined (DO_NOT_USE_ARNIADBENV) - sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ARNIADB); -#else - sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_ARNIADB); -#endif - - argv[argc++] = cmd_name; - argv[argc++] = PRINT_CMD_SHARD; - argv[argc++] = PRINT_CMD_STATUS; - argv[argc++] = "-b"; - argv[argc++] = "-f"; - argv[argc++] = NULL; - - pid = run_child (argv, 1, NULL, stdout_log_file, stderr_log_file, NULL); /* start shard */ - - if (pid < 0) - { - if (_dbmt_error) - { - sprintf (_dbmt_error, "system error : %s shard status", cmd_name); - } - unlink (stdout_log_file); - unlink (stderr_log_file); - return ERR_WITH_MSG; - } - - ret_val = - read_shard_info_output (res, stdout_log_file, stderr_log_file, - _dbmt_error); - unlink (stdout_log_file); - unlink (stderr_log_file); - - return ret_val; -} - - -static int -read_shard_status_output (nvplist *res, char *stdout_file, char *stderr_file, - char *_dbmt_error) -{ - int rtn = ERR_NO_ERROR; - int len = 0; - char str_buf[512]; - char scan_buf[8][64]; - FILE *fp; - - if (access (stderr_file, F_OK) == 0) - { - fp = fopen (stderr_file, "r"); - if (fp != NULL) - { - while (fgets (str_buf, sizeof (str_buf), fp) != NULL) - { - ut_trim (str_buf); - if (strncmp (str_buf, "++", 2) == 0) - { - continue; - } - len += (int) strlen (str_buf); - if (len < (DBMT_ERROR_MSG_SIZE - 1)) - { - strcpy (_dbmt_error, str_buf); - _dbmt_error += len; - } - else - { - strcpy_limit (_dbmt_error, str_buf, DBMT_ERROR_MSG_SIZE); - strcpy_limit (_dbmt_error + DBMT_ERROR_MSG_SIZE - 4, "...", 4); - break; - } - } - fclose (fp); - if (len != 0) - { - return ERR_WITH_MSG; - } - } - } - - - fp = fopen (stdout_file, "r"); - if (fp == NULL) - { - strcpy (_dbmt_error, stdout_file); - return ERR_FILE_OPEN_FAIL; - } - - while (fgets (str_buf, sizeof (str_buf), fp)) - { - if (strstr (str_buf, "++") != NULL) - { - strcpy (_dbmt_error, str_buf); - rtn = ERR_WITH_MSG; - break; - } - - if (strstr (str_buf, "PROXY_ID") == NULL) - { - continue; - } - - /*ingore ------------ */ - fgets (str_buf, sizeof (str_buf), fp); - while (fgets (str_buf, sizeof (str_buf), fp)) - { - /* PROXY_ID SHARD_ID CAS_ID PID QPS LQS PSIZE STATUS */ - if (sscanf (str_buf, "%63s %63s %63s %63s %63s %63s %63s %63s", - scan_buf[0], scan_buf[1], scan_buf[2], scan_buf[3], - scan_buf[4], scan_buf[5], scan_buf[6], scan_buf[7]) < 8) - { - continue; - } - - nv_add_nvp (res, "open", "shard"); - nv_add_nvp (res, "proxy_id", scan_buf[0]); - nv_add_nvp (res, "shard_id", scan_buf[1]); - nv_add_nvp (res, "cas_id", scan_buf[2]); - nv_add_nvp (res, "pid", scan_buf[3]); - nv_add_nvp (res, "qps", scan_buf[4]); - nv_add_nvp (res, "lqs", scan_buf[5]); - nv_add_nvp (res, "psize", scan_buf[6]); - nv_add_nvp (res, "status", scan_buf[7]); - nv_add_nvp (res, "close", "shard"); - } - } - fclose (fp); - return rtn; -} - - -int -ts_get_shard_status (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char stdout_log_file[512]; - char stderr_log_file[512]; - int pid, argc = 0; - int ret_val; - char cmd_name[ARNIADB_CMD_NAME_LEN]; - const char *argv[6]; - char *sname; - static int reqid = 0; - - if ((sname = nv_get_val (req, "shardname")) == NULL) - { - strcpy (_dbmt_error, "shard name"); - return ERR_PARAM_MISSING; - } - /* not thread safe :( */ - reqid++; - sprintf (stdout_log_file, "%s/cmshardstatus.%d.err", sco.dbmt_tmp_dir, reqid); - sprintf (stderr_log_file, "%s/cmshardstatus2.%d.err", sco.dbmt_tmp_dir, reqid); - - cmd_name[0] = '\0'; -#if !defined (DO_NOT_USE_ARNIADBENV) - sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ARNIADB); -#else - sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_ARNIADB); -#endif - - argv[argc++] = cmd_name; - argv[argc++] = PRINT_CMD_SHARD; - argv[argc++] = PRINT_CMD_STATUS; - argv[argc++] = sname; - argv[argc++] = NULL; - - pid = run_child (argv, 1, NULL, stdout_log_file, stderr_log_file, NULL); /* start shard */ - - if (pid < 0) - { - if (_dbmt_error) - { - sprintf (_dbmt_error, "system error : %s shard status %s", cmd_name, sname); - } - unlink (stdout_log_file); - unlink (stderr_log_file); - return ERR_WITH_MSG; - } - - nv_add_nvp (res, "name", sname); - ret_val = - read_shard_status_output (res, stdout_log_file, stderr_log_file, _dbmt_error); - unlink (stdout_log_file); - unlink (stderr_log_file); - - return ret_val; -} - - -static int -read_start_shard_output (char *stdout_file, char *stderr_file, - char *_dbmt_error) -{ - FILE *fp, *fp2; - char buf[1024]; - char *strp; - int retval = 0; - - if (access (stdout_file, F_OK) == 0) - { - fp = fopen (stdout_file, "r"); - if (fp != NULL) - { - while (fgets (buf, sizeof (buf), fp) != NULL) - { - ut_trim (buf); - if (strncmp (buf, "@", 1) == 0) - { - continue; - } - if (strncmp (buf, "++", 2) == 0) - { - if ((strp = strchr (buf, ':')) && strstr (strp, "fail")) - { - retval = -1; - break; - } - } - strcpy (_dbmt_error, buf); - if (strstr (buf, "Cannot")) - { - retval = -1; - break; - } - } - fclose (fp); - } - } - - if (access (stderr_file, F_OK) == 0) - { - fp2 = fopen (stderr_file, "r"); - if (fp2 != NULL) - { - int len = 0; - while (fgets (buf, sizeof (buf), fp2) != NULL) - { - ut_trim (buf); - if (strncmp (buf, "++", 2) == 0 || strncmp (buf, "@", 1) == 0) - { - continue; - } - len += (int) strlen (buf); - if (len < (DBMT_ERROR_MSG_SIZE - 1)) - { - strcpy (_dbmt_error, buf); - _dbmt_error += len; - } - else - { - strcpy_limit (_dbmt_error, buf, DBMT_ERROR_MSG_SIZE); - strcpy_limit (_dbmt_error + DBMT_ERROR_MSG_SIZE - 4, "...", 4); - break; - } - } - - if (len != 0 && retval != -1) - { - retval = 1; - } - fclose (fp2); - } - } - - return retval; -} - - -int -ts_shard_start (nvplist *req, nvplist *res, char *err_buf) -{ - char stdout_log_file[512]; - char stderr_log_file[512]; - int pid, argc = 0; - int ret_val; - char cmd_name[ARNIADB_CMD_NAME_LEN]; - const char *argv[5]; - char *sname = NULL; - - sname = nv_get_val (req, "shardname"); - - sprintf (stdout_log_file, "%s/cmshardstart.%d.err", sco.dbmt_tmp_dir, - (int) getpid ()); - sprintf (stderr_log_file, "%s/cmshardstart2.%d.err", sco.dbmt_tmp_dir, - (int) getpid ()); - - cmd_name[0] = '\0'; -#if !defined (DO_NOT_USE_ARNIADBENV) - sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ARNIADB); -#else - sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_ARNIADB); -#endif - - argv[argc++] = cmd_name; - argv[argc++] = PRINT_CMD_SHARD; - if (sname == NULL) - { - argv[argc++] = PRINT_CMD_START; - } - else - { - argv[argc++] = PRINT_CMD_ON; - argv[argc++] = sname; - } - - argv[argc++] = NULL; - - pid = run_child (argv, 1, NULL, stdout_log_file, stderr_log_file, NULL); /* start shard */ - - if (pid < 0) - { - if (err_buf) - { - sprintf (err_buf, "system error : %s start shard", cmd_name); - } - unlink (stdout_log_file); - unlink (stderr_log_file); - return ERR_WITH_MSG; - } - - ret_val = - read_start_shard_output (stdout_log_file, stderr_log_file, err_buf); - unlink (stdout_log_file); - unlink (stderr_log_file); - - if (ret_val != 0) - { - return ERR_WITH_MSG; - } - - return ERR_NO_ERROR; -} - - -int -ts_shard_stop (nvplist *req, nvplist *res, char *err_buf) -{ - char stdout_log_file[512]; - char stderr_log_file[512]; - int pid, argc = 0; - int ret_val; - char cmd_name[ARNIADB_CMD_NAME_LEN]; - const char *argv[5]; - char *sname = NULL; - - sname = nv_get_val (req, "shardname"); - - sprintf (stdout_log_file, "%s/cmshardstop.%d.err", sco.dbmt_tmp_dir, - (int) getpid ()); - sprintf (stderr_log_file, "%s/cmshardstop2.%d.err", sco.dbmt_tmp_dir, - (int) getpid ()); - - cmd_name[0] = '\0'; -#if !defined (DO_NOT_USE_ARNIADBENV) - sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ARNIADB); -#else - sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_ARNIADB); -#endif - - argv[argc++] = cmd_name; - argv[argc++] = PRINT_CMD_SHARD; - if (sname == NULL) - { - argv[argc++] = PRINT_CMD_STOP; - } - else - { - argv[argc++] = PRINT_CMD_OFF; - argv[argc++] = sname; - } - - argv[argc++] = NULL; - - pid = run_child (argv, 1, NULL, stdout_log_file, stderr_log_file, NULL); /* start shard */ - - if (pid < 0) - { - if (err_buf) - { - sprintf (err_buf, "system error : %s stop shard", cmd_name); - } - unlink (stdout_log_file); - unlink (stderr_log_file); - return -1; - } - - ret_val = - read_start_shard_output (stdout_log_file, stderr_log_file, err_buf); - unlink (stdout_log_file); - unlink (stderr_log_file); - if (ret_val != 0) - { - return ERR_WITH_MSG; - } - - return ERR_NO_ERROR; -} - -static int -read_broker_changer_output (char *stdout_file, char *stderr_file, - char *_dbmt_error) -{ - FILE *fp; - char buf[1024]; - int len = 0; - - strcpy (buf, ""); - - if (access (stdout_file, F_OK) == 0) - { - fp = fopen (stdout_file, "r"); - if (fp != NULL) - { - while (fgets (buf, sizeof (buf), fp) != NULL) - { - if (strncmp (buf, "OK", 2) == 0) - { - fclose (fp); - return ERR_NO_ERROR; - } - ut_trim (buf); - len += (int) strlen (buf); - if (len < DBMT_ERROR_MSG_SIZE - len - 1) - { - strcpy (_dbmt_error, buf); - _dbmt_error += len; - } - else - { - strcpy_limit (_dbmt_error, buf, DBMT_ERROR_MSG_SIZE - len); - strcpy_limit (_dbmt_error + DBMT_ERROR_MSG_SIZE - len - 4, - "...", 4); - break; - } - } - fclose (fp); - } - } - - if (access (stderr_file, F_OK) == 0) - { - fp = fopen (stderr_file, "r"); - if (fp != NULL) - { - while (fgets (buf, sizeof (buf), fp) != NULL) - { - ut_trim (buf); - len += (int) strlen (buf); - if (len < DBMT_ERROR_MSG_SIZE - len - 1) - { - strcpy (_dbmt_error, buf); - _dbmt_error += len; - } - else - { - strcpy_limit (_dbmt_error, buf, DBMT_ERROR_MSG_SIZE - len); - strcpy_limit (_dbmt_error + DBMT_ERROR_MSG_SIZE - len - 4, - "...", 4); - break; - } - } - - fclose (fp); - } - } - - return ERR_SYSTEM_CALL; -} - -int -ts_broker_changer (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char stdout_log_file[512]; - char stderr_log_file[512]; - - char cmd_name[ARNIADB_CMD_NAME_LEN]; - const char *argv[6]; - - char *bname = NULL; - char *casnum = NULL; - char *confname = NULL; - char *confvalue = NULL; - - int argc = 0; - int pid; - int ret_val; - - if ((bname = nv_get_val (req, "bname")) == NULL) - { - sprintf (_dbmt_error, "bname"); - return ERR_PARAM_MISSING; - } - - // casnum is optional. - casnum = nv_get_val (req, "casnum"); - - if ((confname = nv_get_val (req, "confname")) == NULL) - { - sprintf (_dbmt_error, "confname"); - return ERR_PARAM_MISSING; - } - - if ((confvalue = nv_get_val (req, "confvalue")) == NULL) - { - sprintf (_dbmt_error, "confvalue"); - return ERR_PARAM_MISSING; - } - - sprintf (stdout_log_file, "%s/cmbrokerchanger.%d.out", sco.dbmt_tmp_dir, - (int) getpid ()); - sprintf (stderr_log_file, "%s/cmbrokerchanger.%d.err", sco.dbmt_tmp_dir, - (int) getpid ()); - - cmd_name[0] = '\0'; -#if !defined (DO_NOT_USE_ARNIADBENV) - sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, - UTIL_BROKER_CHANGER); -#else - sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_BROKER_CHANGER); -#endif - - argv[argc++] = cmd_name; - argv[argc++] = bname; - - // casnum is optional. - if (casnum != NULL) - { - argv[argc++] = casnum; - } - argv[argc++] = confname; - argv[argc++] = confvalue; - argv[argc] = NULL; - - // run "broker_changer" - pid = run_child (argv, 1, NULL, stdout_log_file, stderr_log_file, NULL); - - if (pid < 0) - { - if (_dbmt_error) - { - sprintf (_dbmt_error, "%s : system error, fork failed!", cmd_name); - } - unlink (stdout_log_file); - unlink (stderr_log_file); - return ERR_SYSTEM_CALL; - } - - ret_val = - read_broker_changer_output (stdout_log_file, stderr_log_file, - _dbmt_error); - - unlink (stdout_log_file); - unlink (stderr_log_file); - - return ret_val; - -} - -static int -read_ha_cmd_output (char *stdout_file, char *stderr_file, char *_dbmt_error) -{ - FILE *fp; - char buf[1024]; - int len = 0; - int len_tmp = 0; - int ret_val = ERR_NO_ERROR; - - if (access (stderr_file, F_OK) == 0) - { - fp = fopen (stderr_file, "r"); - if (fp != NULL) - { - while (fgets (buf, sizeof (buf), fp) != NULL) - { - ut_trim (buf); - len_tmp = (int) strlen (buf); - - if (len_tmp < DBMT_ERROR_MSG_SIZE - len - 1) - { - strcpy (_dbmt_error, buf); - _dbmt_error += len_tmp; - len += len_tmp; - } - else - { - strcpy_limit (_dbmt_error, buf, DBMT_ERROR_MSG_SIZE - len); - strcpy_limit (_dbmt_error + DBMT_ERROR_MSG_SIZE - len - 4, - "...", 4); - } - - ret_val = ERR_SYSTEM_CALL; - } - } - fclose (fp); - } - - if (access (stdout_file, F_OK) == 0 && ret_val == ERR_NO_ERROR) - { - fp = fopen (stdout_file, "r"); - if (fp != NULL) - { - while (fgets (buf, sizeof (buf), fp) != NULL) - { - ut_trim (buf); - len_tmp = (int) strlen (buf); - - if (len_tmp < DBMT_ERROR_MSG_SIZE - len - 1) - { - strcpy (_dbmt_error, buf); - _dbmt_error += len_tmp; - len += len_tmp; - } - else - { - strcpy_limit (_dbmt_error, buf, DBMT_ERROR_MSG_SIZE - len); - strcpy_limit (_dbmt_error + DBMT_ERROR_MSG_SIZE - len - 4, - "...", 4); - } - } - } - fclose (fp); - } - - return ret_val; -} - -static int -handle_ha_status_output (nvplist *res, char *_dbmt_error) -{ - char *iter1 = NULL; - char *iter2 = NULL; - char *applydb_pos = NULL; - char *copydb_pos = NULL; - char *db_names[1000]; - char value[1024]; - int len_tmp; - int num_dbs = 0; - int i; - - // "current_node" - iter1 = strstr (_dbmt_error, "current"); - if (iter1 == NULL) - { - return ERR_WITH_MSG; - } - - iter2 = strstr (iter1, "state"); - if (iter2 == NULL) - { - return ERR_WITH_MSG; - } - - len_tmp = (int) (iter2 - iter1 - 10); - - strncpy (value, iter1 + 8, len_tmp); - value[len_tmp] = '\0'; - nv_add_nvp (res, "current_node", value); - - // "current_node_state" - iter1 = strstr (iter2, ")"); - if (iter1 == NULL) - { - return ERR_WITH_MSG; - } - - len_tmp = (int) (iter1 - iter2 - 6); - strncpy (value, iter2 + 6, len_tmp); - value[len_tmp] = '\0'; - nv_add_nvp (res, "current_node_state", value); - - // "nodeA" - iter1 = strstr (iter1, "Node"); - if (iter1 == NULL) - { - return ERR_WITH_MSG; - } - - iter2 = strstr (iter1, "("); - if (iter2 == NULL) - { - return ERR_WITH_MSG; - } - - len_tmp = (int) (iter2 - iter1 - 6); - strncpy (value, iter1 + 5, len_tmp); - value[len_tmp] = '\0'; - nv_add_nvp (res, "nodeA", value); - - // "nodeA_state" - iter1 = strstr (iter2, "state"); - if (iter1 == NULL) - { - return ERR_WITH_MSG; - } - - iter2 = strstr (iter1, ")"); - if (iter2 == NULL) - { - return ERR_WITH_MSG; - } - - len_tmp = (int) (iter2 - iter1 - 6); - strncpy (value, iter1 + 6, len_tmp); - value[len_tmp] = '\0'; - nv_add_nvp (res, "nodeA_state", value); - - // "nodeB" - iter1 = strstr (iter2, "Node"); - if (iter1 == NULL) - { - return ERR_WITH_MSG; - } - - iter2 = strstr (iter1, "("); - if (iter2 == NULL) - { - return ERR_WITH_MSG; - } - - len_tmp = (int) (iter2 - iter1 - 6); - strncpy (value, iter1 + 5, len_tmp); - value[len_tmp] = '\0'; - nv_add_nvp (res, "nodeB", value); - - // "nodeB_state" - iter1 = strstr (iter2, "state"); - if (iter1 == NULL) - { - return ERR_WITH_MSG; - } - - iter2 = strstr (iter1, ")"); - if (iter2 == NULL) - { - return ERR_WITH_MSG; - } - - len_tmp = (int) (iter2 - iter1 - 6); - strncpy (value, iter1 + 6, len_tmp); - value[len_tmp] = '\0'; - nv_add_nvp (res, "nodeB_state", value); - - // count dbs - - iter1 = strstr (iter2, "Applylogdb"); - if (iter1 == NULL) - { - return ERR_WITH_MSG; - } - - while (iter1 != NULL) - { - char *iter3 = NULL; - - iter3 = strstr (iter1, "@"); - if (iter3 == NULL) - { - return ERR_WITH_MSG; - } - - strncpy (value, iter1 + 11, iter3 - iter1 - 11); - value[iter3 - iter1 - 11] = '\0'; - - db_names[num_dbs] = (char *) malloc (iter3 - iter1 - 10); - strcpy (db_names[num_dbs], value); - num_dbs++; - - iter1 = strstr (iter3, "Applylogdb"); - } - - applydb_pos = strstr (iter2, "Applylogdb"); - if (applydb_pos == NULL) - { - return ERR_WITH_MSG; - } - - copydb_pos = strstr (iter2, "Copylogdb"); - if (copydb_pos == NULL) - { - return ERR_WITH_MSG; - } - - i = 0; - while (i < num_dbs) - { - // for each db, create an array to store "applylogdb" and "copylogdb" - nv_add_nvp (res, "open", "ha_info"); - - nv_add_nvp (res, "dbname", db_names[i]); - - if (applydb_pos != NULL) - { - // "applylogdb" - iter1 = applydb_pos; - iter2 = strstr (iter1, "("); - if (iter2 == NULL) - { - return ERR_WITH_MSG; - } - - len_tmp = (int) (iter2 - iter1 - 12); - strncpy (value, iter1 + 11, len_tmp); - value[len_tmp] = '\0'; - nv_add_nvp (res, "applylogdb", value); - - // "applylogdb_pid" - iter1 = strstr (iter2, "pid"); - if (iter1 == NULL) - { - return ERR_WITH_MSG; - } - - iter2 = strstr (iter1, "state"); - if (iter2 == NULL) - { - return ERR_WITH_MSG; - } - - len_tmp = (int) (iter2 - iter1 - 6); - strncpy (value, iter1 + 4, len_tmp); - value[len_tmp] = '\0'; - nv_add_nvp (res, "applylogdb_pid", value); - - // "applylogdb_state" - iter1 = strstr (iter2, ")"); - if (iter1 == NULL) - { - return ERR_WITH_MSG; - } - - len_tmp = (int) (iter1 - iter2 - 6); - strncpy (value, iter2 + 6, len_tmp); - value[len_tmp] = '\0'; - nv_add_nvp (res, "applylogdb_state", value); - - // for next loop - applydb_pos = strstr (iter1, "Applylogdb"); - } - - if (copydb_pos != NULL) - { - // "copylogdb" - iter1 = copydb_pos; - iter2 = strstr (iter1, "("); - if (iter2 == NULL) - { - return ERR_WITH_MSG; - } - - len_tmp = (int) (iter2 - iter1 - 11); - strncpy (value, iter1 + 10, len_tmp); - value[len_tmp] = '\0'; - nv_add_nvp (res, "copylogdb", value); - - // "copylogdb_pid" - iter1 = strstr (iter2, "pid"); - if (iter1 == NULL) - { - return ERR_WITH_MSG; - } - - iter2 = strstr (iter1, "state"); - if (iter2 == NULL) - { - return ERR_WITH_MSG; - } - - len_tmp = (int) (iter2 - iter1 - 6); - strncpy (value, iter1 + 4, len_tmp); - value[len_tmp] = '\0'; - nv_add_nvp (res, "copylogdb_pid", value); - - // "copylogdb_state" - iter1 = strstr (iter2, ")"); - if (iter1 == NULL) - { - return ERR_WITH_MSG; - } - - len_tmp = (int) (iter1 - iter2 - 6); - strncpy (value, iter2 + 6, len_tmp); - value[len_tmp] = '\0'; - nv_add_nvp (res, "copylogdb_state", value); - - // for next loop - copydb_pos = strstr (iter1, "Copylogdb"); - } - - // finish filling array - nv_add_nvp (res, "close", "ha_info"); - - // release the string after storing it to nvplist - free (db_names[i]); - - i++; - } - - return ERR_NO_ERROR; -} - -int -ts_ha_start (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char stdout_log_file[512]; - char stderr_log_file[512]; - char cmd_name[ARNIADB_CMD_NAME_LEN]; - const char *argv[6]; - char *dbname = NULL; - - int argc = 0; - int pid; - int ret_val; - - // dbname is optional. - dbname = nv_get_val (req, "dbname"); - - sprintf (stdout_log_file, "%s/cmhastart.%d.out", sco.dbmt_tmp_dir, - (int) getpid ()); - sprintf (stderr_log_file, "%s/cmhastart.%d.err", sco.dbmt_tmp_dir, - (int) getpid ()); - - cmd_name[0] = '\0'; -#if !defined (DO_NOT_USE_ARNIADBENV) - sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ARNIADB); -#else - sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_ARNIADB); -#endif - - argv[argc++] = cmd_name; - argv[argc++] = PRINT_CMD_HEARTBEAT; - argv[argc++] = PRINT_CMD_START; - - // casnum is optional. - if (dbname != NULL) - { - argv[argc++] = dbname; - } - argv[argc] = NULL; - - // run "arniadb heartbeat start [dbname]" - pid = run_child (argv, 1, NULL, stdout_log_file, stderr_log_file, NULL); - - if (pid < 0) - { - if (_dbmt_error) - { - sprintf (_dbmt_error, "%s : system error, fork failed!", cmd_name); - } - unlink (stdout_log_file); - unlink (stderr_log_file); - return ERR_SYSTEM_CALL; - } - - ret_val = - read_ha_cmd_output (stdout_log_file, stderr_log_file, _dbmt_error); - - unlink (stdout_log_file); - unlink (stderr_log_file); - - return ret_val; -} - -int -ts_ha_stop (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char stdout_log_file[512]; - char stderr_log_file[512]; - char cmd_name[ARNIADB_CMD_NAME_LEN]; - const char *argv[6]; - char *dbname = NULL; - - int argc = 0; - int pid; - int ret_val; - - - // dbname is optional. - dbname = nv_get_val (req, "dbname"); - - sprintf (stdout_log_file, "%s/cmhastop.%d.out", sco.dbmt_tmp_dir, - (int) getpid ()); - sprintf (stderr_log_file, "%s/cmhastop.%d.err", sco.dbmt_tmp_dir, - (int) getpid ()); - - cmd_name[0] = '\0'; -#if !defined (DO_NOT_USE_ARNIADBENV) - sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ARNIADB); -#else - sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_ARNIADB); -#endif - - argv[argc++] = cmd_name; - argv[argc++] = PRINT_CMD_HEARTBEAT; - argv[argc++] = PRINT_CMD_STOP; - - // dbname is optional. - if (dbname != NULL) - { - argv[argc++] = dbname; - } - argv[argc] = NULL; - - // run "arniadb heartbeat stop [dbname]" - pid = run_child (argv, 1, NULL, stdout_log_file, stderr_log_file, NULL); - - if (pid < 0) - { - if (_dbmt_error) - { - sprintf (_dbmt_error, "%s : system error, fork failed!", cmd_name); - } - unlink (stdout_log_file); - unlink (stderr_log_file); - return ERR_SYSTEM_CALL; - } - - ret_val = - read_ha_cmd_output (stdout_log_file, stderr_log_file, _dbmt_error); - - unlink (stdout_log_file); - unlink (stderr_log_file); - - return ret_val; -} - -int -ts_ha_status (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char stdout_log_file[512]; - char stderr_log_file[512]; - char cmd_name[ARNIADB_CMD_NAME_LEN]; - const char *argv[6]; - int argc = 0; - int pid; - int ret_val; - - - sprintf (stdout_log_file, "%s/cmhastatus.%d.out", sco.dbmt_tmp_dir, - (int) getpid ()); - sprintf (stderr_log_file, "%s/cmhastatus.%d.err", sco.dbmt_tmp_dir, - (int) getpid ()); - - cmd_name[0] = '\0'; -#if !defined (DO_NOT_USE_ARNIADBENV) - sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ARNIADB); -#else - sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_ARNIADB); -#endif - - argv[argc++] = cmd_name; - argv[argc++] = PRINT_CMD_HEARTBEAT; - argv[argc++] = PRINT_CMD_STATUS; - argv[argc] = NULL; - - // run "arniadb heartbeat status" - pid = run_child (argv, 1, NULL, stdout_log_file, stderr_log_file, NULL); - - if (pid < 0) - { - if (_dbmt_error) - { - sprintf (_dbmt_error, "%s : system error, fork failed!", cmd_name); - } - unlink (stdout_log_file); - unlink (stderr_log_file); - return ERR_SYSTEM_CALL; - } - - if ((ret_val = - read_ha_cmd_output (stdout_log_file, stderr_log_file, - _dbmt_error)) != ERR_NO_ERROR) - { - - unlink (stdout_log_file); - unlink (stderr_log_file); - - return ret_val; - } - - unlink (stdout_log_file); - unlink (stderr_log_file); - - // handle the response - if ((ret_val = handle_ha_status_output (res, _dbmt_error)) != ERR_NO_ERROR) - { - return ret_val; - } - - return ret_val; -} - -int -ts_ha_reload (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char stdout_log_file[512]; - char stderr_log_file[512]; - - char cmd_name[ARNIADB_CMD_NAME_LEN]; - const char *argv[6]; - - int argc = 0; - int pid; - int ret_val; - - - sprintf (stdout_log_file, "%s/cmhareload.%d.out", sco.dbmt_tmp_dir, - (int) getpid ()); - sprintf (stderr_log_file, "%s/cmhareload.%d.err", sco.dbmt_tmp_dir, - (int) getpid ()); - - cmd_name[0] = '\0'; -#if !defined (DO_NOT_USE_ARNIADBENV) - sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ARNIADB); -#else - sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_ARNIADB); -#endif - - argv[argc++] = cmd_name; - argv[argc++] = PRINT_CMD_HEARTBEAT; - argv[argc++] = PRINT_CMD_RELOAD; - argv[argc] = NULL; - - // run "arniadb heartbeat reload" - pid = run_child (argv, 1, NULL, stdout_log_file, stderr_log_file, NULL); - - if (pid < 0) - { - if (_dbmt_error) - { - sprintf (_dbmt_error, "%s : system error, fork failed!", cmd_name); - } - unlink (stdout_log_file); - unlink (stderr_log_file); - return ERR_SYSTEM_CALL; - } - - ret_val = - read_ha_cmd_output (stdout_log_file, stderr_log_file, _dbmt_error); - - unlink (stdout_log_file); - unlink (stderr_log_file); - - return ret_val; - -} - -int -ts_ha_copylogdb (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char stdout_log_file[512]; - char stderr_log_file[512]; - - char cmd_name[ARNIADB_CMD_NAME_LEN]; - const char *argv[7]; - - char *dbname = NULL; - char *on_off = NULL; - char *peer_node = NULL; - - int argc = 0; - int pid = -1; - int ret_val = 0; - - - if ((dbname = nv_get_val (req, "dbname")) == NULL) - { - sprintf (_dbmt_error, "dbname"); - return ERR_PARAM_MISSING; - } - - // on_off should be "start" or "stop". - if ((on_off = nv_get_val (req, "on_off")) == NULL) - { - sprintf (_dbmt_error, "on_off"); - return ERR_PARAM_MISSING; - } - else if (strcmp (on_off, "start") && strcmp (on_off, "stop")) - { - return ERR_REQUEST_FORMAT; - } - - if ((peer_node = nv_get_val (req, "peer_node")) == NULL) - { - sprintf (_dbmt_error, "peer_node"); - return ERR_PARAM_MISSING; - } - - sprintf (stdout_log_file, "%s/cmhacopylogdb.%d.out", sco.dbmt_tmp_dir, - (int) getpid ()); - sprintf (stderr_log_file, "%s/cmhacopylogdb.%d.err", sco.dbmt_tmp_dir, - (int) getpid ()); - - cmd_name[0] = '\0'; -#if !defined (DO_NOT_USE_ARNIADBENV) - sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ARNIADB); -#else - sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_ARNIADB); -#endif - - argv[argc++] = cmd_name; - argv[argc++] = PRINT_CMD_HEARTBEAT; - argv[argc++] = UTIL_OPTION_COPYLOGDB; - argv[argc++] = on_off; - argv[argc++] = dbname; - argv[argc++] = peer_node; - argv[argc] = NULL; - - // run "arniadb heartbeat copylogdb dbname peer_node" - pid = run_child (argv, 1, NULL, stdout_log_file, stderr_log_file, NULL); - - if (pid < 0) - { - if (_dbmt_error) - { - sprintf (_dbmt_error, "%s : system error, fork failed!", cmd_name); - } - unlink (stdout_log_file); - unlink (stderr_log_file); - return ERR_SYSTEM_CALL; - } - - //ret_val = read_broker_changer_output(stdout_log_file, stderr_log_file, _dbmt_error); - - unlink (stdout_log_file); - unlink (stderr_log_file); - - return ret_val; - -} - -int -ts_ha_applylogdb (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char stdout_log_file[512]; - char stderr_log_file[512]; - - char cmd_name[ARNIADB_CMD_NAME_LEN]; - const char *argv[7]; - - char *dbname = NULL; - char *on_off = NULL; - char *peer_node = NULL; - - int argc = 0; - int pid = -1; - int ret_val = 0; - - - if ((dbname = nv_get_val (req, "dbname")) == NULL) - { - sprintf (_dbmt_error, "dbname"); - return ERR_PARAM_MISSING; - } - - // on_off should be "start" or "stop". - if ((on_off = nv_get_val (req, "on_off")) == NULL) - { - sprintf (_dbmt_error, "on_off"); - return ERR_PARAM_MISSING; - } - else if (strcmp (on_off, "start") && strcmp (on_off, "stop")) - { - return ERR_REQUEST_FORMAT; - } - - if ((peer_node = nv_get_val (req, "peer_node")) == NULL) - { - sprintf (_dbmt_error, "peer_node"); - return ERR_PARAM_MISSING; - } - - sprintf (stdout_log_file, "%s/cmhacopylogdb.%d.out", sco.dbmt_tmp_dir, - (int) getpid ()); - sprintf (stderr_log_file, "%s/cmhacopylogdb.%d.err", sco.dbmt_tmp_dir, - (int) getpid ()); - - cmd_name[0] = '\0'; -#if !defined (DO_NOT_USE_ARNIADBENV) - sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ARNIADB); -#else - sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_ARNIADB); -#endif - - argv[argc++] = cmd_name; - argv[argc++] = PRINT_CMD_HEARTBEAT; - argv[argc++] = UTIL_OPTION_APPLYLOGDB; - argv[argc++] = on_off; - argv[argc++] = dbname; - argv[argc++] = peer_node; - argv[argc] = NULL; - - // run "arniadb heartbeat applylogdb dbname peer_node" - pid = run_child (argv, 1, NULL, stdout_log_file, stderr_log_file, NULL); - - if (pid < 0) - { - if (_dbmt_error) - { - sprintf (_dbmt_error, "%s : system error, fork failed!", cmd_name); - } - unlink (stdout_log_file); - unlink (stderr_log_file); - return ERR_SYSTEM_CALL; - } - - //ret_val = read_broker_changer_output(stdout_log_file, stderr_log_file, _dbmt_error); - - unlink (stdout_log_file); - unlink (stderr_log_file); - - return ret_val; - -} - -/*static int _get_update_url(char *url) -{ - char cm_conf_file[PATH_MAX]; - char line_buf[MAX_JOB_CONFIG_FILE_LINE_LENGTH]; - - char *iter = NULL; - - FILE *fin; - -#if !defined (DO_NOT_USE_ARNIADBENV) - snprintf (cm_conf_file, PATH_MAX - 1, "%s/conf/%s", sco.szArniadb, ARNIADB_DBMT_CONF); -#else - snprintf (cm_conf_file, PATH_MAX - 1, "%s/%s", ARNIADB_CONFDIR, ARNIADB_DBMT_CONF); -#endif - - fin = fopen(cm_conf_file, "r"); - if (fin == NULL) - { - return ERR_FILE_OPEN_FAIL; - } - - while (fgets(&line_buf, MAX_JOB_CONFIG_FILE_LINE_LENGTH, fin) != NULL) - { - iter = strstr(line_buf, "patch_url"); - if( iter == NULL) - { - continue; - } - - iter = strstr(line_buf, "="); - strcpy (url, iter+2); - - break; - } - - fclose(fin); - - return ERR_NO_ERROR; -}*/ - -static char * -_get_format_time () -{ - char *buff = (char *) malloc (sizeof (char) * LINE_MAX); -#ifdef WINDOWS - -#else - time_t lt; - - time (<); - struct tm *t = localtime (<); - - if (t) - { - strftime (buff, LINE_MAX, "%Y%m%d %H:%M:%S", t); - } - -#endif - return buff; -} - -static void -_write_auto_update_log (char *line_buf, int is_success) -{ - char *log_time; - - char log_path[PATH_MAX]; - - FILE *fin = NULL; - - sprintf (log_path, "%s/log/manager/cms.update.log", sco.szArniadb); - - fin = fopen (log_path, "a"); - - log_time = _get_format_time (); - if (is_success) - { - fprintf (fin, "[%s] %s, update to %s.\n", log_time, line_buf, - sco.szCMSVersion); - } - else - { - fprintf (fin, "[%s] CMS update error: %s\n", log_time, line_buf); - } - - free (log_time); - fclose (fin); - -} - -int -ts_is_update_success (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char err_log[PATH_MAX]; - char output_log[PATH_MAX]; - char line_buf[LINE_MAX]; - - FILE *fin = NULL; - - sprintf (err_log, "%s/cms_auto_update.err", sco.dbmt_tmp_dir); - sprintf (output_log, "%s/cms_auto_update.log", sco.dbmt_tmp_dir); - - fin = fopen (output_log, "r"); - if (fin == NULL) - { - sprintf (_dbmt_error, "%s", output_log); - return ERR_FILE_OPEN_FAIL; - } - - while (fgets (line_buf, LINE_MAX, fin) != NULL) - { - if (strstr (line_buf, "ARNIADB Manager Server is updated.") != NULL) - { - nv_add_nvp (res, "autoupdate_success", "success"); - - _write_auto_update_log (line_buf, TRUE); - fclose (fin); - return ERR_NO_ERROR; - } - - } - fclose (fin); - - nv_add_nvp (res, "autoupdate_result", "failure"); - - fin = fopen (err_log, "r"); - if (fin == NULL) - { - sprintf (_dbmt_error, "%s", err_log); - return ERR_FILE_OPEN_FAIL; - } - - while (fgets (line_buf, LINE_MAX, fin) != NULL) - { - _write_auto_update_log (line_buf, FALSE); - } - fclose (fin); - - - return ERR_NO_ERROR; -} - -int -ts_auto_update (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char *patch_name = NULL; - - char path[PATH_MAX]; - char shell_name[PATH_MAX]; - char err_log[PATH_MAX]; - char output_log[PATH_MAX]; -#ifndef WINDOWS - char cmd[PATH_MAX]; -#endif - char *argv[2]; - - int ret_val = 0; - -#ifndef WINDOWS - pid_t pid = 0; -#endif - - patch_name = nv_get_val (req, "patch_name"); - if (patch_name == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "patch_name"); - return ERR_PARAM_MISSING; - } -#ifdef WINDOWS - sprintf (path, "%s\\", sco.dbmt_tmp_dir); -#else - sprintf (path, "%s/", sco.dbmt_tmp_dir); -#endif - - if ((ret_val = - generate_update_script (patch_name, sco.szAutoUpdateURL, path, - _dbmt_error)) != ERR_NO_ERROR) - { - return ret_val; - } - - sprintf (shell_name, "%s" SHELL_NAME, path); - - argv[0] = shell_name; - argv[1] = NULL; - - sprintf (err_log, "%scms.autoupdate.err", path); - sprintf (output_log, "%scms.autoupdate.log", path); - -#ifdef WINDOWS - ret_val = run_child (argv, 0, NULL, output_log, err_log, NULL); - -#else - sprintf (cmd, "%s >%s 2>%s", shell_name, output_log, err_log); - - // As "system" fucntion will wait for the command return in parent process, fork a new procee to execute it in order to avoid blocking. - if ((pid = fork ()) > 0) - { - return ERR_NO_ERROR; - } - else if (pid == 0) - { - system (cmd); - exit (0); - } - else - { - sprintf (_dbmt_error, "fork()"); - return ERR_SYSTEM_CALL; - } - -#endif - - return ERR_NO_ERROR; -} - -int -ts_list_dir (nvplist *req, nvplist *res, char *_dbmt_error) -{ - char *nvp_path = NULL; - char path[PATH_MAX]; - char full_path[PATH_MAX]; - - path[0] = 0; - full_path[0] = 0; - - if (NULL == (nvp_path = nv_get_val (req, "path"))) - { - strcpy (_dbmt_error, "missing path parameter"); - return ERR_PARAM_MISSING; - } - - if (0 == strncmp (nvp_path, "../", strlen ("../"))) - { - strcpy (_dbmt_error, "path parameter includes invalid dirctories!"); - return ERR_WITH_MSG; - } - if (NULL != strstr (nvp_path, "../")) - { - strcpy (_dbmt_error, "path parameter includes invalid dirctories!"); - return ERR_WITH_MSG; - } - if ('/' == nvp_path[strlen (nvp_path) - 3] - && '.' == nvp_path[strlen (nvp_path) - 2] - && '.' == nvp_path[strlen (nvp_path) - 1]) - { - strcpy (_dbmt_error, "path parameter includes invalid dirctories!"); - return ERR_WITH_MSG; - } - - snprintf (path, sizeof (path), "%s", nvp_path); - if (path[strlen (path) - 1] != '/') - { - snprintf (path, sizeof (path), "%s/", nvp_path); - } - nv_add_nvp (res, "path", path); - -#if !defined (DO_NOT_USE_ARNIADBENV) - snprintf (full_path, PATH_MAX, "%s/%s/", sco.szArniadb, path); -#else - sprintf (full_path, "%s/%s/", ARNIADB, path); -#endif - -#if defined(WINDOWS) - { - HANDLE handle; - WIN32_FIND_DATA ffd; - char find_path[PATH_MAX]; - snprintf (find_path, PATH_MAX - 1, "%s/*", full_path); - - nv_add_nvp (res, "open", "dir"); - handle = FindFirstFile (find_path, &ffd); - if (handle == INVALID_HANDLE_VALUE) - { - sprintf (_dbmt_error, "open directory %s failed!", path); - return ERR_WITH_MSG; - } - while (FindNextFile (handle, &ffd)) - { - if (ffd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN - || ffd.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) - { - continue; - } - else if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) - { - if (0 != strcmp (ffd.cFileName, ".") - && 0 != strcmp (ffd.cFileName, "..")) - { - nv_add_nvp (res, "group", ffd.cFileName); - } - } - } - FindClose (handle); - nv_add_nvp (res, "close", "dir"); - - nv_add_nvp (res, "open", "file"); - handle = FindFirstFile (find_path, &ffd); - if (handle == INVALID_HANDLE_VALUE) - { - sprintf (_dbmt_error, "open directory %s failed!", path); - return ERR_WITH_MSG; - } - while (FindNextFile (handle, &ffd)) - { - if (ffd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN - || ffd.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) - { - continue; - } - else if (! (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) - { - if (0 == strcmp (ffd.cFileName, "cm.pass") - || 0 == strcmp (ffd.cFileName, "cmdb.pass")) - { - continue; - } - nv_add_nvp (res, "group", ffd.cFileName); - } - } - FindClose (handle); - nv_add_nvp (res, "close", "file"); - } - -#else - { - char name_temp[1024]; - DIR *dirptr = NULL; - struct dirent *entry; - - nv_add_nvp (res, "open", "dir"); - if ((dirptr = opendir (full_path)) == NULL) - { - sprintf (_dbmt_error, "open directory %s failed!", path); - return ERR_WITH_MSG; - } - else - { - while ((entry = readdir (dirptr)) != NULL) - { - struct stat stat_file; - if (entry->d_name[0] == '.') - { - continue; - } - strcpy (name_temp, full_path); - strcat (name_temp, entry->d_name); - - stat (name_temp, &stat_file); - if (S_ISDIR (stat_file.st_mode)) - { - nv_add_nvp (res, "group", entry->d_name); - } - } - } - closedir (dirptr); - nv_add_nvp (res, "close", "dir"); - - nv_add_nvp (res, "open", "file"); - if ((dirptr = opendir (full_path)) == NULL) - { - sprintf (_dbmt_error, "open directory %s failed!", path); - return ERR_WITH_MSG; - } - else - { - while ((entry = readdir (dirptr)) != NULL) - { - struct stat stat_file; - if (entry->d_name[0] == '.') - { - continue; - } - strcpy (name_temp, full_path); - strcat (name_temp, entry->d_name); - - stat (name_temp, &stat_file); - if (! (S_ISDIR (stat_file.st_mode))) - { - if (0 == strcmp (entry->d_name, "cm.pass") - || 0 == strcmp (entry->d_name, "cmdb.pass")) - { - continue; - } - nv_add_nvp (res, "group", entry->d_name); - } - } - } - closedir (dirptr); - nv_add_nvp (res, "close", "file"); - } -#endif - - return ERR_NO_ERROR; -} - -int -ts_monitor_process (nvplist *req, nvplist *res, char *_dbmt_error) -{ - // processes need monitoring - const char process_name[][PATH_MAX] = {"arn_master", 0}; - char exist[15]; - int i = 0; - -#ifdef WINDOWS - - PROCESSENTRY32 pe32; - HANDLE process_snap = 0; - pe32.dwSize = sizeof (pe32); - - process_snap = CreateToolhelp32Snapshot (TH32CS_SNAPPROCESS, 0); - if (process_snap == INVALID_HANDLE_VALUE) - { - strcpy (_dbmt_error, "create process snapshot failed!"); - return ERR_SYSTEM_CALL; - } - - i = 0; - while (process_name[i][0] != 0) - { - strcpy (exist, "don't exist"); - if (!Process32First (process_snap, &pe32)) - { - strcpy (_dbmt_error, "get process info failed!"); - return ERR_SYSTEM_CALL; - } - - do - { - if (!strncmp - (process_name[i], pe32.szExeFile, strlen (process_name[i]))) - { - strcpy (exist, "exist"); - break; - } - - } - while (Process32Next (process_snap, &pe32)); - - nv_add_nvp (res, process_name[i], exist); - i++; - } - -#else - char pid_file[PATH_MAX]; - char cmd_name[PATH_MAX]; - - FILE *fin; - int ch; - - sprintf (pid_file, "%s/monitor_process.%u.tmp", sco.dbmt_tmp_dir, - getpid ()); - fin = fopen (pid_file, "w+"); - - i = 0; - while (process_name[i][0] != 0) - { - sprintf (cmd_name, "pgrep -u $(whoami) %s > %s", process_name[i], - pid_file); - system (cmd_name); - - if ((ch = fgetc (fin)) == EOF) - { - strcpy (exist, "don't exist"); - } - else if (ch > '1' && ch < '9') - { - strcpy (exist, "exist"); - } - - nv_add_nvp (res, process_name[i], exist); - i++; - } - - fclose (fin); - unlink (pid_file); -#endif - - return ERR_NO_ERROR; -} - -static int -_make_cert (nvplist *req, X509 **x509p, EVP_PKEY **pkeyp, int bits, - char *_dbmt_error) -{ - char user_info[PATH_MAX]; - char nid_basic_constraints[PATH_MAX]; - char nid_key_usage[PATH_MAX]; - char nid_subject_key_identifier[PATH_MAX]; - char nid_netscape_cert_type[PATH_MAX]; - char nid_netscape_comment[PATH_MAX]; - - X509 *x509_local = NULL; - EVP_PKEY *pub_key = NULL; - RSA *rsa = NULL; - X509_NAME *name = NULL; - BIGNUM *bignum = NULL; - - char *country_name = NULL; - char *state_name = NULL; - char *locality_name = NULL; - char *organization_name = NULL; - char *organizational_unit_name = NULL; - char *common_name = NULL; - char *email_addr = NULL; - char *days = NULL; - - int day = 0; - - user_info[0] = '\0'; - nid_basic_constraints[0] = '\0'; - nid_key_usage[0] = '\0'; - nid_subject_key_identifier[0] = '\0'; - nid_netscape_cert_type[0] = '\0'; - nid_netscape_comment[0] = '\0'; - - country_name = nv_get_val (req, "cname"); - state_name = nv_get_val (req, "stname"); - locality_name = nv_get_val (req, "loname"); - organization_name = nv_get_val (req, "orgname"); - organizational_unit_name = nv_get_val (req, "orgutname"); - common_name = nv_get_val (req, "comname"); - email_addr = nv_get_val (req, "email"); - days = nv_get_val (req, "days"); - - if (days == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "days"); - return ERR_PARAM_MISSING; - } - - if ((pkeyp == NULL) || (*pkeyp == NULL)) - { - if ((pub_key = EVP_PKEY_new ()) == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, - "Cannot make a new private key."); - return ERR_WITH_MSG; - } - } - else - { - pub_key = *pkeyp; - } - - if ((x509p == NULL) || (*x509p == NULL)) - { - if ((x509_local = X509_new ()) == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, - "Cannot make a new certification file."); - return ERR_WITH_MSG; - } - } - else - { - x509_local = *x509p; - } - - /* Generate RSA key using RSA_generate_key_ex to replace RSA_generate_key - * - */ - if ((bignum = BN_new ()) == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, - "Cannot make a new SSL private key file - create bignum failed."); - return ERR_WITH_MSG; - } - if (BN_set_word (bignum, RSA_F4) == 0) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, - "Cannot make a new SSL private key file - set bignum failed."); - return ERR_WITH_MSG; - } - if ((rsa = RSA_new ()) == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, - "Cannot make a new SSL private key file - create RSA failed."); - return ERR_WITH_MSG; - } - if (RSA_generate_key_ex (rsa, bits, bignum, NULL) == 0) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, - "Cannot make a new SSL private key file."); - return ERR_WITH_MSG; - } - if (EVP_PKEY_assign_RSA (pub_key, rsa) == 0) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, - "Failed to generate public key."); - return ERR_WITH_MSG; - } - rsa = NULL; - - X509_set_version (x509_local, 2); - ASN1_INTEGER_set (X509_get_serialNumber (x509_local), 0); - X509_gmtime_adj (X509_get_notBefore (x509_local), 0); - - day = atoi (days); - if (day <= 0) - { - day = 365; - } - X509_gmtime_adj (X509_get_notAfter (x509_local), (long) 60 * 60 * 24 * day); - X509_set_pubkey (x509_local, pub_key); - - name = X509_get_subject_name (x509_local); - - /* This function creates and adds the entry, working out the - * correct string type and performing checks on its length. - * Normally we'd check the return value for errors... - */ - if (country_name != NULL) - { - _add_issuer_info (name, "C", country_name); - } - if (state_name != NULL) - { - _add_issuer_info (name, "ST", state_name); - } - if (locality_name != NULL) - { - _add_issuer_info (name, "L", locality_name); - } - if (organization_name != NULL) - { - _add_issuer_info (name, "O", organization_name); - } - if (organizational_unit_name != NULL) - { - _add_issuer_info (name, "OU", organizational_unit_name); - } - if ((common_name != NULL) && (email_addr != NULL)) - { - snprintf (user_info, PATH_MAX, "%s/%s", common_name, email_addr); - _add_issuer_info (name, "CN", user_info); - } - else if ((common_name != NULL) && (email_addr == NULL)) - { - snprintf (user_info, PATH_MAX, "%s", common_name); - _add_issuer_info (name, "CN", user_info); - } - else if ((common_name == NULL) && (email_addr != NULL)) - { - snprintf (user_info, PATH_MAX, "%s", email_addr); - _add_issuer_info (name, "CN", user_info); - } - - /* Issuer should not be null for all items, - * We have to set at least one issue as default, - * We decide to set organizational_unit_name as the last one. - */ - if ((country_name == NULL) && (state_name == NULL) - && (locality_name == NULL) && (organization_name == NULL) - && (organizational_unit_name == NULL) && (common_name == NULL) - && (email_addr == NULL)) - { - snprintf (user_info, PATH_MAX, "ARNIADB Manger Server Group."); - _add_issuer_info (name, "OU", user_info); - } - /* Its self signed so set the issuer name to be the same as the - * subject. - */ - X509_set_issuer_name (x509_local, name); - - /* Add various extensions: standard extensions */ - snprintf (nid_basic_constraints, PATH_MAX, "critical,CA:TRUE"); - _add_extensions (x509_local, NID_basic_constraints, nid_basic_constraints); - - snprintf (nid_key_usage, PATH_MAX, "critical,keyCertSign,cRLSign"); - _add_extensions (x509_local, NID_key_usage, nid_key_usage); - - snprintf (nid_subject_key_identifier, PATH_MAX, "hash"); - _add_extensions (x509_local, NID_subject_key_identifier, - nid_subject_key_identifier); - - /* Some Netscape specific extensions */ - snprintf (nid_netscape_cert_type, PATH_MAX, "sslCA"); - _add_extensions (x509_local, NID_netscape_cert_type, - nid_netscape_cert_type); - - snprintf (nid_netscape_comment, PATH_MAX, - "ARNIADB Manager server comment extension"); - _add_extensions (x509_local, NID_netscape_comment, nid_netscape_comment); - - if (X509_sign (x509_local, pub_key, EVP_md5 ()) == 0) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, - "Cannot sign with public key."); - return ERR_WITH_MSG; - } - - *x509p = x509_local; - *pkeyp = pub_key; - return ERR_NO_ERROR; -} - -static void -_add_issuer_info (X509_NAME *name, const char *item_name, char *item_value) -{ - X509_NAME_add_entry_by_txt (name, item_name, MBSTRING_ASC, - (const unsigned char *) item_value, -1, -1, 0); -} - -static int -_add_extensions (X509 *cert, int nid, char *value) -{ - X509_EXTENSION *extension; - X509V3_CTX ctx; - /* This sets the 'context' of the extensions. */ - /* No configuration database */ - X509V3_set_ctx_nodb (&ctx); - /* Issuer and subject certs: both the target since it is self signed, - * no request and no CRL - */ - X509V3_set_ctx (&ctx, cert, cert, NULL, NULL, 0); - extension = X509V3_EXT_conf_nid (NULL, &ctx, nid, value); - if (extension == 0) - { - return 1; - } - - X509_add_ext (cert, extension, -1); - X509_EXTENSION_free (extension); - return 0; -} - -static int -_backup_cert (char *_dbmt_error) -{ - char default_backup_cert_path[PATH_MAX]; - char default_cert_path[PATH_MAX]; - - default_backup_cert_path[0] = '\0'; - default_cert_path[0] = '\0'; - - snprintf (default_backup_cert_path, PATH_MAX, "%s.bak", - sco.szSSLCertificate); - if (access (default_backup_cert_path, F_OK) == 0) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, - "Cannot backup SSL certification file: %s.", - sco.szSSLCertificate); - return 1; - } - - snprintf (default_cert_path, PATH_MAX, "%s", sco.szSSLCertificate); - if (access (default_cert_path, F_OK) != 0) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, - "Cannot find SSL certification file: %s.", - sco.szSSLCertificate); - return 1; - } - /*No need to backup custom certification file */ - if (_is_default_cert (_dbmt_error) == 0) - { - return 1; - } - - if (file_copy (default_cert_path, default_backup_cert_path) != 0) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, - "Failed to backup SSL certification file: %s.", - sco.szSSLCertificate); - return 1; - } - return 0; -} - -static int -_recover_cert (char *_dbmt_error) -{ - char default_cert_path[PATH_MAX]; - char default_backup_cert_path[PATH_MAX]; - - default_cert_path[0] = '\0'; - default_backup_cert_path[0] = '\0'; - - /*Check the validation of backup certification file */ - if (_is_exist_default_backup_cert (_dbmt_error) != 1) - { - return 1; - } - - snprintf (default_cert_path, PATH_MAX, "%s", sco.szSSLCertificate); - if (access (default_cert_path, F_OK) == 0) - { - if (uRemoveDir (default_cert_path, REMOVE_DIR_FORCED) != ERR_NO_ERROR) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, - "Cannot delete SSL certification file: %s.", - sco.szSSLCertificate); - return 1; - } - } - - snprintf (default_backup_cert_path, PATH_MAX, "%s.bak", - sco.szSSLCertificate); - if (file_copy (default_backup_cert_path, default_cert_path) != 0) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, - "Failed to recover SSL certification file: %s.", - sco.szSSLCertificate); - return 1; - } - return 0; -} - -int -ts_generate_cert (nvplist *req, nvplist *res, char *_dbmt_error) -{ - BIO *bio_err = NULL; - X509 *x509 = NULL; - EVP_PKEY *pub_key = NULL; - FILE *keyfile = NULL; - FILE *crtfile = NULL; - char keyfilepath[PATH_MAX], crtfilepath[PATH_MAX]; - int ret_val = ERR_NO_ERROR; - - keyfilepath[0] = '\0'; - crtfilepath[0] = '\0'; - - CRYPTO_mem_ctrl (CRYPTO_MEM_CHECK_ON); - - bio_err = BIO_new_fp (stderr, BIO_NOCLOSE); - - /*Backup default certification file. */ - - if (_is_exist_default_backup_cert (_dbmt_error) != 1) - { - if (_backup_cert (_dbmt_error) != 0) - { - ret_val = ERR_WITH_MSG; - goto release_src; - } - } - - ret_val = _make_cert (req, &x509, &pub_key, RSA_KEY_SIZE, _dbmt_error); - if (ret_val != ERR_NO_ERROR) - { - goto release_src; - } - - snprintf (keyfilepath, PATH_MAX, "%s", sco.szSSLKey); - if ((keyfile = fopen (keyfilepath, "w")) == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", sco.szSSLKey); - ret_val = ERR_FILE_OPEN_FAIL; - goto release_src; - } - PEM_write_PrivateKey (keyfile, pub_key, NULL, NULL, 0, NULL, NULL); - fclose (keyfile); - - snprintf (crtfilepath, PATH_MAX, "%s", sco.szSSLCertificate); - if ((crtfile = fopen (crtfilepath, "w")) == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", sco.szSSLCertificate); - ret_val = ERR_FILE_OPEN_FAIL; - goto release_src; - } - if (PEM_write_X509 (crtfile, x509) != 1) - { - _recover_cert (_dbmt_error); - ret_val = ERR_WITH_MSG; - goto release_src; - } - -release_src: - if (crtfile != NULL) - { - fclose (crtfile); - } - if (x509 != NULL) - { - X509_free (x509); - } - if (pub_key != NULL) - { - EVP_PKEY_free (pub_key); - } - -#ifndef OPENSSL_NO_ENGINE - ENGINE_cleanup (); -#endif - CRYPTO_cleanup_all_ex_data (); - if (pub_key != NULL) - { - BIO_free (bio_err); - } - return ret_val; -} - -int -ts_start_statdump (nvplist *req, nvplist *res, char *_dbmt_error) -{ - int ret_val = ERR_NO_ERROR; - char *db_name, *interval_str; - int interval = 0; - char *argv [10]; - char path [512]; - int argc = 0; - char note [20]; - int slot = -1; - db_name = nv_get_val (req, "_DBNAME"); - interval_str = nv_get_val (req, "interval"); - if (!interval_str || !db_name) - { - nv_update_val (res, "note", "no sufficient arguments"); - LOG_ERROR ("start_statdump: dbname or interval was not specified"); - return -1; - } - - if (find_statdumpd_info (db_name) >= 0) - { - nv_update_val (res, "note", "already running"); - return -1; - } - - slot = find_new_statdumpd_info (); - if (slot < 0) - { - nv_update_val (res, "note", "memory allocation error"); - return -1; - } - strcpy (statdump_daemon[slot].dbname, db_name); - interval = atoi (interval_str); - arniadb_cmd_name (path); - - argv[argc++] = path; - argv[argc++] = "statdump"; - argv[argc++] = "-i"; - argv[argc++] = interval_str; - argv[argc++] = db_name; - argv[argc++] = NULL; - -#if defined (WINDOWS) - ret_val = run_child (argv, 0, NULL, NULL, NULL, NULL); -#else - ret_val = run_child (argv, 0, NULL, "/dev/null", "/dev/null", NULL); -#endif - - if (ret_val < 0) - { - nv_update_val (res, "note", "could not execute statdump"); - return -1; - } - - statdump_daemon[slot].status = STATD_RUNNING; - statdump_daemon[slot].pid = ret_val; - nv_update_val (res, "note", db_name); - nv_update_val (res, "status", "success"); - nv_add_nvp_int (res, "pid", ret_val); - - return 0; -} - -extern int errno; - -int -ts_stop_statdump (nvplist *req, nvplist *res, char *_dbmt_error) -{ - int ret_val = ERR_NO_ERROR; - char *db_name; - int slot; - char cmd [1024]; - int ret; - - db_name = nv_get_val (req, "_DBNAME"); - if (!db_name || (slot = find_statdumpd_info (db_name)) < 0) - { - nv_update_val (res, "note", "no statdump running"); - nv_update_val (res, "status", "failed"); - return -1; - } - - nv_update_val (res, "note", db_name); - -#if defined (WINDOWS) - sprintf (cmd, "taskkill /T /F /PID %d", statdump_daemon[slot].pid); -#else - sprintf (cmd, "/bin/ps -o pid --ppid %d | grep -v PID | xargs kill", statdump_daemon[slot].pid); -#endif - - ret_val = system (cmd); - -#if !defined (WINDOWS) - /* - * Double check if the process is still running. - */ - if (ret_val < 0) - { - sprintf (cmd, "/bin/ps -p %d", statdump_daemon[slot].pid); - ret = system (cmd); - if (ret < 0) - { - ret_val = 0; - } - else - { - nv_add_nvp (res, "Linux_error", strerror (errno)); - } - } -#endif - - if (ret_val < 0) - { - nv_add_nvp_int (res, "pid", statdump_daemon[slot].pid); - nv_update_val (res, "status", "failed"); - return ret_val; - } - - statdump_daemon[slot].status = STATD_IDLE; - nv_update_val (res, "status", "success"); - return ret_val; -} - -int -find_new_statdumpd_info () -{ - int i; - if (statdump_daemon == NULL) - { - statdump_daemon = (T_STATDUMP_STAT *) calloc (sizeof(T_STATDUMP_STAT), MAX_STATDUMP_PROC); - if (statdump_daemon == NULL) - { - return -1; - } - else - { - return 0; - } - } - for (i = 0; i < MAX_STATDUMP_PROC; i++) - { - if (statdump_daemon[i].status == STATD_IDLE) - { - return i; - } - } - return -3; -} - -int -find_statdumpd_info (char *dbname) -{ - int i; - - if (statdump_daemon == NULL) - { - return -1; - } - for (i = 0; i < MAX_STATDUMP_PROC; i++) - { - if (statdump_daemon[i].status == STATD_RUNNING && strcmp (statdump_daemon[i].dbname, dbname) == 0) - { - return i; - } - } - return -1; -} - - -static int -_hash_cert (char *hash_value, char *file_path) -{ - MD5_CTX mdContext; - unsigned char data[RSA_KEY_SIZE]; - unsigned char md5_final[MD5_DIGEST_LENGTH]; - char md5_final_hex[MD5_DIGEST_LENGTH]; - int bytes = 0; - int i = 0; - FILE *inFile = NULL; - - if ((inFile = fopen (file_path, "rb")) == NULL) - { - return 1; - } - - MD5_Init (&mdContext); - - while ((bytes = (int) fread (data, 1, RSA_KEY_SIZE, inFile)) != 0) - { - MD5_Update (&mdContext, data, bytes); - } - MD5_Final (md5_final, &mdContext); - fclose (inFile); - - for (i = 0; i < MD5_DIGEST_LENGTH; i++) - { - snprintf (md5_final_hex, 3, "%x", md5_final[i]); - strncat (hash_value, md5_final_hex, 3); - } - return 0; -} - -static int -_is_default_cert (char *_dbmt_error) -{ - char new_hash_value[33]; - char default_cert_path[PATH_MAX]; - const char *default_hash_file = "df6a39a5565f858e40b6a7a3b0dee779"; - int compare_ret = 0; - - new_hash_value[0] = '\0'; - default_cert_path[0] = '\0'; - - snprintf (default_cert_path, PATH_MAX, "%s", sco.szSSLCertificate); - - if (_hash_cert (new_hash_value, default_cert_path) != 0) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, - "Fail to get the value of SSL certification file."); - return -1; - } - - compare_ret = - strncmp (default_hash_file, new_hash_value, strlen (new_hash_value)); - - if (compare_ret == 0) - { - return 1; - } - return 0; -} - -static int -_is_exist_default_backup_cert (char *_dbmt_error) -{ - char new_hash_value[33]; - char default_backup_cert_path[PATH_MAX]; - const char *default_hash_file = "df6a39a5565f858e40b6a7a3b0dee779"; - int compare_ret = 0; - - new_hash_value[0] = '\0'; - default_backup_cert_path[0] = '\0'; - - snprintf (default_backup_cert_path, PATH_MAX, "%s.bak", - sco.szSSLCertificate); - - if (access (default_backup_cert_path, F_OK) != 0) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, - "Cannot find the backup SSL certification file: %s.", - default_backup_cert_path); - return -1; - } - - if (_hash_cert (new_hash_value, default_backup_cert_path) != 0) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, - "Fail to get the value of backup SSL certification file."); - return -1; - } - - compare_ret = - strncmp (default_hash_file, new_hash_value, strlen (new_hash_value)); - - if (compare_ret == 0) - { - return 1; - } - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, - "(%s) is not default backup SSL certification file.", - default_backup_cert_path); - return 0; -} diff --git a/server/src/cm_job_task.h b/server/src/cm_job_task.h deleted file mode 100644 index 72d297d..0000000 --- a/server/src/cm_job_task.h +++ /dev/null @@ -1,439 +0,0 @@ -/* - * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. - * - * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/* - * cm_job_task.h - - */ - -#ifndef _CM_JOB_TASK_H_ -#define _CM_JOB_TASK_H_ - -#if defined(WINDOWS) -#include -#endif - -#include "cm_dep.h" - -#define DBMT_ERROR_MSG_SIZE 5000 - -#ifndef TASKNAME_LEN -#define TASKNAME_LEN 50 -#endif - -#ifndef SIZE_BUFFER_MAX -#define SIZE_BUFFER_MAX 1024 -#endif - -#define SET_TRANSACTION_NO_WAIT_MODE_ENV() \ - do { \ - putenv((char *) "ARNIADB_LOCK_TIMEOUT_IN_SECS=1"); \ - putenv((char *) "ARNIADB_ISOLATION_LEVEL=TRAN_READ_COMMITTED"); \ - } while (0) - -typedef enum -{ - TS_UNDEFINED, - TS_STARTINFO, - TS_USERINFO, - TS_CREATEUSER, - TS_DELETEUSER, - TS_CREATEDB, - TS_DELETEDB, - TS_RENAMEDB, - TS_STARTDB, - TS_STOPDB, - TS_UPDATEUSER, - TS_DBSPACEINFO, - TS_CLASSINFO, - TS_CLASS, - TS_RENAMECLASS, - TS_DROPCLASS, - TS_SETSYSPARAM, - TS_GETALLSYSPARAM, - TS_ADDVOLDB, - TS_CREATECLASS, - TS_CREATEVCLASS, - TS_GETLOGINFO, - TS_VIEWLOG, - TS_RESETLOG, - TS_ADDATTRIBUTE, - TS_DROPATTRIBUTE, - TS_UPDATEATTRIBUTE, - TS_ADDCONSTRAINT, - TS_DROPCONSTRAINT, - TS_ADDSUPER, - TS_DROPSUPER, - TS_GETSUPERCLASSESINFO, - TS_ADDRESOLUTION, - TS_DROPRESOLUTION, - TS_ADDMETHOD, - TS_DROPMETHOD, - TS_UPDATEMETHOD, - TS_ADDMETHODFILE, - TS_DROPMETHODFILE, - TS_ADDQUERYSPEC, - TS_DROPQUERYSPEC, - TS_CHANGEQUERYSPEC, - TS_VALIDATEQUERYSPEC, - TS_VALIDATEVCLASS, - TS_COPYDB, - TS_OPTIMIZEDB, - TS_STATDUMP, - TS_CHECKDB, - TS_COMPACTDB, - TS_BACKUPDBINFO, - TS_BACKUPDB, - TS_UNLOADDB, - TS_UNLOADDBINFO, - TS_LOADDB, - TS_GETTRANINFO, - TS_KILLTRAN, - TS_LOCKDB, - TS_GETBACKUPLIST, - TS_RESTOREDB, - TS_BACKUPVOLINFO, - TS_GETDBSIZE, - TS_GETDBMTUSERINFO, - TS_DELETEDBMTUSER, - TS_UPDATEDBMTUSER, - TS_SETDBMTPASSWD, - TS_ADDDBMTUSER, - TS_GETBACKUPINFO, - TS_ADDBACKUPINFO, - TS_DELETEBACKUPINFO, - TS_SETBACKUPINFO, - TS_GETDBERROR, - TS_GETAUTOADDVOL, - TS_SETAUTOADDVOL, - TS_GENERALDBINFO, - TS_LOADACCESSLOG, - TS_GETACCESSLOGFILES, - TS_GETERRORLOGFILES, - TS_CHECKDIR, - TS_AUTOBACKUPDBERRLOG, - TS_AUTOEXECQUERYERRLOG, - TS_KILL_PROCESS, - TS_GETENV, - TS_GETACCESSRIGHT, - TS_GETADDVOLSTATUS, - TS_GETHISTORY, - TS_SETHISTORY, - TS_GETHISTORYFILELIST, - TS_READHISTORYFILE, - TS_CHECKAUTHORITY, - TS_GETAUTOADDVOLLOG, - TS2_GETINITUNICASINFO, - TS2_GETUNICASINFO, - TS2_STARTUNICAS, - TS2_STOPUNICAS, - TS2_GETADMINLOGINFO, - TS2_GETLOGFILEINFO, - TS2_ADDBROKER, - TS2_GETADDBROKERINFO, - TS2_DELETEBROKER, - TS2_RENAMEBROKER, - TS2_GETBROKERSTATUS, - TS2_GETBROKERCONF, - TS2_GETBROKERONCONF, - TS2_SETBROKERCONF, - TS2_SETBROKERONCONF, - TS2_STARTBROKER, - TS2_STOPBROKER, - TS2_SUSPENDBROKER, - TS2_RESUMEBROKER, - TS2_BROKERJOBFIRST, - TS2_BROKERJOBINFO, - TS2_ADDBROKERAS, - TS2_DROPBROKERAS, - TS2_RESTARTBROKERAS, - TS2_GETBROKERSTATUSLOG, - TS2_GETBROKERMCONF, - TS2_SETBROKERMCONF, - TS2_GETBROKERASLIMIT, - TS2_GETBROKERENVINFO, - TS2_SETBROKERENVINFO, - TS2_ACCESSLISTADDIP, - TS2_ACCESSLISTDELETEIP, - TS2_ACCESSLISTINFO, - TS_CHECKFILE, - TS_REGISTERLOCALDB, - TS_REMOVELOCALDB, - TS_ADDNEWTRIGGER, - TS_ALTERTRIGGER, - TS_DROPTRIGGER, - TS_GETTRIGGERINFO, - TS_GETFILE, - TS_GETAUTOEXECQUERY, - TS_SETAUTOEXECQUERY, - TS_GETDIAGINFO, - TS_GET_DIAGDATA, - TS_GET_BROKER_DIAGDATA, - TS_ADDSTATUSTEMPLATE, - TS_REMOVESTATUSTEMPLATE, - TS_UPDATESTATUSTEMPLATE, - TS_GETSTATUSTEMPLATE, - TS_GETCASLOGFILELIST, - TS_ANALYZECASLOG, - TS_EXECUTECASRUNNER, - TS_REMOVECASRUNNERTMPFILE, - TS_GETCASLOGTOPRESULT, - TS_DBMTUSERLOGIN, - TS_CHANGEOWNER, - TS_REMOVE_LOG, - TS_PARAMDUMP, - TS_PLANDUMP, - TS_GETHOSTSTAT, - TS_GETDBPROCSTAT, - TS_CHANGEMODE, - TS_HEARTBEAT_LIST, - TS_HEARTBEAT_DEACT, - TS_HEARTBEAT_ACT, - TS_GET_STANDBY_SERVER_STAT, - TS_GETDBMODE, - TS_ROLE_CHANGE, - TS_USER_VERIFY, - TS_RUN_SCRIPT, - TS_GET_FOLDERS_WITH_KEYWORD, - TS_WRITE_AND_SAVE_CONF, - TS_RUN_SQL_STATEMENT, - TS_COPY_FOLDER, - TS_DELETE_FOLDER, - TS_GET_FILE_TOTAL_LINE_NUM, - TS_GET_ENVVAR_BY_NAME, - TS_ERROR_TRACE, - TS_LOGIN, - TS_LOGOUT, - TS_GET_CMS_ENV, - TS_KEEPALIVE, - TS_REMOVE_FILES, - TS_JOB_TEST, - TS_DB_SPACE_INFO, - TS_SHARD_START, - TS_SHARD_STOP, - TS_GET_SHARD_INFO, - TS_GET_SHARD_STATUS, - TS_BROKER_CHANGER, - TS_HA_START, - TS_HA_STOP, - TS_HA_STATUS, - TS_HA_APPLYLOGDB, - TS_HA_COPYLOGDB, - TS_HA_RELOAD, - TS_LIST_DIR, - TS_AUTO_UPDATE, - TS_IS_UPDATE_SUCCESS, - TS_MONITOR_PROCESS, - TS_GENERATE_CERT, - TS_START_STATDUMP, - TS_STOP_STATDUMP -} T_TASK_CODE; - -typedef enum -{ - FSVR_NONE, - FSVR_SA, - FSVR_CS, - FSVR_SA_CS, - FSVR_UC, - FSVR_SA_UC -} T_FSVR_TYPE; - -typedef int (*T_TASK_FUNC) (nvplist *req, nvplist *res, char *_dbmt_error); - -typedef unsigned int T_USER_AUTH; - -enum -{ - AU_DBC = 1, - AU_DBO = 2, - AU_BRK = 4, - AU_MON = 8, - AU_JOB = 16, - AU_VAR = 32, - AU_ADMIN = (1u << (sizeof (unsigned) * 8 - 1)) -}; - -#define ALL_AUTHORITY (AU_DBC | AU_DBO | AU_MON | AU_JOB | AU_BRK | AU_VAR) - -typedef struct -{ - const char *task_str; - int task_code; - char access_log_flag; - T_TASK_FUNC task_func; - T_FSVR_TYPE fsvr_type; - T_USER_AUTH user_auth; - -} T_FSERVER_TASK_INFO; - -int ts_userinfo (nvplist *in, nvplist *out, char *_dbmt_error); -int ts_create_user (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_delete_user (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_update_user (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_class_info (nvplist *in, nvplist *out, char *_dbmt_error); -int ts_class (nvplist *in, nvplist *out, char *_dbmt_error); -int ts_update_attribute (nvplist *in, nvplist *out, char *_dbmt_error); -int ts2_get_unicas_info (nvplist *in, nvplist *out, char *_dbmt_error); -int ts2_start_unicas (nvplist *in, nvplist *out, char *_dbmt_error); -int ts2_stop_unicas (nvplist *in, nvplist *out, char *_dbmt_error); -int ts2_get_admin_log_info (nvplist *in, nvplist *out, char *_dbmt_error); -int ts2_get_logfile_info (nvplist *in, nvplist *out, char *_dbmt_error); -int ts2_get_add_broker_info (nvplist *in, nvplist *out, char *_dbmt_error); -int ts2_delete_broker (nvplist *in, nvplist *out, char *_dbmt_error); -int ts2_get_broker_status (nvplist *in, nvplist *out, char *_dbmt_error); -int ts2_set_broker_conf (nvplist *in, nvplist *out, char *_dbmt_error); -int ts2_start_broker (nvplist *in, nvplist *out, char *_dbmt_error); -int ts2_stop_broker (nvplist *in, nvplist *out, char *_dbmt_error); -int ts2_restart_broker_as (nvplist *in, nvplist *out, char *_dbmt_error); -int ts_set_sysparam (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_get_all_sysparam (nvplist *req, nvplist *res, char *_dbmt_error); -int tsCreateDBMTUser (nvplist *req, nvplist *res, char *_dbmt_error); -int tsDeleteDBMTUser (nvplist *req, nvplist *res, char *_dbmt_error); -int tsUpdateDBMTUser (nvplist *req, nvplist *res, char *_dbmt_error); -int tsChangeDBMTUserPasswd (nvplist *req, nvplist *res, char *_dbmt_error); -int tsGetDBMTUserInfo (nvplist *req, nvplist *res, char *_dbmt_error); -int tsCreateDB (nvplist *req, nvplist *res, char *_dbmt_error); -int tsDeleteDB (nvplist *req, nvplist *res, char *_dbmt_error); -int tsRenameDB (nvplist *req, nvplist *res, char *_dbmt_error); -int tsStartDB (nvplist *req, nvplist *res, char *_dbmt_error); -int tsStopDB (nvplist *req, nvplist *res, char *_dbmt_error); -int tsDbspaceInfo (nvplist *req, nvplist *res, char *_dbmt_error); -int tsRunAddvoldb (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_copydb (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_optimizedb (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_plandump (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_paramdump (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_statdump (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_checkdb (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_compactdb (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_backupdb (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_unloaddb (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_loaddb (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_restoredb (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_backup_vol_info (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_get_dbsize (nvplist *req, nvplist *res, char *_dbmt_error); -int tsGetEnvironment (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_startinfo (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_kill_process (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_backupdb_info (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_unloaddb_info (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_get_backup_info (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_set_backup_info (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_add_backup_info (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_delete_backup_info (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_get_log_info (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_view_log (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_reset_log (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_get_autostart_db (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_set_autostart_db (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_get_auto_add_vol (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_set_auto_add_vol (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_get_addvol_status (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_get_tran_info (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_killtran (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_lockdb (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_get_backup_list (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_load_access_log (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_get_access_log_files (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_get_error_log_files (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_check_dir (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_get_autobackupdb_error_log (nvplist *req, nvplist *res, - char *_dbmt_error); -int ts_get_autoexecquery_error_log (nvplist *req, nvplist *res, - char *_dbmt_error); -int tsGetAutoaddvolLog (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_check_file (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_trigger_operation (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_get_triggerinfo (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_set_autoexec_query (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_get_autoexec_query (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_get_diagdata (nvplist *req, nvplist *res, char *diag_error); -int ts_get_broker_diagdata (nvplist *req, nvplist *res, char *diag_error); -int ts_addstatustemplate (nvplist *req, nvplist *res, char *diag_error); -int ts_removestatustemplate (nvplist *req, nvplist *res, char *diag_error); -int ts_updatestatustemplate (nvplist *req, nvplist *res, char *diag_error); -int ts_getstatustemplate (nvplist *req, nvplist *res, char *diag_error); -#if 0 /* ACTIVITY_PROFILE */ -int ts_addactivitytemplate (nvplist *req, nvplist *res, char *diag_error); -int ts_removeactivitytemplate (nvplist *req, nvplist *res, - char *diag_error); -int ts_updateactivitytemplate (nvplist *req, nvplist *res, - char *diag_error); -int ts_getactivitytemplate (nvplist *req, nvplist *res, char *diag_error); -#endif -int ts_analyzecaslog (nvplist *req, nvplist *res, char *diag_error); -int ts_executecasrunner (nvplist *req, nvplist *res, char *diag_error); -int ts_removecasrunnertmpfile (nvplist *req, nvplist *res, - char *diag_error); -int ts_getcaslogtopresult (nvplist *cli_request, nvplist *cli_response, - char *diag_error); -int ts_get_ldb_class_att (nvplist *req, nvplist *res, char *_dbmt_error); -int tsDBMTUserLogin (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_remove_log (nvplist *in, nvplist *out, char *_dbmt_error); -int ts_get_host_stat (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_get_dbproc_stat (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_changemode (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_heartbeat_list (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_get_standby_server_stat (nvplist *req, nvplist *res, - char *_dbmt_error); -int ts_get_db_mode (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_role_change (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_user_verify (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_write_and_save_conf (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_run_sql_statement (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_get_folders_with_keyword (nvplist *req, nvplist *res, - char *_dbmt_error); -int ts_run_script (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_copy_folder (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_delete_folder (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_get_file_total_line_num (nvplist *req, nvplist *res, - char *_dbmt_error); -int ts_get_envvar_by_name (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_error_trace (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_login (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_logout (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_get_cms_env (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_keepalive (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_remove_files (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_job_test (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_dbs_spaceInfo (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_shard_start (nvplist *req, nvplist *res, char *err_buf); -int ts_shard_stop (nvplist *req, nvplist *res, char *err_buf); -int ts_get_shard_info (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_get_shard_status (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_broker_changer (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_ha_start (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_ha_stop (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_ha_status (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_ha_reload (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_ha_applylogdb (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_ha_copylogdb (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_list_dir (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_auto_update (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_is_update_success (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_monitor_process (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_generate_cert (nvplist *req, nvplist *res, char *_dbmt_error); -int -ts_add_nvp_time (nvplist *ref, const char *name, time_t t, const char *fmt, - int type); -int ts_start_statdump (nvplist *req, nvplist *res, char *_dbmt_error); -int ts_stop_statdump (nvplist *req, nvplist *res, char *_dbmt_error); - -#endif /* _CM_JOB_TASK_H_ */ diff --git a/server/src/cm_log.h b/server/src/cm_log.h deleted file mode 100644 index 01a2ac0..0000000 --- a/server/src/cm_log.h +++ /dev/null @@ -1,515 +0,0 @@ -/* - * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. - * - * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -#ifndef __CM_LOG__H__ -#define __CM_LOG__H__ -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#if defined(WINDOWS) -#include -#include -#else -#include -#include -#include -#include -#include -#include /* opendir() ... */ -#endif - -#include "cm_config.h" - -using namespace std; - -#define DEFAULT_LOG_LEVEL xINFO - -#ifdef WINDOWS -#define mutex_t CRITICAL_SECTION -#define mutex_init(mutex) InitializeCriticalSection(&mutex) -#define mutex_lock(mutex) EnterCriticalSection(&mutex) -#define mutex_unlock(mutex) LeaveCriticalSection(&mutex) -#define mutex_destory(mutex) DeleteCriticalSection(&mutex) -#else -#define mutex_t pthread_mutex_t -#define mutex_init(mutex) pthread_mutex_init(&mutex, NULL) -#define mutex_lock(mutex) pthread_mutex_lock(&mutex) -#define mutex_unlock(mutex) pthread_mutex_unlock(&mutex) -#define mutex_destory(mutex) pthread_mutex_destroy(&mutex) -#endif - -#define MAX_DATE_TIME_LENGTH 128 - -class CLog -{ - public: - enum LOGLEVEL - { - xFATAL = 0, - xERROR = 1, - xWARN = 2, - xINFO = 3, - xDEBUG = 4, - }; - - protected: - CLog () - { - sLogLevel = CLog::xINFO; - m_lTruncate = sco.iMaxLogFileSize; - m_pLogFile = fopen (sco.szAccessLog, "a"); - m_pErrFile = fopen (sco.szErrorLog, "a"); - mutex_init (m_cs); - }; - - CLog (bool bappend, LOGLEVEL loglevel = - CLog::DEFAULT_LOG_LEVEL, long maxloglen = sco.iMaxLogFileSize) - { - sLogLevel = loglevel; - m_lTruncate = maxloglen; - - m_pLogFile = fopen (sco.szAccessLog, bappend ? "a" : "w"); - m_pErrFile = fopen (sco.szErrorLog, bappend ? "a" : "w"); - - mutex_init (m_cs); - } - - public: - ~CLog () - { - if (m_pLogFile) - { - fclose (m_pLogFile); - m_pLogFile = NULL; - } - - if (m_pErrFile) - { - fclose (m_pErrFile); - m_pErrFile = NULL; - } - - mutex_destory (m_cs); - } - - private: - LOGLEVEL _logLevel () - { - return sLogLevel; - } - - string _get_format_time () - { - char buff[MAX_DATE_TIME_LENGTH] = "unkonwn"; - time_t lt; - time (<); - tm *t = localtime (<); - if (t) - { - strftime (buff, MAX_DATE_TIME_LENGTH, "%Y%m%d %H:%M:%S", t); - } - return string (buff); - } - - void - _init_file_hander (void) - { - if (m_pLogFile != NULL) - { - fclose (m_pLogFile); - m_pLogFile = NULL; - } - if (m_pErrFile != NULL) - { - fclose (m_pErrFile); - m_pErrFile = NULL; - } - } - - void - _get_current_time_year_mon_day_hour_minute_second (char *current_time) - { - time_t cur_time; - - time (&cur_time); - strftime (current_time, MAX_DATE_TIME_LENGTH, "%Y%m%d%H%M%S", localtime (&cur_time)); - } - -#if defined(WINDOWS) - unsigned int - _get_files_count (list < string > &files_list, const char *roor_dir, string special_key = "") - { - HANDLE handle; - WIN32_FIND_DATA ffd; - char find_path[PATH_MAX]; - string cms_log_name; - - snprintf (find_path, PATH_MAX, "%s/*", roor_dir); - - handle = FindFirstFile (find_path, &ffd); - if (handle == INVALID_HANDLE_VALUE) - { - return 0; - } - while (FindNextFile (handle, &ffd)) - { - if (ffd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN - || ffd.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) - { - continue; - } - else if (! (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) - { - cms_log_name = ffd.cFileName; - if (special_key.length() == 0) - { - files_list.push_back (cms_log_name); - } - else - { - if (cms_log_name.find (special_key) < cms_log_name.length()) - { - files_list.push_back (cms_log_name); - } - } - } - } - FindClose (handle); - - return (unsigned int) files_list.size(); - } - -#else - - unsigned int - _get_files_count (list < string > &files_list, const char *roor_dir, string special_key = "") - { - DIR *dirptr = NULL; - struct dirent *entry; - string cms_log_name; - - if ((dirptr = opendir (roor_dir)) == NULL) - { - return 0; - } - while ((entry = readdir (dirptr)) != NULL) - { - if (strcmp (entry->d_name, ".") == 0 || strcmp (entry->d_name, "..") == 0) - { - continue; - } - - cms_log_name = entry->d_name; - - if (special_key.length() == 0) - { - files_list.push_back (cms_log_name); - } - else - { - if (cms_log_name.find (special_key) < cms_log_name.length()) - { - - files_list.push_back (cms_log_name); - } - } - } - - closedir (dirptr); - return files_list.size(); - } -#endif - - void - _remove_oldest_file (list < string > &files_list) - { - list < string >::iterator itor; - list < string > files_mtime_list; - char log_full_path[PATH_MAX]; - char oldest_file[PATH_MAX]; - struct stat st; - long oldest_time = LONG_MAX; - - char log_path[PATH_MAX]; - snprintf (log_path, PATH_MAX, "%s/%s", sco.szArniadb, DBMT_LOG_DIR); - - if (files_list.empty() == true) - { - return; - } - - for (itor = files_list.begin(); itor != files_list.end(); itor++) - { - snprintf (log_full_path, PATH_MAX, "%s/%s", log_path, (*itor).c_str()); - stat (log_full_path, &st); - if ((long) st.st_mtime < oldest_time) - { - oldest_time = (long) st.st_mtime; - snprintf (oldest_file, PATH_MAX, "%s", log_full_path); - } - } - - unlink (oldest_file); - } - - bool - _backup_log_files (char *base_log_path, string error_log_name, string log_name) - { - int ret_backup_log = -1; - int ret_backup_err = -1; - char backup_log_name[PATH_MAX]; - char backup_err_name[PATH_MAX]; - char cur_time[MAX_DATE_TIME_LENGTH]; - - backup_log_name[0] = '\0'; - backup_err_name[0] = '\0'; - cur_time[0] = '\0'; - - _get_current_time_year_mon_day_hour_minute_second (cur_time); - snprintf (backup_err_name, PATH_MAX, "%s/%s.%s", base_log_path, error_log_name.c_str(), cur_time); - snprintf (backup_log_name, PATH_MAX, "%s/%s.%s", base_log_path, log_name.c_str(), cur_time); - - ret_backup_log = rename (sco.szAccessLog, backup_log_name); - ret_backup_err = rename (sco.szErrorLog, backup_err_name); - - if ((ret_backup_log == -1) || (ret_backup_err == -1)) - { - return false; - } - return true; - } - - - public: - - static CLog *GetInstance (unsigned int logLevel) - { - static CLog *instance_log = NULL; - static CLog *instance_err = NULL; - - if ((logLevel <= CLog::xWARN) && (logLevel >= CLog::xFATAL)) - { - // write log into error log file - - if ((instance_err == NULL) || (access (sco.szErrorLog, F_OK) < 0)) - { - instance_err = new CLog (TRUE); - } - return instance_err; - } - else - { - // write log into normal log file - if ((instance_log == NULL) || (access (sco.szAccessLog, F_OK) < 0)) - { - instance_log = new CLog (TRUE); - } - return instance_log; - } - } - - void setLogLevel (const unsigned int level) - { - sLogLevel = (LOGLEVEL) level; - } - - void formatLog (const int iPriority, const char *fmt, ...) - { - char log_path[PATH_MAX]; - list < string > log_files_list; - - string error_log_name = "arn_manager.err"; - string log_name = "arn_manager.log"; - - log_path[0] = '\0'; - snprintf (log_path, PATH_MAX, "%s/%s", sco.szArniadb, DBMT_LOG_DIR); - - //check log level - if (iPriority > _logLevel ()) - { - return; - } - - //format log message - const char *strLevel; - bool isErrorLog = false; - switch (iPriority) - { - case CLog::xFATAL: - strLevel = "FATAL"; - isErrorLog = true; - break; - case CLog::xERROR: - strLevel = "ERROR"; - isErrorLog = true; - break; - case CLog::xWARN: - strLevel = " WARN"; - isErrorLog = true; - break; - case CLog::xINFO: - strLevel = " INFO"; - break; - case CLog::xDEBUG: - default: - strLevel = "DEBUG"; - break; - } - - if (isErrorLog == true) - { - if (m_pErrFile == NULL) - { - return; - } - } - else - { - if (m_pLogFile == NULL) - { - return; - } - } - - //format log data - size_t size = 1024; - char *buffer = new char[size]; - memset (buffer, 0, size); - - while (1) - { - va_list args; - va_start (args, fmt); -#ifdef _WIN32 - int n = _vsnprintf (buffer, size, fmt, args); -#else - int n = vsnprintf (buffer, size, fmt, args); -#endif - va_end (args); - if ((n > -1) && (static_cast < size_t > (n) < size)) - { - break; - } - - size = (n > -1) ? n + 1 : size * 2; - delete[]buffer; - buffer = new char[size]; - memset (buffer, 0, size); - } - - bool shouldBackupFiles = false; - - if (isErrorLog == true) - { - mutex_lock (m_cs); - - fprintf (m_pErrFile, "[%s] [%s] [%6d] %s\n", - _get_format_time ().c_str (), strLevel, getpid (), buffer); - fflush (m_pErrFile); - - if (ftell (m_pErrFile) > m_lTruncate) - { - shouldBackupFiles = true; - } - mutex_unlock (m_cs); - } - else - { - mutex_lock (m_cs); - - fprintf (m_pLogFile, "[%s] [%s] [%6d] %s\n", - _get_format_time ().c_str (), strLevel, getpid (), buffer); - - fflush (m_pLogFile); - - if (ftell (m_pLogFile) > m_lTruncate) - { - shouldBackupFiles = true; - } - mutex_unlock (m_cs); - } - - // backup log when the file grow too large - if (shouldBackupFiles == true) - { - mutex_lock (m_cs); - - // init open file - close them firstly - _init_file_hander (); - - // then move the arn_manager.log into new name log file. - _backup_log_files (log_path, error_log_name, log_name); - - // remove the oldest file - if (_get_files_count (log_files_list, log_path, error_log_name) > (unsigned int) sco.iMaxLogFiles) - { - _remove_oldest_file (log_files_list); - } - - log_files_list.clear(); - // remove the oldest file - if (_get_files_count (log_files_list, log_path, log_name) > (unsigned int) sco.iMaxLogFiles) - { - _remove_oldest_file (log_files_list); - } - mutex_unlock (m_cs); - } - delete[]buffer; - } - - private: - LOGLEVEL sLogLevel; - mutex_t m_cs; - FILE *m_pLogFile; - FILE *m_pErrFile; - long m_lTruncate; - -}; - -#define STRINGIZE2(s) #s -#define STRINGIZE(s) STRINGIZE2(s) - -#ifndef LogPrefix -#define LogPrefix(fmt) std::string("[").append(__FUNCTION__).append(":").append(STRINGIZE(__LINE__)).append("] ").append(fmt).c_str() -#endif - -#define LOG_DEBUG(fmt, ...) \ - CLog::GetInstance(CLog::xDEBUG)->formatLog(CLog::xDEBUG, LogPrefix(fmt), ##__VA_ARGS__) - -#define LOG_INFO(fmt, ...) \ - CLog::GetInstance(CLog::xINFO)->formatLog(CLog::xINFO, LogPrefix(fmt), ##__VA_ARGS__) - -#define LOG_WARN(fmt, ...) \ - CLog::GetInstance(CLog::xWARN)->formatLog(CLog::xWARN, LogPrefix(fmt), ##__VA_ARGS__) - -#define LOG_ERROR(fmt, ...) \ - CLog::GetInstance(CLog::xERROR)->formatLog(CLog::xERROR, LogPrefix(fmt), ##__VA_ARGS__) - -#define LOG_FATAL(fmt, ...) \ - CLog::GetInstance(CLog::xFATAL)->formatLog(CLog::xFATAL, LogPrefix(fmt), ##__VA_ARGS__) - -#endif diff --git a/server/src/cm_mailer.h b/server/src/cm_mailer.h deleted file mode 100644 index e0af839..0000000 --- a/server/src/cm_mailer.h +++ /dev/null @@ -1,1913 +0,0 @@ -// Note that the only valid version of the GPL as far as jwSMTP -// is concerned is v2 of the license (ie v2, not v2.2 or v3.x or whatever), -// unless explicitly otherwise stated. -// -// This file is part of the jwSMTP library. -// -// jwSMTP library 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; version 2 of the License. -// -// jwSMTP library 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 jwSMTP library; if not, write to the Free Software -// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA -// -// jwSMTP library -// http://johnwiggins.net -// smtplib@johnwiggins.net -// -#ifndef __CM_MAILER_H__ -#define __CM_MAILER_H__ -#ifdef WIN32 -// std::vector This gives this warning in VC.. -// bloody annoying, there is a way round it according to MS. -// The debugger basically cannot browse anything with a name -// longer than 256 characters, "get with the template program MS". -#pragma warning( disable : 4786 ) -// tell the linker which libraries to find functions in -#include -#else -#include -#include -#include -#include -#include -typedef int SOCKET; // get round windows definitions. -#endif -#include -#include // ostrstream -#include // for localtime -#include -#include -#include - -namespace jwsmtp { - -// added the B64 to all members of the enum for SunOS (thanks Ken Weinert) -enum BASE64 -{ - B64_A, B64_B, B64_C, B64_D, B64_E, B64_F, B64_G, B64_H, B64_I, B64_J, B64_K, B64_L, B64_M, B64_N, B64_O, B64_P, B64_Q, B64_R, B64_S, B64_T, B64_U, B64_V, B64_W, B64_X, B64_Y, B64_Z, - B64_a, B64_b, B64_c, B64_d, B64_e, B64_f, B64_g, B64_h, B64_i, B64_j, B64_k, B64_l, B64_m, B64_n, B64_o, B64_p, B64_q, B64_r, B64_s, B64_t, B64_u, B64_v, B64_w, B64_x, B64_y, B64_z, - B64_0, B64_1, B64_2, B64_3, B64_4, B64_5, B64_6, B64_7, B64_8, B64_9, plus, slash, padding -}; - -char getbase64character(const char& in) -{ - switch(in) { - case B64_A: - return 'A'; - case B64_B: - return 'B'; - case B64_C: - return 'C'; - case B64_D: - return 'D'; - case B64_E: - return 'E'; - case B64_F: - return 'F'; - case B64_G: - return 'G'; - case B64_H: - return 'H'; - case B64_I: - return 'I'; - case B64_J: - return 'J'; - case B64_K: - return 'K'; - case B64_L: - return 'L'; - case B64_M: - return 'M'; - case B64_N: - return 'N'; - case B64_O: - return 'O'; - case B64_P: - return 'P'; - case B64_Q: - return 'Q'; - case B64_R: - return 'R'; - case B64_S: - return 'S'; - case B64_T: - return 'T'; - case B64_U: - return 'U'; - case B64_V: - return 'V'; - case B64_W: - return 'W'; - case B64_X: - return 'X'; - case B64_Y: - return 'Y'; - case B64_Z: - return 'Z'; - case B64_a: - return 'a'; - case B64_b: - return 'b'; - case B64_c: - return 'c'; - case B64_d: - return 'd'; - case B64_e: - return 'e'; - case B64_f: - return 'f'; - case B64_g: - return 'g'; - case B64_h: - return 'h'; - case B64_i: - return 'i'; - case B64_j: - return 'j'; - case B64_k: - return 'k'; - case B64_l: - return 'l'; - case B64_m: - return 'm'; - case B64_n: - return 'n'; - case B64_o: - return 'o'; - case B64_p: - return 'p'; - case B64_q: - return 'q'; - case B64_r: - return 'r'; - case B64_s: - return 's'; - case B64_t: - return 't'; - case B64_u: - return 'u'; - case B64_v: - return 'v'; - case B64_w: - return 'w'; - case B64_x: - return 'x'; - case B64_y: - return 'y'; - case B64_z: - return 'z'; - case B64_0: - return '0'; - case B64_1: - return '1'; - case B64_2: - return '2'; - case B64_3: - return '3'; - case B64_4: - return '4'; - case B64_5: - return '5'; - case B64_6: - return '6'; - case B64_7: - return '7'; - case B64_8: - return '8'; - case B64_9: - return '9'; - case plus: - return '+'; - case slash: - return '/'; - case padding: - return '='; - } - return '\0'; // ?????? yikes -} - -std::vector base64encode(const std::vector& input, const bool returns = true) { - std::vector output; - - // add a newline (SMTP demands less than 1000 characters in a message line). - long count = 0; - for(std::vector::size_type p = 0; p < input.size(); p+=3) { - output.push_back(getbase64character((input[p] & 0xFC) >> 2)); - ++count; - - if(p+1 < input.size()) { - output.push_back(getbase64character(((input[p] & 0x03) <<4) | ((input[p+1] & 0xF0) >> 4))); - ++count; - } - if(p+2 < input.size()) { - output.push_back(getbase64character(((input[p+1] & 0x0F) <<2) | ((input[p+2] & 0xC0) >>6))); - output.push_back(getbase64character((input[p+2] & 0x3F))); - ++count; - } - - if(p+1 == input.size()) { - output.push_back(getbase64character(((input[p] & 0x03) <<4))); - } - else if(p+2 == input.size()) { - output.push_back(getbase64character(((input[p+1] & 0x0F) <<2))); - } - - if(returns) { - // 79 characters on a line. - if(count > 75) { - output.push_back('\r'); - output.push_back('\n'); - count = 0; - } - } - } - - int pad(input.size() % 3); - if(pad) { - if(pad == 1) - pad = 2; - else - pad = 1; - } - for(int i = 0; i < pad; ++i) - output.push_back('='); - - return output; -} - -std::string base64encode(const std::string& input, const bool returns = true) { - std::vector in, out; - for(std::string::const_iterator it = input.begin(); it != input.end(); ++it) { - in.push_back(*it); - } - out = base64encode(in, returns); - std::string ret; - for(std::vector::const_iterator it1 = out.begin(); it1 != out.end(); ++it1) { - ret += *it1; - } - return ret; -} - -struct SOCKADDR_IN { - sockaddr_in ADDR; // we are wrapping this structure. - - // this is bad as we just assume that the address "addr" is valid here. - // need a real check and set ok appropriately -// SOCKADDR_IN(sockaddr_in addr):ADDR(addr), ok(true) {} - - SOCKADDR_IN(const std::string& address, unsigned short port, short family = AF_INET) { - ADDR.sin_port = port; - ADDR.sin_family = family; -#ifdef WIN32 - ADDR.sin_addr.S_un.S_addr = inet_addr(address.c_str()); - ok = (ADDR.sin_addr.S_un.S_addr != INADDR_NONE); -#else - ok = (inet_aton(address.c_str(), &ADDR.sin_addr)); -#endif - } - - SOCKADDR_IN(const SOCKADDR_IN& addr) { - ADDR = addr.ADDR; - ok = addr.ok; - } - SOCKADDR_IN operator = (const SOCKADDR_IN& addr) { - ADDR = addr.ADDR; - ok = addr.ok; - return *this; - } - - operator bool() const {return ok;} - - operator const sockaddr_in () const { - return ADDR; - } - operator const sockaddr () const { - sockaddr addr; - std::copy((char*)&ADDR, (char*)&ADDR + sizeof(ADDR), (char*)&addr); - return addr; - } - - size_t get_size() const {return sizeof(ADDR);} - char* get_sin_addr() { - return (char*)&ADDR.sin_addr; - } - void set_port(unsigned short newport) {ADDR.sin_port = newport;} - void set_ip(const std::string& newip) { -#ifdef WIN32 - ADDR.sin_addr.S_un.S_addr = inet_addr(newip.c_str()); - ok = (ADDR.sin_addr.S_un.S_addr != INADDR_NONE); -#else - ok = (inet_aton(newip.c_str(), &ADDR.sin_addr)); -#endif - } - void zeroaddress() { -#ifdef WIN32 - ADDR.sin_addr.S_un.S_addr = 0; -#else - ADDR.sin_addr.s_addr = 0; -#endif - } - -private: - bool ok; -}; - - -bool Connect(SOCKET sockfd, const SOCKADDR_IN& addr) { -#ifdef WIN32 - return bool(connect(sockfd, (sockaddr*)&addr, (int) addr.get_size()) != SOCKET_ERROR); -#else - return bool(connect(sockfd, (sockaddr*)&addr, addr.get_size()) == 0); -#endif -} - -bool Socket(SOCKET& s, int domain, int type, int protocol) { - s = socket(AF_INET, type, protocol); -#ifdef WIN32 - return bool(s != INVALID_SOCKET); -#else - return bool(s != -1); -#endif -} - -bool Send(int &CharsSent, SOCKET s, const char *msg, size_t len, int flags) { - CharsSent = send(s, msg, (int) len, flags); -#ifdef WIN32 - return bool((CharsSent != SOCKET_ERROR)); -#else - return bool((CharsSent != -1)); -#endif -} - -bool Recv(int &CharsRecv, SOCKET s, char *buf, size_t len, int flags) { - CharsRecv = recv(s, buf, (int) len, flags); -#ifdef WIN32 - return bool((CharsRecv != SOCKET_ERROR)); -#else - return bool((CharsRecv != -1)); -#endif -} - -// just wrap the call to shutdown the connection on a socket -// this way I don't have to call it this way everywhere. -void Closesocket(const SOCKET& s) { -#ifdef WIN32 - closesocket(s); -#else - close(s); -#endif -} - -// This does nothing on unix. -// for windoze only, to initialise networking, snore -void initNetworking() { -#ifdef WIN32 - class socks - { - public: - bool init() { - - WORD wVersionRequested; - WSADATA wsaData; - - wVersionRequested = MAKEWORD( 2, 0 ); - int ret = WSAStartup( wVersionRequested, &wsaData); - if(ret) - return false; - initialised = true; - return true; - } - bool IsInitialised() const {return initialised;} - socks():initialised(false){init();} - ~socks() - { - if(initialised) - shutdown(); - } - private: - void shutdown(){WSACleanup();} - bool initialised; - }; - static socks s; -#endif -} - - - - -class mailer -{ -public: - // if MXLookup is true: - // 'server' is a nameserver to lookup an MX record by. - // if MXLookup is false. - // 'server' is an SMTP server which will be attempted directly for mailing - // if an IP address is not found, either MX record or direct to SMTP server, - // an attempt will be made to send mail directly to the server in the mail address. - // e.g. mail to fred@somewhere.com will have a connection attempt made directly to: - // somewhere.com (which is probably wrong and therefore will still fail) - mailer(const char* TOaddress, const char* FROMaddress, - const char* Subject, const std::vector& Message, - const char* server = "127.0.0.1"/*default to localhost*/, - unsigned short Port = SMTP_PORT, // default SMTP port - bool MXLookup = true) : type(LOGIN), - subject(Subject), - server(getserveraddress(TOaddress)), - nameserver(server), - port(htons(Port)), // make the 'port' network byte order. - lookupMXRecord(MXLookup), - auth(false) { - // Parse the email addresses into an Address structure. - setsender(FROMaddress); - addrecipient(TOaddress); - setmessage(Message); - - initNetworking(); // in win32 init networking, else just does nothin' -}; - - mailer(const char* TOaddress, const char* FROMaddress, - const char* Subject, const char* Message, - const char* server = "127.0.0.1"/*default to localhost*/, - unsigned short Port = SMTP_PORT, // default SMTP port - bool MXLookup = true) : type(LOGIN), - subject(Subject), - server(getserveraddress(TOaddress)), - nameserver(server), - port(htons(Port)), // make the 'port' network byte order. - lookupMXRecord(MXLookup), - auth(false) { - // Parse the email addresses into an Address structure. - setsender(FROMaddress); - addrecipient(TOaddress); - setmessage(Message); - - initNetworking(); // in win32 init networking, else just does nothin' -}; - - // defaults to SMTP_PORT & no MX lookup. - // now we can do: - // mailer m; // mail an smtp server direct. - // mailer m2(true); // use MX lookup. - // mailer m2(false, weirdportnumber); // SMTP to a non standard port. - mailer(bool MXLookup = false, unsigned short Port = SMTP_PORT): - type(LOGIN), - port(htons(Port)), - lookupMXRecord(MXLookup), - auth(false) { - initNetworking(); // in win32 init networking, else just does nothin' -}; - - ~mailer() {}; - - // call this operator to have the mail mailed. - // This is to facilitate using multiple threads - // i.e. using boost::thread. (see http://www.boost.org) - // - // e.g. - // mailer mail(args...); - // boost::thread thrd(mail); // operator()() implicitly called. - // thrd.join(); // if needed. - // - // or: - // mailer mail(args...); - // mail.operator()(); - void operator()() { - returnstring = ""; // clear out any errors from previous use - - if(!recipients.size()) { - returnstring = "451 Requested action aborted: local error who am I mailing"; - return; - } - if(!fromAddress.address.length()) { - returnstring = "451 Requested action aborted: local error who am I"; - return; - } - if(!nameserver.length()) { - returnstring = "451 Requested action aborted: local error no SMTP/name server/smtp server"; - return; - } - - std::vector adds; - if(lookupMXRecord) { - if(!gethostaddresses(adds)) { - // error!! we are dead. - returnstring = "451 Requested action aborted: No MX records ascertained"; - return; - } - } - else { // connect directly to an SMTP server. - SOCKADDR_IN addr(nameserver, port, AF_INET); - hostent* host = 0; - if(addr) { - host = gethostbyaddr(addr.get_sin_addr(), sizeof(addr.ADDR.sin_addr), AF_INET); - } - else - host = gethostbyname(nameserver.c_str()); - if(!host) { - returnstring = "451 Requested action aborted: local error in processing"; - return; // error!!! - } - //memcpy(addr.get_sin_addr(), host->h_addr, host->h_length); - std::copy(host->h_addr_list[0], host->h_addr_list[0] + host->h_length, addr.get_sin_addr()); - adds.push_back(addr); - } - - SOCKET s; - if(!Socket(s, AF_INET, SOCK_STREAM, 0)) { - returnstring = "451 Requested action aborted: socket function error"; - return; - } - - if(!adds.size()) { // oops - returnstring = "451 Requested action aborted: No MX records ascertained"; - } - - const std::string OK("250"); - const std::vector smtpheader(makesmtpmessage()); - const int buffsize(1024); - char buff[buffsize] = ""; - - for(std::vector::const_iterator address = adds.begin(); - address < adds.end(); ++address) { - if(!Connect(s, *address)) { - returnstring = "554 Transaction failed: server connect error."; - continue; - } - - // 220 the server line returned here - int len1; - if(!Recv(len1, s, buff, buffsize -1, 0)) { - returnstring = "554 Transaction failed: server connect response error."; - continue; - } - - // get our hostname to pass to the smtp server - char hn[buffsize] = ""; - if(gethostname(hn, buffsize)) { - // no local hostname!!! make one up - strcpy(hn, "flibbletoot"); - } - std::string commandline(std::string("EHLO ") + hn + std::string("\r\n")); - // say hello to the server - - if(!Send(len1, s, commandline.c_str(), commandline.length(), 0)) { - returnstring = "554 Transaction failed: EHLO send"; - continue; - } - if(!Recv(len1, s, buff, buffsize -1, 0)) { - returnstring = "554 Transaction failed: EHLO receipt"; - continue; - } - - buff[len1] = '\0'; - std::string greeting = returnstring = buff; - if(returnstring.substr(0,3) != OK) { - if(auth) { - // oops no ESMTP but using authentication no go bail out! - returnstring = "554 possibly trying to use AUTH without ESMTP server, ERROR!"; - continue; - } - // maybe we only do non extended smtp - // send HELO instead. - commandline[0] = 'H'; - commandline[1] = 'E'; - if(!Send(len1, s, commandline.c_str(), commandline.length(), 0)) { - returnstring = "554 Transaction failed: HELO send"; - continue; - } - if(!Recv(len1, s, buff, buffsize -1, 0)) { - returnstring = "554 Transaction failed: HELO receipt"; - continue; - } - buff[len1] = '\0'; - - returnstring = buff; - if(returnstring.substr(0,3) != OK) { - // we must issue a quit even on an error. - // in keeping with the rfc's - if(Send(len1, s, "QUIT\r\n", 6, 0)) { - char dummy[buffsize]; - Recv(len1, s, dummy, buffsize -1, 0); - } - Closesocket(s); - // don't know what went wrong here if we are connected!! - // we continue because maybe we have more than 1 server to connect to. - continue; - } - } - - if(auth) - if(!authenticate(greeting, s)) - continue; // try the next server, you never know!! - - // MAIL - // S: MAIL FROM: - // R: 250 OK - // e.g. "MAIL FROM:\r\n" - // or "MAIL FROM: John Wiggins " - commandline = "MAIL FROM:<" + fromAddress.address + ">\r\n"; - if(!Send(len1, s, commandline.c_str(), commandline.length(), 0)) { - returnstring = "554 MAIL FROM sending error"; - continue; - } - - if(!Recv(len1, s, buff, buffsize -1, 0)) { - returnstring = "554 MAIL FROM receipt error"; - continue; - } - - buff[len1] = '\0'; - returnstring = buff; - if(returnstring.substr(0,3) != OK) { - // we must issue a quit even on an error. - // in keeping with the rfc's - if(Send(len1, s, "QUIT\r\n", 6, 0)) { - char dummy[buffsize]; - Recv(len1, s, dummy, buffsize -1, 0); - } - Closesocket(s); - // don't know what went wrong here if we are connected!! - // we continue because maybe we have more than 1 server to connect to. - continue; - } - - for(recipient_const_iter recip = recipients.begin(); recip < recipients.end(); ++recip) { - // RCPT - - // S: RCPT TO: - // R: 250 OK - commandline = "RCPT TO: <" + (*recip).first.address + ">\r\n"; - // S: RCPT TO: - // R: 550 No such user here - // - // S: RCPT TO: - // R: 250 OK - if(!Send(len1, s, commandline.c_str(), commandline.length(), 0)) { - returnstring = "554 Transaction failed"; - continue; - } - if(!Recv(len1, s, buff, buffsize -1, 0)) { - returnstring = buff; - continue; - } - buff[len1] = '\0'; - returnstring = buff; - if(returnstring.substr(0,3) != OK) { - // This particular recipient does not exist! - // not strictly an error as we may have more than one recipient - // we should have an error vector e.g. - // vector > errs; - // errs.push_back(make_pair(recip->first, returnstring)); - // - // we then need a function to return this vector. - // e.g. const vector >& getrecipienterrors(); - continue; - } - } - - // DATA - - // S: DATA - // R: 354 Start mail input; end with . - // S: Blah blah blah... - // S: ...etc. etc. etc. - - // S: . - // R: 250 OK - if(!Send(len1, s, "DATA\r\n", 6, 0)) { - returnstring = "554 DATA send error"; - continue; - } - if(!Recv(len1, s, buff, buffsize -1, 0)) { - returnstring = "554 DATA, server response error"; - continue; - } - buff[len1] = '\0'; - returnstring = buff; - if(returnstring.substr(0,3) != "354") { - // we must issue a quit even on an error. - // in keeping with the rfc's - - if(Send(len1, s, "QUIT\r\n", 6, 0)) { - char dummy[buffsize]; - Recv(len1, s, dummy, buffsize -1, 0); - } - Closesocket(s); - continue; - } - // Sending the email - /*if(!Send(len1, s, smtpheader.c_str(), smtpheader.length(), 0)) {*/ - if(!Send(len1, s, &smtpheader[0], smtpheader.size(), 0)) { - returnstring = "554 DATA, server response error (actual send)"; - continue; - } - if(!Recv(len1, s, buff, buffsize -1, 0)) { - returnstring = "554 DATA, server response error (actual send)"; - continue; - } - - // The server should give us a 250 reply if the mail was delivered okay - buff[len1] = '\0'; - returnstring = buff; - if(returnstring.substr(0,3) != OK) { - // we must issue a quit even on an error. - // in keeping with the rfc's - if(Send(len1, s, "QUIT\r\n", 6, 0)) { - char dummy[buffsize]; - Recv(len1, s, dummy, buffsize -1, 0); - } - Closesocket(s); - continue; - } - // hang up the connection - if(Send(len1, s, "QUIT\r\n", 6, 0)) { - char dummy[buffsize]; - Recv(len1, s, dummy, buffsize -1, 0); - } - - // Let the server give us our 250 reply. - //buff[len1] = '\0'; - //returnstring = buff; - - // for future reference the server is meant to give a 221 response to a quit. - if(returnstring.substr(0,3) != "221") { - // maybe will use this later - } - Closesocket(s); // disconnect - - // Let the server give us our 250 reply. - // don't continue as we have delivered the mail - // at this point just leave. all done - //returnstring = "250 Requested mail action okay, completed"; - break; - } -}; - void send() { - operator()(); -}; - - // attach a file to the mail. (MIME 1.0) - // returns false if !filename.length() or - // the file could not be opened for reading...etc. - bool attach(const std::string& filename) { - if(!filename.length()) // do silly checks. - return false; - - std::ifstream file(filename.c_str(), std::ios::binary | std::ios::in); - if(!file) - return false; - - std::vector filedata; - char c = file.get(); - for(; file.good(); c = file.get()) { - if(file.bad()) - break; - filedata.push_back(c); - } - - filedata = base64encode(filedata); - - std::string fn(filename); - std::string::size_type p = fn.find_last_of('/'); - if(p == std::string::npos) - p = fn.find_last_of('\\'); - if(p != std::string::npos) { - p +=1; // get past folder delimeter - fn = fn.substr(p, fn.length() - p); - } - - attachments.push_back(std::make_pair(filedata, fn)); - - return true; -}; - - // remove an attachment from the list of attachments. - // returns false if !filename.length() or - // the file is not attached or there are no attachments. - bool removeattachment(const std::string& filename) { - if(!filename.length()) // do silly checks. - return false; - - if(!attachments.size()) - return false; - - std::string fn(filename); - std::string::size_type p = fn.find_last_of('/'); - if(p == std::string::npos) - p = fn.find_last_of('\\'); - if(p != std::string::npos) { - p +=1; // get past folder delimeter - fn = fn.substr(p, fn.length() - p); - } - // fn is now what is stored in the attachments pair as the second parameter - // i.e. it->second == fn - std::vector, std::string> >::iterator it; - for(it = attachments.begin(); it < attachments.end(); ++it) { - if((*it).second == fn) { - attachments.erase(it); - return true; - } - } - return false; -}; - - // Set a new message (replacing the old) - // will return false and not change the message if newmessage is empty. - bool setmessage(const std::string& newmessage) { - if(!newmessage.length()) - return false; - - message.clear(); // erase the old message - for (std::string::size_type i = 0; i < newmessage.length(); ++i) - message.push_back(newmessage[i]); - - checkRFCcompat(); - - return true; -}; - bool setmessage(const std::vector& newmessage) { - if(!newmessage.size()) - return false; - - message = newmessage; - - checkRFCcompat(); - - return true; -}; - - // Set a new HTML message (replacing the old) - // will return false and not change the message if newmessage is empty. - bool setmessageHTML(const std::string& newmessage) { - if(!newmessage.length()) - return false; - - messageHTML.clear(); // erase the old message - for (std::string::size_type i = 0; i < newmessage.length(); ++i) - messageHTML.push_back(newmessage[i]); - messageHTML = base64encode(messageHTML); - - return true; -}; - bool setmessageHTML(const std::vector& newmessage) { - if(!newmessage.size()) - return false; - - messageHTML = base64encode(newmessage); - - return true; -}; - // use a file for the data - bool setmessageHTMLfile(const std::string& filename) { - if(!filename.length()) - return false; - - std::ifstream file(filename.c_str(), std::ios::binary | std::ios::in); - if(!file) - return false; - std::vector filedata; - char c = file.get(); - for(; file.good(); c = file.get()) { - if(file.bad()) - break; - filedata.push_back(c); - } - - messageHTML = base64encode(filedata); - - return true; -}; - - // Set a new Subject for the mail (replacing the old) - // will return false if newSubject is empty. - bool setsubject(const std::string& newSubject) { - if(!newSubject.length()) - return false; - - subject = newSubject; - return true; -}; - - // sets the nameserver or smtp server to connect to - // dependant on the constructor call, i.e. whether - // 'lookupMXRecord' was set to false or true. - // (see constructor comment for details) - bool setserver(const std::string& nameserver_or_smtpserver) { - if(!nameserver_or_smtpserver.length()) - return false; - - nameserver = nameserver_or_smtpserver; - return true; -}; - - // sets the senders address (fromAddress variable) - bool setsender(const std::string& newsender) { - if(!newsender.length()) - return false; - - Address newaddress(parseaddress(newsender)); - - fromAddress = newaddress; - return true; -}; - - // add a recipient to the recipient list. (maximum allowed recipients 100). - // returns true if the address could be added to the - // recipient list, otherwise false. - // recipient_type must be in the range mailer::TO -> mailer::BCC if - // not recipient_type defaults to BCC (blind copy), see const enum below. - bool addrecipient(const std::string& newrecipient, short recipient_type = TO /*CC, BCC*/) { - // SMTP only allows 100 recipients max at a time. - // rfc821 - if(recipients.size() >= 100) // == would be fine, but let's be stupid safe - return false; - - if(newrecipient.length()) { - // If there are no recipients yet - // set the server address for MX queries - if(!recipients.size()) { - server = getserveraddress(newrecipient); - } - - Address newaddress = parseaddress(newrecipient); - - if(recipient_type > Bcc || recipient_type < TO) - recipient_type = Bcc; // default to blind copy on error(hidden is better) - - recipients.push_back(std::make_pair(newaddress, recipient_type)); - return true; - } - return false; -}; - - // remove a recipient from the recipient list. - // returns true if the address could be removed from the - // recipient list, otherwise false. - bool removerecipient(const std::string& recipient) { - if(recipient.length()) { // there is something to remove - std::vector >::iterator it(recipients.begin()); - for(; it < recipients.end(); ++it) { - if((*it).first.address == recipient) { - recipients.erase(it); - return true; - } - } - // fall through as we did not find this recipient - } - return false; -}; - - // clear all recipients from the recipient list. - void clearrecipients() { - recipients.clear(); -}; - - // clear all attachments from the mail. - void clearattachments() { - attachments.clear(); -}; - - // clear all recipients, message, attachments, errors. - // does not reset the name/smtp server (use setserver for this) - // does not set the senders address (use setsender for this) - void reset() { - recipients.clear(); - attachments.clear(); - // fromAddress = ""; // assume the same sender. - // if this is to be changed use the setserver function to change it. - // nameserver = ""; // we don't do this as the same server is probably used!! - // leave auth type alone. - // leave username password pair alone. - server = ""; - message.clear(); - messageHTML.clear(); - returnstring = ""; // clear out any errors from previous use -}; - - // returns the return code sent by the smtp server or a local error. - // this is the only way to find if there is an error in processing. - // if the mail is sent correctly this string will begin with 250 - // see smtp RFC 821 section 4.2.2 for response codes. - const std::string& response() const { - return returnstring; -}; - - // Constants - // in unix we have to have a named object. - const static enum {TO, Cc, Bcc, SMTP_PORT = 25, DNS_PORT = 53} consts; - - // what type of authentication are we using. - // (if using authentication that is). - enum authtype {LOGIN = 1, PLAIN} type; - - // set the authentication type - // currently LOGIN or PLAIN only. - // The default login type is LOGIN, set in the constructor - void authtype(const enum authtype Type) { - assert(Type == LOGIN || Type == PLAIN); - type = Type; -}; - - // set the username for authentication. - // If this function is called with a non empty string - // jwSMTP will try to use authentication. - // To not use authentication after this, call again - // with the empty string e.g. - // mailerobject.username(""); - void username(const std::string& User) { - auth = (User.length() != 0); - user = User; -}; - // set the password for authentication - void password(const std::string& Pass) { - pass = Pass; -}; - -private: - // create a header with current message and attachments. - std::vector makesmtpmessage() const { - std::string sender(fromAddress.address); - if(sender.length()) { - std::string::size_type pos(sender.find("@")); - if(pos != std::string::npos) { //found the server beginning - sender = sender.substr(0, pos); - } - } - - std::vector ret; - std::string headerline; - if(fromAddress.name.length()) { - headerline = "From: " + fromAddress.address + " (" + fromAddress.name + ") \r\n" - "Reply-To: " + fromAddress.address + "\r\n"; - ret.insert(ret.end(), headerline.begin(), headerline.end()); - } - else { - headerline = "From: " + fromAddress.address + "\r\n" - "Reply-To: " + fromAddress.address + "\r\n"; - ret.insert(ret.end(), headerline.begin(), headerline.end()); - } - headerline.clear(); // clearout our temp variable - - // add the recipients to the header - std::vector to, cc, bcc; - for(recipient_const_iter recip = recipients.begin(); recip < recipients.end(); ++recip) { - if(recip->second == TO) { - to.push_back(recip->first.address); - } - else if(recip->second == Cc) { - cc.push_back(recip->first.address); - } - else if(recip->second == Bcc) { - bcc.push_back(recip->first.address); - } - } - vec_str_const_iter it; // instead of making three on the stack, just one (stops VC whining too) - // next section adds To: Cc: Bcc: lines to the header - int count = (int) to.size(); - if(count) - headerline += "To: "; - for(it = to.begin(); it < to.end(); ++it) { - headerline += *it; - if(count > 1 && ((it + 1) < to.end()) ) - headerline += ",\r\n "; // must add a space after the comma - else - headerline += "\r\n"; - } - count = (int) cc.size(); - if(count) - headerline += "Cc: "; - for(it = cc.begin(); it < cc.end(); ++it) { - headerline += *it; - if(count > 1 && ((it + 1) < cc.end()) ) - headerline += ",\r\n "; // must add a space after the comma - else - headerline += "\r\n"; - } - - // Remove insertion of the Bcc line into the header, I should never have done this, oopsy - // - //count = bcc.size(); - //if(count) - // headerline += "Bcc: "; - //for(it = bcc.begin(); it < bcc.end(); ++it) { - // headerline += *it; - // if(count > 1 && ((it + 1) < bcc.end()) ) - // headerline += ",\r\n "; // must add a space after the comma - // else - // headerline += "\r\n"; - //} - ret.insert(ret.end(), headerline.begin(), headerline.end()); - // end adding To: Cc: Bcc: lines to the header - - const std::string boundary("bounds=_NextP_0056wi_0_8_ty789432_tp"); - bool MIME(false); - if(attachments.size() || messageHTML.size()) - MIME = true; - - if(MIME) { // we have attachments - // use MIME 1.0 - headerline = "MIME-Version: 1.0\r\n" - "Content-Type: multipart/mixed;\r\n" - "\tboundary=\"" + boundary + "\"\r\n"; - ret.insert(ret.end(), headerline.begin(), headerline.end()); - headerline.clear(); - } - - /////////////////////////////////////////////////////////////////////////// - // add the current time. - // format is - // Date: 05 Jan 93 21:22:07 - // Date: 05 Jan 93 21:22:07 -0500 - // Date: 27 Oct 81 15:01:01 PST (RFC 821 example) - time_t t; - time(&t); - char timestring[128] = ""; - const char * timeformat = "Date: %d %b %y %H:%M:%S %Z"; - if(strftime(timestring, 127, timeformat, localtime(&t))) { // got the date - headerline = timestring; - headerline += "\r\n"; - ret.insert(ret.end(), headerline.begin(), headerline.end()); - } - /////////////////////////////////////////////////////////////////////////// - // add the subject - headerline = "Subject: " + subject + "\r\n\r\n"; - ret.insert(ret.end(), headerline.begin(), headerline.end()); - - /////////////////////////////////////////////////////////////////////////// - // - // everything else added is the body of the email message. - // - /////////////////////////////////////////////////////////////////////////// - - if(MIME) { - headerline = "This is a MIME encapsulated message\r\n\r\n"; - headerline += "--" + boundary + "\r\n"; - if(!messageHTML.size()) { - // plain text message first. - headerline += "Content-type: text/plain; charset=iso-8859-1\r\n" - "Content-transfer-encoding: 7BIT\r\n\r\n"; - - ret.insert(ret.end(), headerline.begin(), headerline.end()); - ret.insert(ret.end(), message.begin(), message.end()); - headerline = "\r\n\r\n--" + boundary + "\r\n"; - } - else { // make it multipart/alternative as we have html - const std::string innerboundary("inner_jfd_0078hj_0_8_part_tp"); - headerline += "Content-Type: multipart/alternative;\r\n" - "\tboundary=\"" + innerboundary + "\"\r\n"; - - // need the inner boundary starter. - headerline += "\r\n\r\n--" + innerboundary + "\r\n"; - - // plain text message first. - headerline += "Content-type: text/plain; charset=iso-8859-1\r\n" - "Content-transfer-encoding: 7BIT\r\n\r\n"; - ret.insert(ret.end(), headerline.begin(), headerline.end()); - ret.insert(ret.end(), message.begin(), message.end()); - headerline = "\r\n\r\n--" + innerboundary + "\r\n"; - /////////////////////////////////// - // Add html message here! - headerline += "Content-type: text/html; charset=iso-8859-1\r\n" - "Content-Transfer-Encoding: base64\r\n\r\n"; - - ret.insert(ret.end(), headerline.begin(), headerline.end()); - ret.insert(ret.end(), messageHTML.begin(), messageHTML.end()); - headerline = "\r\n\r\n--" + innerboundary + "--\r\n"; - - // end the boundaries if there are no attachments - if(!attachments.size()) - headerline += "\r\n--" + boundary + "--\r\n"; - else - headerline += "\r\n--" + boundary + "\r\n"; - /////////////////////////////////// - } - ret.insert(ret.end(), headerline.begin(), headerline.end()); - headerline.clear(); - - // now add each attachment. - for(vec_pair_char_str_const_iter it1 = attachments.begin(); - it1 != attachments.end(); ++ it1) { - if(it1->second.length() > 3) { // long enough for an extension - std::string typ(it1->second.substr(it1->second.length()-4, 4)); - if(typ == ".gif") { // gif format presumably - headerline += "Content-Type: image/gif;\r\n"; - } - else if(typ == ".jpg" || typ == "jpeg") { // j-peg format presumably - headerline += "Content-Type: image/jpg;\r\n"; - } - else if(typ == ".txt") { // text format presumably - headerline += "Content-Type: plain/txt;\r\n"; - } - else if(typ == ".bmp") { // windows bitmap format presumably - headerline += "Content-Type: image/bmp;\r\n"; - } - else if(typ == ".htm" || typ == "html") { // hypertext format presumably - headerline += "Content-Type: plain/htm;\r\n"; - } - else if(typ == ".png") { // portable network graphic format presumably - headerline += "Content-Type: image/png;\r\n"; - } - else if(typ == ".exe") { // application - headerline += "Content-Type: application/X-exectype-1;\r\n"; - } - else { // add other types - // everything else - headerline += "Content-Type: application/X-other-1;\r\n"; - } - } - else { - // default to don't know - headerline += "Content-Type: application/X-other-1;\r\n"; - } - - headerline += "\tname=\"" + it1->second + "\"\r\n"; - headerline += "Content-Transfer-Encoding: base64\r\n"; - headerline += "Content-Disposition: attachment; filename=\"" + it1->second + "\"\r\n\r\n"; - ret.insert(ret.end(), headerline.begin(), headerline.end()); - headerline.clear(); - - ret.insert(ret.end(), it1->first.begin(), it1->first.end()); - - // terminate the message with the boundary + "--" - if((it1 + 1) == attachments.end()) - headerline += "\r\n\r\n--" + boundary + "--\r\n"; - else - headerline += "\r\n\r\n--" + boundary + "\r\n"; - ret.insert(ret.end(), headerline.begin(), headerline.end()); - headerline.clear(); - } - } - else // just a plain text message only - ret.insert(ret.end(), message.begin(), message.end()); - - // end the data in the message. - headerline = "\r\n.\r\n"; - ret.insert(ret.end(), headerline.begin(), headerline.end()); - - return ret; -}; - - // this breaks a message line up to be less than 1000 chars per line. - // keeps words intact also --- rfc821 - // Check line returns are in the form "\r\n" - // (qmail balks otherwise, i.e. LAME server) - // also if a period is on a line by itself add a period - // stops prematurely ending the mail before whole message is sent. - void checkRFCcompat(){ - // Check the line breaks. - std::vector::iterator it; - for(it = message.begin(); it != message.end(); ++it) { - // look for \n add \r before if not there. Pretty lame but still. - // haven't thought of a better way yet. - if(*it == '\n') { - if(it == message.begin()) { - it = message.insert(it, '\r'); - ++it; // step past newline - continue; - } - if((*(it -1) != '\r') ) { - // add a return before '\n' - it = message.insert(it, '\r'); - ++it; // step past newline - } - } - } - - // if we get a period on a line by itself - // add another period to stop the server ending the mail prematurely. - // ( suggested by david Irwin ) - if(message.size() == 1) { - if(*(message.begin()) == '.') - message.push_back('.'); - } - else if(message.size() == 2) { - if(*(message.begin()) == '.') { - it = message.begin(); - it = message.insert(it, '.'); - } - } - else { - if(*(message.begin()) == '.') { - it = message.begin(); - it = message.insert(it, '.'); - } - for(it = message.begin()+2; it != message.end(); ++it) { - // follow the rfc. Add '.' if the first character on a line is '.' - if(*it == '\n') { - if( ((it + 1) != message.end()) && (*(it +1) == '.') ) { - it = message.insert(it + 1, '.'); - ++it; // step past - } - } - } - } - - // don't do anything if we are not longer than a 1000 characters - if(message.size() < 1000) - return; - - // now we have checked line breaks - // check line lengths. - int count(1); - for(it = message.begin(); it < message.end(); ++it, ++count) { - if(*it == '\r') { - count = 0; // reset for a new line. - ++it; // get past newline - continue; - } - else if(count >= 998) { - ++it; - if(*it != ' ') { // we are not in a word!! - // it should never get to message.begin() because we - // start at least 998 chars into the message! - // Also, assume a word isn't bigger than 997 chars! (seems reasonable) - std::vector::iterator pos = it; - for(int j = 0; j < 997; ++j, --pos) { - if(*pos == ' ') { - it = ++pos; // get past the space. - break; - } - } - } - if(it < message.end()) - it = message.insert(it, '\r'); - ++it; - if(it < message.end()) - it = message.insert(it, '\n'); - count = 0; // reset for a new line. - } - } - count=1; // reset the count - if(messageHTML.size()) { - for(it = messageHTML.begin(); it < messageHTML.end(); ++it, ++count) { - if(*it == '\r') { - count = 0; // reset for a new line. - ++it; // get past newline - continue; - } - else if(count >= 998) { - ++it; - if(*it != ' ') { // we are in a word!! - // it should never get to message.begin() because we - // start at least 998 chars into the message! - // Also, assume a word isn't bigger than 997 chars! (seems reasonable) - std::vector::iterator pos = it; - for(int j = 0; j < 997; ++j, --pos) { - if(*pos == ' ') { - it = ++pos; // get past the space. - break; - } - } - } - if(it < messageHTML.end()) - it = messageHTML.insert(it, '\r'); - ++it; - if(it < messageHTML.end()) - it = messageHTML.insert(it, '\n'); - count = 0; // reset for a new line. - } - } - } -}; - - // helper function. - // returns the part of the string toaddress after the @ symbol. - // i.e. the 'toaddress' is an email address eg. someone@somewhere.com - // this function returns 'somewhere.com' - std::string getserveraddress(const std::string& toaddress) const { - if(toaddress.length()) { - std::string::size_type pos(toaddress.find("@")); - if(pos != std::string::npos) { //found the server beginning - if(++pos < toaddress.length()) - return toaddress.substr(pos, toaddress.length()- pos); - } - } - return ""; -}; - - // Does the work of getting MX records for the server returned by 'getserveraddress' - // will use the dns server passed to this's constructor in 'nameserver' - // or if MXlookup is false in the constuctor, will return an address - // for the server that 'getserveraddress' returns. - // returns false on failure, true on success - bool gethostaddresses(std::vector& adds) { - adds.clear(); // be safe in case of my utter stupidity - - SOCKADDR_IN addr(nameserver, htons(DNS_PORT), AF_INET); - - hostent* host = 0; - if(addr) - host = gethostbyaddr(addr.get_sin_addr(), sizeof(addr.ADDR.sin_addr), AF_INET); - else - host = gethostbyname(nameserver.c_str()); - - if(!host) { // couldn't get to dns, try to connect directly to 'server' instead. - //////////////////////////////////////////////////////////////////////////////// - // just try to deliver mail directly to "server" - // as we didn't get an MX record. - // addr.sin_family = AF_INET; - addr = SOCKADDR_IN(server, port); - addr.ADDR.sin_port = port; // smtp port!! 25 - if(addr) { - host = gethostbyaddr(addr.get_sin_addr(), sizeof(addr.ADDR.sin_addr), AF_INET); - } - else - host = gethostbyname(server.c_str()); - - if(!host) { - returnstring = "550 Requested action not taken: mailbox unavailable"; - return false; // error!!! - } - - //memcpy((char*)&addr.sin_addr, host->h_addr, host->h_length); - std::copy(host->h_addr_list[0], host->h_addr_list[0] + host->h_length, addr.get_sin_addr()); - adds.push_back(addr); - - return true; - } - else - //memcpy((char*)&addr.sin_addr, host->h_addr, host->h_length); - std::copy(host->h_addr_list[0], host->h_addr_list[0] + host->h_length, addr.get_sin_addr()); - - SOCKET s; - if(!Socket(s, AF_INET, SOCK_DGRAM, 0)) { - returnstring = "451 Requested action aborted: socket function error"; - return false; - } - - if(!Connect(s, addr)) { - returnstring = "451 Requested action aborted: dns server unavailable"; - return false; // dns connection unavailable - } - - // dnsheader info id flags num queries - unsigned char dns[512] = {1,1, 1,0, 0,1, 0,0, 0,0, 0,0}; - int dnspos = 12; // end of dns header - std::string::size_type stringpos(0); - std::string::size_type next(server.find(".")); - if(next != std::string::npos) { // multipart name e.g. "aserver.somewhere.net" - while(stringpos < server.length()) { - std::string part(server.substr(stringpos, next-stringpos)); - dns[dnspos] = (unsigned char) part.length(); - ++dnspos; - for(std::string::size_type i = 0; i < part.length(); ++i, ++dnspos) { - dns[dnspos] = part[i]; - } - - stringpos = ++next; - next = server.find(".", stringpos); - if(next == std::string::npos) { - part = server.substr(stringpos, server.length() - stringpos); - dns[dnspos] = (unsigned char) part.length(); - ++dnspos; - for(std::string::size_type i = 0; i < part.length(); ++i, ++dnspos) { - dns[dnspos] = part[i]; - } - break; - } - } - } - else { // just a single part name. e.g. "aserver" - dns[dnspos] = (unsigned char) server.length(); - ++dnspos; - - for(std::string::size_type i = 0; i < server.length(); ++i, ++dnspos) { - dns[dnspos] = server[i]; - } - } - // in case the server string has a "." on the end - if(server[server.length()-1] == '.') - dns[dnspos] = 0; - else - dns[dnspos++] = 0; - - // add the class & type - dns[dnspos++] = 0; - dns[dnspos++] = 15; // MX record. - - dns[dnspos++] = 0; - dns[dnspos++] = 1; - - // used to have MSG_DONTROUTE this breaks obviously if you are not - // running a local nameserver and using it (as I used to do so I didn't - // notice until now, oops) - int ret; - if(!Send(ret, s, (char*)dns, dnspos, 0)) { - returnstring = "451 Requested action aborted: server seems to have disconnected."; - Closesocket(s); // clean up - return false; - } - if(Recv(ret, s, (char*)dns, 512, 0)) { - Closesocket(s); - // now parse the data sent back from the dns for MX records - if(dnspos > 12) { // we got more than a dns header back - unsigned short numsitenames = ((unsigned short)dns[4]<<8) | dns[5]; - unsigned short numanswerRR = ((unsigned short)dns[6]<<8) | dns[7]; - unsigned short numauthorityRR = ((unsigned short)dns[8]<<8) | dns[9]; - unsigned short numadditionalRR = ((unsigned short)dns[10]<<8) | dns[11]; - - if(!(dns[3] & 0x0F)) { // check for an error - // int auth((dns[2] & 0x04)); // AA bit. the nameserver has given authoritive answer. - int pos = 12; // start after the header. - - std::string questionname; - if(numsitenames) { - parsename(pos, dns, questionname); - pos += 4; // move to the next RR - } - - // This gives this warning in VC. - // bloody annoying, there is a way round it according to microsoft. - // The debugger basically cannot browse anything with a name - // longer than 256 characters, "get with the template program MS". - // #pragma warning( disable : 4786 ) - // #pragma warning( default : 4786 ) - std::vector names; - in_addr address; - std::string name; - // VC++ incompatability scoping - // num should be able to be declared in every for loop here - // not in VC - int num = 0; - for(; num < numanswerRR; ++num) { - name = ""; - parseRR(pos, dns, name, address); - if(name.length()) - names.push_back(name); - } - for(num = 0; num < numauthorityRR; ++num) { - name = ""; - parseRR(pos, dns, name, address); - if(name.length()) - names.push_back(name); - } - for(num = 0; num < numadditionalRR; ++num) { - name = ""; - parseRR(pos, dns, name, address); - if(name.length()) - names.push_back(name); - } - - // now get all the MX records IP addresess - addr.ADDR.sin_family = AF_INET; - addr.ADDR.sin_port = port; // smtp port!! 25 - hostent* host = 0; - for(vec_str_const_iter it = names.begin(); it < names.end(); ++it) { - host = gethostbyname(it->c_str()); - if(!host) { - addr.zeroaddress(); - continue; // just skip it!!! - } - std::copy(host->h_addr_list[0], host->h_addr_list[0] + host->h_length, addr.get_sin_addr()); - adds.push_back(addr); - } - // got the addresses - return true; - } - } - } - else - Closesocket(s); - // what are we doing here!! - return false; -}; - - // Parses a dns Resource Record (see TCP/IP illustrated, STEVENS, page 194) - bool parseRR(int& pos, const unsigned char dns[], std::string& name, in_addr& address) { - if(pos < 12) // didn,t get more than a header. - return false; - if(pos > 512) // oops. - return false; - - int len = dns[pos]; - if(len >= 192) { // pointer - int pos1 = dns[++pos]; - len = dns[pos1]; - } - else { // not a pointer. - parsename(pos, dns, name); - } - // If I do not seperate getting the short values to different - // lines of code, the optimizer in VC++ only increments pos once!!! - unsigned short a = ((unsigned short)dns[++pos]<<8); - unsigned short b = dns[++pos]; - unsigned short Type = a | b; - a = ((unsigned short)dns[++pos]<<8); - b = dns[++pos]; - // unsigned short Class = a | b; - pos += 4; // ttl - a = ((unsigned short)dns[++pos]<<8); - b = dns[++pos]; - unsigned short Datalen = a | b; - if(Type == 15) { // MX record - // first two bytes the precedence of the MX server - a = ((unsigned short)dns[++pos]<<8); - b = dns[++pos]; - // unsigned short order = a | b; // we don't use this here - len = dns[++pos]; - if(len >= 192) { - int pos1 = dns[++pos]; - parsename(pos1, dns, name); - } - else - parsename(pos, dns, name); - } - else if(Type == 12) { // pointer record - pos += Datalen+1; - } - else if(Type == 2) { // nameserver - pos += Datalen+1; - } - else if(Type == 1) { // IP address, Datalen should be 4. - pos += Datalen+1; - } - else { - pos += Datalen+1; - } - return true; -}; - - // Parses a dns name returned in a dns query (see TCP/IP illustrated, STEVENS, page 192) - void parsename(int& pos, const unsigned char dns[], std::string& name) { - int len = dns[pos]; - if(len >= 192) { - int pos1 = ++pos; - ++pos; - parsename(pos1, dns, name); - } - else { - for(int i = 0; i < len; ++i) - name += dns[++pos]; - len = dns[++pos]; - if(len != 0) - name += "."; - if(len >= 192) { - int pos1 = dns[++pos]; - ++pos; - parsename(pos1, dns, name); - } - else if(len > 0) { - parsename(pos, dns, name); - } - else if(len == 0) - ++pos; - } -}; - - // email address wrapper struct - struct Address { - std::string name; // e.g. freddy foobar - std::string address; // e.g. someone@mail.com - }; - - // authenticate against a server. - bool authenticate(const std::string& servergreeting, const SOCKET& s) { - assert(auth && user.length()); // shouldn't be calling this function if this is not set! - int len(0); - if(!user.length()) { // obvioulsy a big whoops - Send(len, s, "QUIT\r\n", 6, 0); - return false; - } - - // now parse the servergreeting looking for the auth type 'type' - // if 'type' is not present exit with error (return false) - std::string at; - if(type == LOGIN) - at = "LOGIN"; - else if(type == PLAIN) - at = "PLAIN"; - else { // oopsy no other auth types yet!! MUST BE A BUG - assert(false); - returnstring = "554 jwSMTP only handles LOGIN or PLAIN authentication at present!"; - Send(len, s, "QUIT\r\n", 6, 0); - return false; - } - - // uppercase servergreeting first. - std::string greeting(servergreeting); - //char ch; - for(std::string::size_type pos = 0; pos < greeting.length(); ++pos) { - //ch = greeting[pos]; - greeting[pos] = toupper(greeting[pos] /*ch*/); - } - if(greeting.find(at) == std::string::npos) { - returnstring = "554 jwSMTP only handles LOGIN or PLAIN authentication at present!"; - Send(len, s, "QUIT\r\n", 6, 0); - return false; // didn't find that type of login! - } - - // ok try and authenticate to the server. - const int buffsize(1024); - char buff[buffsize]; - if(type == LOGIN) { - greeting = "auth " + at + "\r\n"; - if(!Send(len, s, greeting.c_str(), greeting.length(), 0)) { - returnstring = "554 send failure: \"auth " + at + "\""; - return false; - } - if(!Recv(len, s, buff, buffsize, 0)) { - returnstring = "554 receive failure: waiting on username question!"; - return false; - } - buff[len] = '\0'; - returnstring = buff; - - // The server should give us a "334 VXNlcm5hbWU6" base64 username - if(returnstring.substr(0,16) != "334 VXNlcm5hbWU6") { - // returnstring = "554 Server did not return correct response to \'auth login\' command"; - Send(len, s, "QUIT\r\n", 6, 0); - return false; - } - greeting = base64encode(user, false) + "\r\n"; - if(!Send(len, s, greeting.c_str(), greeting.length(), 0)) { - returnstring = "554 send failure: sending username"; - return false; - } - // now get the password question - if(!Recv(len, s, buff, buffsize, 0)) { - returnstring = "554 receive failure: waiting on password question!"; - return false; - } - buff[len] = '\0'; - returnstring = buff; - // The server should give us a "334 UGFzc3dvcmQ6" base64 password - if(returnstring.substr(0,16) != "334 UGFzc3dvcmQ6") { - // returnstring = "554 Server did not return correct password question"; - Send(len, s, "QUIT\r\n", 6, 0); - return false; - } - greeting = base64encode(pass, false) + "\r\n"; - if(!Send(len, s, greeting.c_str(), greeting.length(), 0)) { - returnstring = "554 send failure: sending password"; - return false; - } - // now see if we are authenticated. - if(!Recv(len, s, buff, buffsize, 0)) { - returnstring = "554 receive failure: waiting on auth login response!"; - return false; - } - buff[len] = '\0'; - returnstring = buff; - if(returnstring.substr(0,3) == "235") - return true; - } - // PLAIN authetication - else if(type == PLAIN) { // else if not needed, being anal - // now create the authentication response and send it. - // username\0username\0password\r\n - // i.e. \0fred\0secret\r\n (blank identity) - std::vector enc; - std::string::size_type pos = 0; - for(; pos < user.length(); ++pos) - enc.push_back(user[pos]); - enc.push_back('\0'); - for(pos = 0; pos < user.length(); ++pos) - enc.push_back(user[pos]); - enc.push_back('\0'); - for(pos = 0; pos < pass.length(); ++pos) - enc.push_back(pass[pos]); - - enc = base64encode(enc, false); - greeting = "auth plain "; - for(std::vector::const_iterator it1 = enc.begin(); it1 < enc.end(); ++it1) - greeting += *it1; - greeting += "\r\n"; - - if(!Send(len, s, greeting.c_str(), greeting.length(), 0)) { - returnstring = "554 send failure: sending login:plain authenication info"; - return false; - } - if(!Recv(len, s, buff, buffsize, 0)) { - returnstring = "554 receive failure: waiting on auth plain autheticated response!"; - return false; - } - buff[len] = '\0'; - returnstring = buff; - if(returnstring.substr(0,3) == "235") - return true; - } - - // fall through return an error. - Send(len, s, "QUIT\r\n", 6, 0); - return false; -}; - - // less typing later, these are definately abominations! - typedef std::vector, std::string> >::const_iterator vec_pair_char_str_const_iter; - typedef std::vector >::const_iterator recipient_const_iter; - typedef std::vector >::iterator recipient_iter; - typedef std::vector::const_iterator vec_str_const_iter; - - // split an address into its relevant parts i.e. - // name and actual address and return it in Address. - // this may be usefull out of the class maybe - // it should be a static function or a global? thinking about it. - Address parseaddress(const std::string& addresstoparse) { - Address newaddress; // return value - - // do some silly checks - if(!addresstoparse.length()) - return newaddress; // its empty, oops (this should fail at the server.) - - if(!addresstoparse.find("@") == std::string::npos) { - // no '@' symbol (could be a local address, e.g. root) - // so just assume this. The SMTP server should just deny delivery if its messed up! - newaddress.address = addresstoparse; - return newaddress; - } - // we have one angle bracket but not the other - // (this isn't strictly needed, just thought i'd throw it in) - if(((addresstoparse.find('<') != std::string::npos) && - (addresstoparse.find('>') == std::string::npos)) || - ((addresstoparse.find('>') != std::string::npos) && - (addresstoparse.find('<') == std::string::npos))) { - return newaddress; // its empty, oops (this should fail at the server.) - } - - // we have angle bracketed delimitered address - // like this maybe: - // "foo@bar.com" - // or "foo bar " - // or " foo bar" - if((addresstoparse.find('<') != std::string::npos) && - (addresstoparse.find('>') != std::string::npos)) { - std::string::size_type sta = addresstoparse.find('<'); - std::string::size_type end = addresstoparse.find('>'); - - newaddress.address = addresstoparse.substr(sta + 1, end - sta - 1); - - if(sta > 0) { // name at the beginning - // we are cutting off the last character if the bracket address - // continues without a space into the bracketed address - // e.g. "hoopla girl" - // name becomes 'hoopla gir' - // Fix by David Irwin - // old code: - // end = sta -1; - // newaddress.name = addresstoparse.substr(0, end); - newaddress.name = addresstoparse.substr(0, sta); - return newaddress; - } - else { // name at the end - // no name to get - if(end >= addresstoparse.length()-1) - return newaddress; - - end += 2; - if(end >= addresstoparse.length()) - return newaddress; - - newaddress.name = addresstoparse.substr(end, addresstoparse.length()- end); - // remove whitespace from end if need be - if(newaddress.name[newaddress.name.length()-1] == ' ') - newaddress.name = newaddress.name.substr(0, newaddress.name.length()-1); - return newaddress; - } - } - // if we get here assume an address of the form: foo@bar.com - // and just save it. - newaddress.address = addresstoparse; - - return newaddress; -}; - - // The addresses to send the mail to - std::vector > recipients; - // The address the mail is from. - Address fromAddress; - // Subject of the mail - std::string subject; - // The contents of the mail message - std::vector message; - // The contents of the mail message in html format. - std::vector messageHTML; - // attachments: the file as a stream of char's and the name of the file. - std::vector, std::string> > attachments; - // This will be filled in from the toAddress by getserveraddress - std::string server; - // Name of a nameserver to query - std::string nameserver; - // The port to mail to on the smtp server. - const unsigned short port; - // use dns to query for MX records - const bool lookupMXRecord; - // using authentication - bool auth; - // username for authenticated smtp - std::string user; - // password for authenticated smtp - std::string pass; - // filled in with server return strings - std::string returnstring; -}; - -} // end namespace jwsmtp - -#endif // !ifndef __CM_MAILER_H__ diff --git a/server/src/cm_mon_stat.cpp b/server/src/cm_mon_stat.cpp deleted file mode 100644 index 42504ab..0000000 --- a/server/src/cm_mon_stat.cpp +++ /dev/null @@ -1,1943 +0,0 @@ -/* - * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. - * - * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - -#include - -#include "cm_log.h" -#include "json/json.h" -#include "cm_config.h" -#include "cm_job_task.h" -#include "cm_server_interface.h" -#include "cm_mon_stat.h" -#include "cm_server_extend_interface.h" - -#include -#include -#include - -using namespace std; - -#define DEFAULT_MON_STAT_INTERVAL 60 - -#define MON_DATA_BLOCK ((24 * 60 * 60) / _meta[K_INTERVAL].asInt() + 30 * 24 + 365) -/* MB_SIZE = 1024 * 1024 */ -#define MB_SIZE (1048576) - -// Initial metric value -#define INIT_METRIC_VALUE -1 - -/* monitoring data file names */ -#define META_NAME "meta.json" -#define BROKER_MON "broker_mon" -#define DB_MON "db_mon" -#define VOL_MON "vol_mon" -#define HA_MON "ha_mon" -#define OS_MON "os_mon" -/* end of monitoring data file names */ - -typedef struct -{ - const char *metric; - int pfactor; - bool ddiff; -} T_METRIC; - -/* broker metrics */ -/* two unused metrics*/ -#define BROKER_METRICS_LEN 10 - -#define BROKER_TPS "broker_tps" -#define BROKER_QPS "broker_qps" -#define BROKER_LONG_T "broker_long_t" -#define BROKER_LONG_Q "broker_long_q" -#define BROKER_REQ "broker_req" -#define BROKER_ERR_Q "broker_err_q" -#define BROKER_JQ "broker_jq" - -const T_METRIC BROKER_METRICS[BROKER_METRICS_LEN] = -{ - {BROKER_TPS, 1, true}, - {BROKER_QPS, 1, true}, - {BROKER_LONG_T, 1, true}, - {BROKER_LONG_Q, 1, true}, - {BROKER_REQ, 1, true}, - {BROKER_ERR_Q, 1, true}, - {BROKER_JQ, 1, false}, - {"none1", 1, false}, - {"none2", 1, false}, - {"uptime", 1, false} // uptime must be the last one -}; - -/* DB metrics */ -/* two unused metrics */ -#define DB_METRICS_LEN 19 - -#define DB_CPU_KERNEL "db_cpu_kernel" -#define DB_CPU_USER "db_cpu_user" -#define DB_MEM_PHY "db_mem_phy" -#define DB_MEM_VIR "db_mem_vir" -#define DB_QPS "db_qps" -#define DB_TPS "db_tps" -#define DB_HIT_RATIO "db_hit_ratio" -#define DB_FETCH_PAGES "db_fetch_pages" -#define DB_DIRTY_PAGES "db_dirty_pages" -#define DB_IO_READ "db_io_read" -#define DB_IO_WRITE "db_io_write" -/* HA metrics for DB */ -#define DB_HA_COPY_DELAY_PAGE "db_ha_copy_delay_page" -#define DB_HA_COPY_DELAY_ESTIMATED "db_ha_copy_delay_estimated" -#define DB_HA_APPLY_DELAY_PAGE "db_ha_apply_delay_page" -#define DB_HA_APPLY_DELAY_ESTIMATED "db_ha_apply_delay_estimated" - -#define DB_FREESPACE "db_freespace" - -const T_METRIC DB_METRICS[DB_METRICS_LEN] = -{ - {DB_CPU_KERNEL, 1, true}, - {DB_CPU_USER, 1, true}, - {DB_MEM_PHY, 100, false}, - {DB_MEM_VIR, 100, false}, - {DB_QPS, 1, true}, - {DB_TPS, 1, true}, - {DB_HIT_RATIO, 1, false}, - {DB_FETCH_PAGES, 1, true}, - {DB_DIRTY_PAGES, 1, true}, - {DB_IO_READ, 1, true}, - {DB_IO_WRITE, 1, true}, - {DB_HA_COPY_DELAY_PAGE, 1, true}, - {DB_HA_COPY_DELAY_ESTIMATED, 1, false}, - {DB_HA_APPLY_DELAY_PAGE, 1, true}, - {DB_HA_APPLY_DELAY_ESTIMATED, 1, false}, - {DB_FREESPACE, 100, false}, - {"none1", 1, false}, - {"none2", 1, false}, - {"uptime", 1, false} // uptime must be the last one -}; - -// volume free sapce is a special metrics for DB -#define VOL_FREESPACE "vol_freespace" -#define VOL_METRICS_LEN 2 - -/* OS metrics */ -/* two unused metrics */ -#define OS_METRICS_LEN 10 - -#define OS_CPU_IDLE "os_cpu_idle" -#define OS_CPU_IOWAIT "os_cpu_iowait" -#define OS_CPU_KERNEL "os_cpu_kernel" -#define OS_CPU_USER "os_cpu_user" -#define OS_MEM_PHY_FREE "os_mem_phy_free" -#define OS_MEM_SWAP_FREE "os_mem_swap_free" -#define OS_DISK_FREE "os_disk_free" - -const T_METRIC OS_METRICS[OS_METRICS_LEN] = -{ - {OS_CPU_IDLE, 1, true}, - {OS_CPU_IOWAIT, 1, true}, - {OS_CPU_KERNEL, 1, true}, - {OS_CPU_USER, 1, true}, - {OS_MEM_PHY_FREE, 100, false}, - {OS_MEM_SWAP_FREE, 100, false}, - {OS_DISK_FREE, 100, false}, - {"none1", 1, false}, - {"none2", 1, false}, - {"uptime", 1, false} // uptime must be the last one -}; - -/* end metrics define */ - -/* meta key word */ -#define K_INTERVAL "k_interval" -#define K_TOTAL_VOL_NUM "k_total_vol_num" - -#define K_BROKER_METRICS "k_broker_metrics" -#define K_BROKER_NUM "k_broker_num" -#define K_BROKER_RRD "k_broker_rrd" - -#define K_DB_METRICS "k_db_metrics" -#define K_DB_NUM "k_db_num" -#define K_DB_RRD "k_db_rrd" - -#define K_OS_METRICS "k_os_metrics" -#define K_OS_RRD "k_os_rrd" - -#define K_BROKER_HOUR_AGG_TIME "k_broker_hour_agg_time" -#define K_DB_HOUR_AGG_TIME "k_db_hour_agg_time" -#define K_OS_HOUR_AGG_TIME "k_os_hour_agg_time" - -#define K_BROKER_DAILY_AGG_TIME "k_broker_daily_agg_time" -#define K_DB_DAILY_AGG_TIME "k_db_daily_agg_time" -#define K_OS_DAILY_AGG_TIME "k_os_daily_agg_time" -/* end meta key word */ - -#define JSON_ATOI(x) (atoi((x).asString().c_str())) -#if defined(WINDOWS) -#define JSON_ATOL(x) (_atoi64((x).asString().c_str())) -#define CPU_BASE_FEQ_WIN 1000000 -#else -#define JSON_ATOL(x) (atoll((x).asString().c_str())) -#endif - -static bool init_rrdfile (string filename, int rrdsize, int metrics_len); -static bool get_rrdfile (string filename, int rrdpos, int *buf, int bufsize, int metrics_len); -static bool append_rrdfile (string filename, int rrdsize, int metrics_len); -static bool update_rrdfile (string filename, int rrdpos, int *buf, int bufsize, int mlen); -static bool call_task (Json::Value &req, Json::Value &res, T_TASK_FUNC func, string &errmsg); -static bool get_dbs_list (Json::Value &db_list); -static bool get_active_dbs_list (Json::Value &db_list); -static bool get_brokers_list (Json::Value &brokers_list); -static bool get_volume_list (string dbname, Json::Value &vol_list); -static void mon_last (int *buf, int bufsize, int *agg_data, int idx, int mlen, int pfactor = 1); -static void mon_avg (int *buf, int bufsize, int *agg_data, int idx, int mlen, int pfactor = 1); -static void mon_diff_avg (int *buf, int bufsize, int *agg_data, int idx, int mlen, int interval, int pfactor = 1); -static bool call_task_ext (Json::Value &req, Json::Value &res, T_EXT_TASK_FUNC func); -static bool mdtype_from_str (const string &dtype, MDTYPE &mdtype); - -class scope_lock -{ - public: - scope_lock (MUTEX_T &mutex):_mutex (mutex) - { - MUTEX_LOCK (_mutex); - } - ~scope_lock() - { - MUTEX_UNLOCK (_mutex); - } - private: - MUTEX_T _mutex; -}; - -cm_mon_stat *cm_mon_stat::_instance = NULL; - -cm_mon_stat::cm_mon_stat (string data_path): - _data_path (data_path + "/"), - _meta_file (_data_path + META_NAME) -{ - _daily_idx = -1; - _monthly_idx = -1; - _yearly_idx = -1; - _prev_gather = 0; - _init = false; - MUTEX_INIT (_data_mutex); -} - -cm_mon_stat *cm_mon_stat::get_instance() -{ - if (NULL == _instance) - { - _instance = new cm_mon_stat (sco.sMonStatDataPath); - } - return _instance; -} - -bool cm_mon_stat::get_mon_interval (time_t &interval) const -{ - if (true == _init) - { - interval = _meta[K_INTERVAL].asInt(); - return true; - } - else - { - return false; - } -} - -bool cm_mon_stat::set_mon_interval (time_t interval) -{ - if (false == _init) - { - return false; - } - if (_meta[K_INTERVAL].asInt() == interval) - { - return true; - } - try - { - return reset_meta ((int) interval); - } - catch (exception &) - { - return false; - } -} - -bool cm_mon_stat::initial() -{ - try - { - if (access (_meta_file.c_str(), F_OK) < 0) /* file not exist */ - { - _init = init_meta (DEFAULT_MON_STAT_INTERVAL); - } - else - { - _init = load_meta_file(); - } - } - catch (exception &) - { - _init = false; - } - return _init; -} - -void cm_mon_stat::gather_mon_data (void) -{ - - time_t gather_time = time (NULL); - //try { - if ((0 != _prev_gather) - && (gather_time - _prev_gather < _meta[K_INTERVAL].asInt())) - { - return; - } - if (false == _init) - { - LOG_WARN ("monitoring statistic module is not initialized"); - return; - } - scope_lock slocker (_data_mutex); - - if (false == get_dbs_list (_dbs)) - { - LOG_WARN ("get dbs list failed, time=[%d]", gather_time); - return; - } - - if (false == get_brokers_list (_brokers)) - { - LOG_WARN ("get brokers list failed, time=[%d]", gather_time); - return; - } - - - gather_daily_brokers_mon (gather_time); - gather_daily_dbs_mon (gather_time); - gather_daily_os_mon (gather_time); - _daily_idx = (gather_time % (60 * 60 * 24)) / _meta[K_INTERVAL].asInt(); - - aggregate_2_hour (gather_time); - _monthly_idx = (gather_time % ( 30 * 60 * 60 * 24)) / 3600; - - aggregate_2_day (gather_time); - _yearly_idx = (gather_time % ( 365 * 60 * 60 * 24)) / (3600 * 24); - - _prev_gather = gather_time; - //} - //catch (...) { - // LOG_WARN("gather_mon_data end with exception, time=[%d]", gather_time); - //} -} - -void cm_mon_stat::aggregate_2_hour (time_t gather_time) -{ - int monthly_idx = (gather_time % ( 30 * 60 * 60 * 24)) / 3600; - int buf_base = 3600/_meta[K_INTERVAL].asInt(); - int read_offset = 0; - - if (0 == _daily_idx) - { - read_offset += (23 * 3600) / _meta[K_INTERVAL].asInt(); - } - else - { - read_offset += _daily_idx - (3600 / _meta[K_INTERVAL].asInt()); - } - - int write_offset = 24 * 3600 / _meta[K_INTERVAL].asInt() + monthly_idx; - - aggregate_brokers (read_offset, buf_base, write_offset, HOUR, gather_time); - aggregate_dbs (read_offset, buf_base, write_offset, HOUR, gather_time); - aggregate_os (read_offset, buf_base, write_offset, HOUR, gather_time); -} - -void cm_mon_stat::aggregate_2_day (time_t gather_time) -{ - int yearly_idx = (gather_time % ( 365 * 60 * 60 * 24)) / (3600 * 24); - int buf_base = 24; - int read_offset = 24 * 3600 /_meta[K_INTERVAL].asInt(); - - if (0 == _monthly_idx) - { - read_offset += 29 * 24; - } - else - { - read_offset += _monthly_idx - 24; - } - - int write_offset = 24 * 3600 / _meta[K_INTERVAL].asInt() + 30 * 24 + yearly_idx; - - aggregate_brokers (read_offset, buf_base, write_offset, DAY, gather_time); - aggregate_dbs (read_offset, buf_base, write_offset, DAY, gather_time); - aggregate_os (read_offset, buf_base, write_offset, DAY, gather_time); -} - -void cm_mon_stat::aggregate_os (int read_offset, - int buf_base, - int write_offset, - AGG_TYPE atype, - time_t gather_time) -{ - string key; - int mod = 0; - if (HOUR == atype) - { - key = K_OS_HOUR_AGG_TIME; - mod = 3600; - } - else - { - key = K_OS_DAILY_AGG_TIME; - mod = 3600 * 24; - } - - if (Json::Value::null != _meta[key]) - { - time_t last_time = _meta[key].asInt(); - if (last_time / mod >= gather_time / mod) - { - return; - } - } - int bufsize = buf_base * OS_METRICS_LEN; - int *buf = new (int[bufsize]); - if (false == get_rrdfile (_data_path + OS_MON, read_offset, buf, bufsize, OS_METRICS_LEN)) - { - LOG_WARN ("read os rrd file failed"); - delete [] buf; - return; - } - - int agg_data[OS_METRICS_LEN]; - memset (agg_data, 0, OS_METRICS_LEN * sizeof (int)); - for (int i = 0; i < 4; i++) - { - if (HOUR == atype) - { - mon_diff_avg (buf, bufsize, agg_data, i, OS_METRICS_LEN, _meta[K_INTERVAL].asInt()); - } - else - { - mon_avg (buf, bufsize, agg_data, i, OS_METRICS_LEN); - } - } - mon_avg (buf, bufsize, agg_data, 4, OS_METRICS_LEN, 100); - mon_avg (buf, bufsize, agg_data, 5, OS_METRICS_LEN, 100); - mon_last (buf, bufsize, agg_data, 6, OS_METRICS_LEN, 100); - agg_data[7] = 0; - agg_data[8] = 0; - agg_data[9] = int (gather_time); - - update_rrdfile (_data_path + OS_MON, write_offset, agg_data, OS_METRICS_LEN, OS_METRICS_LEN); - _meta[key] = int (gather_time); - flush_meta_file(); - delete [] buf; -} - -void cm_mon_stat::aggregate_dbs (int read_offset, - int buf_base, - int write_offset, - AGG_TYPE atype, - time_t gather_time) -{ - string key; - int mod = 0; - if (HOUR == atype) - { - key = K_DB_HOUR_AGG_TIME; - mod = 3600; - } - else - { - key = K_DB_DAILY_AGG_TIME; - mod = 3600 * 24; - } - if (Json::Value::null != _meta[key]) - { - time_t last_time = _meta[key].asInt(); - if (last_time / mod >= gather_time / mod) - { - return; - } - } - - // Fix for CUBRIDSUS-11976 - Json::Value active_dbs; - if (false == get_active_dbs_list (active_dbs)) - { - LOG_WARN ("get active dbs list failed, time=[%d]", gather_time); - return; - } - - for (unsigned int i = 0; i < active_dbs.size(); i++) - { - string dbname = active_dbs[i].asString(); - if (false == _meta[K_DB_RRD].isMember (dbname + "_idx")) - { - LOG_WARN ("can't find db [%s] index in meta file", dbname.c_str()); - continue; - } - int db_idx = _meta[K_DB_RRD][dbname + "_idx"].asInt(); - int read_idx = db_idx * MON_DATA_BLOCK + read_offset; - - int bufsize = buf_base * DB_METRICS_LEN; - int *buf = new (int[bufsize]); - - if (false == get_rrdfile (_data_path + DB_MON, read_idx, buf, bufsize, DB_METRICS_LEN)) - { - LOG_WARN ("read db rrd file failed"); - delete [] buf; - return; - } - - int agg_data[DB_METRICS_LEN]; - memset (agg_data, 0, DB_METRICS_LEN * sizeof (int)); - - if (HOUR == atype) - { - mon_diff_avg (buf, bufsize, agg_data, 0, DB_METRICS_LEN, _meta[K_INTERVAL].asInt()); - agg_data[0] = agg_data[0] / _meta[K_INTERVAL].asInt(); - mon_diff_avg (buf, bufsize, agg_data, 1, DB_METRICS_LEN, _meta[K_INTERVAL].asInt()); - agg_data[1] = agg_data[1] / _meta[K_INTERVAL].asInt(); - } - else - { - mon_avg (buf, bufsize, agg_data, 0, DB_METRICS_LEN); - mon_avg (buf, bufsize, agg_data, 1, DB_METRICS_LEN); - } - mon_avg (buf,bufsize, agg_data, 2, DB_METRICS_LEN, 100); - mon_avg (buf,bufsize, agg_data, 3, DB_METRICS_LEN, 100); - if (HOUR == atype) - { - mon_diff_avg (buf, bufsize, agg_data, 4, DB_METRICS_LEN, _meta[K_INTERVAL].asInt()); - agg_data[4] = agg_data[4] / _meta[K_INTERVAL].asInt(); - mon_diff_avg (buf, bufsize, agg_data, 5, DB_METRICS_LEN, _meta[K_INTERVAL].asInt()); - agg_data[5] = agg_data[5] / _meta[K_INTERVAL].asInt(); - } - else - { - mon_avg (buf, bufsize, agg_data, 4, DB_METRICS_LEN); - mon_avg (buf, bufsize, agg_data, 5, DB_METRICS_LEN); - } - mon_avg (buf,bufsize, agg_data, 6, DB_METRICS_LEN); - for (unsigned int i = 7; i < 11; i++) - { - if (HOUR == atype) - { - mon_diff_avg (buf,bufsize, agg_data, i, DB_METRICS_LEN, _meta[K_INTERVAL].asInt()); - agg_data[i] /= _meta[K_INTERVAL].asInt(); - } - else - { - mon_avg (buf,bufsize, agg_data, i, DB_METRICS_LEN); - } - } - // HA metrics - if (HOUR == atype) - { - mon_diff_avg (buf,bufsize, agg_data, 11, DB_METRICS_LEN, _meta[K_INTERVAL].asInt()); - agg_data[11] /= _meta[K_INTERVAL].asInt(); - } - else - { - mon_avg (buf,bufsize, agg_data, 11, DB_METRICS_LEN); - } - mon_avg (buf,bufsize, agg_data, 12, DB_METRICS_LEN); - if (HOUR == atype) - { - mon_diff_avg (buf,bufsize, agg_data, 13, DB_METRICS_LEN, _meta[K_INTERVAL].asInt()); - agg_data[13] /= _meta[K_INTERVAL].asInt(); - } - else - { - mon_avg (buf,bufsize, agg_data, 13, DB_METRICS_LEN); - } - mon_avg (buf,bufsize, agg_data, 14, DB_METRICS_LEN); - mon_last (buf,bufsize, agg_data, 15, DB_METRICS_LEN, 100); - agg_data[16] = 0; - agg_data[17] = 0; - agg_data[18] = int (gather_time); - - int rrdpos = db_idx * MON_DATA_BLOCK + write_offset; - update_rrdfile (_data_path + DB_MON, rrdpos, agg_data, DB_METRICS_LEN, DB_METRICS_LEN); - - // volume - Json::Value vols; - if (false == get_volume_list (dbname, vols)) - { - continue; - } - - for (unsigned int i = 0; i < vols.size(); i++) - { - string vol_name = vols[i].asString(); - if (false == _meta[K_DB_RRD][dbname + "_vol"].isMember (vol_name)) - { - LOG_WARN ("can't find db [%s] vol[%s] index in meta file", dbname.c_str(), vol_name.c_str()); - continue; - } - int vol_idx = _meta[K_DB_RRD][dbname + "_vol"][vol_name].asInt(); - int read_idx = vol_idx * MON_DATA_BLOCK + read_offset; - int bufsize_vol = buf_base * VOL_METRICS_LEN; - int *buf_vol = new (int[bufsize_vol]); - if (false == get_rrdfile (_data_path + VOL_MON, read_idx, buf_vol, bufsize_vol, VOL_METRICS_LEN)) - { - LOG_WARN ("read volume rrd file failed"); - delete [] buf; - delete [] buf_vol; - return; - } - int agg_data[VOL_METRICS_LEN]; - memset (agg_data, 0, VOL_METRICS_LEN * sizeof (int)); - mon_last (buf_vol,bufsize_vol,agg_data,0,VOL_METRICS_LEN, 100); - agg_data[1] = int (gather_time); - - int rrdpos = vol_idx * MON_DATA_BLOCK + write_offset; - update_rrdfile (_data_path + VOL_MON, rrdpos, agg_data, VOL_METRICS_LEN, VOL_METRICS_LEN); - delete [] buf_vol; - } - delete [] buf; - } - _meta[key] = int (gather_time); - flush_meta_file(); -} - -static bool mdtype_from_str (const string &dtype, MDTYPE &mdtype) -{ - if ("daily" == dtype) - { - mdtype = DAILY; - } - else if ("weekly" == dtype) - { - mdtype = WEEKLY; - } - else if ("monthly" == dtype) - { - mdtype = MONTHLY; - } - else if ("yearly" == dtype) - { - mdtype = YEARLY; - } - else - { - return false; - } - return true; -} - -bool cm_mon_stat::get_mon_statistic (const Json::Value req, Json::Value &res, string &errmsg) const -{ - if (false == _init) - { - errmsg = "monitoring staticstic module is not initialized"; - LOG_WARN (errmsg.c_str()); - return false; - } - string metric = req["metric"].asString(); - if (OS_CPU_IDLE == metric - || OS_CPU_IOWAIT == metric - || OS_CPU_KERNEL == metric - || OS_CPU_USER == metric - || DB_CPU_KERNEL == metric - || DB_CPU_USER == metric) - { - if (false == m_get_mon_statistic (req, res, errmsg)) - { - return false; - } - - Json::Value os_idle_req, os_idle_res; - os_idle_req = req; - os_idle_req["metric"] = OS_CPU_IDLE; - if (false == m_get_mon_statistic (os_idle_req, os_idle_res, errmsg)) - { - res.removeMember ("data"); - return false; - } - - Json::Value os_iowait_req, os_iowait_res; - os_iowait_req = req; - os_iowait_req["metric"] = OS_CPU_IOWAIT; - if (false == m_get_mon_statistic (os_iowait_req, os_iowait_res, errmsg)) - { - res.removeMember ("data"); - return false; - } - - Json::Value os_kernel_req, os_kernel_res; - os_kernel_req = req; - os_kernel_req["metric"] = OS_CPU_KERNEL; - if (false == m_get_mon_statistic (os_kernel_req, os_kernel_res, errmsg)) - { - res.removeMember ("data"); - return false; - } - - Json::Value os_user_req, os_user_res; - os_user_req = req; - os_user_req["metric"] = OS_CPU_USER; - if (false == m_get_mon_statistic (os_user_req, os_user_res, errmsg)) - { - res.removeMember ("data"); - return false; - } - - for (unsigned int i = 0; i < res["data"].size(); i++) - { - if (res["data"][i].asInt() == INIT_METRIC_VALUE) - { - continue; - } - else if (os_idle_res["data"][i].asInt() != INIT_METRIC_VALUE - && os_iowait_req["data"][i].asInt() != INIT_METRIC_VALUE - && os_kernel_res["data"][i].asInt() != INIT_METRIC_VALUE - && os_user_res["data"][i].asInt() != INIT_METRIC_VALUE) - { - int total = os_idle_res["data"][i].asInt() + os_iowait_req["data"][i].asInt() - + os_kernel_res["data"][i].asInt() + os_user_res["data"][i].asInt(); - if (total <= 0) - { - res["data"][i] = 0; - } - else - { - // Because of percentage and accurating to the second decimal places, - // so it should be multiply by 10000. - res["data"][i] = int (float (res["data"][i].asInt()) * 10000 / total); - } - } - else - { - res["data"][i] = INIT_METRIC_VALUE; - } - } - return true; - } - else - { - return m_get_mon_statistic (req, res, errmsg); - } -} - -// the data maybe wrong for the begin of the return data array -bool cm_mon_stat::m_get_mon_statistic (const Json::Value req, Json::Value &res, string &errmsg) const -{ - res["metric"] = req["metric"]; - res["dtype"] = req["dtype"]; - - string metric = req["metric"].asString(); - - MDTYPE mdtype = DAILY; - if (false == mdtype_from_str (req["dtype"].asString(), mdtype)) - { - errmsg = string ("Error format of dtype [") + req["dtype"].asString() + "] in request"; - LOG_WARN (errmsg.c_str()); - return false; - } - - int m_idx = 0; - int i = 0; - int pfactor = 1; - bool d_diff = false; - - if (0 == strncmp ("db_", metric.c_str(), strlen ("db_"))) - { - string dbname = req["dbname"].asString(); - res["dbname"] = dbname; - if (false == _meta[K_DB_RRD].isMember (dbname + "_idx")) - { - errmsg = string ("Can't find dbname[") + dbname + "] in meta[k_db_rrd]"; - LOG_WARN (errmsg.c_str()); - return false; - } - int db_idx = _meta[K_DB_RRD][dbname + "_idx"].asInt(); - for (i = 0; i < DB_METRICS_LEN; i++) - { - if (DB_METRICS[i].metric == metric) - { - m_idx = i; - pfactor = DB_METRICS[i].pfactor; - d_diff = DB_METRICS[i].ddiff; - break; - } - } - if (i == DB_METRICS_LEN) - { - errmsg = string ("Can't find DB metric[") + metric + "] from request"; - LOG_WARN (errmsg.c_str()); - return false; - } - string data_path = _data_path + DB_MON; - return get_rrd_data (mdtype, data_path, db_idx, m_idx, pfactor, d_diff, DB_METRICS_LEN, res, errmsg); - } - - if (0 == strncmp ("vol_", metric.c_str(), strlen ("vol_"))) - { - string dbname = req["dbname"].asString(); - string volname = req["volname"].asString(); - res["dbname"] = dbname; - res["volname"] = volname; - if (false == _meta[K_DB_RRD].isMember (dbname + "_vol")) - { - errmsg = string ("Can't find dbname_vol[") + dbname + "] in meta[k_db_rrd]"; - LOG_WARN (errmsg.c_str()); - return false; - } - if (false == _meta[K_DB_RRD][dbname + "_vol"].isMember (volname)) - { - errmsg = string ("Can't find volname[") + volname + "] in DB [" + dbname + "] meta[k_db_rrd]"; - LOG_WARN (errmsg.c_str()); - return false; - } - int vol_idx = _meta[K_DB_RRD][dbname + "_vol"][volname].asInt(); - if (VOL_FREESPACE != metric) - { - errmsg = string ("Can't find volume metric[") + metric + "] from request"; - LOG_WARN (errmsg.c_str()); - return false; - } - string data_path = _data_path + VOL_MON; - return get_rrd_data (mdtype, data_path, vol_idx, m_idx, 100, d_diff, VOL_METRICS_LEN, res, errmsg); - } - - if (0 == strncmp ("broker_", metric.c_str(), strlen ("broker_"))) - { - string bname = req["bname"].asString(); - res["bname"] = bname; - if (false == _meta[K_BROKER_RRD].isMember (bname + "_idx")) - { - errmsg = string ("Can't find broker [") + bname + "] in meta[k_db_rrd]"; - LOG_WARN (errmsg.c_str()); - return false; - } - int b_idx = _meta[K_BROKER_RRD][bname + "_idx"].asInt(); - for (i = 0; i < BROKER_METRICS_LEN; i++) - { - if (BROKER_METRICS[i].metric == metric) - { - m_idx = i; - pfactor = BROKER_METRICS[i].pfactor; - d_diff = BROKER_METRICS[i].ddiff; - break; - } - } - if (i == BROKER_METRICS_LEN) - { - errmsg = string ("Can't find broker metric[") + metric + "] from request"; - LOG_WARN (errmsg.c_str()); - return false; - } - string data_path = _data_path + BROKER_MON; - return get_rrd_data (mdtype, data_path, b_idx, m_idx, pfactor, d_diff, BROKER_METRICS_LEN, res, errmsg); - } - - if (0 == strncmp ("os_", metric.c_str(), strlen ("os_"))) - { - for (i = 0; i < OS_METRICS_LEN; i++) - { - if (OS_METRICS[i].metric == metric) - { - m_idx = i; - pfactor = OS_METRICS[i].pfactor; - d_diff = OS_METRICS[i].ddiff; - break; - } - } - if (i == OS_METRICS_LEN) - { - errmsg = string ("Can't find os metric[") + metric + "] from request"; - LOG_WARN (errmsg.c_str()); - return false; - } - string data_path = _data_path + OS_MON; - return get_rrd_data (mdtype, data_path, 0, m_idx, pfactor, d_diff, OS_METRICS_LEN, res, errmsg); - } - - return false; -} - -bool cm_mon_stat::get_rrd_data (MDTYPE mdtype, string dpath, int didx, - int midx, int pfactor, bool ddiff, int mlen, - Json::Value &res, string &errmsg) const -{ - int read_rrd_idx = didx * MON_DATA_BLOCK; - int bufsize = 0; - switch (mdtype) - { - case DAILY: - bufsize = mlen * (24 * 60 * 60 / _meta[K_INTERVAL].asInt()); - break; - case WEEKLY: - case MONTHLY: - bufsize = mlen * 30 * 24; - read_rrd_idx += 24 * 60 * 60 / _meta[K_INTERVAL].asInt(); - break; - case YEARLY: - bufsize = mlen * 365; - read_rrd_idx += 24 * 60 * 60 / _meta[K_INTERVAL].asInt() + 24 * 30; - break; - } - int *buf = new (int[bufsize]); - if (false == get_rrdfile (dpath, read_rrd_idx, buf, bufsize, mlen)) - { - errmsg = string ("read rrd file failed [") + dpath + "]"; - LOG_WARN (errmsg.c_str()); - delete [] buf; - return false; - } - - time_t cur_time = time (NULL); - int read_buf_idx = 0; - int daily_mod = (3600 * 24) / _meta[K_INTERVAL].asInt(); - switch (mdtype) - { - case DAILY: - read_buf_idx = _daily_idx < 0 ? - (cur_time % (60 * 60 * 24)) / _meta[K_INTERVAL].asInt():_daily_idx + 1; - if (true == ddiff) - { - // Smoothing data functionality is added - int value = INIT_METRIC_VALUE; - int start = 0; // for count the num if the it's not updated from the beginning - for (int i = 1; i < daily_mod; i++) - { - int cur = buf[ ((read_buf_idx + i) % daily_mod) * mlen + midx]; - int cur_up = buf[ ((read_buf_idx + i) % daily_mod) * mlen + mlen - 1]; - int pre = buf[ ((read_buf_idx + i - 1) % daily_mod) * mlen + midx]; - int pre_up = buf[ ((read_buf_idx + i - 1) % daily_mod) * mlen + mlen - 1]; - if ((cur_up < pre_up) || (cur_up - pre_up > 2 * _meta[K_INTERVAL].asInt())) - { - if (-1 != start) - { - start++; - } - else - { - res["data"].append (value); // using last value - } - } - else - { - if (cur == INIT_METRIC_VALUE) - { - value = INIT_METRIC_VALUE; - } - else if (pre == INIT_METRIC_VALUE) - { - value = int ((float (cur) * (100/pfactor)) / _meta[K_INTERVAL].asInt()); - } - else - { - value = int ((float (cur >= pre ? cur - pre: cur) * (100/pfactor)) / _meta[K_INTERVAL].asInt()); - } - res["data"].append (value); - if (-1 != start) // If from the start, add extra value - { - while (start >= 0) - { - res["data"].append (value); - start--; - } - } - } - } - if (Json::Value::null == res["data"]) - { - for (int i = 0; i < daily_mod; i++) - { - res["data"].append (0); - } - } - } - else - { - for (int i = read_buf_idx; i < read_buf_idx + daily_mod; i++) - { - res["data"].append (buf[ (i % daily_mod) * mlen + midx] * (100/pfactor)); - } - } - break; - case WEEKLY: - read_buf_idx = _monthly_idx < 0 ? (cur_time % (30 * 60 * 60 * 24)) / 3600 :_monthly_idx + 1; - read_buf_idx += 30 * 24; - for (int i = read_buf_idx - 24*7; i < read_buf_idx; i++) - { - res["data"].append (buf[ (i% (30*24)) * mlen + midx]); - } - break; - case MONTHLY: - read_buf_idx = _monthly_idx < 0 ? (cur_time % (30 * 60 * 60 * 24)) / 3600 :_monthly_idx + 1; - for (int i = read_buf_idx; i < 30 * 24 + read_buf_idx; i++) - { - res["data"].append (buf[ (i% (30*24)) * mlen + midx]); - } - break; - case YEARLY: - read_buf_idx = _yearly_idx < 0 ? (cur_time % (365 * 3600 * 24)) / (3600*24) :_yearly_idx + 1; - for (int i = read_buf_idx; i < 365; i++) - { - res["data"].append (buf[i * mlen + midx]); - } - for (int i = 0; i < read_buf_idx; i++) - { - res["data"].append (buf[i * mlen + midx]); - } - break; - } - delete [] buf; - return true; -} - -static bool get_volume_list (string dbname, Json::Value &vol_list) -{ - Json::Value req, res; - req["dbname"] = dbname; - req["_DBNAME"] = dbname; - string errmsg; - if (false == call_task (req, res, tsDbspaceInfo, errmsg)) - { - LOG_WARN ("call getdbspaceinfo failed, error code[%d], error message [%s]", - res["retval"].asInt(), errmsg.c_str()); - return false; - } - for (unsigned int i = 0; i < res["spaceinfo"].size(); i++) - { - vol_list.append (res["spaceinfo"][i]["spacename"].asString()); - } - return true; -} - -void cm_mon_stat::aggregate_brokers (int read_offset, - int buf_base, - int write_offset, - AGG_TYPE atype, - time_t gather_time) -{ - string key; - int mod = 0; - if (HOUR == atype) - { - key = K_BROKER_HOUR_AGG_TIME; - mod = 3600; - } - else - { - key = K_BROKER_DAILY_AGG_TIME; - mod = 3600 * 24; - } - if (Json::Value::null != _meta[key]) - { - time_t last_time = _meta[key].asInt(); - if (last_time / mod >= gather_time / mod) - { - return; - } - } - - for (unsigned int i = 0; i < _brokers.size(); i++) - { - string bname = _brokers[i].asString(); - if (false == _meta[K_BROKER_RRD].isMember (bname + "_idx")) - { - LOG_WARN ("can't find broker [%s] index in meta file", bname.c_str()); - continue; - } - int broker_idx = _meta[K_BROKER_RRD][bname + "_idx"].asInt(); - - int read_idx = broker_idx * MON_DATA_BLOCK + read_offset; - - int bufsize = buf_base * BROKER_METRICS_LEN; - int *buf = new (int[bufsize]); - - if (false == get_rrdfile (_data_path + BROKER_MON, read_idx, buf, bufsize, BROKER_METRICS_LEN)) - { - LOG_WARN ("read broker rrd file failed"); - delete [] buf; - return; - } - - int agg_data[BROKER_METRICS_LEN]; - memset (agg_data, 0, BROKER_METRICS_LEN * sizeof (int)); - for (int i = 0; i < 6; i ++) - { - if (HOUR == atype) - { - mon_diff_avg (buf, bufsize, agg_data, i, BROKER_METRICS_LEN, _meta[K_INTERVAL].asInt()); - agg_data[i] = agg_data[i] / _meta[K_INTERVAL].asInt(); - } - else - { - mon_avg (buf, bufsize, agg_data, i, BROKER_METRICS_LEN); - } - } - mon_avg (buf, bufsize, agg_data, 6, BROKER_METRICS_LEN); - agg_data[7] = 0; - agg_data[8] = 0; - agg_data[9] = int (gather_time); - - int rrdpos = broker_idx * MON_DATA_BLOCK + write_offset; - update_rrdfile (_data_path + BROKER_MON, rrdpos, agg_data, BROKER_METRICS_LEN, BROKER_METRICS_LEN); - delete [] buf; - } - _meta[key] = int (gather_time); - flush_meta_file(); -} - -static void mon_last (int *buf, int bufsize, int *agg_data, int idx, int mlen, int pfactor) -{ - if (buf[bufsize - mlen + idx] != INIT_METRIC_VALUE) - { - agg_data[idx] = buf[bufsize - mlen + idx] * (100 / pfactor); - } - else - { - agg_data[idx] = 0; - } -} - -// pfactor is used to control the precision, the default is accurating to 2 decimal places - -static void mon_avg (int *buf, int bufsize, int *agg_data, int idx, int mlen, int pfactor) -{ - int count = 0; - for (int i = 0; i < bufsize/mlen; i++) - { - if (buf[i * mlen + idx] != INIT_METRIC_VALUE) - { - agg_data[idx] += buf[i * mlen + idx]; - count++; - } - } - if (count != 0) - { - agg_data[idx] = agg_data[idx] * (100/pfactor) / count; - } - else - { - agg_data[idx] = 0; - } -} - -// pfactor is used to control the precision, the default is accurating to 2 decimal places - -static void mon_diff_avg (int *buf, int bufsize, int *agg_data, int idx, int mlen, int interval, int pfactor) -{ - int count = 0; - for (int i = 0; i < bufsize/mlen - 1; i++) - { - int pre = buf[i * mlen + idx]; - int pre_up = buf[i * mlen + mlen - 1]; - int next = buf[ (i + 1) * mlen + idx]; - int next_up = buf[ (i + 1) * mlen + mlen - 1]; - if (next == INIT_METRIC_VALUE) - { - continue; - } - if (pre == INIT_METRIC_VALUE) - { - agg_data[idx] += next; - count++; - continue; - } - if ((pre <= next) && (next_up > pre_up) && (next_up - pre_up < 2*interval)) - { - agg_data[idx] += (next - pre); - count++; - } - } - if (0 != count) - { - agg_data[idx] = agg_data[idx] * (100/pfactor) / count; - } - else - { - agg_data[idx] = 0; - } -} - -void cm_mon_stat::gather_daily_brokers_mon (time_t gather_time) -{ - int broker_data[BROKER_METRICS_LEN]; - memset (broker_data, 0, BROKER_METRICS_LEN * sizeof (int)); - - int daily_idx = (gather_time % (60 * 60 * 24)) / _meta[K_INTERVAL].asInt(); - - Json::Value req, brokers_info; - string errmsg; - if (false == call_task (req, brokers_info, ts2_get_unicas_info, errmsg)) - { - LOG_ERROR ("failed to get brokers infomation, time=[%d], error code[%d], error message [%s]", - gather_time, brokers_info["retval"].asInt(), errmsg.c_str()); - return; - } - if (brokers_info.isMember ("brokersinfo")) - { - for (unsigned int i = 0; i < brokers_info["brokersinfo"][0u]["broker"].size(); i++) - { - Json::Value &bdata = brokers_info["brokersinfo"][0u]["broker"][i]; - string bname = bdata["name"].asString(); - - // resize broker rrdfile - if (false == _meta[K_BROKER_RRD].isMember (bname + "_idx")) - { - if (false == append_rrdfile (_data_path + BROKER_MON, MON_DATA_BLOCK, BROKER_METRICS_LEN)) - { - continue; - } - _meta[K_BROKER_RRD][bname + "_idx"] = _meta[K_BROKER_NUM].asInt(); - _meta[K_BROKER_NUM] = _meta[K_BROKER_NUM].asInt() + 1; - if (false == flush_meta_file()) - { - continue; - } - } - - broker_data[0] = JSON_ATOI (bdata["tran"]); - broker_data[1] = JSON_ATOI (bdata["query"]); - broker_data[2] = JSON_ATOI (bdata["long_tran"]); - broker_data[3] = JSON_ATOI (bdata["long_query"]); - broker_data[4] = JSON_ATOI (bdata["req"]); - broker_data[5] = JSON_ATOI (bdata["error_query"]); - broker_data[6] = JSON_ATOI (bdata["jq"]); - broker_data[7] = 0; - broker_data[8] = 0; - broker_data[9] = int (gather_time); - - int broker_idx = _meta[K_BROKER_RRD][bname+"_idx"].asInt(); - int rrdpos = broker_idx * MON_DATA_BLOCK + daily_idx; - update_rrdfile (_data_path + BROKER_MON, rrdpos, broker_data, BROKER_METRICS_LEN, BROKER_METRICS_LEN); - } - } - else - { - LOG_ERROR ("error format of brokers infomation, time=[%d]", gather_time); - } -} - -bool cm_mon_stat::gather_dbs_tran_query (time_t gather_time, Json::Value &db_tq) -{ - string bstr = _brokers[0u].asString(); - - for (unsigned int i = 1; i < _brokers.size(); i ++) - { - bstr += "," + _brokers[i].asString(); - } - - Json::Value as_req, as_res; - as_req["bname"] = bstr; - string errmsg; - if (false != call_task (as_req, as_res, ts2_get_broker_status, errmsg)) - { - Json::Value b_as; - // more than one broker - if (as_res.isMember ("broker")) - { - b_as = as_res["broker"]; - } - else if (as_res.isMember ("asinfo")) // one broker - { - b_as.append (as_res); - } - else - { - LOG_WARN ("get broker status failed, time=[%d]", gather_time); - return false; - } - - for (unsigned int i = 0; i < b_as.size(); i++) - { - for (unsigned int j = 0; j < b_as[i]["asinfo"].size(); j++) - { - string dbname = b_as[i]["asinfo"][j]["as_dbname"].asString(); - if (0 != dbname.length()) - { - if (db_tq.isMember (dbname)) - { - db_tq[dbname]["query"] = db_tq[dbname]["query"].asInt() + JSON_ATOI (b_as[i]["asinfo"][j]["as_num_query"]); - db_tq[dbname]["tran"] = db_tq[dbname]["tran"].asInt() + JSON_ATOI (b_as[i]["asinfo"][j]["as_num_tran"]); - } - else - { - db_tq[dbname]["query"] = JSON_ATOI (b_as[i]["asinfo"][j]["as_num_query"]); - db_tq[dbname]["tran"] = JSON_ATOI (b_as[i]["asinfo"][j]["as_num_tran"]); - } - } - } - } - } - else - { - LOG_WARN ("get brokers status failed, time=[%d], error code [%d], error message [%s]", - gather_time, as_res["retval"].asInt(), errmsg.c_str()); - return false; - } - return true; -} - -void cm_mon_stat::gather_daily_dbs_mon (time_t gather_time) -{ - int db_data[DB_METRICS_LEN]; - Json::Value db_tq; - if (false == gather_dbs_tran_query (gather_time, db_tq)) - { - return; - } - - int daily_idx = (gather_time % (60 * 60 * 24)) / _meta[K_INTERVAL].asInt(); - - Json::Value active_dbs; - if (false == get_active_dbs_list (active_dbs)) - { - LOG_WARN ("get active dbs list failed, time=[%d]", gather_time); - return; - } - - Json::Value ha_req, ha_res; - ha_req["task"] = "ha_status"; - bool has_ha_info = false; - string errmsg; - string ha_rmt_hostname; - if (true == call_task (ha_req, ha_res, ts_ha_status, errmsg)) - { - has_ha_info = true; - if ("master" == ha_res["current_node_state"].asString()) - { - ha_rmt_hostname = ha_res["nodeA"].asString(); - } - else - { - ha_rmt_hostname = ha_res["nodeB"].asString(); - } - } - else if (ERR_SYSTEM_CALL != ha_res["retval"].asInt()) - { - LOG_WARN ("Get HA status failed, time=[%d], error code [%d], error message [%s]", - gather_time, ha_res["retval"].asInt(), errmsg.c_str()); - } - - for (unsigned int i = 0; i < active_dbs.size(); i++) - { - memset (db_data, 0, DB_METRICS_LEN * sizeof (int)); - string dbname = active_dbs[i].asString(); - // resize db rrdfile - if (false == _meta[K_DB_RRD].isMember (dbname + "_idx")) - { - if (false == append_rrdfile (_data_path + DB_MON, MON_DATA_BLOCK, DB_METRICS_LEN)) - { - LOG_WARN ("append rrd file for new db failed, time=[%d]", gather_time); - continue; - } - _meta[K_DB_RRD][dbname + "_idx"] = _meta[K_DB_NUM].asInt(); - _meta[K_DB_NUM] = _meta[K_DB_NUM].asInt() + 1; - if (false == flush_meta_file()) - { - LOG_WARN ("flush meta file failed, time=[%d]", gather_time); - continue; - } - } - - Json::Value req, res; - req["dbname"] = dbname; - req["_DBNAME"] = dbname; - errmsg = ""; - if (false == call_task (req, res, ts_get_dbproc_stat, errmsg)) - { - LOG_WARN ("call getdbprocstatus failed, time=[%d], error code[%d], error message [%s]", - gather_time, res["retval"].asInt(), errmsg.c_str()); - continue; - } -#if defined(WINDOWS) - db_data[0] = JSON_ATOI (res["dbstat"][0u]["cpu_kernel"]) / CPU_BASE_FEQ_WIN; - db_data[1] = JSON_ATOI (res["dbstat"][0u]["cpu_user"]) / CPU_BASE_FEQ_WIN; -#else - db_data[0] = JSON_ATOI (res["dbstat"][0u]["cpu_kernel"]); - db_data[1] = JSON_ATOI (res["dbstat"][0u]["cpu_user"]); -#endif - db_data[2] = int (JSON_ATOL (res["dbstat"][0u]["mem_physical"]) * 100 / MB_SIZE); - db_data[3] = int (JSON_ATOL (res["dbstat"][0u]["mem_virtual"]) * 100 / MB_SIZE); - if (db_tq.isMember (dbname)) - { - db_data[4] = db_tq[dbname]["query"].asInt(); - db_data[5] = db_tq[dbname]["tran"].asInt(); - } - else - { - db_data[4] = 0; - db_data[5] = 0; - } - - //statdump - res.clear(); - errmsg = ""; - if (false == call_task (req, res, ts_statdump, errmsg)) - { - LOG_WARN ("call statdump failed, time=[%d], error code[%d], error message [%s]", - gather_time, res["retval"].asInt(), errmsg.c_str()); - continue; - } - db_data[6] = JSON_ATOI (res["data_page_buffer_hit_ratio"]); - db_data[7] = JSON_ATOI (res["num_data_page_fetches"]); - db_data[8] = JSON_ATOI (res["num_data_page_dirties"]); - db_data[9] = JSON_ATOI (res["num_file_ioreads"]); - db_data[10] = JSON_ATOI (res["num_file_iowrites"]); - - // HA monitoring - if (true == has_ha_info) - { - // TODO: HA monitoring - for (unsigned int i = 0; i < ha_res["ha_info"].size(); i++) - { - if (dbname == ha_res["ha_info"][i]["dbname"].asString()) - { - Json::Value req, res; - req["task"] = "gethaapplyinfo"; - req["dbname"] = dbname; - req["remotehostname"] = ha_rmt_hostname; - string copylog = ha_res["ha_info"][i]["copylogdb"].asString(); - unsigned int colon_idx = (unsigned int) copylog.find (':'); - if (string::npos == colon_idx) - { - LOG_WARN ("Error format of copylogdb, time=[%d], copylogdb=[%s]", - gather_time, req["copylogdb"].asString().c_str()); - break; - } - req["copylogpath"] = copylog.substr (colon_idx + 1); - if (false == call_task_ext (req, res, ext_get_ha_apply_info)) - { - LOG_WARN ("Get HA apply info failed, time=[%d], dbname=[%s]", - gather_time, req["dbname"].asString().c_str()); - break; - } - db_data[11] = JSON_ATOI (res["copyinglog_coun"]); - db_data[12] = JSON_ATOI (res["copyinglog_estimated_time"]); - db_data[13] = JSON_ATOI (res["applyinglog_count"]); - db_data[14] = JSON_ATOI (res["applyinglog_estimated_time"]); - } - } - } - - // dbspaceinfo - res.clear(); - req["_DBNAME"] = dbname; - errmsg = ""; - if (false == call_task (req, res, tsDbspaceInfo, errmsg)) - { - LOG_WARN ("call getdbspaceinfo failed, time=[%d], error code[%d], error message [%s]", - gather_time, res["retval"].asInt(), errmsg.c_str()); - continue; - } - db_data[15] = int (JSON_ATOL (res["freespace"]) * JSON_ATOL (res["pagesize"]) * 100 / MB_SIZE); - db_data[16] = 0; - db_data[17] = 0; - db_data[18] = int (gather_time); - - // update rrdfile - int rrdpos = _meta[K_DB_RRD][dbname + "_idx"].asInt() * MON_DATA_BLOCK + daily_idx; - update_rrdfile (_data_path +"/"+ DB_MON, rrdpos, db_data, DB_METRICS_LEN, DB_METRICS_LEN); - // volume - for (unsigned int i = 0; i < res["spaceinfo"].size(); i++) - { - string vol_name = res["spaceinfo"][i]["spacename"].asString(); - if (false == _meta[K_DB_RRD][dbname + "_vol"].isMember (vol_name)) - { - if (0 == _meta[K_TOTAL_VOL_NUM].asInt()) - { - init_rrdfile (_data_path + VOL_MON, MON_DATA_BLOCK, VOL_METRICS_LEN); - } - else - { - append_rrdfile (_data_path + VOL_MON, MON_DATA_BLOCK, VOL_METRICS_LEN); - } - _meta[K_DB_RRD][dbname + "_vol"][vol_name] = _meta[K_TOTAL_VOL_NUM].asInt(); - _meta[K_TOTAL_VOL_NUM] = _meta[K_TOTAL_VOL_NUM].asInt() + 1; - if (false == flush_meta_file()) - { - LOG_WARN ("flush meta file failed, time=[%d]", gather_time); - continue; - } - } - - // in MB - int vol_data[VOL_METRICS_LEN]; - vol_data[0] = int (JSON_ATOL (res["spaceinfo"][i]["freepage"]) - * JSON_ATOL (res["pagesize"]) * 100 / MB_SIZE); - vol_data[1] = int (gather_time); - int vol_idx = _meta[K_DB_RRD][dbname + "_vol"][vol_name].asInt(); - int rrdpos = vol_idx * MON_DATA_BLOCK + daily_idx; - update_rrdfile (_data_path +"/"+ VOL_MON, rrdpos, vol_data, VOL_METRICS_LEN, VOL_METRICS_LEN); - } - } -} - -void cm_mon_stat::gather_daily_os_mon (time_t gather_time) -{ - int os_data[OS_METRICS_LEN]; - memset (os_data, 0, OS_METRICS_LEN * sizeof (int)); - int daily_idx = (gather_time % (60 * 60 * 24)) / _meta[K_INTERVAL].asInt(); - - Json::Value req, res; - string errmsg; - if (false != call_task (req, res, ts_get_host_stat, errmsg)) - { -#if defined(WINDOWS) - // Fix for TOOLS-3417 - // using reducer to make the number doesn't excced MAX_INT - os_data[0] = int (JSON_ATOL (res["cpu_idle"])/CPU_BASE_FEQ_WIN); - os_data[1] = int (JSON_ATOL (res["cpu_iowait"])/CPU_BASE_FEQ_WIN); - os_data[2] = int (JSON_ATOL (res["cpu_kernel"])/CPU_BASE_FEQ_WIN); - os_data[3] = int (JSON_ATOL (res["cpu_user"])/CPU_BASE_FEQ_WIN); -#else - os_data[0] = int (JSON_ATOI (res["cpu_idle"])); - os_data[1] = int (JSON_ATOI (res["cpu_iowait"])); - os_data[2] = int (JSON_ATOI (res["cpu_kernel"])); - os_data[3] = int (JSON_ATOI (res["cpu_user"])); -#endif - os_data[4] = int (JSON_ATOL (res["mem_phy_free"]) * 100 / MB_SIZE); - os_data[5] = int (JSON_ATOL (res["mem_swap_free"]) * 100 / MB_SIZE); - } - else - { - LOG_WARN ("get host statu failed, time=[%d], error code[%d], error message [%s]", - gather_time, res["retval"].asInt(), errmsg.c_str()); - return; - } - res.clear(); - if (false != call_task_ext (req, res, ext_get_sys_diskinfo)) - { - int total_free = 0; - for (unsigned int i = 0; i < res["disk_info"].size(); i++) - { - total_free += int (JSON_ATOL (res["disk_info"][i]["free_size"]) * 100 / MB_SIZE); - } - os_data[6] = total_free; - } - else - { - LOG_WARN ("get system disk info failed, time=[%d], error message [%s]", - gather_time, res["note"].asString().c_str()); - return; - } - os_data[7] = 0; - os_data[8] = 0; - os_data[9] = int (gather_time); - update_rrdfile (_data_path + OS_MON, daily_idx, os_data, OS_METRICS_LEN, OS_METRICS_LEN); -} - -bool cm_mon_stat::init_meta (int interval) -{ - _meta[K_INTERVAL] = interval; - _meta[K_TOTAL_VOL_NUM] = 0; - - // init broker - Json::Value req, brokers_info; - string errmsg; - if (false == call_task (req, brokers_info, ts2_get_unicas_info, errmsg)) - { - LOG_ERROR ("failed to get brokers infomation, error code[%d], error message [%s]", - brokers_info["retval"].asInt(), errmsg.c_str()); - throw exception(); - } - for (int i = 0; i < BROKER_METRICS_LEN; i++) - { - _meta[K_BROKER_METRICS][BROKER_METRICS[i].metric] = i; - } - if (brokers_info.isMember ("brokersinfo")) - { - _meta[K_BROKER_NUM] = brokers_info["brokersinfo"][0u]["broker"].size(); - for (int i = 0; i < _meta[K_BROKER_NUM].asInt(); i++) - { - string bname = brokers_info["brokersinfo"][0u]["broker"][i]["name"].asString(); - _meta[K_BROKER_RRD][bname + "_idx"] = i; - - } - int rrdsize = MON_DATA_BLOCK * _meta[K_BROKER_NUM].asInt(); - init_rrdfile (_data_path + BROKER_MON, rrdsize, BROKER_METRICS_LEN); - } - else - { - throw exception(); - } - - // init db - Json::Value dbs_info; - if (false == call_task (req, dbs_info, ts_startinfo, errmsg)) - { - LOG_ERROR ("failed to get DBs infomation, error code[%d], error message [%s]", - dbs_info["retval"].asInt(), errmsg.c_str()); - throw exception(); - } - - for (int i = 0; i < DB_METRICS_LEN; i++) - { - _meta[K_DB_METRICS][DB_METRICS[i].metric] = i; - } - if (dbs_info.isMember ("dblist")) - { - Json::Value &dbs = dbs_info["dblist"][0u]["dbs"]; - _meta[K_DB_NUM] = dbs.size(); - for (int i = 0; i < _meta[K_DB_NUM].asInt(); i++) - { - string dbname = dbs[i]["dbname"].asString(); - _meta[K_DB_RRD][dbname + "_idx"] = i; - } - int rrdsize = MON_DATA_BLOCK * _meta[K_DB_NUM].asInt(); - init_rrdfile (_data_path + DB_MON, rrdsize, DB_METRICS_LEN); - } - else - { - _meta[K_DB_NUM] = 0; - init_rrdfile (_data_path + VOL_MON, 0, 0); - init_rrdfile (_data_path + DB_MON, 0, 0); - LOG_WARN ("no dblist for DBs info"); - } - - // init OS - for (int i = 0; i < OS_METRICS_LEN; i++) - { - _meta[K_OS_METRICS][OS_METRICS[i].metric] = i; - } - _meta[K_OS_RRD]["os_idx"] = 0; - init_rrdfile (_data_path + OS_MON, MON_DATA_BLOCK, OS_METRICS_LEN); - - return flush_meta_file(); -} - -bool cm_mon_stat::reset_meta (int new_interval) -{ - scope_lock slocker (_data_mutex); - - // reset broker - if (false == reset_mon_file (_data_path + BROKER_MON, _meta[K_BROKER_NUM].asInt(), BROKER_METRICS_LEN, new_interval)) - { - LOG_ERROR ("reset broker monitoring file failed"); - return false; - } - // reset DBs - if (false == reset_mon_file (_data_path + DB_MON, _meta[K_DB_NUM].asInt(), DB_METRICS_LEN, new_interval)) - { - LOG_ERROR ("reset DB monitoring file failed"); - return false; - } - // reset volume - if (false == reset_mon_file (_data_path + VOL_MON, _meta[K_TOTAL_VOL_NUM].asInt(), VOL_METRICS_LEN, new_interval)) - { - LOG_ERROR ("reset volume monitoring file failed"); - return false; - } - // reset os - if (false == reset_mon_file (_data_path + OS_MON, 1, OS_METRICS_LEN, new_interval)) - { - LOG_ERROR ("reset os monitoring file failed"); - return false; - } - _meta[K_INTERVAL] = new_interval; - return flush_meta_file(); -} - -bool cm_mon_stat::reset_mon_file (string fpath, int block_num, int mlen, int new_interval) -{ - int ori_bufsize = MON_DATA_BLOCK * block_num * mlen; - int *ori_buf = new (int[ori_bufsize]); - if (false == get_rrdfile (fpath, 0, ori_buf, ori_bufsize, mlen)) - { - LOG_ERROR ("get_rrdfile failed, file name[%s]", fpath.c_str()); - delete [] ori_buf; - return false; - } - - int old_daily_data_block = (24 * 60 * 60) / _meta[K_INTERVAL].asInt(); - int new_mon_data_block = (24 * 60 * 60) / new_interval + 30 * 24 + 365; - int new_rrdsize = new_mon_data_block * block_num; - if (false == init_rrdfile (fpath, new_rrdsize, mlen)) - { - LOG_ERROR ("init_rrdfile failed, file name[%s]", fpath.c_str()); - delete [] ori_buf; - return false; - } - - for (int i = 0; i < block_num; i++) - { - int *ptr = ori_buf + i * MON_DATA_BLOCK + old_daily_data_block; - int rrdpos = i * new_mon_data_block + (24 * 60 * 60) / new_interval; - if (false == update_rrdfile (fpath, rrdpos, ptr, (30 * 24 + 365) * mlen, mlen)) - { - LOG_ERROR ("update_rrdfile failed, file name[%s], block number[%d]", fpath.c_str(), i); - delete [] ori_buf; - return false; - } - } - delete [] ori_buf; - return true; -} - -bool cm_mon_stat::flush_meta_file (void) -{ - Json::StyledWriter writer; - ofstream ofs (_meta_file.c_str()); - if (!ofs.bad()) - { - ofs << writer.write (_meta) << endl; - ofs.close(); - return true; - } - - return false; -} - -bool cm_mon_stat::load_meta_file (void) -{ - Json::Reader reader; - ifstream ifs (_meta_file.c_str()); - if (!ifs.bad()) - { - bool rtn = reader.parse (ifs, _meta); - if (false == rtn) - { - LOG_ERROR ("failed to load monitoring meta file [%s]", _meta_file.c_str()); - } - ifs.close(); - return rtn; - } - else - { - LOG_ERROR ("failed to load monitoring meta file [%s]", _meta_file.c_str()); - return false; - } -} - -int json_to_nv (Json::Value &root, const char *name, nvplist *nv); -int nv_to_json (nvplist *ref, char *value, int &index, Json::Value &root); - -static bool init_rrdfile (string filename, int rrdsize, int metrics_len) -{ - int bufsize = rrdsize * metrics_len; - int *buf = new (int[bufsize]); - memset ((void *)buf, INIT_METRIC_VALUE, bufsize * sizeof (int)); - ofstream ofs (filename.c_str(), ios_base::out | ios_base::binary | ios_base::trunc); - if (ofs.fail()) - { - LOG_ERROR ("failed to open monitoring data file [%s]", filename.c_str()); - delete [] buf; - throw exception(); - } - ofs.write ((char *)buf, bufsize * sizeof (int)); - ofs.close(); - delete [] buf; - return true; -} - -static bool update_rrdfile (string filename, int rrdpos, int *buf, int bufsize, int mlen) -{ - fstream fs (filename.c_str(), ios_base::in | ios_base::out | ios_base::binary); - if (fs.fail()) - { - LOG_ERROR ("failed to open monitoring data file [%s]", filename.c_str()); - return false; - } - fs.seekp (rrdpos * sizeof (int) * mlen); - fs.write ((char *) buf, bufsize * sizeof (int)); - fs.close(); - return true; -} - -static bool get_rrdfile (string filename, int rrdpos, int *buf, int bufsize, int metrics_len) -{ - fstream fs (filename.c_str(), ios_base::in | ios_base::binary); - if (fs.fail()) - { - LOG_ERROR ("failed to open monitoring data file [%s]", filename.c_str()); - return false; - } - fs.seekp (rrdpos * sizeof (int) * metrics_len); - fs.read ((char *) buf, bufsize * sizeof (int)); - if (fs.eof()) - { - LOG_ERROR ("failed to read monitoring data, rrdpos:[%d], bufsize:[%d], file:[%s]", rrdpos, bufsize, filename.c_str()); - return false; - } - fs.close(); - return true; -} - -static bool append_rrdfile (string filename, int rrdsize, int metrics_len ) -{ - int bufsize = rrdsize * metrics_len; - int *buf = new (int[bufsize]); - memset (buf, 0, bufsize * sizeof (int)); - ofstream ofs (filename.c_str(), ios_base::out | ios_base::binary | ios_base::app); - if (ofs.fail()) - { - LOG_ERROR ("failed to open monitoring data file [%s]", filename.c_str()); - delete [] buf; - return false; - } - ofs.write ((char *)buf, bufsize * sizeof (int)); - ofs.close(); - delete [] buf; - return true; -} - -static bool get_dbs_list (Json::Value &db_list) -{ - Json::Value req, dbs_info; - db_list.clear(); - string errmsg; - if (false == call_task (req, dbs_info, ts_startinfo, errmsg)) - { - LOG_ERROR ("failed to get DBs infomation, error code[%d], error message [%s]", - dbs_info["retval"].asInt(), errmsg.c_str()); - return false; - } - if (dbs_info.isMember ("dblist")) - { - Json::Value &dbs = dbs_info["dblist"][0u]["dbs"]; - for (unsigned int i = 0; i < dbs.size(); i++) - { - db_list.append (dbs[i]["dbname"].asString()); - } - } - else - { - LOG_ERROR ("no dblist for DBs info"); - return false; - } - return true; -} - -static bool get_active_dbs_list (Json::Value &db_list) -{ - Json::Value req, dbs_info; - db_list.clear(); - string errmsg; - if (false == call_task (req, dbs_info, ts_startinfo, errmsg)) - { - LOG_ERROR ("failed to get active DBs infomation, error code[%d], error message [%s]", - dbs_info["retval"].asInt(), errmsg.c_str()); - return false; - } - if (dbs_info.isMember ("activelist")) - { - if (0 == dbs_info["activelist"].size() - || false == dbs_info["activelist"][0u].isMember ("active")) - { - return true; - } - Json::Value &dbs = dbs_info["activelist"][0u]["active"]; - - for (unsigned int i = 0; i < dbs.size(); i++) - { - db_list.append (dbs[i]["dbname"].asString()); - } - } - else - { - LOG_ERROR ("no active dblist for DBs info"); - return false; - } - return true; -} - -static bool get_brokers_list (Json::Value &brokers_list) -{ - Json::Value req, brokers_info; - brokers_list.clear(); - string errmsg; - if (false == call_task (req, brokers_info, ts2_get_unicas_info, errmsg)) - { - LOG_ERROR ("failed to get brokers infomation, error code[%d], error message [%s]", - brokers_info["retval"].asInt(), errmsg.c_str()); - return false; - } - if (brokers_info.isMember ("brokersinfo")) - { - Json::Value &brokers = brokers_info["brokersinfo"][0u]["broker"]; - - for (unsigned int i = 0; i < brokers.size(); i++) - { - brokers_list.append (brokers[i]["name"].asString()); - } - } - else - { - LOG_ERROR ("no key brokersinfo for getbrokerstatus"); - return false; - } - return true; -} - -static bool call_task (Json::Value &req, Json::Value &res, T_TASK_FUNC func, string &errmsg) -{ - bool ret = false; - nvplist *cli_request, *cli_response; - cli_request = nv_create (5, NULL, "\n", ":", "\n"); - cli_response = nv_create (5, NULL, "\n", ":", "\n"); - try - { - int index = 0; - char dbmt_error[DBMT_ERROR_MSG_SIZE]; - dbmt_error[0] = 0; - - json_to_nv (req, NULL, cli_request); - int retval = (*func) (cli_request, cli_response, dbmt_error); - nv_to_json (cli_response, NULL, index, res); - res["retval"] = retval; - errmsg = dbmt_error; - if ((1 == retval) || (ERR_NO_ERROR == retval)) - { - ret = true; - } - else - { - //LOG_WARN("Failed with return value %d, error message is [%s]", retval, dbmt_error); - ret = false; - } - } - catch (exception &) - { - ret = false; - } - nv_destroy (cli_request); - nv_destroy (cli_response); - return ret; -} - -static bool call_task_ext (Json::Value &req, Json::Value &res, T_EXT_TASK_FUNC func) -{ - try - { - (*func) (req, res); - if (STATUS_SUCCESS != res["status"].asString()) - { - return false; - } - return true; - } - catch (exception &e) - { - res["status"] = STATUS_FAILURE; - res["note"] = e.what (); - return false; - } -} diff --git a/server/src/cm_mon_stat.h b/server/src/cm_mon_stat.h deleted file mode 100644 index 45021ac..0000000 --- a/server/src/cm_mon_stat.h +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. - * - * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - -/** -* @brief cm_mon_stat.h include the definition of cm_mon_stat class. -*/ - -#ifndef _CM_MON_STAT_H_ -#define _CM_MON_STAT_H_ - -#ifndef PATH_MAX -#define PATH_MAX 1024 -#endif - -#include -#include -#include - -#include "json/json.h" -#include "cm_porting.h" - -using namespace std; - -enum AGG_TYPE -{ - HOUR, DAY -}; - -enum MDTYPE -{ - DAILY = 0, - WEEKLY, - MONTHLY, - YEARLY -}; - -// TODO: need a switch for monitoring data collection - -class cm_mon_stat -{ - public: - static cm_mon_stat *get_instance (void); - bool initial (void); - void gather_mon_data (void); - bool set_mon_interval (time_t interval); - bool get_mon_interval (time_t &interval) const; - bool get_mon_statistic (const Json::Value req, Json::Value &res, - string &errmsg) const; - - protected: - cm_mon_stat (string data_path); - virtual ~ cm_mon_stat (void) - { - MUTEX_DESTROY (_data_mutex); - delete _instance; - _instance = NULL; - } - - private: - bool init_meta (int interval); - bool reset_meta (int new_interval); - bool flush_meta_file (); - bool load_meta_file (); - void aggregate_2_hour (time_t gather_time); - void aggregate_2_day (time_t gather_time); - void aggregate_os (int read_offset, int buf_base, int write_offset, - AGG_TYPE atype, time_t gather_time); - void aggregate_dbs (int read_offset, int buf_base, int write_offset, - AGG_TYPE atype, time_t gather_time); - void aggregate_brokers (int read_offset, int buf_base, int write_offset, - AGG_TYPE atype, time_t gather_time); - void gather_daily_brokers_mon (time_t gather_time); - bool gather_dbs_tran_query (time_t gather_time, Json::Value &db_tq); - void gather_daily_dbs_mon (time_t gather_time); - void gather_daily_os_mon (time_t gather_time); - bool reset_mon_file (string fpath, int block_num, int mlen, - int new_interval); - bool get_rrd_data (MDTYPE mdtype, string dpath, int didx, int midx, - int pfactor, bool ddiff, int mlen, Json::Value &res, string &errmsg) const; - bool m_get_mon_statistic (const Json::Value req, Json::Value &res, string &errmsg) const; - - private: - static cm_mon_stat *_instance; - const string _data_path; - const string _meta_file; - Json::Value _meta; - - int _daily_idx; - int _monthly_idx; - int _yearly_idx; - time_t _prev_gather; - Json::Value _brokers; - Json::Value _dbs; - MUTEX_T _data_mutex; - bool _init; -}; - -#endif /* _CM_MON_STAT_H_ */ diff --git a/server/src/cm_porting.h b/server/src/cm_porting.h deleted file mode 100644 index 13e7c6c..0000000 --- a/server/src/cm_porting.h +++ /dev/null @@ -1,339 +0,0 @@ -/* - * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. - * - * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/* - * cm_porting.h - - */ - -#ifndef _CM_PORTING_H_ -#define _CM_PORTING_H_ - -/* - * IMPORTED SYSTEM HEADER FILES - */ -#include "config.h" - -#include - -#if defined(WINDOWS) && !defined (EOVERFLOW) -#define EOVERFLOW 75 -#endif - - -#if !defined(WINDOWS) -#include -#include -#include -#else -#include -#endif - -/* - * IMPORTED OTHER HEADER FILES - */ - -/* - * EXPORTED DEFINITIONS - */ -#if defined(WINDOWS) -#define PATH_MAX 256 -#endif - -#if !defined(NAME_MAX) -#define NAME_MAX 256 -#endif - -#define MOVE_FILE(SRC_FILE, DEST_FILE) \ - (unlink(DEST_FILE) || 1 ? rename(SRC_FILE, DEST_FILE) : -1) - -#if defined(WINDOWS) -#define CLOSE_SOCKET(X) if (!IS_INVALID_SOCKET(X)) closesocket(X) -#else -#define CLOSE_SOCKET(X) if (!IS_INVALID_SOCKET(X)) close(X) -#endif - -#if defined(WINDOWS) -#define mkdir(dir, mode) _mkdir(dir) -#define access(dir, mode) _access(dir, mode) -#define unlink(file) _unlink(file) -#define getpid() _getpid() -#define O_RDONLY _O_RDONLY -#define strcasecmp(str1, str2) _stricmp(str1, str2) -#define strncasecmp(str1, str2, size) _strnicmp(str1, str2, size) -#define snprintf _snprintf - -#define R_OK 4 -#define W_OK 2 -#define F_OK 0 -#define X_OK F_OK - -/* -* MAXHOSTNAMELEN definition -* This is defined in sys/param.h on the linux. -*/ -#define MAXHOSTNAMELEN 64 - -#endif - -#if defined(WINDOWS) -#define SLEEP_SEC(X) Sleep((X) * 1000) -#define SLEEP_MILISEC(sec, msec) Sleep((sec) * 1000 + (msec)) -#else -#define SLEEP_SEC(X) sleep(X) -#define SLEEP_MILISEC(sec, msec) \ - do { \ - struct timeval sleep_time_val; \ - sleep_time_val.tv_sec = sec; \ - sleep_time_val.tv_usec = (msec) * 1000; \ - select(0, 0, 0, 0, &sleep_time_val); \ - } while(0) -#endif - -#if defined(WINDOWS) -#define TIMEVAL_MAKE(X) _ftime(X) -#define TIMEVAL_GET_SEC(X) ((int) ((X)->time)) -#define TIMEVAL_GET_MSEC(X) ((int) ((X)->millitm)) -#else -#define TIMEVAL_MAKE(X) gettimeofday(X, NULL) -#define TIMEVAL_GET_SEC(X) ((int) ((X)->tv_sec)) -#define TIMEVAL_GET_MSEC(X) ((int) (((X)->tv_usec) / 1000)) -#endif - -#if defined(WINDOWS) -#define THREAD_BEGIN(THR_ID, FUNC, ARG) \ - do { \ - THR_ID = _beginthread(FUNC, 0, (void*) (ARG)); \ - } while(0) -#elif HPUX10_2 -#define THREAD_BEGIN(THR_ID, FUNC, ARG) \ - do { \ - pthread_create(&(THR_ID), pthread_attr_default, FUNC, ARG); \ - pthread_detach(THR_ID); \ - } while (0) -#elif UNIXWARE7 -#define THREAD_BEGIN(THR_ID, FUNC, ARG) \ - do { \ - pthread_attr_t thread_attr; \ - pthread_attr_init(&thread_attr); \ - pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED); \ - pthread_attr_setstacksize(&thread_attr, 100 * 1024); \ - if (pthread_create(&(THR_ID), &thread_attr, FUNC, ARG) < 0){ \ - free ((void *) ARG); \ - ARG = NULL; \ - } \ - pthread_attr_destroy(&thread_attr); \ - } while (0) -#else -#define THREAD_BEGIN(THR_ID, FUNC, ARG) \ - do { \ - pthread_attr_t thread_attr; \ - pthread_attr_init(&thread_attr); \ - pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED); \ - if (pthread_create(&(THR_ID), &thread_attr, FUNC, ARG) < 0){ \ - free ((void *) ARG); \ - ARG = NULL; \ - } \ - pthread_attr_destroy(&thread_attr); \ - } while (0) -#endif - -#if defined(WINDOWS) -#define THREAD_CANCEL(THR_ID) \ - do{ \ - if (THR_ID){ \ - TerminateThread((HANDLE)THR_ID, 0); \ - } \ - } while(0) -#else -#define THREAD_CANCEL(THR_ID) \ - do{ \ - if (THR_ID){ \ - pthread_cancel (THR_ID); \ - } \ - } while(0) -#endif - - -#ifdef UNIXWARE7 -#define PROC_FORK() fork1() -#else -#define PROC_FORK() fork() -#endif - -/* - * EXPORTED TYPE DEFINITIONS - */ - -#if defined(WINDOWS) -typedef struct _timeb T_TIMEVAL; -#else -typedef struct timeval T_TIMEVAL; -#endif - -#if defined(WINDOWS) || defined(SOLARIS) || defined(HPUX) -typedef int T_SOCKLEN; -#elif defined(UNIXWARE7) -typedef size_t T_SOCKLEN; -#else -typedef socklen_t T_SOCKLEN; -#endif - -#if defined(WINDOWS) -#define IS_INVALID_SOCKET(socket) ((socket) == INVALID_SOCKET) -#else -typedef int SOCKET; -#define INVALID_SOCKET (-1) -#define IS_INVALID_SOCKET(socket) ((socket) < 0) -#endif - -#ifdef HAVE_INT64_T -typedef int64_t INT64; -#elif SIZEOF_LONG == 8 -typedef long INT64; -#elif SIZEOF_LONG_LONG == 8 -/* typedef long long INT64; */ -#else -#error "Error: INT64" -#endif - -/* - * EXPORTED DEFINITIONS - */ - -#if defined(WINDOWS) -#define THREAD_FUNC void -#define T_THREAD uintptr_t -#else -#define THREAD_FUNC void* -#define T_THREAD pthread_t -#endif - -#if defined(WINDOWS) -#define DEL_FILE "del" -#define DEL_FILE_OPT "/F /Q" -#define DEL_DIR "rmdir" -#define DEL_DIR_OPT "/S /Q" -#else -#define DEL_FILE "rm" -#define DEL_FILE_OPT "-f" -#define DEL_DIR "rm" -#define DEL_DIR_OPT "-rf" -#endif - -#if !defined(WINDOWS) -#define TRUE 1 -#define FALSE 0 -#endif - -#if !HAVE_BZERO && HAVE_MEMSET -#define bzero(buf, bytes) ((void) memset (buf, 0, bytes)) -#endif - -/* MUTEX & COND TYPE */ -#if defined(WINDOWS) -#define MUTEX_T HANDLE -#define COND_T HANDLE -#else -#define MUTEX_T pthread_mutex_t -#define COND_T pthread_cond_t -#endif - -/* MUTEX SIGNAL */ -#if defined(WINDOWS) -#define MUTEX_INIT(MUTEX) \ - ((MUTEX = CreateMutex(NULL, FALSE, NULL)) != NULL ? \ - 0 : -1 ) - -#define MUTEX_DESTROY(handle) \ - ( (handle = (void *)(!CloseHandle(handle))) == 0 ? \ - 0 : -1) - -#define MUTEX_LOCK(mutex) \ - ( WaitForSingleObject(mutex, INFINITE) == WAIT_OBJECT_0 ? \ - 0 : -1) - -#define MUTEX_UNLOCK(mutex) \ - ( ReleaseMutex(mutex) != 0 ? 0 : -1 ) -#elif HPUX10_2 -#define MUTEX_INIT(MUTEX) \ - pthread_mutex_init(MUTEX, pthread_mutexattr_default); -#else - -#define MUTEX_INIT(mutex) \ - ( pthread_mutex_init(&(mutex), NULL) == 0 ? \ - 0 : -1) - -#define MUTEX_DESTROY(mutex) \ - ( pthread_mutex_destroy(&(mutex)) == 0 ? \ - 0 : -1) - -#define MUTEX_LOCK(mutex) \ - ( pthread_mutex_lock(&(mutex)) == 0 ? \ - 0 : -1) - -#define MUTEX_UNLOCK(mutex) \ - ( pthread_mutex_unlock(&(mutex)) == 0 ? \ - 0 : -1) - -#endif - -/* CONDITION SIGNAL */ -#if defined(WINDOWS) -/* Creates an Event of auto-reset mode */ -#define COND_INIT(cond_var) \ - ((cond_var = CreateEvent(NULL, FALSE, FALSE, NULL)) != NULL ? 0 : -1) - -#define COND_WAIT(cond_var, mutex) \ - (SignalObjectAndWait(mutex, cond_var, INFINITE, FALSE) == WAIT_OBJECT_0 ? \ - 0 : -1) - -#define COND_TIMEDWAIT(cond_var, mutex, timeout) \ - SignalObjectAndWait(mutex, cond_var, timeout, FALSE) - -/* For an auto-reset event object, PulseEvent() returns after releasing a - * waiting thread. If no threads are waiting, nothing happens - it simply - * returns. - */ -#define COND_SIGNAL(cond_var) (PulseEvent(cond_var) !=0 ? 0 : -1) - -/* SetEvent() just wakes up one thread. It's actually not the broadcast. */ -#define COND_BROADCAST(cond_var) (SetEvent(cond_var) !=0 ? 0 : -1 ) - -#define COND_DESTROY(cond_var) \ - ( (cond_var = (void *)CloseHandle(cond_var)) != 0 ? 0 : -1) -#else -/* Caution: - * There are some differences between pthreads and win32 threads - * over these macros of condition signal. Under the win32 threads, - * 1. COND_WAIT() returns without acquiring lock. - * 2. COND_BROADCAST() does not release all waiting threads, but keep - * signaling until only a thread is released. It continues signaling - * even if there is no thread to be waken up when this macro is called. - * You should take these into account for portability. - */ -#define COND_INIT(condvar) pthread_cond_init(&(condvar), NULL) -#define COND_WAIT(c, m) pthread_cond_wait(&(c), &(m)) -#define COND_TIMEDWAIT(c, m, t) pthread_cond_timedwait(&(c), &(m), &(t)) -#define COND_SIGNAL(c) pthread_cond_signal(&(c)) -#define COND_BROADCAST(c) pthread_cond_broadcast(&(c)) -#define COND_DESTROY(condvar) pthread_cond_destroy(&(condvar)) -#endif - -#endif /* _CM_PORTING_H_ */ diff --git a/server/src/cm_server_autoupdate.cpp b/server/src/cm_server_autoupdate.cpp deleted file mode 100644 index 59fbaca..0000000 --- a/server/src/cm_server_autoupdate.cpp +++ /dev/null @@ -1,386 +0,0 @@ -/* - * Copyright (C) 2014 Search Solution Corporation. All rights reserved by Search Solution. - * - * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - -/* -* cm_server.autoupdate.cpp -*/ - -#include "cm_server_autoupdate.h" -#include "cm_compress.h" -#include "cm_config.h" -#include "cm_dep.h" - -#ifdef WINDOWS -#include -#include -#include -#else -#include -#endif - -#ifdef WINDOWS - -#undef UNICODE -#pragma comment(lib, "wininet.lib") - -int -generate_update_script (char *patch_name, char *url, char *path, - char *_dbmt_error) -{ - unsigned char file_buffer[DOWNLOAD_BUFFER]; - - char zip_file[PATH_MAX]; - char zip_folder[PATH_MAX]; - char host_name[NAME_MAX]; - char remote_path[PATH_MAX]; - char shell_name[PATH_MAX]; - - HINTERNET handle_open = 0; - HINTERNET handle_connect = 0; - HINTERNET handle_request = 0; - - DWORD read_bytes = 0; - - FILE *fout; - - size_t sum_size = 0; - - if (url == NULL || strcmp (url, "") == 0) - { - strncpy (host_name, DEFAULT_UPDATE_HOST_NAME, PATH_MAX); - sprintf (remote_path, DEFAULT_UPDATE_REMOTE_PATH "%s", patch_name); - } - else - { - // TODO: use a static function instead, and offer more strict conditions. - - char *iter1, *iter2; - - iter1 = strstr (url, "//"); - iter2 = strstr (iter1 + 2, "/"); - - strncpy (host_name, iter1 + 2, iter2 - iter1 - 2); - strncpy (remote_path, iter2, PATH_MAX); - } - - if (InternetAttemptConnect (0) != ERROR_SUCCESS) - { - sprintf (_dbmt_error, - "InternetAttemptConnect(): CM Server is offline."); - return ERR_SYSTEM_CALL; - } - - handle_open = - InternetOpen (TEXT ("auto_update"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, - NULL, 0); - if (handle_open == NULL) - { - sprintf (_dbmt_error, "InternetOpen() : failed."); - - return ERR_SYSTEM_CALL; - } - - handle_connect = - InternetConnect (handle_open, host_name, INTERNET_INVALID_PORT_NUMBER, - NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0); - if (handle_connect == NULL) - { - sprintf (_dbmt_error, "InternetConnect(): failed."); - - InternetCloseHandle (handle_open); - - return ERR_SYSTEM_CALL; - } - - handle_request = - HttpOpenRequest (handle_connect, TEXT ("GET"), remote_path, NULL, NULL, - NULL, INTERNET_FLAG_RELOAD, 0); - if (handle_request == NULL) - { - sprintf (_dbmt_error, "HttpOpenRequest(): failed."); - - InternetCloseHandle (handle_connect); - InternetCloseHandle (handle_open); - - return ERR_SYSTEM_CALL; - } - - if (!HttpSendRequest (handle_request, NULL, 0, NULL, 0)) - { - int err = GetLastError (); - sprintf (_dbmt_error, - "HttpSendRequest(): failed, an error %d happened.", err); - - InternetCloseHandle (handle_request); - InternetCloseHandle (handle_connect); - InternetCloseHandle (handle_open); - - return ERR_SYSTEM_CALL; - } - - sprintf (zip_file, "%s%s", path, patch_name); - fout = fopen (zip_file, "wb+"); - if (fout == NULL) - { - sprintf (_dbmt_error, "%s", zip_file); - return ERR_FILE_OPEN_FAIL; - } - - do - { - - if (!InternetReadFile - (handle_request, file_buffer, DOWNLOAD_BUFFER, &read_bytes)) - { - sprintf (_dbmt_error, "InternetReadFile(): download file failed!"); - - InternetCloseHandle (handle_request); - InternetCloseHandle (handle_connect); - InternetCloseHandle (handle_open); - - fclose (fout); - - return ERR_SYSTEM_CALL; - } - - fwrite (file_buffer, sizeof (unsigned char), read_bytes, fout); - - sum_size += read_bytes; - printf ("sum_size = %d\n", sum_size); - - } - while (read_bytes == DOWNLOAD_BUFFER); - - fclose (fout); - - strncpy (zip_folder, path, PATH_MAX); - strcat (zip_folder, "patch"); - // create the folder for extracting zip file, otherwise unzip will fail. - if (access (zip_folder, 0) != 0 && !CreateDirectory (zip_folder, NULL)) - { - sprintf (_dbmt_error, "CreateDirectory(): create %s dir failed.", - zip_folder); - return ERR_SYSTEM_CALL; - } - - if (!unzip (zip_file, zip_folder)) - { - sprintf (_dbmt_error, "unzip %s failed.", zip_file); - return ERR_SYSTEM_CALL; - } - - sprintf (shell_name, "%s" SHELL_NAME, path); - fout = fopen (shell_name, "w+"); - if (fout == NULL) - { - sprintf (_dbmt_error, SHELL_NAME); - return ERR_FILE_OPEN_FAIL; - } - - // backup - fprintf (fout, "md %sbackup\n", path); - fprintf (fout, - "if exist %s\\bin\\arn_manager.exe copy /y %s\\bin\\arn_manager.exe %sbackup\\.\n", - sco.szArniadb, sco.szArniadb, path); - fprintf (fout, - "if exist %s\\bin\\cm_admin.exe copy /y %s\\bin\\cm_admin.exe %sbackup\\.\n", - sco.szArniadb, sco.szArniadb, path); - - fprintf (fout, "arniadb service stop\n"); - fprintf (fout, "arn_manager stop\n"); - - //update - fprintf (fout, "if exist %s\\arn_* copy /y %s\\arn_* %s\\bin\\.\n", - zip_folder, zip_folder, sco.szArniadb); - fprintf (fout, - "if exist %s\\cm_admin copy /y %s\\cm_admin.exe %s\\bin\\.\n", - zip_folder, zip_folder, sco.szArniadb); - fprintf (fout, - "for /f %%%%c in ('dir /b %s\\conf\\') do type %s\\conf\\%%%%c >> %s\\conf\\%%%%c\n", - zip_folder, zip_folder, sco.szArniadb); - - fprintf (fout, "ping 127.0.0.1 -n 40 -w 1000 > nul\n"); - fprintf (fout, "arniadb service start\n"); - fprintf (fout, "arn_manager start\n"); - fprintf (fout, "echo \"ARNIADB Manager Server is updated.\"", path); - - fclose (fout); - - return ERR_NO_ERROR; -} - -#else - -int -generate_update_script (char *patch_name, char *url, char *path, - char *_dbmt_error) -{ - FILE *fout; - char shell_name[PATH_MAX]; - char chmod_cmd[PATH_MAX]; - - if (url == NULL || strcmp (url, "") == 0) - { - strncpy (url, DEFAULT_PATCH_URL, PATH_MAX); - } - - sprintf (shell_name, "%s" SHELL_NAME, path); - - fout = fopen (shell_name, "w"); - if (fout == NULL) - { - sprintf (_dbmt_error, SHELL_NAME); - return ERR_FILE_OPEN_FAIL; - } - - fprintf (fout, "rm -rf %spatch*\n", path); - fprintf (fout, "wget -T 60 %s -P %s\n", url, path); - fprintf (fout, "if [ $? -ne 0 ]; then\n"); - fprintf (fout, "\techo \"download patch file failed!\"\nfi\n"); - - fprintf (fout, "unzip -u %s%s -d %spatch\n", path, patch_name, path); - fprintf (fout, "if [ $? -ne 0 ]; then\n"); - fprintf (fout, "\techo \"unzip patch file failed!\"\nfi\n"); - - fprintf (fout, "mkdir %sbackup\n", path); - fprintf (fout, - "cp %s/bin/cm_admin %s/bin/arn_manager %sbackup/.\n", - sco.szArniadb, sco.szArniadb, path); - fprintf (fout, - "if [ -e %spatch/arn_manager ]; then\n", path); - fprintf (fout, "\tcp %spatch/arn_* %s/bin/. -f\nfi\n", path, sco.szArniadb); - - fprintf (fout, "if [ -e %spatch/cm_admin ]; then\n", path); - fprintf (fout, "\tcp %spatch/cm_admin %s/bin/. -f\nfi\n", path, - sco.szArniadb); - - - fprintf (fout, "if [ -d %spatch/conf ]; then\n", path); - fprintf (fout, "\tfor conf_file in $(ls %spatch/conf)\n\tdo\n", path); - fprintf (fout, "\t\tcp %s/conf/$conf_file %sbackup/.\n", sco.szArniadb, - path); - fprintf (fout, - "\t\tcat %spatch/conf/$conf_file >> %s/conf/$conf_file\n\tdone\nfi\n", - path, sco.szArniadb); - - fprintf (fout, "arniadb service restart\n"); - fprintf (fout, "echo \"ARNIADB Manager Server is updated.n"); - - fclose (fout); - - sprintf (chmod_cmd, "chmod +x %s", shell_name); - system (chmod_cmd); - - return ERR_NO_ERROR; -} - -#endif - -mz_bool -unzip (const char *zip_file, const char *unzip_dir) -{ - - mz_uint i; - - mz_bool status; - - mz_uint num_files, file_index; - - mz_zip_archive zip_archive; - - char unzip_file[MAX_LINE]; - - if (NULL == zip_file || NULL == unzip_dir) - { - return MZ_FALSE; - } - - //Now try to open the archive. - memset (&zip_archive, 0, sizeof (zip_archive)); - - status = mz_zip_reader_init_file (&zip_archive, zip_file, 0); - - if (!status) - { - return MZ_FALSE; - } - - num_files = mz_zip_reader_get_num_files (&zip_archive); - - //Get and print information about each file in the archive. - for (i = 0; i < num_files; i++) - { - - mz_zip_archive_file_stat file_stat; - status = mz_zip_reader_file_stat (&zip_archive, i, &file_stat); - - if (!status) - { - mz_zip_reader_end (&zip_archive); - return MZ_FALSE; - } - - snprintf (unzip_file, MAX_LINE, "%s/%s", unzip_dir, - file_stat.m_filename); - - file_index = - mz_zip_reader_locate_file (&zip_archive, file_stat.m_filename, NULL, - 0); - - if (mz_zip_reader_is_file_a_directory (&zip_archive, file_index)) - { - //create sub directory according to the folder's name, which is zipped in zip file. -#ifdef WINDOWS - if (access (unzip_file, 0) != 0 - && !CreateDirectory (unzip_file, NULL)) -#else - mode_t old_mode = umask (0); - if (access (unzip_file, 0) != 0 && mkdir (unzip_file, 0700) != 0) -#endif - { -#ifndef WINDOWS - umask (old_mode); -#endif - mz_zip_reader_end (&zip_archive); - return MZ_FALSE; - } -#ifndef WINDOWS - umask (old_mode); -#endif - continue; - } - - status = - mz_zip_reader_extract_file_to_file (&zip_archive, - file_stat.m_filename, unzip_file, - 0); - - if (!status) - { - mz_zip_reader_end (&zip_archive); - return MZ_FALSE; - } - } - - - mz_zip_reader_end (&zip_archive); - - return MZ_TRUE; - -} diff --git a/server/src/cm_server_autoupdate.h b/server/src/cm_server_autoupdate.h deleted file mode 100644 index 2eb0cc3..0000000 --- a/server/src/cm_server_autoupdate.h +++ /dev/null @@ -1,24 +0,0 @@ -#ifndef _CM_SERVER_AUTOUPDATE_H_ -#define _CM_SERVER_AUTOUPDATE_H_ - -#ifdef WINDOWS - -#define DEFAULT_UPDATE_HOST_NAME "jira.arniadb.org" -#define DEFAULT_UPDATE_REMOTE_PATH "/secure/attachment/14895/" -#define DOWNLOAD_BUFFER 16384 -#define SHELL_NAME "auto_update.bat" - -#else - -#define DEFAULT_PATCH_URL "http://jira.arniadb.org/secure/attachment/14806/patch_9.1.0001.zip" -#define SHELL_NAME "auto_update.sh" - -#endif - -#define MAX_LINE 1024 - -int generate_update_script (char *patch_name, char *url, char *path, - char *_dbmt_error); -int unzip (const char *zip_file, const char *unzip_dir); - -#endif diff --git a/server/src/cm_server_extend_interface.cpp b/server/src/cm_server_extend_interface.cpp deleted file mode 100644 index 096137f..0000000 --- a/server/src/cm_server_extend_interface.cpp +++ /dev/null @@ -1,2707 +0,0 @@ -/* - * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. - * - * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - -#include "cm_log.h" - -#include -#ifdef WINDOWS -#include -#else -#include -#include -#include -#endif - -#include "cm_dep.h" -#include "cm_stat.h" -#include "cm_cmd_exec.h" -#include "cm_server_util.h" -#include "cm_text_encryption.h" -#include "cm_server_extend_interface.h" -#include "cm_mailer.h" -#include "cm_mon_stat.h" -#include "cm_user.h" - -#include -#include - -using namespace std; - -#ifndef MAX_PATH -#define MAX_PATH 260 -#endif - -#if defined(WINDOWS) -#define snprintf _snprintf -#ifndef strncasecmp -#define strncasecmp _strnicmp -#endif -#endif - -#define MIN_PASSWD_LENGTH 4 -#define MAX_TIME_LENGTH 10 - - -extern T_USER_TOKEN_INFO *user_token_info; -static T_EXTEND_TASK_INFO ext_task_info[] = -{ - {"getsysdiskinfo", 0, ext_get_sys_diskinfo, ALL_AUTHORITY}, - {"getprocstat", 0, ext_get_proc_info, ALL_AUTHORITY}, - {"setloglevel", 0, ext_set_log_level, AU_DBC | AU_DBO | AU_MON}, - {"setautostart", 0, ext_set_auto_start, AU_DBC | AU_DBO | AU_JOB}, - {"getautostart", 0, ext_get_auto_start, ALL_AUTHORITY}, - {"getautojobconf", 0, ext_get_autojob_conf, ALL_AUTHORITY}, - {"setautojobconf", 0, ext_set_autojob_conf, AU_DBC | AU_DBO | AU_JOB}, - {"execautostart", 0, ext_exec_auto_start, ALL_AUTHORITY}, - {"getdberrorlog", 0, ext_get_db_err_log, ALL_AUTHORITY}, - {"getbrokerlog", 0, ext_get_broker_start_log, ALL_AUTHORITY}, - {"sendmail", 0, ext_send_mail, ALL_AUTHORITY}, - {"automail", 0, ext_exec_auto_mail, AU_DBC | AU_DBO | AU_MON}, - {"readprivatedata", 0, ext_read_private_data, ALL_AUTHORITY}, - {"writeprivatedata", 0, ext_write_private_data, AU_DBC | AU_DBO | AU_BRK}, - {"setautoexecquery", 0, ext_set_autoexec_query, AU_DBC | AU_DBO | AU_JOB}, - {"gethaapplyinfo", 0, ext_get_ha_apply_info, ALL_AUTHORITY}, - {"adddbmtuser_new", 0, ext_add_dbmt_user_new, AU_DBC}, - {"updatedbmtuser_new", 0, ext_update_dbmt_user_new, AU_DBC | AU_DBO}, - {"getdbmtuserinfo_new", 0, ext_get_dbmt_user_info_new, AU_DBC | AU_DBO}, - {"get_mon_interval", 0, ext_get_mon_interval, AU_MON}, - {"set_mon_interval", 0, ext_set_mon_interval, AU_ADMIN}, - {"get_mon_statistic", 0, ext_get_mon_statistic, AU_MON}, - {NULL, 0, NULL, 0} -}; - -static bool -ext_get_id_from_token (const char *token, char token_content[][TOKEN_LENGTH+1]) -{ - char tmp_token[TOKEN_LENGTH+1]; - char *tmp_token_content[3]; - - uDecrypt (TOKEN_LENGTH, token, tmp_token); - - if (string_tokenize2 (tmp_token, tmp_token_content, 3, ':') < 0) - { - return false; - } - - // ip - strcpy (token_content[0], tmp_token_content[0]); - // port - strcpy (token_content[1], tmp_token_content[1]); - // id - strcpy (token_content[2], tmp_token_content[2]); - - return true; -} - -int -build_server_header (Json::Value &response, const int status, - const char *note) -{ - response["status"] = - (status == ERR_NO_ERROR) ? STATUS_SUCCESS : STATUS_FAILURE; - response["note"] = string (note); - return status; -} - -int -get_ext_task_info (const char *task, int access_flag, - T_EXT_TASK_FUNC *task_func, T_USER_AUTH *auth) -{ - int i; - - for (i = 0; ext_task_info[i].task_str != NULL; i++) - { - if (!strcmp (task, ext_task_info[i].task_str)) - { - if (access_flag < ext_task_info[i].access_level) - { - return 0; - } - if (task_func) - { - *task_func = ext_task_info[i].task_func; - } - - if (auth) - { - *auth = ext_task_info[i].user_auth; - } - - return 1; - } - } - - return 0; -} - -string -ull_to_str (const unsigned long long num) -{ - char buf[MAX_PATH]; - snprintf (buf, MAX_PATH, "%llu", num); - return string (buf); -} - -#ifdef WINDOWS -int -ext_get_sys_diskinfo (Json::Value &request, Json::Value &response) -{ - int flag = 0; - DWORD drives = GetLogicalDrives (); - ULARGE_INTEGER total_size; - ULARGE_INTEGER free_size; - Json::Value drive; - string drivename; - - while (drives) - { - if (drives & 1) - { - drivename = 'A' + flag; - drivename += ":"; - if (GetDriveType (drivename.c_str ()) == DRIVE_FIXED) - { - drive.clear (); - GetDiskFreeSpaceEx (drivename.c_str (), NULL, &total_size, - &free_size); - drive["name"] = drivename; - drive["total_size"] = ull_to_str (total_size.QuadPart); - drive["free_size"] = ull_to_str (free_size.QuadPart); - - response["disk_info"].append (drive); - } - } - drives >>= 1; - flag++; - } - - return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); -} -#else -int -ext_get_sys_diskinfo (Json::Value &request, Json::Value &response) -{ - struct statvfs buf; - int error; - Json::Value drive; - error = statvfs ("/", &buf); - - if (error < 0) - { - return build_server_header (response, ERR_WITH_MSG, - "get file system info error!"); - } - - drive["name"] = "/"; - drive["total_size"] = ull_to_str (buf.f_bsize * buf.f_blocks); - drive["free_size"] = ull_to_str (buf.f_bsize * buf.f_bfree); - - response["disk_info"].append (drive); - - return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); -} -#endif - -int -ext_get_proc_info (Json::Value &request, Json::Value &response) -{ - T_CMS_PROC_STAT stat; - int pid; - - pid = request.get ("pid", getpid ()).asInt (); - ut_get_proc_stat (&stat, pid); - - response["pid"] = stat.pid; - response["cpu_kernel"] = (unsigned int) stat.cpu_kernel; - response["cpu_user"] = (unsigned int) stat.cpu_user; - response["mem_physical"] = (unsigned int) stat.mem_physical; - response["mem_virtual"] = (unsigned int) stat.mem_virtual; - - return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); -} - -int -ext_set_log_level (Json::Value &request, Json::Value &response) -{ - unsigned int loglevel; - - loglevel = request.get ("log_level", CLog::xINFO).asUInt (); - - if (loglevel > CLog::xDEBUG) - { - return build_server_header (response, ERR_WITH_MSG, "invalid log level!"); - } - CLog::GetInstance (loglevel)->setLogLevel (loglevel); - response["log_level"] = loglevel; - return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); -} - -bool load_json_from_file (string filepath, Json::Value &root) -{ - bool rtn = FALSE; - Json::Reader reader; - ifstream ifs (filepath.c_str()); - if (!ifs.bad()) - { - rtn = reader.parse (ifs, root); - ifs.close(); - } - return rtn; -} - -bool write_json_to_file (string filepath, Json::Value &root) -{ - Json::StyledWriter writer; - ofstream ofs (filepath.c_str()); - if (!ofs.bad()) - { - ofs << writer.write (root) << endl; - ofs.close(); - return TRUE; - } - - return FALSE; -} - -int ext_arn_broker_start (Json::Value &request, Json::Value &response) -{ - string task = request["task"].asString(); - nvplist *cli_request, *cli_response; - char _dbmt_error[DBMT_ERROR_MSG_SIZE]; - int ret = ERR_NO_ERROR; - - memset (_dbmt_error, 0, sizeof (_dbmt_error)); - - cli_request = nv_create (5, NULL, "\n", ":", "\n"); - cli_response = nv_create (5, NULL, "\n", ":", "\n"); - - nv_add_nvp (cli_request, "task", task.c_str()); - - if (request["bname"] != Json::Value::null) - { - nv_add_nvp (cli_request, "bname", request["bname"].asString().c_str()); - ret = ts2_start_broker (cli_request, cli_response, _dbmt_error); - } - else - { - ret = ts2_start_unicas (cli_request, cli_response, _dbmt_error); - } - - if (ret == ERR_NO_ERROR) - { - response["status"] = STATUS_SUCCESS; - response["note"] = STATUS_NONE; - } - else - { - response["status"] = STATUS_FAILURE; - response["note"] = _dbmt_error; - } - nv_destroy (cli_request); - nv_destroy (cli_response); - return 0; -} - -bool ext_get_auto_jobs (const string jobkey, Json::Value &jobvalue) -{ - char conf_path[MAX_PATH]; - Json::Value root_jobs; - - if (load_json_from_file ( conf_get_dbmt_file (FID_AUTO_JOBS_CONF, conf_path), root_jobs) == FALSE) - { - LOG_DEBUG ("load json from %s error.", conf_path); - return FALSE; - } - if (jobkey == "") - { - jobvalue = root_jobs; - } - else - { - jobvalue = root_jobs[jobkey]; - } - return TRUE; -} - -bool ext_set_auto_jobs (const string jobkey, Json::Value &jobvalue) -{ - char conf_path[MAX_PATH]; - Json::Value root_jobs; - - if (load_json_from_file ( conf_get_dbmt_file (FID_AUTO_JOBS_CONF, conf_path), root_jobs) == FALSE) - { - LOG_WARN ("%s is not exist!", conf_path); - } - root_jobs[jobkey] = jobvalue; - return write_json_to_file (conf_path, root_jobs); -} - - -int -ext_get_auto_start (Json::Value &request, Json::Value &response) -{ - Json::Value root_jobs; - - if (ext_get_auto_jobs (EXT_JOBS_AUTO_START, root_jobs) == FALSE) - { - response[EXT_JOBS_AUTO_START] = Json::Value::null; - return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); - } - response[EXT_JOBS_AUTO_START] = root_jobs; - - return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); -} - -int -ext_set_auto_start (Json::Value &request, Json::Value &response) -{ - Json::Value root_jobs; - JSON_FIND_V (request, EXT_JOBS_AUTO_START, - build_server_header (response, ERR_PARAM_MISSING, "Parameter(auto_start) missing in the request")); - - JSON_FIND_V (request, "service", - build_server_header (response, ERR_PARAM_MISSING, "Parameter(service) missing in the request")); - - if (ext_get_auto_jobs (EXT_JOBS_AUTO_START, root_jobs) == FALSE) - { - LOG_WARN ("autojob configure file is not exist or error format!"); - } - - root_jobs[request["service"].asString()] = request[EXT_JOBS_AUTO_START]; - - if (ext_set_auto_jobs ( EXT_JOBS_AUTO_START, root_jobs) == FALSE) - { - LOG_WARN ("set auto_start jobs fail!"); - return build_server_header (response, ERR_WITH_MSG, "set auto_start jobs fail!"); - } - - return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); -} - -int -ext_get_autojob_conf (Json::Value &request, Json::Value &response) -{ - Json::Value root_jobs; - char decrypted[PASSWD_LENGTH + 1]; - string userpasswd; - string key = request.get ("service", "").asString(); - - if (ext_get_auto_jobs (key, root_jobs) == FALSE) - { - return build_server_header (response, ERR_WITH_MSG, "failed to get autojob conf"); - } - if (key == "mail_config") - { - userpasswd = root_jobs.get ("password", "").asString(); - uDecrypt (PASSWD_LENGTH, userpasswd.c_str(), decrypted); - root_jobs["password"] = decrypted; - } - - response["jobconf"] = root_jobs; - - return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); -} - -int -ext_set_autojob_conf (Json::Value &request, Json::Value &response) -{ - Json::Value root_jobs; - string keyvalue, password; - char encrypted[PASSWD_ENC_LENGTH]; - - JSON_FIND_V (request, "service", - build_server_header (response, ERR_PARAM_MISSING, "Parameter(service) missing in the request")); - - keyvalue = request["service"].asString(); - if (keyvalue == "mail_config") - { - if (request["jobconf"] != Json::Value::null - && request["jobconf"].type() == Json::objectValue - && request["jobconf"]["password"] != Json::Value::null) - { - password = request["jobconf"]["password"].asString(); - uEncrypt (PASSWD_LENGTH, password.c_str(), encrypted); - request["jobconf"]["password"] = encrypted; - } - else - { - return build_server_header (response, ERR_WITH_MSG, "error mail_config format!"); - } - } - if (ext_set_auto_jobs ( keyvalue, request["jobconf"]) == FALSE) - { - LOG_WARN ("set %s fail!", keyvalue.c_str()); - return build_server_header (response, ERR_WITH_MSG, "set autojob conf fail!"); - } - - return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); -} - -int ext_get_active_dbs (Json::Value &activedbs) -{ - T_SERVER_STATUS_RESULT *cmd_res; - int i; - cmd_res = cmd_server_status (); - if (cmd_res == NULL) - { - return 1; - } - T_SERVER_STATUS_INFO *info = (T_SERVER_STATUS_INFO *) cmd_res->result; - for (i = 0; i < cmd_res->num_result; i++) - { - activedbs .append (info[i].db_name); - } - cmd_servstat_result_free (cmd_res); - return 0; -} - -int ext_get_active_brokers (Json::Value &activebrokers) -{ - T_CM_BROKER_INFO_ALL uc_info; - T_CM_BROKER_CONF uc_conf; - T_CM_ERROR error; - Json::Value broker; - int i; - - if (cm_get_broker_conf (&uc_conf, NULL, &error) < 0) - { - return 1; - } - if (cm_get_broker_info (&uc_info, &error) < 0) - { - activebrokers["brokerstatus"] = "OFF"; - } - else - { - for (i = 0; i < uc_info.num_info; i++) - { - broker["name"] = uc_info.br_info[i].name; - broker["state"] = uc_info.br_info[i].status; - activebrokers["brokers"].append (broker); - } - activebrokers["brokerstatus"] = "ON"; - cm_broker_info_free (&uc_info); - } - - cm_broker_conf_free (&uc_conf); - return 0; -} - - -static void -ext_autojobs_log (const char *service, const char *serv_name, const char *errmsg) -{ - time_t tt; - tm *t; - FILE *outfile; - char logfile[MAX_PATH]; - char strbuf[MAX_PATH] = "unknown"; - - tt = time (&tt); - - snprintf (logfile, MAX_PATH, "%s/%s/autojobs.log", sco.szArniadb, DBMT_LOG_DIR); - - outfile = fopen (logfile, "a"); - if (outfile == NULL) - { - return; - } - t = localtime (&tt); - if (t) - { - strftime ( strbuf, MAX_PATH, "%Y%m%d_%H:%M:%S", t); - } - fprintf (outfile, "%s %s %s : %s\n",strbuf, service, serv_name, errmsg); - fclose (outfile); -} - - -int ext_exec_dbs_auto_start (const Json::Value &autodbs, Json::Value &response) -{ - unsigned int i, j, found; - char err_buf[ERR_MSG_SIZE]; - Json::Value activedbs; - string dbname; - - if (autodbs == Json::Value::null) - { - return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); - } - - if (ext_get_active_dbs (activedbs)) - { - LOG_ERROR ("get active db list failed!"); - return build_server_header (response, ERR_WITH_MSG, "get active db list failed!"); - } - - for (i = 0; i < autodbs.size(); i++) - { - found = 0; - dbname = autodbs[i].asString(); - for (j = 0; j < activedbs.size(); j++) - { - if (activedbs[j].asString() == dbname) - { - found = 1; - break; - } - } - - if (found == 0) - { - if (cmd_start_server ((char *)dbname.c_str(), err_buf, sizeof (err_buf)) < 0) - { - ext_autojobs_log ("databases", dbname.c_str(), err_buf); - response[EXT_JOBS_AUTO_START]["databases"][dbname] = err_buf; - } - else - { - ext_autojobs_log ("databases", dbname.c_str(), STATUS_SUCCESS); - response[EXT_JOBS_AUTO_START]["databases"][dbname] = STATUS_SUCCESS; - } - } - } - - return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); -} - -int ext_exec_brokers_auto_start (const Json::Value &autobrokers, Json::Value &response) -{ - unsigned int i,t; - Json::Value activebrokers, request; - string bname; - - if (autobrokers == Json::Value::null || autobrokers.size() == 0) - { - return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); - } - - if (ext_get_active_brokers (activebrokers)) - { - LOG_ERROR ("get active db list failed!"); - return build_server_header (response, ERR_WITH_MSG, "get active db list failed!"); - } - - if (activebrokers["brokerstatus"].asString() == "OFF") - { - request["task"] = "startbroker"; - ext_arn_broker_start (request, response); - - if (response["status"] != "success") - { - ext_autojobs_log ("brokers", "unicas", response["note"].asString().c_str()); - response[EXT_JOBS_AUTO_START]["brokers"]["@unicas"] = response["note"].asString(); - } - else - { - ext_autojobs_log ("brokers", "unicas", STATUS_SUCCESS); - response[EXT_JOBS_AUTO_START]["brokers"]["@unicas"] = STATUS_SUCCESS; - } - } - - for (t = 0; t < autobrokers.size(); t++) - { - for (i = 0; i < activebrokers["brokers"].size(); i++) - { - bname = activebrokers["brokers"][i]["name"].asString(); - if (bname == autobrokers[t].asString() && - activebrokers["brokers"][i]["state"].asString() == "OFF") - { - request["task"] = "broker_start"; - request["bname"] = bname; - ext_arn_broker_start (request, response); - - if (response["status"] != "success") - { - ext_autojobs_log ("brokers", bname.c_str(), response["note"].asString().c_str()); - response[EXT_JOBS_AUTO_START]["brokers"][bname] = response["note"].asString(); - } - else - { - ext_autojobs_log ("brokers", bname.c_str(), STATUS_SUCCESS); - response[EXT_JOBS_AUTO_START]["brokers"][bname] = STATUS_SUCCESS; - } - } - } - } - return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); -} - -string format_time (string str_time) -{ - string::iterator itor; - itor = str_time.begin(); - while ( itor != str_time.end()) - { - if (*itor == ' ' || *itor == '/' || *itor == ':') - { - itor = str_time.erase (itor); - } - else - { - itor++; - } - } - return str_time; -} - -string build_report_log (Json::Value &report) -{ - unsigned int i, j; - int log_type; - string report_log, url_prefix, db_name, tmp_str; - string start_time, end_time; - Json::Value logdata; - - start_time = report.get ("start_time", "").asString(); - end_time = report.get ("end_time", "").asString(); - url_prefix = report.get ("url_prefix", "").asString(); - db_name= report.get ("dbname", "").asString(); - log_type= report.get ("log_type", 0).asInt(); - - report_log = "
Hi, This is timed log report."; - report_log += "
"; - report_log += "
start time : " + start_time; - report_log += "
end time : " + end_time; - report_log += "
"; - switch (log_type) - { - case 0: - logdata = report["db"]; - if (logdata != Json::Value::null) - { - if (logdata["result"] != Json::Value::null) - { - report_log += ""; - for (i = 0; i < logdata["result"].size(); i++) - { - //report_log += ""; - tmp_str = ""; - if (report_log.size() > 1024) - { - report_log += ""; - break; - } - } - report_log += "
Databases Log Message
" + logdata["result"][i]["file"].asString() + "
"; - for (j = 0; j < logdata["result"][i]["logs"].size(); j++) - { - tmp_str += "
" + logdata["result"][i]["logs"][j].asString(); - if (tmp_str.size() > 256) - { - tmp_str += "
more logs in " + logdata["result"][i]["file"].asString(); - break; - } - } - report_log += tmp_str + "
......
"; - } - else - { - report_log += "
*** No record ***"; - } - } - else - { - report_log += "
*** No record ***"; - } - break; - case 1: - logdata = report["broker"]; - report_log += "
Log type : Broker start/stop log"; - if (logdata != Json::Value::null) - { - if (logdata["log"] != Json::Value::null) - { - report_log += ""; - for (i = 0; i < logdata["log"].size(); i++) - { - report_log += ""; - } - report_log += "
Broker Log Description
" + logdata["log"][i].asString() + "
"; - } - else - { - report_log += "
*** No record ***"; - } - } - else - { - report_log += "
*** No record ***"; - } - break; - default: - break; - } - report_log += "
See More Detail Log: ARNIADB Web Manager"; - return report_log; -} - -int update_next_report_time (Json::Value &mailreport) -{ - return 0; -} - -int ext_exec_mail_report (Json::Value &mailreport, Json::Value &response) -{ - unsigned int i, period_type, save_flag = 0; - Json::Value log_request, log_response, mail_conf; - time_t cur_time, next_time; - char format_time[PATH_MAX], next_exec_time[PATH_MAX]; - string next_exec, prev_exec, mailhead, mailbody, userpasswd; - char decrypted[PASSWD_LENGTH + 1]; - - if (mailreport == Json::Value::null || mailreport.size() == 0) - { - return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); - } - - if (ext_get_auto_jobs (EXT_JOBS_MAIL_CONF, mail_conf) == FALSE) - { - LOG_ERROR ("get mail config failed!"); - return build_server_header (response, ERR_WITH_MSG, "get mail config failed!"); - } - - if (mail_conf == Json::Value::null || mail_conf["onoff"].asInt() == 0) - { - return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); - } - - userpasswd = mail_conf.get ("password", "").asString(); - uDecrypt (PASSWD_LENGTH, userpasswd.c_str(), decrypted); - mail_conf["password"] = decrypted; - - cur_time = time (NULL); - time_to_str (cur_time, "%4d/%02d/%02d %02d:%02d:%02d", format_time, TIME_STR_FMT_DATE_TIME); - for (i = 0; i < mailreport.size(); i++) - { - if (mailreport[i]["receiver"] == Json::Value::null) - { - continue; - } - if (mailreport[i]["dbname"] == Json::Value::null) - { - continue; - } - if (mailreport[i]["url_prefix"] == Json::Value::null) - { - continue; - } - - next_exec = ""; - prev_exec = ""; - mailbody = ""; - if (mailreport[i]["prev_exec"] != Json::Value::null) - { - prev_exec = mailreport[i]["prev_exec"].asString(); - } - if (mailreport[i]["next_exec"] != Json::Value::null) - { - next_exec = mailreport[i]["next_exec"].asString(); - } - if ( strcmp (format_time, next_exec.c_str()) < 0) - { - continue; - } - - log_request["dbname"] = mailreport[i]["dbname"].asString(); - log_request["start_time"] = prev_exec; - log_request["end_time"] = format_time; - - mailhead = "Log Report for ARNIADB"; - - log_response["dbname"] = mailreport[i]["dbname"].asString(); - log_response["url_prefix"] = mailreport[i]["url_prefix"].asString(); - log_response["start_time"] = prev_exec; - log_response["end_time"] = format_time; - log_response["log_type"] = mailreport[i].get ("log_type", 0).asInt(); - - ext_get_db_err_log (log_request, log_response["db"]); - ext_get_broker_start_log (log_request, log_response["broker"]); - mailbody += build_report_log (log_response); - - mail_conf["receiver"] = mailreport[i]["receiver"]; - mail_conf["msg_header"] = mailhead; - mail_conf["msg_body"] = mailbody; - mail_conf["body_type"] = 1; - ext_send_mail (mail_conf, response); - - period_type = mailreport[i].get ("period_type", 2).asInt(); - switch (period_type) - { - case 0: /* daily */ - next_time = cur_time + 24 * 60 * 60; - break; - case 1: /* weekly */ - next_time = cur_time + 7 * 24 * 60 * 60; - break; - default: /* monthly */ - next_time = cur_time + 30 * 24 * 60 * 60; - break; - } - time_to_str (next_time, "%4d/%02d/%02d %02d:%02d:%02d", next_exec_time, TIME_STR_FMT_DATE_TIME); - mailreport[i]["next_exec"] = next_exec_time; - mailreport[i]["prev_exec"] = format_time; - save_flag = 1; - } - - if (save_flag) - { - ext_set_auto_jobs ("mail_report", mailreport); - } - - return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); -} - -int ext_exec_auto_mail (Json::Value &request, Json::Value &response) -{ - Json::Value mail_report; - if (ext_get_auto_jobs (EXT_JOBS_MAIL_REPORT, mail_report) == FALSE) - { - LOG_WARN ("get mail report config failed!"); - return build_server_header (response, ERR_WITH_MSG, "get mail report config failed!"); - } - return ext_exec_mail_report (mail_report, response); -} - -int ext_exec_auto_start (Json::Value &request, Json::Value &response) -{ - Json::Value autojobs; - string dbname; - - if (ext_get_auto_jobs (EXT_JOBS_AUTO_START, autojobs) == FALSE) - { - LOG_DEBUG ("get auto start jobs failed."); - return build_server_header (response, ERR_WITH_MSG, "get auto start jobs failed."); - } - - if (autojobs == Json::Value::null) - { - return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); - } - - ext_exec_brokers_auto_start (autojobs["brokers"], response); - ext_exec_dbs_auto_start (autojobs["databases"], response); - - return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); -} - -int ext_exec_auto_jobs (Json::Value &request, Json::Value &response) -{ - ext_exec_auto_start (request, response); - // Fix for TOOLS-3452 - // Delivery this fuctionality next version Aug/3/2013 - //ext_exec_auto_mail(request, response); - return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); -} - - -int ext_get_db_err_log (Json::Value &request, Json::Value &response) -{ - string start_d, end_d; - string dbname; - char log_dir[PATH_MAX], find_file[PATH_MAX], format_time[PATH_MAX]; - char buf[1024], logbuf[1024]; -#if defined(WINDOWS) - WIN32_FIND_DATA data; - HANDLE handle; - int found; -#else - DIR *dirp = NULL; - struct dirent *dp = NULL; -#endif - struct stat statbuf; - char *fname; - int fname_len = 0, logsize = 0; - Json::Value logitem; - FILE *fd; - JSON_FIND_V (request, "dbname", - build_server_header (response, ERR_PARAM_MISSING, "Parameter(dbname) missing in the request")); - - dbname = request["dbname"].asString(); - if (request["start_time"] != Json::Value::null) - { - start_d = request["start_time"].asString(); - } - if (request["end_time"] != Json::Value::null) - { - end_d = request["end_time"].asString(); - } - response["start_time"] = start_d; - response["end_time"] = end_d; - response["dbname"] = dbname; - - if (uRetrieveDBDirectory (dbname.c_str(), log_dir) != ERR_NO_ERROR) - { - return build_server_header (response, ERR_DBDIRNAME_NULL, "Can not find the directory!"); - } - - snprintf (find_file, PATH_MAX - 1, "%s/%s", sco.szArniadb, ARNIADB_ERROR_LOG_DIR); -#if defined(WINDOWS) - snprintf (&find_file[strlen (find_file)], PATH_MAX - strlen (find_file) - 1, "/*"); - if ((handle = FindFirstFile (find_file, &data)) == INVALID_HANDLE_VALUE) -#else - if ((dirp = opendir (find_file)) == NULL) -#endif - { - return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); - } -#if defined(WINDOWS) - for (found = 1; found; found = FindNextFile (handle, &data)) -#else - while ((dp = readdir (dirp)) != NULL) -#endif - { -#if defined(WINDOWS) - fname = data.cFileName; -#else - fname = dp->d_name; -#endif - fname_len = (int) strlen (fname); - /* the "4" is the size of ".err" */ - if (fname_len < 4 || (strcmp (fname + fname_len - 4, ".err") != 0)) - { - continue; - } - if (memcmp (fname, dbname.c_str(), dbname.size())) - { - continue; - } - snprintf (buf, sizeof (buf) - 1, "%s/%s/%s", sco.szArniadb, ARNIADB_ERROR_LOG_DIR, fname); - if (stat (buf, &statbuf) == 0) - { - time_to_str (statbuf.st_mtime, "%4d/%02d/%02d %02d:%02d:%02d", format_time, TIME_STR_FMT_DATE_TIME); - if (!start_d.empty() && strcmp (start_d.c_str(), format_time) > 0) - { - continue; - } - if (!end_d.empty() && strcmp (end_d.c_str(), format_time) < 0) - { - continue; - } - logitem.clear(); - logitem["file"] = buf; - fd = fopen (buf, "r"); - if (fd == NULL) - { - continue; - } - while (fgets (logbuf, sizeof (logbuf), fd) != NULL) - { - ut_trim (logbuf); - logitem["logs"].append (logbuf); - logsize++; - if (logsize > 2000) - { - break; - } - } - fclose (fd); - response["result"].append (logitem); - if (logsize > 2000) - { - response["overflow"] = 1; - break; - } - } - } -#if defined(WINDOWS) - FindClose (handle); -#else - closedir (dirp); -#endif - - return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); -} - - -int ext_get_broker_start_log (Json::Value &request, Json::Value &response) -{ - char log_file[PATH_MAX]; - char logbuf[1024]; - FILE *fd; - string start_d, end_d; - char *tok[2]; - string format_time, strlog; - int logsize = 0; - - snprintf (log_file, PATH_MAX - 1, "%s/%s/arniadb_broker.log", sco.szArniadb, ARNIADB_BROKER_LOG_DIR); - fd = fopen (log_file, "r"); - if (fd == NULL) - { - return build_server_header (response, ERR_WITH_MSG, "Can't find arniadb_broker.log"); - } - - if (request["start_time"] != Json::Value::null) - { - start_d = request["start_time"].asString(); - } - if (request["end_time"] != Json::Value::null) - { - end_d = request["end_time"].asString(); - } - response["start_time"] = start_d; - response["end_time"] = end_d; - response["file"] = log_file; - - while (fgets (logbuf, sizeof (logbuf), fd) != NULL) - { - ut_trim (logbuf); - strlog = logbuf; - if (string_tokenize (logbuf, tok, 2) < 0) - { - continue; - } - format_time = string (tok[0]) + " " + string (tok[1]); - if (!start_d.empty() && strcmp (start_d.c_str(), format_time.c_str()) > 0) - { - continue; - } - if (!end_d.empty() && strcmp (end_d.c_str(), format_time.c_str()) < 0) - { - continue; - } - response["log"].append (strlog); - logsize++; - if (logsize > 2000) - { - response["overflow"] = 1; - break; - } - } - fclose (fd); - return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); -} - -int ext_send_mail (Json::Value &request, Json::Value &response) -{ - string sender, receiver; - string smtp_server, uname, passwd; - string msg_body, msg_header; - jwsmtp::mailer mail; - int auth_type, body_type; - Json::Value result; - - JSON_FIND_V (request, "sender", - build_server_header (response, ERR_PARAM_MISSING, "Parameter(sender) missing in the request")); - JSON_FIND_V (request, "receiver", - build_server_header (response, ERR_PARAM_MISSING, "Parameter(receiver) missing in the request")); - JSON_FIND_V (request, "smtp_server", - build_server_header (response, ERR_PARAM_MISSING, "Parameter(smtp_server) missing in the request")); - JSON_FIND_V (request, "username", - build_server_header (response, ERR_PARAM_MISSING, "Parameter(username) missing in the request")); - JSON_FIND_V (request, "password", - build_server_header (response, ERR_PARAM_MISSING, "Parameter(password) missing in the request")); - - sender = request["sender"].asString(); - mail.setsender (sender); - - receiver = request["receiver"].asString(); - mail.addrecipient (receiver); - - smtp_server = request["smtp_server"].asString(); - mail.setserver (smtp_server); - - auth_type = request.get ("authtype", 2).asInt(); - mail.authtype ((enum jwsmtp::mailer::authtype)auth_type); - - uname = request["username"].asString(); - mail.username (uname); - - passwd = request["password"].asString(); - mail.password (passwd); - - msg_header = request.get ("msg_header", "").asString(); - mail.setsubject (msg_header); - - msg_body = request.get ("msg_body", "").asString(); - body_type = request.get ("body_type", 0).asInt(); - if (body_type == 1) - { - mail.setmessageHTML (msg_body); - } - else - { - mail.setmessage (msg_body); - } - - mail.send(); - result["receiver"] = receiver; - result["message"] = mail.response(); - response["response"].append (result); - return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); -} - -int ext_write_private_data (Json::Value &request, Json::Value &response) -{ - FILE *outfile; - unsigned int i; - string confname; - Json::Value confdata; - char conf_path[PATH_MAX]; - - JSON_FIND_V (request, "confname", - build_server_header (response, ERR_PARAM_MISSING, "Parameter(confname) missing in the request")); - - confname= request["confname"].asString(); - snprintf (conf_path, PATH_MAX, "%s/%s/%s", sco.szArniadb, DBMT_LOG_DIR, confname.c_str()); - - outfile = fopen (conf_path, "w"); - if (outfile == NULL) - { - return build_server_header (response, ERR_FILE_OPEN_FAIL, string ("open " + string (conf_path) + " failed!").c_str()); - } - confdata = request["confdata"]; - for (i = 0; i < confdata.size(); i++) - { - fprintf (outfile, "%s\n", confdata[i].asString().c_str()); - } - fclose (outfile); - - return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); -} - -int ext_read_private_data (Json::Value &request, Json::Value &response) -{ - FILE *infile; - string confname; - char conf_path[PATH_MAX], strbuf[1024 * 200]; - - JSON_FIND_V (request, "confname", - build_server_header (response, ERR_PARAM_MISSING, "Parameter(confname) missing in the request")); - - confname= request["confname"].asString(); - snprintf (conf_path, PATH_MAX, "%s/%s/%s", sco.szArniadb, DBMT_LOG_DIR, confname.c_str()); - - infile = fopen (conf_path, "r"); - if (infile == NULL) - { - return build_server_header (response, ERR_FILE_OPEN_FAIL, string ("open " + confname + " failed!").c_str()); - } - while (fgets (strbuf, sizeof (strbuf), infile) != NULL) - { - uRemoveCRLF (strbuf); - response["confdata"].append (strbuf); - } - fclose (infile); - - return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); -} - -static int _find_dba_password (const string &dbname, const string &query_id, char *userpass, char *_dbmt_error) -{ - char autoexecquery_conf_file[PATH_MAX]; - ifstream conf_file; - char line_buf[LINE_MAX]; - bool is_find = false; - - autoexecquery_conf_file[0] = '\0'; - line_buf[0] = '\0'; - - conf_get_dbmt_file (FID_AUTO_EXECQUERY_CONF, autoexecquery_conf_file); - conf_file.open (autoexecquery_conf_file, ios::in); - if (!conf_file.good()) - { - strncpy (_dbmt_error, autoexecquery_conf_file, DBMT_ERROR_MSG_SIZE); - return ERR_FILE_OPEN_FAIL; - } - - strncpy (userpass, "", PASSWD_ENC_LENGTH); - - while (conf_file.getline (line_buf, LINE_MAX)) - { - istringstream stream_buf (line_buf); - string tmp_dbname; - string tmp_queryid; - string tmp_id; - string tmp_password; - - stream_buf >> tmp_dbname >> tmp_queryid >> tmp_id >> tmp_password; - - if (tmp_dbname == dbname || tmp_queryid == query_id) - { - strncpy (userpass, tmp_password.c_str(), PASSWD_ENC_LENGTH); - is_find = true; - break; - } - } - conf_file.close(); - - if (!is_find) - { - strncpy (_dbmt_error, autoexecquery_conf_file, DBMT_ERROR_MSG_SIZE); - return ERR_FILE_INTEGRITY; - } - - return ERR_NO_ERROR; -} - -int ext_set_autoexec_query (Json::Value &request, Json::Value &response) -{ - char autoexecquery_conf_file[PATH_MAX]; - char tmp_conf_file[PATH_MAX]; - char token_content[3][TOKEN_LENGTH+1]; - char userpass[PASSWD_ENC_LENGTH]; - char line_buf[MAX_JOB_CONFIG_FILE_LINE_LENGTH]; - char _dbmt_error[DBMT_ERROR_MSG_SIZE]; - unsigned int index = 0; // for json operator [](UInt). - int ret_val = 0; - Json::Value planlist; - Json::Value queryplan; - string sql_script; - string conf_item[AUTOEXECQUERY_CONF_ENTRY_NUM]; - fstream conf_file; - ofstream tmp_file; - - - autoexecquery_conf_file[0] = '\0'; - tmp_conf_file[0] = '\0'; - token_content[0][0] = '\0'; - token_content[1][0] = '\0'; - token_content[2][0] = '\0'; - userpass[0] = '\0'; - line_buf[0] = '\0'; - _dbmt_error[0] = '\0'; - - conf_get_dbmt_file (FID_AUTO_EXECQUERY_CONF, autoexecquery_conf_file); - if (access (autoexecquery_conf_file, F_OK) == 0) - { - conf_file.open (autoexecquery_conf_file, ios::in); - } - else - { - conf_file.open (autoexecquery_conf_file, ios::in | ios::out); - } - if (!conf_file.good()) - { - char tmp[DBMT_ERROR_MSG_SIZE]; - snprintf (tmp, DBMT_ERROR_MSG_SIZE-1, "File(%s) open error", autoexecquery_conf_file); - return build_server_header (response, ERR_FILE_OPEN_FAIL, tmp); - } - - // open a temp file for new auto query config. - snprintf (tmp_conf_file, PATH_MAX-1, "%s/DBMT_task_045.%d", sco.dbmt_tmp_dir, static_cast (getpid())); - tmp_file.open (tmp_conf_file, ios::out); - if (!tmp_file.good()) - { - return build_server_header (response, ERR_FILE_OPEN_FAIL, "Temporal file open error."); - } - - // dbname - conf_item[0] = request["dbname"].asString(); - - // get manager id from token - if (!ext_get_id_from_token (request["token"].asString().c_str(), token_content)) - { - return build_server_header (response, ERR_INVALID_TOKEN, - "Request is rejected due to invalid token. Please reconnect."); - } - conf_item[4] = token_content[2]; - - while (conf_file.getline (line_buf, sizeof (line_buf))) - { - istringstream stream_buf (line_buf); - string ignored_info, db_name, db_uid; - - stream_buf >> db_name >> ignored_info >> ignored_info >> ignored_info >> db_uid; - - if (db_name != conf_item[0] || db_uid != conf_item[4]) - { - tmp_file << line_buf << endl; - } - - } - conf_file.close(); - tmp_file.close(); - - index = 0; - - JSON_FIND_V (request, "dbname", - build_server_header (response, ERR_PARAM_MISSING, "Parameter(dbname) missing in the request")); - JSON_FIND_V (request, "token", - build_server_header (response, ERR_PARAM_MISSING, "Parameter(token) missing in the request")); - JSON_FIND_V (request, "planlist", - build_server_header (response, ERR_PARAM_MISSING, "Parameter(planlist) missing in the request")); - planlist = request["planlist"]; - - JSON_FIND_V (planlist[index], "queryplan", - build_server_header (response, ERR_PARAM_MISSING, "Parameter(planquery) missing in the request")); - queryplan = planlist[index]["queryplan"]; - - - - for (index = 0; index < queryplan.size(); ++index) - { - - JSON_FIND_V (queryplan[index], "username", - build_server_header (response, ERR_PARAM_MISSING, "Parameter(username) missing in the request")); - JSON_FIND_V (queryplan[index], "userpass", - build_server_header (response, ERR_PARAM_MISSING, "Parameter(userpass) missing in the request")); - JSON_FIND_V (queryplan[index], "period", - build_server_header (response, ERR_PARAM_MISSING, "Parameter(period) missing in the request")); - JSON_FIND_V (queryplan[index], "detail", - build_server_header (response, ERR_PARAM_MISSING, "Parameter(detail) missing in the request")); - JSON_FIND_V (queryplan[index], "query_string", - build_server_header (response, ERR_PARAM_MISSING, "Parameter(query_string) missing in the request")); - JSON_FIND_V (queryplan[index], "query_id", - build_server_header (response, ERR_PARAM_MISSING, "Parameter(query_id) missing in the request")); - - tmp_file.open (tmp_conf_file, ios::out | ios::app); - if (!tmp_file.good()) - { - return build_server_header (response, ERR_FILE_OPEN_FAIL, "Temporal file open error."); - } - - - // query_id - conf_item[1] = queryplan[index]["query_id"].asString(); - - // the name of dba - conf_item[2] = queryplan[index]["username"].asString(); - - // get password after encrpition. - // if password equals to "none" or "<>", - // that means this query plan just use empty password. - // if password equals to "unknown" or "<>", - // that means this query plan just use previous password. - // for more details, see tools-3464. - if (queryplan[index]["userpass"].asString() == "none" || - queryplan[index]["userpass"].asString() == "<>") - { - uEncrypt (PASSWD_LENGTH, "", userpass); - } - else if (queryplan[index]["userpass"].asString() == "unknown" || - queryplan[index]["userpass"].asString() == "<>") - { - if ((ret_val = _find_dba_password (conf_item[0], conf_item[1], userpass, _dbmt_error)) != ERR_NO_ERROR) - { - return build_server_header (response, ret_val, _dbmt_error); - } - } - else - { - uEncrypt (PASSWD_LENGTH, queryplan[index]["userpass"].asString().c_str(), userpass); - } - conf_item[3] = userpass; - - // period - conf_item[5] = queryplan[index]["period"].asString(); - - // details of period - conf_item[6] = queryplan[index]["detail"].asString(); - - // get sql script, checking its length - sql_script = queryplan[index]["query_string"].asString(); - if (sql_script.length() == 0 || sql_script.length() > MAX_AUTOQUERY_SCRIPT_SIZE) - { - char tmp[DBMT_ERROR_MSG_SIZE]; - snprintf (tmp, DBMT_ERROR_MSG_SIZE-1, "Query script too long. MAX_AUTOQUERY_SCRIPT_SIZE:%d.", - MAX_AUTOQUERY_SCRIPT_SIZE); - tmp_file.close(); - - return build_server_header (response, ERR_WITH_MSG, tmp); - } - conf_item[7] = sql_script; - - for (int i = 0; i < 7; ++i) - { - tmp_file << conf_item[i] << ' '; - } - tmp_file << conf_item[7] << endl; - - tmp_file.close(); - - } - - move_file (tmp_conf_file, autoexecquery_conf_file); - - return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); - -} - -static int _read_apply_info_cmd_output (const string &stdout_file, const string &stderr_file, string (& str_result)[8]) -{ - ifstream in_file; - string line_buf; - unsigned found; - - in_file.open (stderr_file.c_str(), ios::in); - - if (getline (in_file, line_buf)) - { - in_file.close(); - return ERR_GENERAL_ERROR; - } - - in_file.close(); - - in_file.open (stdout_file.c_str(), ios::in); - - int i = 0; - int j = 4; - while (getline (in_file, line_buf)) - { - if (line_buf.find ("Delay in Applying Copied Log") != string::npos) - { - i = 2; - continue; - } - - if (line_buf.find ("Delayed log page count") != string::npos) - { - found = (unsigned int) line_buf.find (":"); - - str_result[i++] = line_buf.substr (found+2); - continue; - } - - if (line_buf.find ("Estimated Delay") != string::npos) - { - - unsigned int tmp_pos = (unsigned int) line_buf.find ("second(s)"); - found = (unsigned int) line_buf.find (":"); - - str_result[i++] = line_buf.substr (found+2, tmp_pos-found-3); - if (str_result[i-1] == "-") - { - str_result[i-1] = ""; - } - continue; - } - - if (line_buf.find ("*** Active") != string::npos) - { - j = 6; - continue; - } - - if (line_buf.find ("EOF LSA") != string::npos) - { - found = (unsigned int) line_buf.find (":"); - str_result[j] = line_buf.substr (found+2); - found = (unsigned int) str_result [j].find (" "); - str_result [j++].erase (found); - - found = (unsigned int) line_buf.find ("|"); - str_result[j++] = line_buf.substr (found+2); - } - } - - return ERR_NO_ERROR; -} - -int ext_get_ha_apply_info (Json::Value &request, Json::Value &response) -{ - - string opt_applyinfo = "applyinfo"; - string opt_L = "-L"; - string opt_r = "-r"; - string opt_a = "-a"; - string copy_log_path; - string remote_host_name; - string dbname; - string str_result[8]; - - char cmd_name[ARNIADB_CMD_NAME_LEN]; - const char *argv[9]; - char stdout_log_file[512]; - char stderr_log_file[512]; - - int retval; - - Json::Value copied_active_eof_lsa, active_eof_lsa; - - JSON_FIND_V (request, "copylogpath", - build_server_header (response, ERR_PARAM_MISSING, "Parameter(copylogpath) missing in the request")); - JSON_FIND_V (request, "remotehostname", - build_server_header (response, ERR_PARAM_MISSING, "Parameter(remotehostname) missing in the request")); - JSON_FIND_V (request, "dbname", - build_server_header (response, ERR_PARAM_MISSING, "Parameter(remotehostname) missing in the request")); - - sprintf (stdout_log_file, "%s/cmhastop.%d.out", sco.dbmt_tmp_dir, (int)getpid()); - sprintf (stderr_log_file, "%s/cmhastop.%d.err", sco.dbmt_tmp_dir, (int)getpid()); - - copy_log_path = request["copylogpath"].asString(); - remote_host_name = request["remotehostname"].asString(); - dbname = request["dbname"].asString(); - - arniadb_cmd_name (cmd_name); - - argv[0] = cmd_name; - argv[1] = opt_applyinfo.c_str(); - argv[2] = opt_L.c_str(); - argv[3] = copy_log_path.c_str(); - argv[4] = opt_r.c_str(); - argv[5] = remote_host_name.c_str(); - argv[6] = opt_a.c_str(); - argv[7] = dbname.c_str(); - argv[8] = NULL; - - run_child (argv, 1, NULL, stdout_log_file, stderr_log_file, NULL); - - if ((retval=_read_apply_info_cmd_output (stdout_log_file, stderr_log_file, str_result)) != ERR_NO_ERROR) - { - return build_server_header (response, retval, "Invalid options or command format!"); - } - - response["copyinglog_count"] = str_result[0]; - response["copyinglog_estimated_time"] = str_result[1]; - response["applyinglog_count"] = str_result[2]; - response["applyinglog_estimated_time"] = str_result[3]; - - copied_active_eof_lsa.clear (); - active_eof_lsa.clear (); - - copied_active_eof_lsa ["pageid"] = str_result[4]; - copied_active_eof_lsa ["offset"] = str_result[5]; - active_eof_lsa ["pageid"] = str_result[6]; - active_eof_lsa ["offset"] = str_result[7]; - - response["copied_active_eof_lsa"] = copied_active_eof_lsa; - response["active_eof_lsa"] = active_eof_lsa; - - return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); -} - -int ext_add_dbmt_user_new (Json::Value &request, Json::Value &response) -{ - T_DBMT_USER dbmt_user; - T_DBMT_USER_AUTHINFO *authinfo = NULL; - T_DBMT_USER_DBINFO *dbinfo = NULL; - - char dbmt_error[DBMT_ERROR_MSG_SIZE]; - char dbmt_password[PASSWD_ENC_LENGTH]; - char str_auth[12]; // the length of number 2^32 - - T_USER_AUTH auth = 0; - int num_authinfo = 0; - int num_dbmt_user = 0; - int num_dbinfo = 0; - int retval; - - string user_id, password; - - Json::Value authoritylist; - Json::Value dbauthlist; - - - JSON_FIND_V (request, "targetid", - build_server_header (response, ERR_PARAM_MISSING, "Parameter(targetid) missing in the request")); - JSON_FIND_V (request, "password", - build_server_header (response, ERR_PARAM_MISSING, "Parameter(password) missing in the request")); - - user_id = request["targetid"].asString(); - password = request["password"].asString(); - - if (0 != IsValidUserName (user_id.c_str())) - { - return build_server_header (response, ERR_WITH_MSG, - "Invalid user name! User name should begin with a letter, and can only contain letters, digits or underscore. The length should be between 4 and 32."); - } - - if (password.length() > PASSWD_LENGTH || password.length() < MIN_PASSWD_LENGTH) - { - return build_server_header (response, ERR_WITH_MSG, "Invalid password! The length should be between 4 and 32."); - } - - if ((retval = dbmt_user_read (&dbmt_user, dbmt_error) != ERR_NO_ERROR)) - { - return build_server_header (response, retval, dbmt_error); - } - - uEncrypt (PASSWD_LENGTH, password.c_str(), dbmt_password); - - num_dbmt_user = dbmt_user.num_dbmt_user; - for (int i = 0; i < dbmt_user.num_dbmt_user; ++i) - { - if (strcmp (dbmt_user.user_info[i].user_name, user_id.c_str()) == 0) - { - dbmt_user_free (&dbmt_user); - sprintf (dbmt_error, "ARNIADB Manager user(%s) already exist.", user_id.c_str()); - return build_server_header (response, ERR_DBMTUSER_EXIST, dbmt_error); - } - } - - // set user authority info - JSON_FIND_V (request, "authoritylist", build_server_header (response, ERR_PARAM_MISSING, - "Parameter(authoritylist) missing in the request")); - authoritylist = request["authoritylist"]; - Json::Value json_value = authoritylist; - - if (json_value["admin"] != Json::Value::null) - { - if (json_value["admin"].asString() != "yes") - { - dbmt_user_free (&dbmt_user); - return build_server_header (response, ERR_WITH_MSG, "The value of 'admin' should be 'yes'!"); - } - auth |= AU_ADMIN; - - authinfo = (T_DBMT_USER_AUTHINFO *) increase_capacity (authinfo, sizeof (T_DBMT_USER_AUTHINFO), num_authinfo, - num_authinfo + 2); - if (authinfo == NULL) - { - dbmt_user_free (&dbmt_user); - return build_server_header (response, ERR_MEM_ALLOC, "Memory Allocation error."); - } - - dbmt_user_set_authinfo (& (authinfo[1]), "admin", "yes"); - num_authinfo += 2; - } - else - { - JSON_FIND_V (json_value, "dbc", build_server_header (response, ERR_PARAM_MISSING, - "Parameter(dbc or admin) missing in the authoritylist")); - JSON_FIND_V (json_value, "dbo", build_server_header (response, ERR_PARAM_MISSING, - "Parameter(dbo or admin) missing in the authoritylist")); - JSON_FIND_V (json_value, "brk", build_server_header (response, ERR_PARAM_MISSING, - "Parameter(brk or admin) missing in the authoritylist")); - JSON_FIND_V (json_value, "mon", build_server_header (response, ERR_PARAM_MISSING, - "Parameter(mon or admin) missing in the authoritylist")); - JSON_FIND_V (json_value, "job", build_server_header (response, ERR_PARAM_MISSING, - "Parameter(job or admin) missing in the authoritylist")); - JSON_FIND_V (json_value, "var", build_server_header (response, ERR_PARAM_MISSING, - "Parameter(var or admin) missing in the authoritylist")); - - if (json_value["dbc"].asString() == "yes") - { - auth |= AU_DBC; - } - else if (json_value["dbc"].asString() != "no") - { - return build_server_header (response, ERR_WITH_MSG, "invalid value in 'dbc', it can only accept either 'yes' or 'no'."); - } - - if (json_value["dbo"].asString() == "yes") - { - auth |= AU_DBO; - } - else if (json_value["dbo"].asString() != "no") - { - return build_server_header (response, ERR_WITH_MSG, "invalid value in 'dbo', it can only accept either 'yes' or 'no'."); - } - - if (json_value["brk"].asString() == "yes") - { - auth |= AU_BRK; - } - else if (json_value["brk"].asString() != "no") - { - return build_server_header (response, ERR_WITH_MSG, "invalid value in 'brk', it can only accept either 'yes' or 'no'."); - } - - if (json_value["mon"].asString() == "yes") - { - auth |= AU_MON; - } - else if (json_value["mon"].asString() != "no") - { - return build_server_header (response, ERR_WITH_MSG, "invalid value in 'mon', it can only accept either 'yes' or 'no'."); - } - - if (json_value["job"].asString() == "yes") - { - auth |= AU_JOB; - } - else if (json_value["job"].asString() != "no") - { - return build_server_header (response, ERR_WITH_MSG, "invalid value in 'job', it can only accept either 'yes' or 'no'."); - } - - if (json_value["var"].asString() == "yes") - { - auth |= AU_VAR; - } - else if (json_value["var"].asString() != "no") - { - return build_server_header (response, ERR_WITH_MSG, "invalid value in 'var', it can only accept either 'yes' or 'no'."); - } - - // all authorites are set as 'no' - if (auth == 0) - { - return build_server_header (response, ERR_WITH_MSG, "It can't be allowed to set all authorities as \"no\"."); - } - - authinfo = (T_DBMT_USER_AUTHINFO *) increase_capacity (authinfo, sizeof (T_DBMT_USER_AUTHINFO), num_authinfo, - num_authinfo + 7); - if (authinfo == NULL) - { - dbmt_user_free (&dbmt_user); - return build_server_header (response, ERR_MEM_ALLOC, "Memory Allocation error."); - } - num_authinfo += 7; - - // maybe only for debug - dbmt_user_set_authinfo (& (authinfo[1]), "dbc", ((AU_DBC & auth)? "yes" : "no")); - dbmt_user_set_authinfo (& (authinfo[2]), "dbo", ((AU_DBO & auth)? "yes" : "no")); - dbmt_user_set_authinfo (& (authinfo[3]), "brk", ((AU_BRK & auth)? "yes" : "no")); - dbmt_user_set_authinfo (& (authinfo[4]), "mon", ((AU_MON & auth)? "yes" : "no")); - dbmt_user_set_authinfo (& (authinfo[5]), "job", ((AU_JOB & auth)? "yes" : "no")); - dbmt_user_set_authinfo (& (authinfo[6]), "var", ((AU_VAR & auth)? "yes" : "no")); - } - - sprintf (str_auth, "%u", auth); - dbmt_user_set_authinfo (& (authinfo[0]), "user_auth", str_auth); - - LOG_DEBUG ("set user authority info successfully."); - - // set db authority info - JSON_FIND_V (request, "dbauth", build_server_header (response, ERR_PARAM_MISSING, - "Parameter(dbauth) missing in the request")); - - dbauthlist = request["dbauth"]; - - for (unsigned int i = 0; i < dbauthlist.size(); ++i) - { - string dbname, dbid, dbpassword, broker_address; - - JSON_FIND_V (dbauthlist[i], "dbname", build_server_header (response, ERR_PARAM_MISSING, - "Parameter(dbname) missing in the authoritylist")); - JSON_FIND_V (dbauthlist[i], "dbid", build_server_header (response, ERR_PARAM_MISSING, - "Parameter(dbid) missing in the authoritylist")); - JSON_FIND_V (dbauthlist[i], "dbpassword", build_server_header (response, ERR_PARAM_MISSING, - "Parameter(dbpassword) missing in the authoritylist")); - JSON_FIND_V (dbauthlist[i], "dbbrokeraddress", build_server_header (response, ERR_PARAM_MISSING, - "Parameter(dbbrokeraddress) missing in the authoritylist")); - - dbname = dbauthlist[i]["dbname"].asString(); - dbid = dbauthlist[i]["dbid"].asString(); - dbpassword = dbauthlist[i]["dbpassword"].asString(); - broker_address = dbauthlist[i]["dbbrokeraddress"].asString(); - - dbinfo = (T_DBMT_USER_DBINFO *) increase_capacity (dbinfo, sizeof (T_DBMT_USER_DBINFO), - num_dbinfo, num_dbinfo + 1); - if (dbinfo == NULL) - { - FREE_MEM (authinfo); - dbmt_user_free (&dbmt_user); - - return build_server_header (response, ERR_MEM_ALLOC, "Memory Allocation error."); - } - num_dbinfo++; - - dbmt_user_set_dbinfo (& (dbinfo[num_dbinfo-1]), dbname.c_str(), "admin", dbid.c_str(), broker_address.c_str()); - } - - LOG_DEBUG ("set db authority info successfully."); - - // store user authority info & db authority info into dbmt_user - dbmt_user.user_info = (T_DBMT_USER_INFO *) increase_capacity (dbmt_user.user_info, sizeof (T_DBMT_USER_INFO), - num_dbmt_user, num_dbmt_user + 1); - - - if (dbmt_user.user_info == NULL) - { - FREE_MEM (authinfo); - FREE_MEM (dbinfo); - return build_server_header (response, ERR_MEM_ALLOC, "Memory Allocation error.") ; - } - - num_dbmt_user++; - dbmt_user_set_userinfo (& (dbmt_user.user_info[num_dbmt_user-1]), user_id.c_str(), dbmt_password, num_authinfo, - authinfo, num_dbinfo, dbinfo); - dbmt_user.num_dbmt_user = num_dbmt_user; - - - LOG_DEBUG ("store to dbmt_user successfully."); - - if ((retval = dbmt_user_write_auth (&dbmt_user, dbmt_error)) != ERR_NO_ERROR) - { - dbmt_user_free (&dbmt_user); - - return build_server_header (response, retval, dbmt_error); - } - if ((retval = dbmt_user_write_pass (&dbmt_user, dbmt_error)) != ERR_NO_ERROR) - { - dbmt_user_free (&dbmt_user); - - return build_server_header (response, retval, dbmt_error); - } - - if ((retval = ext_ut_add_dblist_to_response (response)) != ERR_NO_ERROR) - { - dbmt_user_free (&dbmt_user); - - return build_server_header (response, retval, "database.txt open error"); - } - - if ((retval = ext_ut_add_userlist_to_response (response, dbmt_user)) != ERR_NO_ERROR) - { - dbmt_user_free (&dbmt_user); - - return build_server_header (response, retval, "add userlist to response error!"); - } - - dbmt_user_free (&dbmt_user); - - return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); -} - -int ext_update_dbmt_user_new (Json::Value &request, Json::Value &response) -{ - - T_DBMT_USER_AUTHINFO *authinfo = NULL; - T_DBMT_USER_DBINFO *dbinfo = NULL; - T_DBMT_USER dbmt_user; - - T_USER_AUTH auth = 0; - - char dbmt_error[DBMT_ERROR_MSG_SIZE]; - - string user_id; - - Json::Value json_value; - Json::Value dbauthlist; - - int num_authinfo = 0; - int num_dbinfo = 0; - int pos = 0; - int retval; - - - char str_auth[12]; // the length of number 2^32 - - JSON_FIND_V (request, "targetid", - build_server_header (response, ERR_PARAM_MISSING, "Parameter(targetid) missing in the request.")); - - user_id = request["targetid"].asString(); - - if ((json_value = request["authoritylist"]) != Json::Value::null) - { - - if (json_value["admin"] != Json::Value::null) - { - if (json_value["admin"].asString() != "yes") - { - return build_server_header (response, ERR_WITH_MSG, "The value of 'admin' should be 'yes'!"); - } - - auth |= AU_ADMIN; - - authinfo = (T_DBMT_USER_AUTHINFO *) increase_capacity (authinfo, sizeof (T_DBMT_USER_AUTHINFO), num_authinfo, - num_authinfo + 2); - if (authinfo == NULL) - { - return build_server_header (response, ERR_MEM_ALLOC, "Memory Allocation error."); - } - - dbmt_user_set_authinfo (& (authinfo[1]), "admin", "yes"); - num_authinfo += 2; - } - else - { - JSON_FIND_V (json_value, "dbc", build_server_header (response, ERR_PARAM_MISSING, - "Parameter(dbc or admin) missing in the authoritylist")); - JSON_FIND_V (json_value, "dbo", build_server_header (response, ERR_PARAM_MISSING, - "Parameter(dbo or admin) missing in the authoritylist")); - JSON_FIND_V (json_value, "brk", build_server_header (response, ERR_PARAM_MISSING, - "Parameter(brk or admin) missing in the authoritylist")); - JSON_FIND_V (json_value, "mon", build_server_header (response, ERR_PARAM_MISSING, - "Parameter(mon or admin) missing in the authoritylist")); - JSON_FIND_V (json_value, "job", build_server_header (response, ERR_PARAM_MISSING, - "Parameter(job or admin) missing in the authoritylist")); - JSON_FIND_V (json_value, "var", build_server_header (response, ERR_PARAM_MISSING, - "Parameter(var or admin) missing in the authoritylist")); - - - if (json_value["dbc"].asString() == "yes") - { - auth |= AU_DBC; - } - else if (json_value["dbc"].asString() != "no") - { - return build_server_header (response, ERR_WITH_MSG, "invalid value in 'dbc', it can only accept either 'yes' or 'no'."); - } - - if (json_value["dbo"].asString() == "yes") - { - auth |= AU_DBO; - } - else if (json_value["dbo"].asString() != "no") - { - return build_server_header (response, ERR_WITH_MSG, "invalid value in 'dbo', it can only accept either 'yes' or 'no'."); - } - - if (json_value["brk"].asString() == "yes") - { - auth |= AU_BRK; - } - else if (json_value["brk"].asString() != "no") - { - return build_server_header (response, ERR_WITH_MSG, "invalid value in 'brk', it can only accept either 'yes' or 'no'."); - } - - if (json_value["mon"].asString() == "yes") - { - auth |= AU_MON; - } - else if (json_value["mon"].asString() != "no") - { - return build_server_header (response, ERR_WITH_MSG, "invalid value in 'mon', it can only accept either 'yes' or 'no'."); - } - - if (json_value["job"].asString() == "yes") - { - auth |= AU_JOB; - } - else if (json_value["job"].asString() != "no") - { - return build_server_header (response, ERR_WITH_MSG, "invalid value in 'job', it can only accept either 'yes' or 'no'."); - } - - if (json_value["var"].asString() == "yes") - { - auth |= AU_VAR; - } - else if (json_value["var"].asString() != "no") - { - return build_server_header (response, ERR_WITH_MSG, "invalid value in 'var', it can only accept either 'yes' or 'no'."); - } - - // all authorites are set as 'no' - if (auth == 0) - { - return build_server_header (response, ERR_WITH_MSG, "It can't be allowed to set all authorities as \"no\"."); - } - - authinfo = (T_DBMT_USER_AUTHINFO *) increase_capacity (authinfo, sizeof (T_DBMT_USER_AUTHINFO), num_authinfo, - num_authinfo + 7); - if (authinfo == NULL) - { - return build_server_header (response, ERR_MEM_ALLOC, "Memory Allocation error."); - } - num_authinfo += 7; - - // maybe only for debug - dbmt_user_set_authinfo (& (authinfo[1]), "dbc", ((AU_DBC & auth)? "yes" : "no")); - dbmt_user_set_authinfo (& (authinfo[2]), "dbo", ((AU_DBO & auth)? "yes" : "no")); - dbmt_user_set_authinfo (& (authinfo[3]), "brk", ((AU_BRK & auth)? "yes" : "no")); - dbmt_user_set_authinfo (& (authinfo[4]), "mon", ((AU_MON & auth)? "yes" : "no")); - dbmt_user_set_authinfo (& (authinfo[5]), "job", ((AU_JOB & auth)? "yes" : "no")); - dbmt_user_set_authinfo (& (authinfo[6]), "var", ((AU_VAR & auth)? "yes" : "no")); - - } - - sprintf (str_auth, "%u", auth); - dbmt_user_set_authinfo (& (authinfo[0]), "user_auth", str_auth); - - } - - // set db authority info - //JSON_FIND_V(request, "dbauth", build_server_header(response, ERR_PARAM_MISSING, "Parameter(dbauth) missing in the request")); - - if ((dbauthlist = request["dbauth"]) != Json::Value::null) - { - - for (unsigned int i = 0; i < dbauthlist.size(); ++i) - { - - string dbname, dbid, dbpassword, broker_address; - - JSON_FIND_V (dbauthlist[i], "dbname", build_server_header (response, ERR_PARAM_MISSING, - "Parameter(dbname) missing in the authoritylist")); - JSON_FIND_V (dbauthlist[i], "dbid", build_server_header (response, ERR_PARAM_MISSING, - "Parameter(dbid) missing in the authoritylist")); - JSON_FIND_V (dbauthlist[i], "dbpassword", build_server_header (response, ERR_PARAM_MISSING, - "Parameter(dbpassword) missing in the authoritylist")); - JSON_FIND_V (dbauthlist[i], "dbbrokeraddress", build_server_header (response, ERR_PARAM_MISSING, - "Parameter(dbbrokeraddress) missing in the authoritylist")); - - dbname = dbauthlist[i]["dbname"].asString(); - dbid = dbauthlist[i]["dbid"].asString(); - dbpassword = dbauthlist[i]["dbpassword"].asString(); - broker_address = dbauthlist[i]["dbbrokeraddress"].asString(); - - dbinfo = (T_DBMT_USER_DBINFO *) increase_capacity (dbinfo, sizeof (T_DBMT_USER_DBINFO), - num_dbinfo, num_dbinfo + 1); - if (dbinfo == NULL) - { - FREE_MEM (authinfo); - - return build_server_header (response, ERR_MEM_ALLOC, "Memory Allocation error."); - } - num_dbinfo++; - - dbmt_user_set_dbinfo (& (dbinfo[num_dbinfo-1]), dbname.c_str(), "admin", dbid.c_str(), broker_address.c_str()); - - } - } - - if ((retval = dbmt_user_read (&dbmt_user, dbmt_error)) != ERR_NO_ERROR) - { - FREE_MEM (authinfo); - FREE_MEM (dbinfo); - return build_server_header (response, retval, dbmt_error); - } - - pos = -1; - for (int i = 0; i < dbmt_user.num_dbmt_user; ++i) - { - if (!strcmp (dbmt_user.user_info[i].user_name, user_id.c_str())) - { - pos = i; - break; - } - } - - if (pos < 0) - { - FREE_MEM (authinfo); - FREE_MEM (dbinfo); - dbmt_user_free (&dbmt_user); - - return build_server_header (response, ERR_GENERAL_ERROR, "the user doesn't exist!"); - } - - if (authinfo != NULL) - { - free (dbmt_user.user_info[pos].authinfo); - dbmt_user.user_info[pos].authinfo = authinfo; - dbmt_user.user_info[pos].num_authinfo = num_authinfo; - - } - - if (dbinfo != NULL) - { - if (dbmt_user.user_info[pos].dbinfo == NULL) - { - dbmt_user.user_info[pos].dbinfo = dbinfo; - dbmt_user.user_info[pos].num_dbinfo = num_dbinfo; - } - else - { - T_DBMT_USER_INFO *current_user = dbmt_user.user_info+pos; - for (int i = 0; i < num_dbinfo; ++i ) - { - int tmp_pos = -1; - for (int j = 0; j < current_user->num_dbinfo; ++j) - { - if (!strcmp (current_user->dbinfo[j].dbname, dbinfo[i].dbname)) - { - tmp_pos = j; - } - } - - if (tmp_pos < 0) - { - current_user->dbinfo = (T_DBMT_USER_DBINFO *)increase_capacity (current_user->dbinfo, - sizeof (T_DBMT_USER_DBINFO), - current_user->num_dbinfo, - current_user->num_dbinfo+1); - - if (current_user->dbinfo == NULL) - { - FREE_MEM (dbinfo); - dbmt_user_free (&dbmt_user); - - return build_server_header (response, ERR_MEM_ALLOC, "Memory allocation error."); - } - tmp_pos = current_user->num_dbinfo; - current_user->num_dbinfo++; - } - - dbmt_user_set_dbinfo (& (current_user->dbinfo[tmp_pos]), - dbinfo[i].dbname, - dbinfo[i].auth, - dbinfo[i].uid, - dbinfo[i].broker_address); - } - } - } - - if ((retval = dbmt_user_write_auth (&dbmt_user, dbmt_error)) != ERR_NO_ERROR) - { - FREE_MEM (dbinfo); - dbmt_user_free (&dbmt_user); - - return build_server_header (response, retval, dbmt_error); - } - - - if ((retval = ext_ut_add_dblist_to_response (response)) != ERR_NO_ERROR) - { - FREE_MEM (dbinfo); - dbmt_user_free (&dbmt_user); - - return build_server_header (response, retval, "database.txt open error"); - } - - if ((retval = ext_ut_add_userlist_to_response (response, dbmt_user)) != ERR_NO_ERROR) - { - FREE_MEM (dbinfo); - dbmt_user_free (&dbmt_user); - - return build_server_header (response, retval, "add userlist to response error!"); - } - - - FREE_MEM (dbinfo); - dbmt_user_free (&dbmt_user); - - return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); -} - -int ext_get_dbmt_user_info_new (Json::Value &request, Json::Value &response) -{ - - T_DBMT_USER dbmt_user; - char dbmt_error[DBMT_ERROR_MSG_SIZE]; - int retval; - - if ((retval = dbmt_user_read (&dbmt_user, dbmt_error)) != ERR_NO_ERROR) - { - dbmt_user_free (&dbmt_user); - return build_server_header (response, retval, dbmt_error); - } - - - if ((retval = ext_ut_add_dblist_to_response (response)) != ERR_NO_ERROR) - { - dbmt_user_free (&dbmt_user); - return build_server_header (response, retval, "database.txt open error"); - } - - if ((retval = ext_ut_add_userlist_to_response (response, dbmt_user)) != ERR_NO_ERROR) - { - dbmt_user_free (&dbmt_user); - return build_server_header (response, retval, "add userlist to response error!"); - } - - dbmt_user_free (&dbmt_user); - return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); -} - -// utility fucntions. -// -// -ext_ut_validate_userid -// -ext_ut_add_dblist_to_response -// -ext_ut_add_userlist_to_response -// -ext_ut_validate_token -// -ext_ut_generate_token - -int ext_ut_add_dblist_to_response (Json::Value &response, bool is_add_dbpath) -{ - - char dbtxt_file[PATH_MAX]; - char hostname[128]; - ifstream in_file; - string line_buf; - Json::Value dblist; - Json::Value dbs; - - snprintf (dbtxt_file, PATH_MAX-1, "%s/%s", sco.szArniadb_databases, ARNIADB_DATABASE_TXT); - if (access (dbtxt_file, F_OK) == 0) - { - in_file.open (dbtxt_file, ios::in); - } - else - { - return ERR_DATABASETXT_OPEN; - } - if (!in_file.good()) - { - return ERR_DATABASETXT_OPEN; - } - - memset (hostname, 0, sizeof (hostname)); - gethostname (hostname, sizeof (hostname)); - - string str_hostname = hostname; - - while (getline (in_file, line_buf)) - { - istringstream in_str (line_buf); - istringstream in_hname; - string dbname, dbpath, hname_list, hname[2]; - Json::Value db; - - in_str >> dbname >> dbpath >> hname_list; - in_hname.str (hname_list); - - int i = 0; - while (getline (in_hname, hname[i], ':')) - { - if (hname[i] == "127.0.0.1" || hname[i] == str_hostname || hname[i] == "localhost") - { - db["dbname"] = dbname; - if (is_add_dbpath) - { - db["dbdir"] = dbpath; - } - dbs.append (db); - break; - } - i++; - } - } - - dblist["dbs"] = dbs; - response["dblist"].append (dblist); - - return ERR_NO_ERROR; -} - -int ext_ut_add_userlist_to_response (Json::Value &response, const T_DBMT_USER &dbmt_user, bool is_add_pwd) -{ - Json::Value userlist; - - for (int i = 0; i < dbmt_user.num_dbmt_user; ++i) - { - Json::Value user; - Json::Value authority_list; - Json::Value dbauth; - Json::Value json_value; - string user_auth; - ostringstream tmp_oss; - - if (dbmt_user.user_info[i].user_name[0] == '\0') - { - continue; - } - - user[ENCRYPT_ARG ("id")] = dbmt_user.user_info[i].user_name; - if (is_add_pwd) - { - user["passwd"] = dbmt_user.user_info[i].user_passwd; - } - - json_value.clear(); - - // add user authority info - for (int j = 0; j < dbmt_user.user_info[i].num_authinfo; ++j) - { - if (dbmt_user.user_info[i].authinfo[j].domain[0] == '\0') - { - continue; - } - - if (!strcmp (dbmt_user.user_info[i].authinfo[j].domain, "dbo")) - { - json_value["dbo"] = dbmt_user.user_info[i].authinfo[j].auth; - continue; - } - - if (!strcmp (dbmt_user.user_info[i].authinfo[j].domain, "dbc")) - { - json_value["dbc"] = dbmt_user.user_info[i].authinfo[j].auth; - continue; - } - - if (!strcmp (dbmt_user.user_info[i].authinfo[j].domain, "brk")) - { - json_value["brk"] = dbmt_user.user_info[i].authinfo[j].auth; - continue; - } - - if (!strcmp (dbmt_user.user_info[i].authinfo[j].domain, "mon")) - { - json_value["mon"] = dbmt_user.user_info[i].authinfo[j].auth; - continue; - } - - if (!strcmp (dbmt_user.user_info[i].authinfo[j].domain, "job")) - { - json_value["job"] = dbmt_user.user_info[i].authinfo[j].auth; - continue; - } - - if (!strcmp (dbmt_user.user_info[i].authinfo[j].domain, "var")) - { - json_value["var"] = dbmt_user.user_info[i].authinfo[j].auth; - continue; - } - - if (!strcmp (dbmt_user.user_info[i].authinfo[j].domain, "all")) - { - json_value["all"] = dbmt_user.user_info[i].authinfo[j].auth; - continue; - } - - if (!strcmp (dbmt_user.user_info[i].authinfo[j].domain, "user_auth")) - { - user_auth = dbmt_user.user_info[i].authinfo[j].auth; - continue; - } - } - - authority_list.append (json_value); - - tmp_oss << AU_ADMIN; - if (!strcasecmp (dbmt_user.user_info[i].user_name, "admin") || - user_auth == tmp_oss.str()) - { - user["user_auth"] = "admin"; - } - else - { - user["user_auth"] = user_auth; - } - user["authority_list"] = authority_list; - - json_value.clear(); - // add user db info - for (int j = 0; j < dbmt_user.user_info[i].num_dbinfo; ++j) - { - json_value[ENCRYPT_ARG ("dbid")] = dbmt_user.user_info[i].dbinfo[j].uid; - json_value["dbname"] = dbmt_user.user_info[i].dbinfo[j].dbname; - json_value["dbbrokeraddress"] = dbmt_user.user_info[i].dbinfo[j].broker_address; - - dbauth["auth_info"].append (json_value); - } - - user["dbauth"].append (dbauth); - userlist["user"].append (user); - } - response["userlist"].append (userlist); - - return ERR_NO_ERROR; -} - -static bool _validate_token_active_time (time_t &active_time) -{ - size_t len = 0; - - active_time = 0; - len = strlen (sco.szTokenActiveTime); - - if (len > MAX_TIME_LENGTH) - { - return false; - } - - for (int i = 0; i < len; ++i) - { - if (!isdigit (sco.szTokenActiveTime[i])) - { - return false; - } - } - - active_time = atol (sco.szTokenActiveTime); - - if (active_time == 0) - { - return false; - } - - if (active_time == LONG_MAX) - { - LOG_WARN ("token_active_time in cm.conf maybe more than 2147483647, correct it to 2147483647."); - } - - return true; -} - -bool ext_ut_validate_token (const char *token) -{ - T_USER_TOKEN_INFO *token_info; - string token_enc; - string token_content[5]; // client_ip, client_port, client_id, proc_id, login_time - istringstream tmp_iss; - time_t now_time = time (0); - time_t active_time; - char token_dec[TOKEN_LENGTH + 1]; - - if (strlen (token) > TOKEN_ENC_LENGTH) - { - return false; - } - - uDecrypt (TOKEN_LENGTH, token, token_dec); - tmp_iss.str (string (token_dec)); - - int i = 0; - while (getline (tmp_iss, token_content[i++], ':')); - - token_info = dbmt_user_search_token_info (token_content[2].c_str()); - if (token_info == NULL) - { - return false; - } - - if (strcmp (token_info->token, token) != 0) - { - return false; - } - - if (!_validate_token_active_time (active_time)) - { - active_time = 7200; - } - - if (now_time - token_info->login_time > active_time) - { - return false; - } - - token_info->login_time = now_time; - - return true; -} - -int ext_ut_validate_token (Json::Value &request, Json::Value &response) -{ - - T_USER_TOKEN_INFO *token_info; - string task; - string token; - string token_content[5]; // client_ip, client_port, client_id, proc_id, login_time - istringstream tmp_iss; - time_t now_time = time (0); - time_t active_time; - char token_dec[TOKEN_LENGTH+1]; - - if (request["task"].asString() == "login" || request["task"].asString() == "getcmsenv") - { - return build_server_header (response, ERR_NO_ERROR, "none"); - } - - - if (request["task"] == Json::Value::null) - { - return build_server_header (response, ERR_PARAM_MISSING, "Parameter(task) missing in the request."); - } - - if (request["token"] == Json::Value::null) - { - return build_server_header (response, ERR_PARAM_MISSING, "Parameter(token) missing in the request."); - } - - if (request["task"].asString() == "") - { - return build_server_header (response, ERR_WITH_MSG, "Task can't be null."); - } - - if (request["token"].asString() == "") - { - return build_server_header (response, ERR_INVALID_TOKEN, "Request is rejected due to invalid token. Please reconnect."); - } - - task = request["task"].asString(); - token = request["token"].asString(); - if (token.length() > TOKEN_ENC_LENGTH) - { - return build_server_header (response, ERR_INVALID_TOKEN, "Request is rejected due to invalid token. Please reconnect."); - } - - uDecrypt (TOKEN_LENGTH, token.c_str(), token_dec); - tmp_iss.str (string (token_dec)); - - int i = 0; - while (getline (tmp_iss, token_content[i++], ':')); - - token_info = dbmt_user_search_token_info (token_content[2].c_str()); - if (token_info == NULL) - { - return build_server_header (response, ERR_INVALID_TOKEN, "Request is rejected due to invalid token. Please reconnect."); - } - - - if (strcmp (token_info->token, token.c_str())) - { - return build_server_header (response, ERR_INVALID_TOKEN, "Request is rejected due to invalid token. Please reconnect."); - } - - - if (!_validate_token_active_time (active_time)) - { - active_time = 7200; - } - - if (now_time-token_info->login_time > active_time) - { - return build_server_header (response, ERR_INVALID_TOKEN, "Request is rejected due to invalid token. Please reconnect."); - } - - token_info->login_time = now_time; - - request["_IP"] = token_content[0]; - request["_PORT"] = token_content[1]; - request["_ID"] = token_content[2]; - - return build_server_header (response, ERR_NO_ERROR, "none"); -} - -bool ext_ut_validate_auth (Json::Value &request) -{ - T_USER_AUTH auth_task = 0; - T_USER_AUTH auth_user = 0; - T_DBMT_USER dbmt_user; - T_DBMT_USER_AUTHINFO *auth_info = NULL; - - string task; - string user_id; - - char dbmt_error[DBMT_ERROR_MSG_SIZE]; - int num_authinfo = 0; - - if (request["task"].asString() == "login" || request["task"].asString() == "getcmsenv") - { - return true; - } - - if (request["task"] == Json::Value::null || request["_ID"] == Json::Value::null) - { - return false; - } - - task = request["task"].asString(); - user_id = request["_ID"].asString(); - - if (ut_get_task_info (task.c_str(), NULL, NULL, &auth_task) == 0 && - get_ext_task_info (task.c_str(), 0, NULL, &auth_task) == 0) - { - // As the task doesn't exist, this failure will be checked in next step. - return true; - } - - if (dbmt_user_read (&dbmt_user, dbmt_error) != ERR_NO_ERROR) - { - return false; - } - - bool matches = false; - for (int index = 0; index < dbmt_user.num_dbmt_user; ++index) - { - if (strcmp (dbmt_user.user_info[index].user_name, user_id.c_str()) == 0) - { - auth_info = dbmt_user.user_info[index].authinfo; - num_authinfo = dbmt_user.user_info[index].num_authinfo; - matches = true; - break; - } - } - - // the user doesn't exist - if (!matches) - { - dbmt_user_free (&dbmt_user); - return false; - } - - for (int index = 0; index < num_authinfo; ++index) - { - if (!strcmp (auth_info[index].domain, "user_auth")) - { - istringstream (string (auth_info[index].auth)) >> auth_user; - break; - } - } - - dbmt_user_free (&dbmt_user); - - // assign default authority to old users. - if (auth_user == 0) - { - if (user_id == "admin") - { - auth_user = AU_ADMIN; - } - else - { - auth_user = ALL_AUTHORITY; - } - } - - if (auth_user == AU_ADMIN) - { - return true; - } - - return (auth_user & auth_task) ? true : false; -} - -int ext_get_mon_interval (Json::Value &request, Json::Value &response) -{ - response["task"] = request["task"]; - time_t interval; - if (false == (cm_mon_stat::get_instance())->get_mon_interval (interval)) - { - return build_server_header (response, ERR_WITH_MSG, - "Get interval failed, because the monitoring module is not initialized!"); - } - response["interval"] = int (interval); - return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); -} - -int ext_set_mon_interval (Json::Value &request, Json::Value &response) -{ - int interval = 0; - response["task"] = request["task"]; - JSON_FIND_V (request, "interval", - build_server_header (response, ERR_PARAM_MISSING, "Parameter(interval) missing in the request")); - interval = request["interval"].asInt(); - if (interval < MIN_INTERVAL) - { - stringstream sstr; - sstr << "The interval " << interval << " seconds is less than the minimum interval " << MIN_INTERVAL << " seconds"; - return build_server_header (response, ERR_WITH_MSG, sstr.str().c_str()); - } - if (interval >= MAX_INTERVAL) - { - stringstream sstr; - sstr << "The interval " << interval << " seconds is bigger than or equal to the maximum interval " << MAX_INTERVAL << - " seconds"; - return build_server_header (response, ERR_WITH_MSG, sstr.str().c_str()); - } - if (true == (cm_mon_stat::get_instance())->set_mon_interval (interval)) - { - return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); - } - else - { - return build_server_header (response, ERR_WITH_MSG, - "Set monitoring interval for monitoring statistic failed!"); - } -} - -int ext_get_mon_statistic (Json::Value &request, Json::Value &response) -{ - response["task"] = request["task"]; - string errmsg = ""; - JSON_FIND_V (request, "metric", - build_server_header (response, ERR_PARAM_MISSING, "Parameter(metric) missing in the request")); - JSON_FIND_V (request, "dtype", - build_server_header (response, ERR_PARAM_MISSING, "Parameter(dtype) missing in the request")); - if (0 == strncmp ("db_", request["metric"].asString().c_str(), strlen ("db_"))) - { - JSON_FIND_V (request, "dbname", - build_server_header (response, ERR_PARAM_MISSING, "Parameter(dbname) missing in the request")); - } - if (0 == strncmp ("vol_", request["metric"].asString().c_str(), strlen ("vol_"))) - { - JSON_FIND_V (request, "dbname", - build_server_header (response, ERR_PARAM_MISSING, "Parameter(dbname) missing in the request")); - JSON_FIND_V (request, "volname", - build_server_header (response, ERR_PARAM_MISSING, "Parameter(volname) missing in the request")); - } - if (0 == strncmp ("broker_", request["metric"].asString().c_str(), strlen ("broker_"))) - { - JSON_FIND_V (request, "bname", - build_server_header (response, ERR_PARAM_MISSING, "Parameter(bname) missing in the request")); - } - if (true == (cm_mon_stat::get_instance())->get_mon_statistic (request, response, errmsg)) - { - return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); - } - else - { - return build_server_header (response, ERR_WITH_MSG, errmsg.c_str()); - } -} diff --git a/server/src/cm_server_extend_interface.h b/server/src/cm_server_extend_interface.h deleted file mode 100644 index 9e6e22d..0000000 --- a/server/src/cm_server_extend_interface.h +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. - * - * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - -#ifndef __CM_SERVER_EXTEND_INFERFACE_H_ -#define __CM_SERVER_EXTEND_INFERFACE_H_ - -#include "cm_user.h" - -#include -#include -#include - -#define STATUS_SUCCESS "success" -#define STATUS_FAILURE "failure" -#define STATUS_NONE "none" - -#define MIN_INTERVAL 10 -#define MAX_INTERVAL 3600 - -#define JSON_FIND_V(root, key, err) \ - if (Json::Value::null == root[key]) \ - return err; - -typedef int (*T_EXT_TASK_FUNC) (Json::Value &request, - Json::Value &response); - -typedef struct -{ - const char *task_str; - int access_level; - T_EXT_TASK_FUNC task_func; - T_USER_AUTH user_auth; -} T_EXTEND_TASK_INFO; - -int build_server_header (Json::Value &response, const int status, - const char *note); -int get_ext_task_info (const char *task, int access_flag, - T_EXT_TASK_FUNC *task_func, T_USER_AUTH *auth); -int ext_get_sys_diskinfo (Json::Value &request, Json::Value &response); -int ext_get_proc_info (Json::Value &request, Json::Value &response); -int ext_set_log_level (Json::Value &request, Json::Value &response); -int ext_set_auto_start (Json::Value &request, Json::Value &response); -int ext_get_auto_start (Json::Value &request, Json::Value &response); -int ext_exec_auto_start (Json::Value &request, Json::Value &response); -int ext_exec_auto_jobs (Json::Value &request, Json::Value &response); -int ext_arn_broker_start (Json::Value &request, Json::Value &response); -int ext_get_db_err_log (Json::Value &request, Json::Value &response); -int ext_get_broker_start_log (Json::Value &request, Json::Value &response); -int ext_send_mail (Json::Value &request, Json::Value &response); -int ext_exec_auto_mail (Json::Value &request, Json::Value &response); -int ext_get_autojob_conf (Json::Value &request, Json::Value &response); -int ext_set_autojob_conf (Json::Value &request, Json::Value &response); -int ext_read_private_data (Json::Value &request, Json::Value &response); -int ext_write_private_data (Json::Value &request, Json::Value &response); -int ext_set_autoexec_query (Json::Value &request, Json::Value &response); -int ext_get_ha_apply_info (Json::Value &request, Json::Value &response); -int ext_get_mon_interval (Json::Value &request, Json::Value &reponse); -int ext_set_mon_interval (Json::Value &request, Json::Value &reponse); -int ext_get_mon_statistic (Json::Value &request, Json::Value &reponse); -int ext_add_dbmt_user_new (Json::Value &request, Json::Value &response); -int ext_update_dbmt_user_new (Json::Value &request, Json::Value &response); -int ext_get_dbmt_user_info_new (Json::Value &request, - Json::Value &response); - -#define EXT_JOBS_AUTO_START "auto_start" -#define EXT_JOBS_MAIL_CONF "mail_config" -#define EXT_JOBS_MAIL_REPORT "mail_report" - -/* utility */ -bool ext_set_auto_jobs (const std::string jobkey, Json::Value &jobvalue); -bool ext_get_auto_jobs (const std::string jobkey, Json::Value &jobvalue); -bool ext_ut_validate_userid (const std::string userid); -int ext_ut_add_dblist_to_response (Json::Value &res, bool is_add_dbpath = - false); -int ext_ut_add_userlist_to_response (Json::Value &response, - const T_DBMT_USER &dbmt_user, - bool is_add_pwd = false); -std::string ext_ut_generate_token (const std::string &client_ip, - const std::string &client_id, int proc_id, - time_t login_time); -int ext_ut_validate_token (Json::Value &resquest, Json::Value &response); -bool ext_ut_validate_token (const char *token); -bool ext_ut_validate_auth (Json::Value &request); - -#endif diff --git a/server/src/cm_server_interface.cpp b/server/src/cm_server_interface.cpp deleted file mode 100644 index f44f088..0000000 --- a/server/src/cm_server_interface.cpp +++ /dev/null @@ -1,757 +0,0 @@ -/* - * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. - * - * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef WINDOWS -#include -#else -#include -#include -#include -#include -#endif - -#include "cm_server_interface.h" -#include "cm_server_extend_interface.h" -#include "cm_log.h" -#include "cm_mon_stat.h" - -using namespace std; - -#ifndef MAX_PATH -#define MAX_PATH 256 -#endif - -extern T_EMGR_VERSION CLIENT_VERSION; - -typedef struct -{ - char arniadb[MAX_PATH]; /*arniadb home; ARNIADB=/root/ARNIADB */ - char arniadb_databases[MAX_PATH]; /*arniadb databases home,default $(arniadb home)/databases */ - char arniadb_err_log[MAX_PATH]; /*arniadb err log, use for save cmd log */ - // char arniadb_charset[MAX_PATH]; -} arniadb_env_t; -mutex_t cm_mutex; -/*global arniadb env*/ -arniadb_env_t arn_httpd_env; - -/** - * @brief initial monitoring stat information - * - * @return -1: error, 1: ok - */ -int -mon_stat_init (void) -{ -#if !defined (DO_NOT_USE_ARNIADBENV) - sprintf (sco.sMonStatDataPath, "%s/%s", sco.szArniadb, DBMT_MON_DATA_DIR); -#else - sprintf (sco.sMonStatDataPath, "%s", ARNIADB_MONDATADIR); -#endif - - if (access (sco.sMonStatDataPath, F_OK) < 0) - { - if (mkdir (sco.sMonStatDataPath, 0755) < 0) - { - fprintf (stderr, "Error while creating monitoring data path(%s)\n", - sco.sMonStatDataPath); - return -1; - } - } - - if (!cm_mon_stat::get_instance ()->initial ()) - { - fprintf (stderr, "Error while loading monitoring data information\n"); - return -1; - } - return 1; -} - -void -arn_cm_init_env () -{ - char conf_name[256]; - char tmpstrbuf[DBMT_ERROR_MSG_SIZE]; - char process_name[PATH_MAX]; - char default_arniadb_lang_type[PATH_MAX]; - char default_arniadb_lang_msg_type[PATH_MAX]; - - tmpstrbuf[0]= '\0'; - // char *charset = NULL; - snprintf (process_name, PATH_MAX, "%s", CMS_NAME); - snprintf (default_arniadb_lang_type, PATH_MAX, "ARNIADB_LANG=en_US"); - snprintf (default_arniadb_lang_msg_type, PATH_MAX, "ARNIADB_MSG_LANG=en_US"); - - sys_config_init (); - uReadEnvVariables (process_name); - - if (uReadSystemConfig () < 0) - { - snprintf (tmpstrbuf, DBMT_ERROR_MSG_SIZE, "ARNIADB Manager Server : Cannot find the configuration file[%s].\n", - conf_get_dbmt_file (FID_DBMT_CONF, conf_name)); - ut_record_arniadb_utility_log_stderr (tmpstrbuf); - exit (1); - } - make_default_env (); - - /* check system configuration */ - if (uCheckSystemConfig (process_name) < 0) - { - ut_record_arniadb_utility_log_stderr ("ARNIADB Manager Server : Error while checking system configuration file.\n"); - exit (1); - } - - if (mon_stat_init () < 0) - { - ut_record_arniadb_utility_log_stderr ("ARNIADB Manager Server : Error while checking monitoring data.\n"); - exit (1); - } - - memset (&arn_httpd_env, 0, sizeof (arniadb_env_t)); - putenv (default_arniadb_lang_type); /* set as default language type */ - putenv (default_arniadb_lang_msg_type); /* set as default language type */ - //putenv ("ARNIADB_CHARSET=en_US"); /* set as default language type */ - - snprintf (arn_httpd_env.arniadb_err_log, MAX_PATH, - "ARNIADB_ERROR_LOG=%s/cmclt.%d.err", sco.dbmt_tmp_dir, (int) getpid ()); - putenv (arn_httpd_env.arniadb_err_log); - - snprintf (arn_httpd_env.arniadb, MAX_PATH, "ARNIADB=%s", sco.szArniadb); - putenv (arn_httpd_env.arniadb); - - snprintf (arn_httpd_env.arniadb_databases, MAX_PATH, "ARNIADB_DATABASES=%s", - sco.szArniadb_databases); - putenv (arn_httpd_env.arniadb_databases); - - /* charset = getenv ("ARNIADB_CHARSET"); - if (charset != NULL) - { - snprintf (arn_httpd_env.arniadb_charset, MAX_PATH, "ARNIADB_CHARSET=%s", - charset); - } - else - { - snprintf (arn_httpd_env.arniadb_charset, MAX_PATH, - "ARNIADB_CHARSET=en_US"); - putenv (arn_httpd_env.arniadb_charset); - } - */ - mutex_init (cm_mutex); - return; -} - -void -arn_cm_destory_env () -{ - mutex_destory (cm_mutex); -} - -int -ch_build_request (Json::Value &req, nvplist *cli_request) -{ - static int i = 0; - nv_add_nvp_int (cli_request, "_STAMP", i++); - nv_add_nvp (cli_request, "_PROGNAME", CMS_NAME); - - return 1; -} - -static int -is_no_token_cmd (int task_code) -{ - int no_token_cmd[] = { TS_LOGIN, TS_GET_CMS_ENV, -1 }; - int i; - for (i = 0; no_token_cmd[i] != -1; i++) - { - if (task_code == no_token_cmd[i]) - { - return 1; - } - } - - return 0; -} - -/* -inherit for cm_job, find the task function, and exec; -*/ -int -ch_process_request (nvplist *req, nvplist *res) -{ - int task_code; - int retval = ERR_NO_ERROR; - char *dbname, *task; - // char *charset = NULL; - // static char charsetenv[PATH_MAX] = ""; - char dbid[32]; - char dbpasswd[80]; - T_TASK_FUNC task_func; - char access_log_flag; - char _dbmt_error[DBMT_ERROR_MSG_SIZE]; - int major_ver, minor_ver; - char *cli_ver; - - int elapsed_msec = 0; - struct timeval task_begin, task_end; - char elapsed_time_str[20]; - - memset (_dbmt_error, 0, sizeof (_dbmt_error)); - - task = nv_get_val (req, "task"); - dbname = nv_get_val (req, "dbname"); - //charset = nv_get_val (req, "charset"); - - task_code = ut_get_task_info (task, &access_log_flag, &task_func, NULL); - switch (task_code) - { - /* case TS_ANALYZECASLOG: */ - case TS_GET_DIAGDATA: - nv_reset_nvp (res); - nv_init (res, 5, NULL, "\n", ":DIAG_DEL:", "END__DIAGDATA\n"); - break; - } - - /* insert task,status,note to the front of response */ - nv_add_nvp (res, "task", task); - nv_add_nvp (res, "status", "none"); - nv_add_nvp (res, "note", "none"); - - if (!is_no_token_cmd (task_code)) - { - /* - if (ut_validate_token (req) == 0) - { - retval = ERR_INVALID_TOKEN; - uGenerateStatus (req, res, retval, _dbmt_error); - return 0; - } - */ - - /* if database name is specified */ - if (dbname) - { - memset (dbid, 0, 32); - memset (dbpasswd, 0, 80); - _ut_get_dbaccess (req, dbid, dbpasswd); - nv_add_nvp (req, "_DBID", dbid); - nv_add_nvp (req, "_DBPASSWD", dbpasswd); - nv_add_nvp (req, "_DBNAME", dbname); - } - } - - /* set CLIENT_VERSION */ - cli_ver = nv_get_val (req, "_CLIENT_VERSION"); - make_version_info (cli_ver == NULL ? "1.0" : cli_ver, &major_ver, - &minor_ver); - CLIENT_VERSION = EMGR_MAKE_VER (major_ver, minor_ver); /* global variable */ - - sprintf (_dbmt_error, "?"); /* prevent to have null string */ - if (task_code == TS_UNDEFINED) - { - if (task != NULL) - { - strcpy (_dbmt_error, task); - } - retval = ERR_UNDEFINED_TASK; - } - else - { - if (access_log_flag) - { - ut_access_log (req, NULL); - } - - /* if (charset != NULL) - { - snprintf (charsetenv, PATH_MAX, "ARNIADB_CHARSET=%s", charset); - putenv (charsetenv); - } - */ - /* record the start time of running arn_manager */ - gettimeofday (&task_begin, NULL); - - retval = (*task_func) (req, res, _dbmt_error); - - /* record the end time of running arn_manager */ - gettimeofday (&task_end, NULL); - /* if (charset != NULL) - { - putenv (arn_httpd_env.arniadb_charset); - } - */ - /* caculate the running time of arn_manager. */ - _ut_timeval_diff (&task_begin, &task_end, &elapsed_msec); - - /* add arn_manager task running time to response. */ - snprintf (elapsed_time_str, sizeof (elapsed_time_str), "%d ms", - elapsed_msec); - nv_add_nvp (res, "__EXEC_TIME", elapsed_time_str); - } - - uGenerateStatus (req, res, retval, _dbmt_error); - - // FREE_MEM (cli_ver); - - return 0; -} - -int -json_to_nv (Json::Value &root, const char *name, nvplist *nv) -{ - switch (root.type ()) - { - case Json::arrayValue: - { - int size = root.size (); - - for (int index = 0; index < size; ++index) - { - if (!strcmp (name, "line") || !strcmp (name, "confdata") - || !strcmp (name, "group")) - { - json_to_nv (root[index], name, nv); - } - else - { - nv_add_nvp (nv, "open", name); - json_to_nv (root[index], name, nv); - nv_add_nvp (nv, "close", name); - } - } - } - break; - case Json::objectValue: - { - Json::Value::Members members (root.getMemberNames ()); - for (Json::Value::Members::iterator it = members.begin (); - it != members.end (); ++it) - { - json_to_nv (root[*it], (*it).c_str (), nv); - } - } - break; - case Json::intValue: - nv_add_nvp_int (nv, name, root.asInt ()); - break; - default: - nv_add_nvp (nv, name, root.asString ().c_str ()); - break; - } - - return 0; -} - -#define IS_SPECIAL_KEY (!strcmp(pname, "line") || !strcmp(pname, "confdata") \ - || !strcmp(pname, "group") || !strcmp(pname, "classattribute") \ - || !strcmp(pname, "attribute")) -/* -transform struct nvplist to json. -*/ -int -nv_to_json (nvplist *ref, char *value, int &index, Json::Value &root) -{ - Json::Value array; - Json::StyledWriter writer; - char *pvalue, *pname; - for (; index < ref->nvplist_size; ++index) - { - if (ref->nvpairs[index] == NULL - || dst_buffer (ref->nvpairs[index]->name) == NULL) - { - continue; - } - pname = dst_buffer (ref->nvpairs[index]->name); - pvalue = dst_buffer (ref->nvpairs[index]->value); - if (!strcmp (pname, "open")) - { - array.clear (); - nv_to_json (ref, pvalue, ++index, array); - if (!array.empty ()) - { - root[pvalue].append (array); - } - else - { - root[pvalue] = array; - } - } - else if (!strcmp (pname, "close") && !strcmp (pvalue, value)) - { - break; - } - else if (IS_SPECIAL_KEY) - { - root[pname].append ((pvalue == NULL) ? "" : pvalue); - } - else - { - root[pname] = (pvalue == NULL) ? "" : pvalue; - } - } - - return 1; -} - -void -dump_json (Json::Value &root) -{ - Json::StyledWriter writer; - printf ("%s\n", writer.write (root).c_str ()); -} - -void -dump_nvplist (nvplist *root, char *dumpfile) -{ - nv_writeto (root, dumpfile); -} - - -int -arn_cm_extend_request (Json::Value &request, Json::Value &response) -{ - T_EXT_TASK_FUNC task_func = NULL; - string task; - try - { - task = request["task"].asString (); - response["task"] = task; - if (get_ext_task_info (task.c_str (), 0, &task_func, NULL)) - { - (*task_func) (request, response); - return 1; - } - } - catch (exception &e) - { - response["status"] = STATUS_FAILURE; - response["note"] = e.what (); - return 1; - } - return 0; -} - -class async_request -{ - public: - unsigned int uuid; - Json::Value request; - Json::Value response; - int status; -#ifndef WINDOWS - pthread_mutex_t *mutex; - pthread_cond_t *cond; -#endif -}; - -list < async_request * >request_list; - -#ifdef WINDOWS -DWORD WINAPI -cm_async_request_handler (LPVOID lpArg) -#else -void * -cm_async_request_handler (void *lpArg) -#endif -{ - int index = 0; - nvplist *cli_request, *cli_response; - async_request *async_param = (async_request *) lpArg; - Json::Value &request = async_param->request; - Json::Value &response = async_param->response; - - cli_request = nv_create (5, NULL, "\n", ":", "\n"); - cli_response = nv_create (5, NULL, "\n", ":", "\n"); - try - { - json_to_nv (request, NULL, cli_request); - ch_build_request (request, cli_request); - ch_process_request (cli_request, cli_response); - nv_to_json (cli_response, NULL, index, response); - } - catch (exception &e) - { - response["status"] = ERR_REQUEST_FORMAT; - response["note"] = e.what (); - } - - async_param->status = 1; - nv_destroy (cli_request); - nv_destroy (cli_response); - -#ifndef WINDOWS - pthread_mutex_lock (async_param->mutex); - pthread_cond_broadcast (async_param->cond); - pthread_mutex_unlock (async_param->mutex); -#endif - - return NULL; -} - -#ifdef WINDOWS -int -cm_execute_request_async (Json::Value &request, Json::Value &response, - unsigned long time_out = 600) -{ - HANDLE hHandles; - DWORD ThreadID; - DWORD dwWaitResult; - static unsigned int req_id = 0; - async_request *pstmt = (async_request *) new (async_request); - if (pstmt == NULL) - { - return ERR_MEM_ALLOC; - } - - pstmt->request = request; - pstmt->status = 0; - pstmt->uuid = req_id++; - - hHandles = - CreateThread (NULL, 0, cm_async_request_handler, pstmt, 0, &ThreadID); - if (hHandles == NULL) - { - delete (pstmt); - return build_server_header (response, ERR_WITH_MSG, - "failed to execute task"); - } - - //dwWaitResult = WaitForSingleObject (hHandles, time_out * 1000); // time-out interval - - dwWaitResult = WaitForSingleObject (hHandles, INFINITE); //no timeout. - - if (dwWaitResult == WAIT_TIMEOUT) - { - CloseHandle (hHandles); - request_list.push_back (pstmt); - response["uuid"] = pstmt->uuid; - return build_server_header (response, ERR_WITH_MSG, "timeout"); - } - - CloseHandle (hHandles); - response = pstmt->response; - delete (pstmt); - return ERR_NO_ERROR; -} -#else -int -cm_execute_request_async (Json::Value &request, Json::Value &response, - unsigned long time_out = 600) -{ - int err = 0; - pthread_t async_thrd; -#if defined(AIX) - pthread_attr_t thread_attr; -#endif - pthread_cond_t cond; - pthread_mutex_t mutex; - timespec to; - static unsigned int req_id = 0; - async_request *pstmt = (async_request *) new (async_request); - if (pstmt == NULL) - { - return ERR_MEM_ALLOC; - } - - err = pthread_mutex_init (&mutex, NULL); - if (err != 0) - { - LOG_ERROR ("cm_execute_request_async : fail to set thread mutex."); - return build_server_header (response, ERR_WITH_MSG, - "failed to run task."); - } - - err = pthread_cond_init (&cond, NULL); - if (err != 0) - { - LOG_ERROR ("cm_execute_request_async : fail to set thread condition."); - return build_server_header (response, ERR_WITH_MSG, - "failed to run task."); - } - - pstmt->request = request; - pstmt->status = 0; - - pstmt->uuid = req_id++; - - pstmt->mutex = &mutex; - pstmt->cond = &cond; - -#if defined(AIX) - err = pthread_attr_init (&thread_attr); - if (err != 0) - { - LOG_ERROR ("cm_execute_request_async : fail to set thread attribute."); - return build_server_header (response, ERR_WITH_MSG, - "failed to run task."); - } - - err = pthread_attr_setdetachstate (&thread_attr, PTHREAD_CREATE_DETACHED); - if (err != 0) - { - LOG_ERROR ("cm_execute_request_async : fail to set thread detach state."); - return build_server_header (response, ERR_WITH_MSG, - "failed to run task."); - } - - /* AIX's pthread is slightly different from other systems. - Its performance highly depends on the pthread's scope and it's related - kernel parameters. */ - err = pthread_attr_setscope (&thread_attr, PTHREAD_SCOPE_PROCESS); - if (err != 0) - { - LOG_ERROR ("cm_execute_request_async : fail to set thread scope."); - return build_server_header (response, ERR_WITH_MSG, - "failed to run task."); - } - - err = pthread_attr_setstacksize (&thread_attr, AIX_STACKSIZE_PER_THREAD); - if (err != 0) - { - LOG_ERROR ("cm_execute_request_async : fail to set thread stack size."); - return build_server_header (response, ERR_WITH_MSG, - "failed to run task."); - } - - err = pthread_create (&async_thrd, &thread_attr, cm_async_request_handler, pstmt); -#else /* except AIX */ - err = pthread_create (&async_thrd, NULL, cm_async_request_handler, pstmt); -#endif - - if (err != 0) - { - delete (pstmt); - pthread_mutex_destroy (&mutex); - pthread_cond_destroy (&cond); - LOG_ERROR ("cm_execute_request_async : fail to create thread."); - return build_server_header (response, ERR_WITH_MSG, - "failed to run task."); - } - pthread_mutex_lock (&mutex); - to.tv_sec = time (NULL) + time_out; - to.tv_nsec = 0; - //err = pthread_cond_timedwait (&cond, &mutex, &to); - err = pthread_cond_wait (&cond, &mutex); - pthread_mutex_unlock (&mutex); - if (err == ETIMEDOUT) - { - request_list.push_back (pstmt); - response["uuid"] = pstmt->uuid; - LOG_ERROR ("cm_execute_request_async : Timeout for running task."); - return build_server_header (response, ERR_WITH_MSG, "timeout"); - } - - pthread_join (async_thrd, NULL); - - pthread_mutex_destroy (&mutex); - pthread_cond_destroy (&cond); - response = pstmt->response; - delete (pstmt); - return ERR_NO_ERROR; -} -#endif - -int -arn_check_async_status (Json::Value &request, Json::Value &response) -{ - string task; - unsigned int uuid; - list < async_request * >::iterator itor; - task = request["task"].asString (); - - if (task != "gettaskstatus") - { - return 0; - } - if (request["uuid"] == Json::Value::null || !request["uuid"].isInt ()) - { - return build_server_header (response, ERR_WITH_MSG, "invalid uuid"); - } - uuid = request["uuid"].asInt (); - for (itor = request_list.begin (); itor != request_list.end (); itor++) - { - if ((*itor)->uuid != uuid) - { - continue; - } - break; - } - if (itor == request_list.end ()) - { - return build_server_header (response, ERR_WITH_MSG, "uuid not found"); - } - - if ((*itor)->status == 0) - { - return build_server_header (response, ERR_WITH_MSG, "task not return"); - } - response = (*itor)->response; - request_list.erase (itor); - return ERR_NO_ERROR; -} - -int -arn_cm_request_handler (Json::Value &request, Json::Value &response) -{ - - mutex_lock (cm_mutex); - - - // leave a back door for testing... - if (ext_ut_validate_token (request, response) != ERR_NO_ERROR && request["token"].asString() != "test") - { - response["task"] = request["task"].asString(); - mutex_unlock (cm_mutex); - return 1; - } - - // leave a back door for testing... - if (!ext_ut_validate_auth (request) && request["token"].asString() != "test") - { - response["status"] = STATUS_FAILURE; - response["note"] = "The user don't have authority to execute the task: " + request["task"].asString(); - response["task"] = request["task"].asString(); - - mutex_unlock (cm_mutex); - return 1; - } - - if (arn_check_async_status (request, response)) - { - mutex_unlock (cm_mutex); - return 1; - } - if (arn_cm_extend_request (request, response)) - { - mutex_unlock (cm_mutex); - return 1; - } - cm_execute_request_async (request, response, sco.iHttpTimeout); - - mutex_unlock (cm_mutex); - return 1; -} diff --git a/server/src/cm_server_interface.h b/server/src/cm_server_interface.h deleted file mode 100644 index 60ba045..0000000 --- a/server/src/cm_server_interface.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. - * - * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - -#ifndef __CM_API_H__ -#define __CM_API_H__ -#include - -#include "cm_stat.h" -#include "cm_dep.h" -#include "cm_config.h" -#include "cm_job_task.h" -#include "cm_server_util.h" - -int arn_cm_request_handler (Json::Value &request, Json::Value &response); -void arn_cm_init_env (); - -#endif /* */ diff --git a/server/src/cm_server_stat.c b/server/src/cm_server_stat.c deleted file mode 100644 index f30be6b..0000000 --- a/server/src/cm_server_stat.c +++ /dev/null @@ -1,463 +0,0 @@ -/* - * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. - * - * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/* - * server_stat.c - - */ - -#ident "$Id$" - -#include -#include /* CPU_WAIT */ -#if !defined(AIX) -#include -#endif -#include -#include /* strncmp() */ -#include /* sysconf() */ -#if !defined(HPUX) -#include /* prpsinfo_t */ -#endif -#include /* open() */ -#include -#ifdef HOST_MONITOR_PROC -#include -#endif - -#include "cm_porting.h" -#include "cm_server_stat.h" -#include "cm_dep.h" -#include "cm_server_util.h" -#include "cm_config.h" - -#define MAX_CPU 16 - -#define CHECK_KCID(nk,ok) \ - do { \ - if (nk == -1) { \ - return -1; \ - } \ - if (nk != ok) { \ - goto kcid_changed; \ - } \ - } while (0) - -#define PAGETOM(NUMPAGE, PAGESIZE) ((((NUMPAGE) >> 10) * (PAGESIZE)) >> 10) * 10 - -#ifdef HOST_MONITOR_PROC -static long percentages (int cnt, int *out1, register long *new1, - register long *old, long *diffs); -static void get_swapinfo (int *total, int *fr); -static int get_system_info (kstat_ctl_t *kc, sys_stat *sst); -#ifdef HOST_MONITOR_IO -static void record_iostat (nvplist *res); -#endif /* ifdef HOST_MONITOR_IO */ -#endif /* ifdef HOST_MONITOR_PROC */ - -void -record_system_info (sys_stat *sstat) -{ -#ifdef HOST_MONITOR_PROC - static kstat_ctl_t *kc = NULL; - - while (kc == NULL) - { - kc = kstat_open (); - SLEEP_MILISEC (0, 100); - } - - while (get_system_info (kc, sstat) < 0) - { - SLEEP_MILISEC (0, 100); - } -#endif -} - -void -record_arniadb_proc_info (userdata *ud) -{ -#ifdef HOST_MONITOR_PROC - int i, fd; - prpsinfo_t psbuff; - char procbuf[50]; - int *vect = ud->dbvect; - db_stat *buff = ud->dbbuf; - - /* for each db, update 7 values of process */ - for (i = 0; i < MAX_INSTALLED_DB; ++i) - { - if (vect[i]) - { - sprintf (procbuf, "/proc/%d", buff[i].db_pid); - if ((fd = open (procbuf, O_RDONLY)) == -1) - { - ud->dbsrv_refresh_flag = 1; - continue; - } - if (ioctl (fd, PIOCPSINFO, &psbuff) == -1) - { - ud->dbsrv_refresh_flag = 1; - close (fd); - continue; - } - close (fd); - - /* fill in the structure */ - buff[i].db_size = (unsigned long) psbuff.pr_bysize >> 10; - buff[i].proc_stat[0] = psbuff.pr_sname; - buff[i].db_start_time = psbuff.pr_start.tv_sec; - buff[i].db_cpu_usage = (((double) psbuff.pr_pctcpu) / 0x8000 * 100); - buff[i].db_mem_usage = (((double) psbuff.pr_pctmem) / 0x8000 * 100); - } - } -#endif -} - -void -record_unicas_proc_info (int vect[], cas_stat buff[]) -{ -#ifdef HOST_MONITOR_PROC - int i, fd; - prpsinfo_t psbuff; - char procbuf[50]; - - for (i = 0; i < MAX_UNICAS_PROC; ++i) - { - if (vect[i]) - { - sprintf (procbuf, "/proc/%d", buff[i].cas_pid); - - if ((fd = open (procbuf, O_RDONLY)) == -1) - { - vect[i] = 0; - continue; - } - if (ioctl (fd, PIOCPSINFO, &psbuff) == -1) - { - continue; - } - close (fd); - - /* fill in the structure */ - buff[i].cas_size = (unsigned long) psbuff.pr_bysize >> 10; - buff[i].proc_stat[0] = psbuff.pr_sname; - buff[i].cas_start_time = psbuff.pr_start.tv_sec; - buff[i].cas_cpu_usage = - (((double) psbuff.pr_pctcpu) / 0x8000 * 100); - buff[i].cas_mem_usage = - (((double) psbuff.pr_pctmem) / 0x8000 * 100); - } - } -#endif -} - -#ifdef HOST_MONITOR_PROC -static long -percentages (int cnt, int *out1, register long *new1, register long *old, - long *diffs) -{ - register int i; - register long change; - register long total_change; - register long *dp; - long half_total; - - /* initialization */ - total_change = 0; - dp = diffs; - - /* calculate changes for each state and the overall change */ - for (i = 0; i < cnt; i++) - { - if ((change = *new1 - *old) < 0) - { - /* this only happens when the counter wraps */ - change = (int) ((unsigned long) *new1 - (unsigned long) *old); - } - total_change += (*dp++ = change); - *old++ = *new1++; - } - - /* avoid divide by zero potential */ - if (total_change == 0) - { - total_change = 1; - } - - /* calculate percentages based on overall change, rounding up */ - half_total = total_change / 2l; - for (i = 0; i < cnt; i++) - { - *out1++ = (int) ((*diffs++ * 1000 + half_total) / total_change); - } - /* return the total in case the caller wants to use it */ - return (total_change); -} - -static void -get_swapinfo (int *total, int *fr) -{ -#ifdef SC_AINFO - struct anoninfo anon; - - if (swapctl (SC_AINFO, &anon) == -1) - { - *total = *fr = 0; - return; - } - *total = anon.ani_max; - *fr = anon.ani_max - anon.ani_resv; -#else - register int cnt, i; - register int t, f; - struct swaptable *swt; - struct swapent *ste; - static char path[256]; - - /* get total number of swap entries */ - cnt = swapctl (SC_GETNSWP, 0); - - /* allocate enough space to hold count + n swapents */ - swt = - (struct swaptable *) malloc (sizeof (int) + - cnt * sizeof (struct swapent)); - if (swt == NULL) - { - *total = 0; - *fr = 0; - return; - } - swt->swt_n = cnt; - - /* fill in ste_path pointers: we don't care about the paths, so we point - them all to the same buffer */ - ste = & (swt->swt_ent[0]); - i = cnt; - while (--i >= 0) - { - ste++->ste_path = path; - } - - /* grab all swap info */ - swapctl (SC_LIST, swt); - - /* walk thru the structs and sum up the fields */ - t = f = 0; - ste = & (swt->swt_ent[0]); - i = cnt; - while (--i >= 0) - { - /* don't count slots being deleted */ - if (! (ste->ste_flags & ST_INDEL) && ! (ste->ste_flags & ST_DOINGDEL)) - { - t += ste->ste_pages; - f += ste->ste_free; - } - ste++; - } - - /* fill in the results */ - *total = t; - *fr = f; - free (swt); -#endif -} - -static int -get_system_info (kstat_ctl_t *kc, sys_stat *sst) -{ - kstat_t *ksp; - kstat_named_t *kn; - kid_t kcid, nkcid; - int totalswap, freeswap; - int i, j; - cpu_stat_t cpu_stat[MAX_CPU]; - static int pagesize = 0, maxmem = 0; - static long cp_time[CPUSTATES]; - static long cp_old[CPUSTATES]; - static long cp_diff[CPUSTATES]; - static kstat_t *cpu_ks[MAX_CPU]; - static int ncpu = 0; - static int freemem_check_time = 0; - int changed = 0; - - kcid = kc->kc_chain_id; - -kcid_changed: - - nkcid = kstat_chain_update (kc); - if (nkcid) - { - kcid = nkcid; - changed = 1; - } - CHECK_KCID (nkcid, 0); - - ksp = kstat_lookup (kc, "unix", -1, "system_misc"); - nkcid = kstat_read (kc, ksp, NULL); - CHECK_KCID (nkcid, kcid); - - /* - * collect load average information - */ - kn = kstat_data_lookup (ksp, "avenrun_1min"); - sst->load_avg[0] = kn->value.ui32; - kn = kstat_data_lookup (ksp, "avenrun_5min"); - sst->load_avg[1] = kn->value.ui32; - kn = kstat_data_lookup (ksp, "avenrun_15min"); - sst->load_avg[2] = kn->value.ui32; - - /* - * collect cpu information - */ - if (changed == 1 || ncpu == 0) - { - ncpu = 0; - for (ksp = kc->kc_chain; ksp && ncpu < MAX_CPU; ksp = ksp->ks_next) - { - if (strncmp (ksp->ks_name, "cpu_stat", 8) == 0) - { - nkcid = kstat_read (kc, ksp, NULL); - CHECK_KCID (nkcid, kcid); - cpu_ks[ncpu] = ksp; - ncpu++; - } - } - } - - for (i = 0; i < ncpu; i++) - { - nkcid = kstat_read (kc, cpu_ks[i], & (cpu_stat[i])); - CHECK_KCID (nkcid, kcid); - } - - for (j = 0; j < CPUSTATES; j++) - { - cp_time[j] = 0L; - } - - for (i = 0; i < ncpu; i++) - { - for (j = 0; j < CPU_WAIT; j++) - { - cp_time[j] += (long) cpu_stat[i].cpu_sysinfo.cpu[j]; - } - - cp_time[CPUSTATE_IOWAIT] += (long) cpu_stat[i].cpu_sysinfo.wait[W_IO] + - (long) cpu_stat[i].cpu_sysinfo.wait[W_PIO]; - cp_time[CPUSTATE_SWAP] = (long) cpu_stat[i].cpu_sysinfo.wait[W_SWAP]; - } - - percentages (CPUSTATES, sst->cpu_states, cp_time, cp_old, cp_diff); - - /* - * collect memory information - */ - if (pagesize == 0) - { - pagesize = sysconf (_SC_PAGESIZE); - } - if (maxmem == 0) - { - maxmem = sysconf (_SC_PHYS_PAGES); - sst->memory_stats[0] = PAGETOM (maxmem, pagesize); - } - - if (time (NULL) - freemem_check_time > 30) - { - ksp = kstat_lookup (kc, "unix", 0, "system_pages"); - nkcid = kstat_read (kc, ksp, NULL); - CHECK_KCID (nkcid, kcid); - - kn = kstat_data_lookup (ksp, "freemem"); - sst->memory_stats[2] = PAGETOM (kn->value.ui32, pagesize); - - if (sst->memory_stats[0] - sst->memory_stats[2] > 0) - { - sst->memory_stats[1] = sst->memory_stats[0] - sst->memory_stats[2]; - } - freemem_check_time = time (NULL); - } - -#if 0 - kn = kstat_data_lookup (ksp, "availrmem"); -#endif - - get_swapinfo (&totalswap, &freeswap); - sst->memory_stats[3] = PAGETOM ((totalswap - freeswap), pagesize); - sst->memory_stats[4] = PAGETOM (freeswap, pagesize); - - return 1; -} - -#ifdef HOST_MONITOR_IO -static void -record_iostat (nvplist *res) -{ - FILE *infile; - char buf[1024], d[256], rs[16], ws[16], krs[16], kws[16], wait[16], - actv[16], svc_t[16], w[16], b[16], tmpfile[256]; - sprintf (tmpfile, "%s/DBMT_rec_iostat.%d", sco.dbmt_tmp_dir, - (int) getpid ()); - sprintf (buf, "/usr/bin/iostat -x > %s", tmpfile); - - if (system (buf) != 0) /* iostat */ - { - return; - } - infile = fopen (tmpfile, "r"); - if (infile == NULL) - { - return; - } - fgets (buf, 1024, infile); - fgets (buf, 1024, infile); - while (fgets (buf, 1024, infile)) - { - if (sscanf (buf, "%s %s %s %s %s %s %s %s %s %s", - d, rs, ws, krs, kws, wait, actv, svc_t, w, b) != 10) - { - continue; - } - /* name of the disk */ - nv_add_nvp (res, "device", d); - /* reads per second */ - nv_add_nvp (res, "rs", rs); - /* writes per second */ - nv_add_nvp (res, "ws", ws); - /* KBs read per second */ - nv_add_nvp (res, "krs", krs); - /* KBs written per second */ - nv_add_nvp (res, "kws", kws); - /* avg # of transactions waiting for service */ - nv_add_nvp (res, "wait", wait); - /* avg # of transactions being serviced */ - nv_add_nvp (res, "actv", actv); - /* avg service time in milliseconds */ - nv_add_nvp (res, "svc_t", svc_t); - /* % of time there are transactions waiting for service */ - nv_add_nvp (res, "w", w); - /* % of time the disk is busy */ - nv_add_nvp (res, "b", b); - } - fclose (infile); -} -#endif /* ifdef HOST_MONITOR_IO */ -#endif /* ifdef HOST_MONITOR_PROC */ diff --git a/server/src/cm_server_stat.h b/server/src/cm_server_stat.h deleted file mode 100644 index 69aa6e6..0000000 --- a/server/src/cm_server_stat.h +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. - * - * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/* - * cm_server_stat.h - - */ - -#ifndef _CM_SERVER_STAT_H_ -#define _CM_SERVER_STAT_H_ - -#ident "$Id$" - -#include - -#if !defined(HOST_MONITOR_PROC) && defined(HOST_MONITOR_IO) -#undef HOST_MONITOR_IO -#endif - -#include "cm_dep.h" -#include "cm_config.h" - -#define CPUSTATES 5 -#define CPUSTATE_IOWAIT 3 -#define CPUSTATE_SWAP 4 - -typedef struct -{ -#ifdef HOST_MONITOR_PROC - int load_avg[3]; - int memory_stats[5]; - int cpu_states[CPUSTATES]; -#else - int dummy; -#endif -} sys_stat; - -typedef struct -{ -#ifdef HOST_MONITOR_PROC - char db_name[64]; - int db_pid; - unsigned long db_size; - char proc_stat[2]; - time_t db_start_time; - double db_cpu_usage; - double db_mem_usage; -#else - int dummy; -#endif -} db_stat; - -typedef struct -{ -#ifdef HOST_MONITOR_PROC - char cas_name[64]; - int cas_pid; - unsigned long cas_size; - char proc_stat[2]; - time_t cas_start_time; - double cas_cpu_usage; - double cas_mem_usage; -#else - int dummy; -#endif -} cas_stat; - -typedef struct -{ - char dbsrv_refresh_flag; - time_t last_request_time; - sys_stat ssbuf; - int dbvect[MAX_INSTALLED_DB]; /* 0:inactive, 1:active */ - db_stat dbbuf[MAX_INSTALLED_DB]; - int casvect[MAX_UNICAS_PROC]; - cas_stat casbuf[MAX_UNICAS_PROC]; -} userdata; - -void record_system_info (sys_stat *sstat); -void record_arniadb_proc_info (userdata *ud); -void record_unicas_proc_info (int casv[], cas_stat casb[]); - -#endif /* _CM_SERVER_STAT_H_ */ diff --git a/server/src/cm_server_util.cpp b/server/src/cm_server_util.cpp deleted file mode 100644 index 9a32eed..0000000 --- a/server/src/cm_server_util.cpp +++ /dev/null @@ -1,3790 +0,0 @@ -/* - * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. - * - * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/* - * cm_server_util.cpp - - */ - -#include -#include -#include -#include -#include -#include -#include /* isalpha() */ - -#if defined(WINDOWS) -#include -#include -#include -#include -#include -#include -#include -#else -#include /* umask() */ -#include /* umask(), stat() */ -#include -#include /* opendir() ... */ -#include -#include -#include -#include -#include -#include -#if defined(LINUX) -#include -#endif /* LINUX */ -#if !defined(HPUX) -#include -#endif -#include -#endif - -#if defined(AIX) -#include -#endif - -#include "cm_log.h" -#include "cm_connect_info.h" -#include "cm_porting.h" -#include "cm_server_util.h" -#include "cm_dep.h" -#include "cm_config.h" -#include "cm_job_task.h" -#include "cm_cmd_exec.h" -#include "cm_text_encryption.h" -#include "cm_stat.h" -#include "cm_user.h" - -#include - -#ifdef FSERVER_SLAVE -#define DEF_TASK_FUNC(TASK_FUNC_PTR) TASK_FUNC_PTR -#else -#define DEF_TASK_FUNC(TASK_FUNC_PTR) NULL -#endif - -/* for ut_getdelim */ -#define MAX_LINE ((int)(10*1024*1024)) -#define MIN_CHUNK 4096 - -static T_FSERVER_TASK_INFO task_info[] = -{ - {"startinfo", TS_STARTINFO, 0, DEF_TASK_FUNC (ts_startinfo), FSVR_SA, ALL_AUTHORITY}, - {"userinfo", TS_USERINFO, 0, DEF_TASK_FUNC (ts_userinfo), FSVR_CS, ALL_AUTHORITY}, - {"createuser", TS_CREATEUSER, 1, DEF_TASK_FUNC (ts_create_user), FSVR_CS, AU_DBO}, - {"deleteuser", TS_DELETEUSER, 1, DEF_TASK_FUNC (ts_delete_user), FSVR_CS, AU_DBO}, - {"updateuser", TS_UPDATEUSER, 1, DEF_TASK_FUNC (ts_update_user), FSVR_CS, AU_DBO}, - {"createdb", TS_CREATEDB, 1, DEF_TASK_FUNC (tsCreateDB), FSVR_SA, AU_DBC}, - {"deletedb", TS_DELETEDB, 1, DEF_TASK_FUNC (tsDeleteDB), FSVR_SA, AU_DBC}, - {"renamedb", TS_RENAMEDB, 1, DEF_TASK_FUNC (tsRenameDB), FSVR_SA, AU_DBC}, - {"startdb", TS_STARTDB, 0, DEF_TASK_FUNC (tsStartDB), FSVR_NONE, AU_DBC | AU_DBO}, - {"stopdb", TS_STOPDB, 0, DEF_TASK_FUNC (tsStopDB), FSVR_CS,AU_DBC | AU_DBO}, - {"dbspaceinfo", TS_DBSPACEINFO, 0, DEF_TASK_FUNC (tsDbspaceInfo), FSVR_SA_CS, ALL_AUTHORITY}, - {"classinfo", TS_CLASSINFO, 0, DEF_TASK_FUNC (ts_class_info), FSVR_SA_CS, ALL_AUTHORITY}, - {"class", TS_CLASS, 0, DEF_TASK_FUNC (ts_class), FSVR_CS, ALL_AUTHORITY}, - {"setsysparam", TS_SETSYSPARAM, 1, DEF_TASK_FUNC (ts_set_sysparam), FSVR_NONE, AU_DBC | AU_DBO}, - {"getallsysparam", TS_GETALLSYSPARAM, 0, DEF_TASK_FUNC (ts_get_all_sysparam), FSVR_NONE, ALL_AUTHORITY}, - {"addvoldb", TS_ADDVOLDB, 1, DEF_TASK_FUNC (tsRunAddvoldb), FSVR_SA_CS, AU_DBC | AU_DBO}, - {"getloginfo", TS_GETLOGINFO, 0, DEF_TASK_FUNC (ts_get_log_info), FSVR_NONE, ALL_AUTHORITY}, - {"viewlog", TS_VIEWLOG, 0, DEF_TASK_FUNC (ts_view_log), FSVR_NONE, ALL_AUTHORITY}, - {"viewlog2", TS_VIEWLOG, 0, DEF_TASK_FUNC (ts_view_log), FSVR_NONE, ALL_AUTHORITY}, - {"resetlog", TS_RESETLOG, 0, DEF_TASK_FUNC (ts_reset_log), FSVR_NONE, AU_DBC | AU_DBO}, - {"getenv", TS_GETENV, 0, DEF_TASK_FUNC (tsGetEnvironment), FSVR_SA_UC, ALL_AUTHORITY}, - {"updateattribute", TS_UPDATEATTRIBUTE, 1, DEF_TASK_FUNC (ts_update_attribute), FSVR_CS, ALL_AUTHORITY}, - {"kill_process", TS_KILL_PROCESS, 1, DEF_TASK_FUNC (ts_kill_process), FSVR_NONE, AU_DBC | AU_DBO}, - {"copydb", TS_COPYDB, 1, DEF_TASK_FUNC (ts_copydb), FSVR_SA, AU_DBC}, - {"optimizedb", TS_OPTIMIZEDB, 1, DEF_TASK_FUNC (ts_optimizedb), FSVR_SA_CS, AU_DBC | AU_DBO}, - {"plandump", TS_PLANDUMP, 1, DEF_TASK_FUNC (ts_plandump), FSVR_CS, ALL_AUTHORITY}, - {"paramdump", TS_PARAMDUMP, 1, DEF_TASK_FUNC (ts_paramdump), FSVR_SA_CS, ALL_AUTHORITY}, - {"statdump", TS_STATDUMP, 1, DEF_TASK_FUNC (ts_statdump), FSVR_CS, ALL_AUTHORITY}, - {"checkdb", TS_CHECKDB, 0, DEF_TASK_FUNC (ts_checkdb), FSVR_SA_CS, AU_DBC | AU_DBO}, - {"compactdb", TS_COMPACTDB, 1, DEF_TASK_FUNC (ts_compactdb), FSVR_SA, AU_DBC | AU_DBO}, - {"backupdbinfo", TS_BACKUPDBINFO, 0, DEF_TASK_FUNC (ts_backupdb_info), FSVR_NONE, ALL_AUTHORITY}, - {"backupdb", TS_BACKUPDB, 0, DEF_TASK_FUNC (ts_backupdb), FSVR_SA_CS, AU_DBC | AU_DBO}, - {"unloaddb", TS_UNLOADDB, 1, DEF_TASK_FUNC (ts_unloaddb), FSVR_SA, AU_DBC | AU_DBO}, - {"unloadinfo", TS_UNLOADDBINFO, 0, DEF_TASK_FUNC (ts_unloaddb_info), FSVR_NONE, ALL_AUTHORITY}, - {"loaddb", TS_LOADDB, 1, DEF_TASK_FUNC (ts_loaddb), FSVR_SA, AU_DBC | AU_DBO}, - {"gettransactioninfo", TS_GETTRANINFO, 0, DEF_TASK_FUNC (ts_get_tran_info), FSVR_CS, ALL_AUTHORITY}, - {"killtransaction", TS_KILLTRAN, 1, DEF_TASK_FUNC (ts_killtran), FSVR_CS, AU_DBC | AU_DBO | AU_MON}, - {"lockdb", TS_LOCKDB, 0, DEF_TASK_FUNC (ts_lockdb), FSVR_CS, ALL_AUTHORITY}, - {"getbackuplist", TS_GETBACKUPLIST, 0, DEF_TASK_FUNC (ts_get_backup_list), FSVR_NONE, ALL_AUTHORITY}, - {"restoredb", TS_RESTOREDB, 1, DEF_TASK_FUNC (ts_restoredb), FSVR_SA, AU_DBC | AU_DBO}, - {"backupvolinfo", TS_BACKUPVOLINFO, 0, DEF_TASK_FUNC (ts_backup_vol_info), FSVR_SA, ALL_AUTHORITY}, - {"getdbsize", TS_GETDBSIZE, 0, DEF_TASK_FUNC (ts_get_dbsize), FSVR_SA_CS, ALL_AUTHORITY}, - {"getbackupinfo", TS_GETBACKUPINFO, 0, DEF_TASK_FUNC (ts_get_backup_info), FSVR_NONE, ALL_AUTHORITY}, - {"addbackupinfo", TS_ADDBACKUPINFO, 1, DEF_TASK_FUNC (ts_add_backup_info), FSVR_NONE, AU_DBC | AU_DBO | AU_JOB}, - { - "deletebackupinfo", TS_DELETEBACKUPINFO, 1, DEF_TASK_FUNC (ts_delete_backup_info), - FSVR_NONE, AU_DBC | AU_DBO | AU_JOB - }, - {"setbackupinfo", TS_SETBACKUPINFO, 0, DEF_TASK_FUNC (ts_set_backup_info), FSVR_NONE, AU_DBC | AU_DBO | AU_JOB}, - {"getautoaddvol", TS_GETAUTOADDVOL, 0, DEF_TASK_FUNC (ts_get_auto_add_vol), FSVR_NONE, ALL_AUTHORITY}, - {"setautoaddvol", TS_SETAUTOADDVOL, 1, DEF_TASK_FUNC (ts_set_auto_add_vol), FSVR_NONE, AU_DBC | AU_DBO}, - {"checkdir", TS_CHECKDIR, 0, DEF_TASK_FUNC (ts_check_dir), FSVR_NONE, ALL_AUTHORITY}, - { - "getautobackupdberrlog", TS_AUTOBACKUPDBERRLOG, 0, DEF_TASK_FUNC (ts_get_autobackupdb_error_log), - FSVR_NONE, ALL_AUTHORITY - }, - { - "getautoexecqueryerrlog", TS_AUTOEXECQUERYERRLOG, 0, DEF_TASK_FUNC (ts_get_autoexecquery_error_log), - FSVR_NONE, ALL_AUTHORITY - }, - { - "getdbmtuserinfo", TS_GETDBMTUSERINFO, 0, DEF_TASK_FUNC (tsGetDBMTUserInfo), - FSVR_NONE, ALL_AUTHORITY - }, - {"deletedbmtuser", TS_DELETEDBMTUSER, 1, DEF_TASK_FUNC (tsDeleteDBMTUser), FSVR_NONE, AU_DBC}, - {"updatedbmtuser", TS_UPDATEDBMTUSER, 1, DEF_TASK_FUNC (tsUpdateDBMTUser), FSVR_NONE, AU_DBC}, - {"setdbmtpasswd", TS_SETDBMTPASSWD, 1,DEF_TASK_FUNC (tsChangeDBMTUserPasswd), FSVR_NONE, ALL_AUTHORITY ^ AU_DBC}, - {"adddbmtuser", TS_ADDDBMTUSER, 1, DEF_TASK_FUNC (tsCreateDBMTUser), FSVR_NONE, AU_DBC}, - {"getaddvolstatus", TS_GETADDVOLSTATUS, 0, DEF_TASK_FUNC (ts_get_addvol_status), FSVR_NONE, ALL_AUTHORITY}, - {"getautoaddvollog", TS_GETAUTOADDVOLLOG, 0, DEF_TASK_FUNC (tsGetAutoaddvolLog), FSVR_UC, ALL_AUTHORITY}, - {"getinitbrokersinfo", TS2_GETINITUNICASINFO, 0, DEF_TASK_FUNC (ts2_get_unicas_info), FSVR_UC, ALL_AUTHORITY}, - {"getbrokersinfo", TS2_GETUNICASINFO, 0, DEF_TASK_FUNC (ts2_get_unicas_info), FSVR_UC, ALL_AUTHORITY}, - {"startbroker", TS2_STARTUNICAS, 0, DEF_TASK_FUNC (ts2_start_unicas), FSVR_UC, AU_DBC | AU_DBO | AU_BRK}, - {"stopbroker", TS2_STOPUNICAS, 0, DEF_TASK_FUNC (ts2_stop_unicas), FSVR_UC, AU_DBC | AU_DBO | AU_BRK}, - {"getadminloginfo", TS2_GETADMINLOGINFO, 0, DEF_TASK_FUNC (ts2_get_admin_log_info), FSVR_UC, ALL_AUTHORITY}, - {"getlogfileinfo", TS2_GETLOGFILEINFO, 0, DEF_TASK_FUNC (ts2_get_logfile_info), FSVR_UC, ALL_AUTHORITY}, - {"getaddbrokerinfo", TS2_GETADDBROKERINFO, 0, DEF_TASK_FUNC (ts2_get_add_broker_info), FSVR_UC, ALL_AUTHORITY}, - {"deletebroker", TS2_DELETEBROKER, 1, DEF_TASK_FUNC (ts2_delete_broker), FSVR_UC, AU_DBC | AU_DBO | AU_BRK}, - {"getbrokerstatus", TS2_GETBROKERSTATUS, 0, DEF_TASK_FUNC (ts2_get_broker_status), FSVR_UC, ALL_AUTHORITY}, - {"broker_setparam", TS2_SETBROKERCONF, 1, DEF_TASK_FUNC (ts2_set_broker_conf), FSVR_UC, AU_DBC | AU_DBO | AU_BRK}, - {"broker_start", TS2_STARTBROKER, 0, DEF_TASK_FUNC (ts2_start_broker), FSVR_UC, AU_DBC | AU_DBO | AU_BRK}, - {"broker_stop", TS2_STOPBROKER, 0, DEF_TASK_FUNC (ts2_stop_broker), FSVR_UC, AU_DBC | AU_DBO | AU_BRK}, - { - "broker_restart", TS2_RESTARTBROKERAS, 0, DEF_TASK_FUNC (ts2_restart_broker_as), - FSVR_UC, AU_DBC | AU_DBO | AU_BRK - }, - {"checkfile", TS_CHECKFILE, 0, DEF_TASK_FUNC (ts_check_file), FSVR_NONE, ALL_AUTHORITY}, - {"loadaccesslog", TS_LOADACCESSLOG, 0, DEF_TASK_FUNC (ts_load_access_log), FSVR_NONE, ALL_AUTHORITY}, - {"getaccesslogfiles", TS_GETACCESSLOGFILES, 0, DEF_TASK_FUNC (ts_get_access_log_files), FSVR_NONE, ALL_AUTHORITY}, - {"geterrorlogfiles", TS_GETERRORLOGFILES, 0, DEF_TASK_FUNC (ts_get_error_log_files), FSVR_NONE, ALL_AUTHORITY}, - {"addtrigger", TS_ADDNEWTRIGGER, 1, DEF_TASK_FUNC (ts_trigger_operation), FSVR_SA_CS, AU_DBC | AU_DBO}, - {"altertrigger", TS_ALTERTRIGGER, 1, DEF_TASK_FUNC (ts_trigger_operation), FSVR_SA_CS, AU_DBC | AU_DBO}, - {"droptrigger", TS_DROPTRIGGER, 1, DEF_TASK_FUNC (ts_trigger_operation), FSVR_SA_CS, AU_DBC | AU_DBO}, - {"gettriggerinfo", TS_GETTRIGGERINFO, 0, DEF_TASK_FUNC (ts_get_triggerinfo), FSVR_SA_CS, ALL_AUTHORITY}, - {"getautoexecquery", TS_GETAUTOEXECQUERY, 0, DEF_TASK_FUNC (ts_get_autoexec_query), FSVR_SA_CS, ALL_AUTHORITY}, - { - "setautoexecquery", TS_SETAUTOEXECQUERY, 1, DEF_TASK_FUNC (ts_set_autoexec_query), - FSVR_SA_CS, AU_DBC | AU_DBO | AU_JOB - }, - {"getdiagdata", TS_GET_DIAGDATA, 0, DEF_TASK_FUNC (ts_get_diagdata), FSVR_NONE, ALL_AUTHORITY}, - {"getbrokerdiagdata", TS_GET_BROKER_DIAGDATA, 0, DEF_TASK_FUNC (ts_get_broker_diagdata), FSVR_NONE, ALL_AUTHORITY}, - { - "addstatustemplate", TS_ADDSTATUSTEMPLATE, 0, DEF_TASK_FUNC (ts_addstatustemplate), - FSVR_NONE, AU_DBC | AU_DBO | AU_MON - }, - { - "updatestatustemplate", TS_UPDATESTATUSTEMPLATE, 0, DEF_TASK_FUNC (ts_updatestatustemplate), - FSVR_NONE, AU_DBC | AU_DBO | AU_MON - }, - { - "removestatustemplate", TS_REMOVESTATUSTEMPLATE, 0, DEF_TASK_FUNC (ts_removestatustemplate), - FSVR_NONE, AU_DBC | AU_DBO | AU_MON - }, - {"getstatustemplate", TS_GETSTATUSTEMPLATE, 0, DEF_TASK_FUNC (ts_getstatustemplate), FSVR_NONE, ALL_AUTHORITY}, - {"analyzecaslog", TS_ANALYZECASLOG, 0, DEF_TASK_FUNC (ts_analyzecaslog), FSVR_NONE, ALL_AUTHORITY}, - { - "executecasrunner", TS_EXECUTECASRUNNER, 0, DEF_TASK_FUNC (ts_executecasrunner), - FSVR_NONE, AU_DBC | AU_DBO | AU_BRK | AU_MON - }, - { - "removecasrunnertmpfile", TS_REMOVECASRUNNERTMPFILE, 0, DEF_TASK_FUNC (ts_removecasrunnertmpfile), - FSVR_NONE, AU_DBC | AU_DBO | AU_BRK | AU_MON - }, - {"getcaslogtopresult", TS_GETCASLOGTOPRESULT, 0, DEF_TASK_FUNC (ts_getcaslogtopresult), FSVR_NONE, ALL_AUTHORITY}, - {"dbmtuserlogin", TS_DBMTUSERLOGIN, 0, DEF_TASK_FUNC (tsDBMTUserLogin), FSVR_NONE, ALL_AUTHORITY}, - {"removelog", TS_REMOVE_LOG, 0, DEF_TASK_FUNC (ts_remove_log), FSVR_NONE, ALL_AUTHORITY}, - {"getdbprocstat", TS_GETDBPROCSTAT, 0, DEF_TASK_FUNC (ts_get_dbproc_stat), FSVR_SA_CS, ALL_AUTHORITY}, - {"gethoststat", TS_GETHOSTSTAT, 0, DEF_TASK_FUNC (ts_get_host_stat), FSVR_SA_CS, ALL_AUTHORITY}, - {"heartbeatlist", TS_HEARTBEAT_LIST, 0, DEF_TASK_FUNC (ts_heartbeat_list), FSVR_SA_CS, ALL_AUTHORITY}, - {"changemode", TS_CHANGEMODE, 0, DEF_TASK_FUNC (ts_changemode), FSVR_CS, AU_DBC | AU_DBO}, - {"getdbmode", TS_GETDBMODE, 0, DEF_TASK_FUNC (ts_get_db_mode), FSVR_SA_CS, ALL_AUTHORITY}, - { - "getstandbyserverstat", TS_GET_STANDBY_SERVER_STAT, 0, DEF_TASK_FUNC (ts_get_standby_server_stat), - FSVR_SA_CS, ALL_AUTHORITY - }, - {"rolechange", TS_ROLE_CHANGE, 0, DEF_TASK_FUNC (ts_role_change), FSVR_CS, AU_DBC | AU_DBO}, - {"userverify", TS_USER_VERIFY, 0, DEF_TASK_FUNC (ts_user_verify), FSVR_SA_CS, ALL_AUTHORITY}, - {"runsqlstatement", TS_RUN_SQL_STATEMENT, 0, DEF_TASK_FUNC (ts_run_sql_statement), FSVR_SA_CS, ALL_AUTHORITY}, - {"writeandsaveconf", TS_WRITE_AND_SAVE_CONF, 0, DEF_TASK_FUNC (ts_write_and_save_conf), FSVR_SA_CS, AU_DBC | AU_DBO}, - {"getfiletotallinenum", TS_GET_FILE_TOTAL_LINE_NUM, 0, DEF_TASK_FUNC (ts_get_file_total_line_num), FSVR_SA_CS, ALL_AUTHORITY}, - {"runscript", TS_RUN_SCRIPT, 0, DEF_TASK_FUNC (ts_run_script), FSVR_SA_CS, ALL_AUTHORITY}, - {"copyfolder", TS_COPY_FOLDER, 0, DEF_TASK_FUNC (ts_copy_folder), FSVR_SA_CS, AU_DBC | AU_DBO}, - {"deletefolder", TS_DELETE_FOLDER, 0, DEF_TASK_FUNC (ts_delete_folder), FSVR_SA_CS, AU_DBC | AU_DBO}, - { - "getfolderswithkeyword", TS_GET_FOLDERS_WITH_KEYWORD, 0,DEF_TASK_FUNC (ts_get_folders_with_keyword), - FSVR_SA_CS, ALL_AUTHORITY - }, - {"getenvvarbyname", TS_GET_ENVVAR_BY_NAME, 0, DEF_TASK_FUNC (ts_get_envvar_by_name), FSVR_SA_CS, ALL_AUTHORITY}, - {"errortrace", TS_ERROR_TRACE, 0, DEF_TASK_FUNC (ts_error_trace), FSVR_SA_CS, ALL_AUTHORITY}, - {"login", TS_LOGIN, 0, DEF_TASK_FUNC (ts_login), FSVR_SA_CS, ALL_AUTHORITY}, - {"logout", TS_LOGOUT, 0, DEF_TASK_FUNC (ts_logout), FSVR_SA_CS, ALL_AUTHORITY}, - {"getcmsenv", TS_GET_CMS_ENV, 0, DEF_TASK_FUNC (ts_get_cms_env), FSVR_SA_CS, ALL_AUTHORITY}, - {"keepalive", TS_KEEPALIVE, 0, DEF_TASK_FUNC (ts_keepalive), FSVR_CS, ALL_AUTHORITY}, - {"removefiles", TS_REMOVE_FILES, 0, DEF_TASK_FUNC (ts_remove_files), FSVR_NONE, AU_DBC | AU_DBO}, - {"#jobtest", TS_JOB_TEST, 0, DEF_TASK_FUNC (ts_job_test), FSVR_NONE, ALL_AUTHORITY}, - {"dbspace", TS_DB_SPACE_INFO, 0, DEF_TASK_FUNC (ts_dbs_spaceInfo), FSVR_NONE, ALL_AUTHORITY}, - {"shard_start", TS_SHARD_START, 0, DEF_TASK_FUNC (ts_shard_start), FSVR_NONE, AU_DBC | AU_DBO | AU_BRK}, - {"shard_stop", TS_SHARD_STOP, 0, DEF_TASK_FUNC (ts_shard_stop), FSVR_NONE, AU_DBC | AU_DBO | AU_BRK}, - {"getshardinfo", TS_GET_SHARD_INFO, 0, DEF_TASK_FUNC (ts_get_shard_info), FSVR_NONE, ALL_AUTHORITY}, - {"getshardstatus", TS_GET_SHARD_STATUS, 0, DEF_TASK_FUNC (ts_get_shard_status), FSVR_NONE, ALL_AUTHORITY}, - {"broker_changer", TS_BROKER_CHANGER, 0, DEF_TASK_FUNC (ts_broker_changer), FSVR_NONE, AU_DBC | AU_DBO | AU_BRK}, - {"ha_start", TS_HA_START, 0, DEF_TASK_FUNC (ts_ha_start), FSVR_NONE, AU_DBC | AU_DBO}, - {"ha_stop", TS_HA_STOP, 0, DEF_TASK_FUNC (ts_ha_stop), FSVR_NONE, AU_DBC | AU_DBO}, - {"ha_status", TS_HA_STATUS, 0, DEF_TASK_FUNC (ts_ha_status), FSVR_NONE, ALL_AUTHORITY}, - {"ha_copylogdb", TS_HA_COPYLOGDB, 0, DEF_TASK_FUNC (ts_ha_copylogdb), FSVR_NONE, AU_DBC | AU_DBO}, - {"ha_applylogdb", TS_HA_APPLYLOGDB, 0, DEF_TASK_FUNC (ts_ha_applylogdb), FSVR_NONE, AU_DBC | AU_DBO}, - {"ha_reload", TS_HA_RELOAD, 0, DEF_TASK_FUNC (ts_ha_reload), FSVR_NONE, AU_DBC | AU_DBO}, - {"list_dir", TS_LIST_DIR, 0, DEF_TASK_FUNC (ts_list_dir), FSVR_NONE, ALL_AUTHORITY}, - {"autoupdate", TS_AUTO_UPDATE, 0, DEF_TASK_FUNC (ts_auto_update), FSVR_NONE, AU_ADMIN}, - {"isupdatesuccess", TS_IS_UPDATE_SUCCESS, 0, DEF_TASK_FUNC (ts_is_update_success), FSVR_NONE, AU_ADMIN}, - {"monitorprocess", TS_MONITOR_PROCESS, 0, DEF_TASK_FUNC (ts_monitor_process), FSVR_NONE, ALL_AUTHORITY}, - {"generatecert", TS_GENERATE_CERT, 0, DEF_TASK_FUNC (ts_generate_cert), FSVR_NONE, ALL_AUTHORITY}, - {"start_statdump", TS_START_STATDUMP, 0, DEF_TASK_FUNC (ts_start_statdump), FSVR_CS, ALL_AUTHORITY}, - {"stop_statdump", TS_STOP_STATDUMP, 0, DEF_TASK_FUNC (ts_stop_statdump), FSVR_CS, ALL_AUTHORITY}, - {NULL, TS_UNDEFINED, 0, NULL, FSVR_NONE, 0} -}; - -#if defined(WINDOWS) - -typedef BOOL (WINAPI *GET_SYSTEM_TIMES) (LPFILETIME, LPFILETIME, LPFILETIME); -typedef NTSTATUS (WINAPI *NT_QUERY_SYSTEM_INFORMATION) (SYSTEM_INFORMATION_CLASS, PVOID, ULONG, PULONG); - -/* - * 0 - init_state. - * 1 - load GetSystemTime. - * 2 - load NtQuerySystemInformation. - * 3 - error state. - */ -static volatile int s_symbol_loaded = 0; -static volatile GET_SYSTEM_TIMES s_pfnGetSystemTimes = NULL; -static volatile NT_QUERY_SYSTEM_INFORMATION s_pfnNtQuerySystemInformation = NULL; -#endif - -static int _maybe_ip_addr (char *hostname); -static int _ip_equal_hostent (struct hostent *hp, char *token); -static int get_short_filename (char *ret_name, int ret_name_len, - char *short_filename); -static bool is_process_running (const char *process_name, unsigned int sleep_time); - -/** -* is_process_running is to check process running or not by checking pid -* process_name: the name of process that must be in $ARNIADB/bin -* sleep_time: millisecond -*/ -static bool -is_process_running (const char *process_name, unsigned int sleep_time) -{ - FILE *input = NULL; - char buf[16], cmd[PATH_MAX]; - - SLEEP_MILISEC (0, sleep_time); - -#if !defined (DO_NOT_USE_ARNIADBENV) - sprintf (cmd, "%s/%s/%s getpid", sco.szArniadb, ARNIADB_DIR_BIN, - process_name); -#else - sprintf (cmd, "%s/%s getpid", ARNIADB_BINDIR, process_name); -#endif - input = popen (cmd, "r"); - if (input == NULL) - { - return false; - } - - memset (buf, '\0', sizeof (buf)); - if ((fgets (buf, 16, input) == NULL) || atoi (buf) <= 0) - { - pclose (input); - return false; - } - - pclose (input); - - return true; -} - -#if !defined(WINDOWS) -int -run_child_linux (const char *pname, const char *const argv[], int wait_flag, - const char *stdin_file, char *stdout_file, char *stderr_file, - int *exit_status) -{ - int pid = 0; - - if (exit_status != NULL) - { - *exit_status = 0; - } - - if (wait_flag) - { - signal (SIGCHLD, SIG_DFL); - } - else - { - signal (SIGCHLD, SIG_IGN); - } - - pid = fork (); - if (pid == 0) - { - FILE *fp = NULL; - - close_all_fds (3); - - if (stdin_file != NULL) - { - fp = fopen (stdin_file, "r"); - if (fp != NULL) - { - dup2 (fileno (fp), 0); - fclose (fp); - } - } - - if (stdout_file != NULL) - { - unlink (stdout_file); - fp = fopen (stdout_file, "w"); - if (fp != NULL) - { - dup2 (fileno (fp), 1); - fclose (fp); - } - } - - - if (stderr_file != NULL) - { - unlink (stderr_file); - fp = fopen (stderr_file, "w"); - if (fp != NULL) - { - dup2 (fileno (fp), 2); - fclose (fp); - } - } - - execv (pname, (char *const *) argv); - exit (0); - } - - if (pid < 0) - { - return -1; - } - - if (wait_flag) - { - int status = 0; - waitpid (pid, &status, 0); - if (exit_status != NULL) - { - *exit_status = status; - } - return 0; - } - else - { - return pid; - } -} -#endif - -int -_op_check_is_localhost (char *token, char *hname) -{ - struct hostent *hp; - - if ((hp = gethostbyname (hname)) == NULL) - { - return -1; - } - - /* if token is an ip address. */ - if (_maybe_ip_addr (token) > 0) - { - /* if token equal 127.0.0.1 or the ip is in the list of hname. */ - if ((strcmp (token, "127.0.0.1") == 0) - || _ip_equal_hostent (hp, token) == 0) - { - return 0; - } - } - else - { - /* - * if token is not an ip address, - * then compare it with the hostname ignore case. - */ - if ((strcasecmp (token, hname) == 0) - || (strcasecmp (token, "localhost") == 0)) - { - return 0; - } - } - return -1; -} - -static int -_maybe_ip_addr (char *hostname) -{ - if (hostname == NULL) - { - return 0; - } - return (isdigit (hostname[0]) ? 1 : 0); -} - -static int -_ip_equal_hostent (struct hostent *hp, char *token) -{ - int i; - int retval = -1; - const char *tmpstr = NULL; - struct in_addr inaddr; - - if (hp == NULL) - { - return retval; - } - - for (i = 0; hp->h_addr_list[i] != NULL; i++) - { - /* change ip address of hname to string. */ - inaddr.s_addr = * (unsigned long *) hp->h_addr_list[i]; - tmpstr = inet_ntoa (inaddr); - - /* compare the ip string with token. */ - if (strcmp (token, tmpstr) == 0) - { - retval = 0; - break; - } - } - return retval; -} - -void -append_host_to_dbname (char *name_buf, const char *dbname, int buf_len) -{ - snprintf (name_buf, buf_len, "%s@127.0.0.1", dbname); -} - -void * -increase_capacity (void *ptr, int block_size, int old_count, int new_count) -{ - if (new_count <= old_count || new_count <= 0) - { - return NULL; - } - - if (ptr == NULL) - { - if ((ptr = MALLOC (block_size * new_count)) == NULL) - { - return NULL; - } - memset (ptr, 0, block_size * new_count); - } - else - { - if ((ptr = realloc (ptr, block_size * new_count)) == NULL) - { - return NULL; - } - memset ((char *) ptr + old_count * block_size, 0, - block_size * (new_count - old_count)); - } - - return ptr; -} - -char * -strcpy_limit (char *dest, const char *src, int buf_len) -{ - strncpy (dest, src, buf_len - 1); - dest[buf_len - 1] = '\0'; - return dest; -} - -int -ut_getdelim (char **lineptr, int *n, int delimiter, FILE *fp) -{ - int result = -1; - int cur_len = 0; - int c; - - if (lineptr == NULL || n == NULL || fp == NULL) - { - return -1; - } - - if (*lineptr == NULL || *n == 0) - { - char *new_lineptr; - *n = MIN_CHUNK; - new_lineptr = (char *) realloc (*lineptr, *n); - - if (new_lineptr == NULL) - { - return -1; - } - *lineptr = new_lineptr; - } - - for (;;) - { - c = getc (fp); - if (c == EOF) - { - result = -1; - break; - } - - /* Make enough space for len+1 (for final NUL) bytes. */ - if (cur_len + 1 >= *n) - { - int line_len = 2 * *n + 1; - char *new_lineptr; - - if (line_len > MAX_LINE) - { - line_len = MAX_LINE; - } - if (cur_len + 1 >= line_len) - { - return -1; - } - - new_lineptr = (char *) realloc (*lineptr, line_len); - if (new_lineptr == NULL) - { - return -1; - } - - *lineptr = new_lineptr; - *n = line_len; - } - (*lineptr)[cur_len] = c; - cur_len++; - - if (c == delimiter) - { - break; - } - } - (*lineptr)[cur_len] = '\0'; - result = cur_len ? cur_len : result; - - return result; -} - -int -ut_getline (char **lineptr, int *n, FILE *fp) -{ - return ut_getdelim (lineptr, n, '\n', fp); -} - -void -uRemoveCRLF (char *str) -{ - size_t i; - if (str == NULL) - { - return; - } - for (i = strlen (str) - 1; (i >= 0) && (str[i] == 10 || str[i] == 13); i--) - { - str[i] = '\0'; - } -} - -char * -time_to_str (time_t t, const char *fmt, char *buf, int type) -{ - struct tm ltm; - struct tm *tm_p; - - tm_p = localtime (&t); - if (tm_p == NULL) - { - *buf = '\0'; - return buf; - } - ltm = *tm_p; - - if (type == TIME_STR_FMT_DATE) - { - sprintf (buf, fmt, ltm.tm_year + 1900, ltm.tm_mon + 1, ltm.tm_mday); - } - else if (type == TIME_STR_FMT_TIME) - { - sprintf (buf, fmt, ltm.tm_hour, ltm.tm_min, ltm.tm_sec); - } - else /* TIME_STR_FMT_DATE_TIME */ - sprintf (buf, fmt, ltm.tm_year + 1900, ltm.tm_mon + 1, ltm.tm_mday, - ltm.tm_hour, ltm.tm_min, ltm.tm_sec); - return buf; -} - -int -uStringEqual (const char *str1, const char *str2) -{ - if (str1 == NULL || str2 == NULL) - { - return 0; - } - if (strcmp (str1, str2) == 0) - { - return 1; - } - return 0; -} - -int -uStringEqualIgnoreCase (const char *str1, const char *str2) -{ - if (str1 == NULL || str2 == NULL) - { - return 0; - } - if (strcasecmp (str1, str2) == 0) - { - return 1; - } - return 0; -} - -void -write_manager_error_log (const char *protocol_str, const char *msg) -{ - char message[DBMT_ERROR_MSG_SIZE]; - - snprintf (message, DBMT_ERROR_MSG_SIZE, "%s %s", protocol_str, msg); - - LOG_ERROR (message); -} - -void -ut_error_log (nvplist *req, const char *errmsg) -{ - const char *id, *addr, *task; - char strbuf[512]; - - if ((task = nv_get_val (req, "task")) == NULL) - { - task = "-"; - } - if ((addr = nv_get_val (req, "_CLIENTIP")) == NULL) - { - addr = "-"; - } - if ((id = nv_get_val (req, "_ID")) == NULL) - { - id = "-"; - } - if (errmsg == NULL) - { - errmsg = "-"; - } - - snprintf (strbuf, sizeof (strbuf), "%s %s %s %s", ACCESS_ERR, id, addr, task); - - write_manager_error_log (strbuf, errmsg); -} - -void -write_manager_access_log (const char *protocol_str, const char *msg) -{ - char message[DBMT_ERROR_MSG_SIZE]; - - snprintf (message, DBMT_ERROR_MSG_SIZE, "%s %s", protocol_str, msg); - - LOG_INFO (message); -} - -void -ut_access_log (nvplist *req, const char *msg) -{ - const char *id, *cli_addr, *task; - char strbuf[512]; - - strbuf[0] = '\0'; - - if ((task = nv_get_val (req, "task")) == NULL) - { - task = "-"; - } - if ((cli_addr = nv_get_val (req, "_CLIENTIP")) == NULL) - { - cli_addr = "-"; - } - if ((id = nv_get_val (req, "_ID")) == NULL) - { - id = "-"; - } - if (msg == NULL) - { - msg = ""; - } - - snprintf (strbuf, sizeof (strbuf), "%s %s %s %s", ACCESS_LOG, id, cli_addr, task); - - write_manager_access_log (strbuf, msg); -} - -int -ut_get_task_info (const char *task, char *access_log_flag, - T_TASK_FUNC *task_func, T_USER_AUTH *auth) -{ - int i; - - for (i = 0; task_info[i].task_str != NULL; i++) - { - if (uStringEqual (task, task_info[i].task_str)) - { - if (access_log_flag) - { - *access_log_flag = task_info[i].access_log_flag; - } - if (task_func) - { - *task_func = task_info[i].task_func; - } - - if (auth) - { - *auth = task_info[i].user_auth; - } - return task_info[i].task_code; - } - } - - return TS_UNDEFINED; -} - -int -ut_send_response (SOCKET fd, nvplist *res) -{ - int i; - - if (res == NULL) - { - return -1; - } - - for (i = 0; i < res->nvplist_size; ++i) - { - if (res->nvpairs[i] == NULL) - { - continue; - } - write_to_socket (fd, dst_buffer (res->nvpairs[i]->name), - dst_length (res->nvpairs[i]->name)); - write_to_socket (fd, dst_buffer (res->delimiter), res->delimiter->dlen); - - if (strncmp (res->nvpairs[i]->name->dbuf, ENCRYPT_SIGN, - strlen (ENCRYPT_SIGN)) == 0) - { - int str_len; - char *encrypt_buf; - - str_len = dst_length (res->nvpairs[i]->value); - str_len = MAX (str_len, MIN_ENCRYPT_LEN); - - /* make the len to be multiple of 8. */ - str_len = MAKE_MUTIPLE_EIGHT (str_len); - - if ((encrypt_buf = (char *) MALLOC (str_len * 2 + 1)) == NULL) - { - return -1; - } - - uEncrypt (str_len, dst_buffer (res->nvpairs[i]->value), - encrypt_buf); - write_to_socket (fd, encrypt_buf, (int) strlen (encrypt_buf)); - - FREE_MEM (encrypt_buf); - } - else - { - write_to_socket (fd, dst_buffer (res->nvpairs[i]->value), - dst_length (res->nvpairs[i]->value)); - } - write_to_socket (fd, dst_buffer (res->endmarker), res->endmarker->dlen); - } - write_to_socket (fd, dst_buffer (res->listcloser), res->listcloser->dlen); - - return 0; -} - -/* - * read incoming data and construct name-value pair list of request - */ -int -ut_receive_request (SOCKET fd, nvplist *req) -{ - int rc; - char c; - dstring *linebuf = NULL; - char *p; - - linebuf = dst_create (); - - while ((rc = read_from_socket (fd, &c, 1)) == 1) - { - char *dstbuf; - - if (c == '\n') - { - /* if null string, stop parsing */ - if (dst_length (linebuf) == 0) - { - dst_destroy (linebuf); - return 0; - } - - dstbuf = dst_buffer (linebuf); - if (dstbuf != NULL) - { - p = strchr (dstbuf, ':'); - if (p) - { - *p = '\0'; - p++; - if (strncmp (dstbuf, ENCRYPT_SIGN, strlen (ENCRYPT_SIGN)) == 0) - { - int len; - char *decrypt_buf; - - len = (int) strlen (p); - if (len % 2) - { - goto error_return; - } - - len /= 2; - if ((decrypt_buf = (char *) MALLOC (len + 1)) == NULL) - { - goto error_return; - } - - /* decrypt the value. */ - uDecrypt (len, p, decrypt_buf); - nv_add_nvp (req, dstbuf + strlen (ENCRYPT_SIGN), - decrypt_buf); - free (decrypt_buf); - } - else - { - nv_add_nvp (req, dst_buffer (linebuf), p); - } - } - } - dst_reset (linebuf); - } - else - { - if (c != '\r') - { - dst_append (linebuf, &c, 1); - } - } - } - -error_return: - dst_destroy (linebuf); - return -1; -} - -void -ut_daemon_start (void) -{ -#if defined(WINDOWS) - return; -#else - int childpid; - - /* Ignore the terminal stop signals */ - signal (SIGTTOU, SIG_IGN); - signal (SIGTTIN, SIG_IGN); - signal (SIGTSTP, SIG_IGN); - -#if 0 - /* to make it run in background */ - signal (SIGHUP, SIG_IGN); - childpid = PROC_FORK (); - if (childpid > 0) - { - exit (0); /* kill parent */ - } -#endif - - /* setpgrp(); */ - setsid (); /* become process group leader and */ - /* disconnect from control terminal */ - - signal (SIGHUP, SIG_IGN); - childpid = PROC_FORK (); /* to prevent from reaquiring control terminal */ - if (childpid > 0) - { - exit (0); /* kill parent */ - } - -#if 0 - /* change current working directory */ - chdir ("/"); - /* clear umask */ - umask (0); -#endif -#endif /* ifndef WINDOWS */ -} - -int -ut_write_pid (char *pid_file) -{ - FILE *pidfp; - - pidfp = fopen (pid_file, "w"); - if (pidfp == NULL) - { - perror ("fopen"); - return -1; - } - fprintf (pidfp, "%d\n", (int) getpid ()); - fclose (pidfp); - return 0; -} - -void -server_fd_clear (fd_set srv_fds) -{ -#if !defined(WINDOWS) - SOCKET i; - int fd; - - for (i = 3; i < 1024; i++) - { - if (!FD_ISSET (i, &srv_fds)) - { - close (i); - } - } - - fd = open ("/dev/null", O_RDWR); -#ifndef DIAG_DEBUG - dup2 (fd, 1); -#endif - dup2 (fd, 2); -#endif /* !WINDOWS */ -} - -int -uRetrieveDBDirectory (const char *dbname, char *target) -{ - int ret_val = ERR_NO_ERROR; -#ifdef WINDOWS - char temp_name[512]; -#endif - - ret_val = uReadDBtxtFile (dbname, 1, target); -#ifdef WINDOWS - if (ret_val == ERR_NO_ERROR) - { - strcpy (temp_name, target); - memset (target, '\0', strlen (target)); - if (GetLongPathName (temp_name, target, PATH_MAX) == 0) - { - strcpy (target, temp_name); - } - } -#endif - - return ret_val; -} - -int -_isRegisteredDB (char *dn) -{ - if (uReadDBtxtFile (dn, 0, NULL) == ERR_NO_ERROR) - { - return 1; - } - - return 0; -} - -#if 0 -/* dblist should have enough space */ -/* db names are delimited by '\0' for ease of using it */ -int -uReadDBnfo (char *dblist) -{ - int retval = 0; - char strbuf[512]; - char *p; - FILE *infp; - int lock_fd; - - lock_fd = - uCreateLockFile (conf_get_dbmt_file (FID_LOCK_PSVR_DBINFO, strbuf)); - if (lock_fd < 0) - { - return -1; - } - - infp = fopen (conf_get_dbmt_file (FID_PSVR_DBINFO_TEMP, strbuf), "r"); - if (infp == NULL) - { - retval = -1; - } - else - { - fgets (strbuf, sizeof (strbuf), infp); - retval = atoi (strbuf); - - p = dblist; - while (fgets (strbuf, sizeof (strbuf), infp)) - { - ut_trim (strbuf); - strcpy (p, strbuf); - p += (strlen (p) + 1); - } - fclose (infp); - } - - uRemoveLockFile (lock_fd); - - return retval; -} -#endif -void -uWriteDBnfo (void) -{ - T_SERVER_STATUS_RESULT *cmd_res; - - cmd_res = cmd_server_status (); - uWriteDBnfo2 (cmd_res); - cmd_servstat_result_free (cmd_res); -} - -void -uWriteDBnfo2 (T_SERVER_STATUS_RESULT *cmd_res) -{ - int i; - int dbcnt; - char strbuf[1024]; - int dbvect[MAX_INSTALLED_DB]; - int lock_fd; - FILE *outfp; - T_SERVER_STATUS_INFO *info; - - lock_fd = - uCreateLockFile (conf_get_dbmt_file (FID_LOCK_PSVR_DBINFO, strbuf)); - if (lock_fd < 0) - { - return; - } - - outfp = fopen (conf_get_dbmt_file (FID_PSVR_DBINFO_TEMP, strbuf), "w"); - if (outfp != NULL) - { - dbcnt = 0; - if (cmd_res == NULL) - { - fprintf (outfp, "%d\n", dbcnt); - } - else - { - info = (T_SERVER_STATUS_INFO *) cmd_res->result; - for (i = 0; i < cmd_res->num_result; i++) - { - if (_isRegisteredDB (info[i].db_name)) - { - dbvect[dbcnt] = i; - ++dbcnt; - } - } - fprintf (outfp, "%d\n", dbcnt); - info = (T_SERVER_STATUS_INFO *) cmd_res->result; - for (i = 0; i < dbcnt; i++) - { - fprintf (outfp, "%s\n", info[dbvect[i]].db_name); - } - } - fclose (outfp); - } - - uRemoveLockFile (lock_fd); -} - -int -ut_get_dblist (nvplist *res, char dbdir_flag) -{ - FILE *infile; - char *dbinfo[4]; - char strbuf[1024], file[PATH_MAX]; - char hname[128]; - struct hostent *hp; - unsigned char ip_addr[4]; - char *token = NULL; - - snprintf (file, PATH_MAX - 1, "%s/%s", sco.szArniadb_databases, - ARNIADB_DATABASE_TXT); - if ((infile = fopen (file, "rt")) == NULL) - { - return ERR_DATABASETXT_OPEN; - } - - memset (hname, 0, sizeof (hname)); - gethostname (hname, sizeof (hname)); - if ((hp = gethostbyname (hname)) == NULL) - { - fclose (infile); - return ERR_NO_ERROR; - } - memcpy (ip_addr, hp->h_addr_list[0], 4); - - nv_add_nvp (res, "open", "dblist"); - while (fgets (strbuf, sizeof (strbuf), infile)) - { - ut_trim (strbuf); - - if ((strbuf[0] == '#') || (string_tokenize (strbuf, dbinfo, 4) < 0)) - { - continue; - } - - for (token = strtok (dbinfo[2], ":"); token != NULL; - token = strtok (NULL, ":")) - { - if ((hp = gethostbyname (token)) == NULL) - { - continue; - } - - if (_op_check_is_localhost (token, hname) >= 0) - { -#ifdef JSON_SUPPORT - nv_add_nvp (res, "open", "dbs"); -#endif - nv_add_nvp (res, "dbname", dbinfo[0]); - - if (dbdir_flag) - { - nv_add_nvp (res, "dbdir", dbinfo[1]); - } -#ifdef JSON_SUPPORT - nv_add_nvp (res, "close", "dbs"); -#endif - break; - } - } - } - nv_add_nvp (res, "close", "dblist"); - fclose (infile); - return ERR_NO_ERROR; -} - -int -uCreateLockFile (char *lockfile) -{ - int outfd; -#if !defined(WINDOWS) - struct flock lock; -#endif - - outfd = open (lockfile, O_WRONLY | O_CREAT | O_TRUNC, 0666); - - if (outfd < 0) - { - return outfd; - } - -#if defined(WINDOWS) - while (_locking (outfd, _LK_NBLCK, 1) < 0) - { - Sleep (100); - } -#else - lock.l_type = F_WRLCK; - lock.l_start = 0; - lock.l_whence = SEEK_SET; - lock.l_len = 0; - - while (fcntl (outfd, F_SETLK, &lock) < 0) - { - SLEEP_MILISEC (0, 10); - } -#endif - - return outfd; -} - -void -uRemoveLockFile (int outfd) -{ -#if !defined(WINDOWS) - struct flock lock; - - lock.l_type = F_UNLCK; - lock.l_start = 0; - lock.l_whence = SEEK_SET; - lock.l_len = 0; -#endif - -#if defined(WINDOWS) - _locking (outfd, _LK_UNLCK, 1); -#else - fcntl (outfd, F_SETLK, &lock); -#endif - close (outfd); -} - -int -uRemoveDir (char *dir, int remove_file_in_dir) -{ - char path[1024]; - char command[2048]; - - if (dir == NULL) - { - return ERR_DIR_REMOVE_FAIL; - } - - strcpy (path, dir); - memset (command, '\0', sizeof (command)); - ut_trim (path); - -#if defined(WINDOWS) - unix_style_path (path); -#endif - - if (access (path, F_OK) == 0) - { - if (remove_file_in_dir == REMOVE_DIR_FORCED) - { - sprintf (command, "%s %s \"%s\"", DEL_DIR, DEL_DIR_OPT, path); - if (system (command) == -1) - { - return ERR_DIR_REMOVE_FAIL; - } - } - else - { - if (rmdir (path) == -1) - { - return ERR_DIR_REMOVE_FAIL; - } - } - } - - return ERR_NO_ERROR; -} - -#if defined(WINDOWS) -int -folder_copy (const char *src_folder, const char *dest_folder) -{ - WIN32_FIND_DATA FileData; - HANDLE hSearch; - DWORD dwAttrs; - char src_dir[PATH_MAX]; - char dest_dir[PATH_MAX]; - char search_file[PATH_MAX]; - int retval = 0; - - if (src_dir == NULL || dest_dir == NULL) - { - goto err_return; - } - - strcpy_limit (src_dir, src_folder, sizeof (src_dir)); - strcpy_limit (dest_dir, dest_folder, sizeof (dest_dir)); - ut_trim (src_dir); - ut_trim (dest_dir); - - /* create a new directory. */ - if (access (dest_dir, F_OK) != 0) - { - if (uCreateDir (dest_dir) != ERR_NO_ERROR) - { - goto err_return; - } - } - - if (access (src_dir, F_OK) != 0 || access (dest_dir, F_OK) != 0) - { - goto err_clean_return; - } - - unix_style_path (src_dir); - unix_style_path (dest_dir); - - /* Start searching for text files in the current directory. */ - snprintf (search_file, sizeof (search_file), "%s/*", src_dir); - hSearch = FindFirstFile (search_file, &FileData); - - if (hSearch == INVALID_HANDLE_VALUE) - { - goto err_clean_return; - } - - while (FindNextFile (hSearch, &FileData)) - { - char src_path[PATH_MAX]; - char dest_path[PATH_MAX]; - - snprintf (src_path, PATH_MAX - 1, "%s/%s", src_dir, FileData.cFileName); - snprintf (dest_path, PATH_MAX - 1, "%s/%s", dest_dir, - FileData.cFileName); - - if (FileData.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY) - { - /* ignore folder "." and "..". */ - if (strcmp (FileData.cFileName, ".") == 0 - || strcmp (FileData.cFileName, "..") == 0) - { - continue; - } - - folder_copy (src_path, dest_path); - continue; - } - - if (file_copy (src_path, dest_path) == 0) - { - dwAttrs = GetFileAttributes (dest_path); - if (dwAttrs == INVALID_FILE_ATTRIBUTES) - { - goto err_clean_return; - } - } - else - { - goto err_clean_return; - } - } - - /* Close the search handle. */ - FindClose (hSearch); - - return 0; - -err_clean_return: - uRemoveDir (dest_dir, REMOVE_DIR_FORCED); -err_return: - FindClose (hSearch); - return -1; -} -#else -int -folder_copy (const char *src_folder, const char *dest_folder) -{ - char src_dir[PATH_MAX]; - char dest_dir[PATH_MAX]; - struct dirent *dirp; - struct stat statbuf; - DIR *dp = NULL; - - if (src_dir == NULL || dest_dir == NULL) - { - goto err_return; - } - - strcpy_limit (src_dir, src_folder, sizeof (src_dir)); - strcpy_limit (dest_dir, dest_folder, sizeof (dest_dir)); - ut_trim (src_dir); - ut_trim (dest_dir); - - if (access (dest_dir, F_OK) != 0) - { - if (uCreateDir (dest_dir) != ERR_NO_ERROR) - { - goto err_return; - } - } - - if (access (src_dir, F_OK) != 0 || access (dest_dir, F_OK) != 0) - { - goto err_clean_return; - } - - stat (src_dir, &statbuf); - chmod (dest_dir, statbuf.st_mode); - - /* copy all the files that in src_path to dest_path. */ - dp = opendir (src_dir); - if (dp == NULL) - { - goto err_clean_return; - } - - while ((dirp = readdir (dp)) != NULL) - { - char src_path[PATH_MAX]; - char dest_path[PATH_MAX]; - - snprintf (src_path, sizeof (src_path) - 1, "%s/%s", src_dir, - dirp->d_name); - snprintf (dest_path, sizeof (dest_path) - 1, "%s/%s", dest_dir, - dirp->d_name); - - stat (src_path, &statbuf); - - if (S_ISDIR (statbuf.st_mode)) - { - if (uStringEqual (dirp->d_name, ".") - || uStringEqual (dirp->d_name, "..")) - { - continue; - } - - if (folder_copy (src_path, dest_path) < 0) - { - goto err_clean_return; - } - } - else - { - if (file_copy (src_path, dest_path) < 0) - { - goto err_clean_return; - } - } - } - - closedir (dp); - - return 0; - -err_clean_return: - uRemoveDir (dest_dir, REMOVE_DIR_FORCED); -err_return: - if (dp != NULL) - { - closedir (dp); - } - return -1; -} -#endif - -int -uCreateDir (char *new_dir) -{ - char *p, path[1024]; - - if (new_dir == NULL) - { - return ERR_DIR_CREATE_FAIL; - } - memset (path, 0, 1024); - strncpy (path, new_dir, 1023); - ut_trim (path); - -#if defined(WINDOWS) - unix_style_path (path); -#endif - -#if defined(WINDOWS) - if (path[0] == '/') - { - p = path + 1; - } - else if (strlen (path) > 3 && path[2] == '/') - { - p = path + 3; - } - else - { - return ERR_DIR_CREATE_FAIL; - } -#else - if (path[0] != '/') - { - return ERR_DIR_CREATE_FAIL; - } - p = path + 1; -#endif - - while (p != NULL) - { - p = strchr (p, '/'); - if (p != NULL) - { - *p = '\0'; - } - if (access (path, F_OK) < 0) - { - if (mkdir (path, 0700) < 0) - { - return ERR_DIR_CREATE_FAIL; - } - } - if (p != NULL) - { - *p = '/'; - p++; - } - } - return ERR_NO_ERROR; -} - -void -close_all_fds (int init_fd) -{ - int i; - - for (i = init_fd; i < 1024; i++) - { - close (i); - } -} - -char * -ut_trim (char *str) -{ - char *p; - char *s; - - if (str == NULL) - { - return (str); - } - - for (s = str; - *s != '\0' && (*s == ' ' || *s == '\t' || *s == '\n' || *s == '\r'); - s++) - ; - if (*s == '\0') - { - *str = '\0'; - return (str); - } - - /* *s must be a non-white char */ - for (p = s; *p != '\0'; p++) - ; - for (p--; *p == ' ' || *p == '\t' || *p == '\n' || *p == '\r'; p--) - ; - *++p = '\0'; - - if (s != str) - { - memmove (str, s, strlen (s) + 1); - } - - return (str); -} - -#if defined(WINDOWS) -int -ut_disk_free_space (char *path) -{ - char buf[1024]; - DWORD a, b, c, d; - - strcpy (buf, path); - ut_trim (buf); - if (buf[1] == ':') - { - strcpy (buf + 2, "/"); - } - else - { - strcpy (buf, "c:/"); - } - - if (GetDiskFreeSpace (buf, &a, &b, &c, &d) == 0) - { - return 0; - } - - return ((c >> 10) * ((b * a) >> 10)); -} -#else -int -ut_disk_free_space (char *path) -{ - struct statvfs sv; - - if (statvfs (path, &sv) < 0) - { - return 0; - } - - return ((((sv.f_bavail) >> 10) * sv.f_frsize) >> 10); -} -#endif - -char * -ip2str (unsigned char *ip, char *ip_str) -{ - sprintf (ip_str, "%d.%d.%d.%d", (unsigned char) ip[0], - (unsigned char) ip[1], - (unsigned char) ip[2], (unsigned char) ip[3]); - return ip_str; -} - -int -string_tokenize_accept_laststring_space (char *str, char *tok[], int num_tok) -{ - int i; - char *p; - - tok[0] = str; - for (i = 1; i < num_tok; i++) - { - tok[i] = strpbrk (tok[i - 1], " \t"); - if (tok[i] == NULL) - { - return -1; - } - * (tok[i]) = '\0'; - p = (tok[i]) + 1; - for (; *p && (*p == ' ' || *p == '\t'); p++) - ; - if (*p == '\0') - { - return -1; - } - tok[i] = p; - } - - return 0; -} - -int -string_tokenize (char *str, char *tok[], int num_tok) -{ - int i; - char *p; - - tok[0] = str; - for (i = 1; i < num_tok; i++) - { - tok[i] = strpbrk (tok[i - 1], " \t"); - if (tok[i] == NULL) - { - return -1; - } - * (tok[i]) = '\0'; - p = (tok[i]) + 1; - for (; *p && (*p == ' ' || *p == '\t'); p++) - ; - if (*p == '\0') - { - return -1; - } - tok[i] = p; - } - p = strpbrk (tok[num_tok - 1], " \t"); - if (p) - { - *p = '\0'; - } - - return 0; -} - -int -string_tokenize2 (char *str, char *tok[], int num_tok, int c) -{ - int i; - char *p; - - for (i = 0; i < num_tok; i++) - { - tok[i] = NULL; - } - - if (str == NULL) - { - return -1; - } - - tok[0] = str; - for (i = 1; i < num_tok; i++) - { - tok[i] = strchr (tok[i - 1], c); - if (tok[i] == NULL) - { - return -1; - } - * (tok[i]) = '\0'; - (tok[i])++; - } - p = strchr (tok[num_tok - 1], c); - if (p) - { - *p = '\0'; - } - - return 0; -} - -int -read_from_socket (SOCKET sock_fd, char *buf, int size) -{ - int read_len; - fd_set read_mask; - int nfound; - int maxfd; - - FD_ZERO (&read_mask); - FD_SET (sock_fd, (fd_set *) & read_mask); - maxfd = (int) sock_fd + 1; -again: - nfound = select (maxfd, &read_mask, (fd_set *) 0, (fd_set *) 0, NULL); - if (nfound < 0) - { - goto again; /* interrupted by a signal */ - } - - if (FD_ISSET (sock_fd, (fd_set *) & read_mask)) - { - read_len = recv (sock_fd, buf, size, 0); - } - else - { - return -1; - } - - return read_len; -} - -int -write_to_socket (SOCKET sock_fd, const char *buf, int size) -{ - int write_len; - fd_set write_mask; - int nfound; - int maxfd; - - if (IS_INVALID_SOCKET (sock_fd)) - { - return -1; - } - - FD_ZERO (&write_mask); - FD_SET (sock_fd, (fd_set *) & write_mask); - maxfd = (int) sock_fd + 1; -again: - nfound = select (maxfd, (fd_set *) 0, &write_mask, (fd_set *) 0, NULL); - if (nfound < 0) - { - goto again; /* interrupted by a signal */ - } - - if (FD_ISSET (sock_fd, (fd_set *) & write_mask)) - { - write_len = send (sock_fd, buf, size, 0); - } - else - { - return -1; - } - - return write_len; -} - -#if defined(WINDOWS) -int -kill (int pid, int signo) -{ - HANDLE phandle; - - phandle = OpenProcess (PROCESS_TERMINATE, FALSE, pid); - if (phandle == NULL) - { - int error = GetLastError (); - if (error == ERROR_ACCESS_DENIED) - { - errno = EPERM; - } - else - { - errno = ESRCH; - } - return -1; - } - - if (signo == SIGTERM) - { - TerminateProcess (phandle, 0); - } - - CloseHandle (phandle); - return 0; -} -#endif - -#if defined(WINDOWS) -void -unix_style_path (char *path) -{ - char *p; - for (p = path; *p; p++) - { - if (*p == '\\') - { - *p = '/'; - } - } -} - -char * -nt_style_path (char *path, char *new_path_buf) -{ - char *p; - char *q; - char tmp_path_buf[1024]; - - if (path == new_path_buf) - { - strcpy (tmp_path_buf, path); - q = tmp_path_buf; - } - else - { - q = new_path_buf; - } - if (strlen (path) < 2 || path[1] != ':') - { - *q++ = _getdrive () + 'A' - 1; - *q++ = ':'; - *q++ = '\\'; - } - - for (p = path; *p; p++, q++) - { - if (*p == '/') - { - *q = '\\'; - } - else - { - *q = *p; - } - } - *q = '\0'; - for (q--; q != new_path_buf; q--) - { - if (*q == '\\') - { - *q = '\0'; - } - else - { - break; - } - } - if (*q == ':') - { - q++; - *q++ = '\\'; - *q++ = '\\'; - *q = '\0'; - } - if (path == new_path_buf) - { - strcpy (new_path_buf, tmp_path_buf); - } - return new_path_buf; -} -#endif - -int -make_version_info (const char *cli_ver, int *major_ver, int *minor_ver) -{ - const char *p; - if (cli_ver == NULL) - { - return 0; - } - - p = cli_ver; - *major_ver = atoi (p); - p = strchr (p, '.'); - if (p != NULL) - { - *minor_ver = atoi (p + 1); - } - else - { - *minor_ver = 0; - } - - return 1; -} - -int -file_copy (char *src_file, char *dest_file) -{ - char strbuf[1024]; - int src_fd, dest_fd; - size_t read_size, write_size; - int mode = 0644; - -#if !defined(WINDOWS) - struct stat statbuf; - - if (stat (src_file, &statbuf) == 0) - { - mode = statbuf.st_mode; - } -#endif - - if ((src_fd = open (src_file, O_RDONLY)) == -1) - { - return -1; - } - - if ((dest_fd = open (dest_file, O_WRONLY | O_CREAT | O_TRUNC, mode)) == -1) - { - close (src_fd); - return -1; - } - -#if defined(WINDOWS) - if (setmode (src_fd, O_BINARY) == -1 || setmode (dest_fd, O_BINARY) == -1) - { - close (src_fd); - close (dest_fd); - return -1; - } -#endif - - while ((read_size = read (src_fd, strbuf, sizeof (strbuf))) > 0) - { - if (read_size > sizeof (strbuf) - || (write_size = - write (dest_fd, strbuf, (unsigned int) read_size)) < read_size) - { - close (src_fd); - close (dest_fd); - unlink (dest_file); - return -1; - } - } - - close (src_fd); - close (dest_fd); - - return 0; -} - -int -move_file (char *src_file, char *dest_file) -{ - if (file_copy (src_file, dest_file) < 0) - { - return -1; - } - else - { - unlink (src_file); - } - - return 0; -} - -#if defined(WINDOWS) -void -remove_end_of_dir_ch (char *path) -{ - if (path && path[strlen (path) - 1] == '\\') - { - path[strlen (path) - 1] = '\0'; - } -} -#endif - -int -is_cmserver_process (int pid, const char *module_name) -{ -#if defined(WINDOWS) - HANDLE hModuleSnap = NULL; - MODULEENTRY32 me32 = { 0 }; - - hModuleSnap = CreateToolhelp32Snapshot (TH32CS_SNAPMODULE, pid); - if (hModuleSnap == (HANDLE) - 1) - { - return -1; - } - - me32.dwSize = sizeof (MODULEENTRY32); - - if (Module32First (hModuleSnap, &me32)) - { - do - { - if (strcasecmp (me32.szModule, module_name) == 0) - { - CloseHandle (hModuleSnap); - return 1; - } - } - while (Module32Next (hModuleSnap, &me32)); - } - CloseHandle (hModuleSnap); - return 0; -#elif defined(LINUX) - FILE *fp = NULL; - char proc_path[PATH_MAX]; - char cmd_line[LINE_MAX]; - char *cmd_name = NULL; - - snprintf (proc_path, sizeof (proc_path), "/proc/%d/cmdline", pid); - - if (access (proc_path, F_OK) != 0) - { - return 0; - } - - if ((fp = fopen (proc_path, "r")) == NULL) - { - return 0; - } - - if (fread (cmd_line, sizeof (char), sizeof (cmd_line) - 1, fp) <= 0) - { - fclose (fp); - return 0; - } - - // Only the module_name should be compared - cmd_name = strrchr (cmd_line, '/'); - if (cmd_name == NULL) - { - cmd_name = cmd_line; - } - else - { - cmd_name += 1; - } - - if (!uStringEqual (cmd_name, module_name)) - { - fclose (fp); - return 0; - } - - fclose (fp); - return 1; -#elif defined(AIX) - const char *argv[10]; - int argc = 0; - int return_value = 0; - char cmjs_pid[10]; - char result_file[1024]; - char buf[1024], cur_pid[10], prog_name[32]; - FILE *fRes; - - /*Init var */ - cmjs_pid[0] = '\0'; - result_file[0] = '\0'; - buf[0] = '\0'; - cur_pid[0] = '\0'; - prog_name[0] = '\0'; - - snprintf (cmjs_pid, sizeof (cmjs_pid) - 1, "%d", pid); - snprintf (result_file, sizeof (result_file) - 1, "%s/DBMT_js.%d", - sco.dbmt_tmp_dir, (int) getpid ()); - argv[argc++] = "/usr/bin/ps"; - argv[argc++] = "-e"; - argv[argc] = NULL; - - if (run_child (argv, 1, NULL, result_file, NULL, NULL) < 0) - { - /* ps */ - return -1; - } - - fRes = fopen (result_file, "r"); - if (fRes) - { - while (fgets (buf, 1024, fRes)) - { - if (sscanf (buf, "%9s %*s %*s %31s", cur_pid, prog_name) != 2) - { - continue; - } - - if (strcmp (cur_pid, cmjs_pid) == 0 - && strcmp (prog_name, module_name) == 0) - { - return_value = 1; - break; - } - } - - fclose (fRes); - } - - unlink (result_file); - return return_value; -#endif -} - -int -make_default_env (void) -{ - int retval = ERR_NO_ERROR; - char strbuf[512]; - FILE *fd; - - /* create log/manager directory */ -#if !defined (DO_NOT_USE_ARNIADBENV) - sprintf (strbuf, "%s/%s", sco.szArniadb, DBMT_LOG_DIR); -#else - sprintf (strbuf, "%s", DBMT_LOG_DIR); -#endif - if ((retval = uCreateDir (strbuf)) != ERR_NO_ERROR) - { - return retval; - } - - /* create var/manager direcory */ -#if !defined (DO_NOT_USE_ARNIADBENV) - sprintf (strbuf, "%s/%s", sco.szArniadb, DBMT_PID_DIR); -#else - sprintf (strbuf, "%s", DBMT_PID_DIR); -#endif - if ((retval = uCreateDir (strbuf)) != ERR_NO_ERROR) - { - return retval; - } - - /* create databases directory */ - sprintf (strbuf, "%s", sco.szArniadb_databases); - if ((retval = uCreateDir (strbuf)) != ERR_NO_ERROR) - { - return retval; - } - - /* if databases.txt file doesn't exist, create 0 byte file. */ - sprintf (strbuf, "%s/%s", sco.szArniadb_databases, ARNIADB_DATABASE_TXT); - if (access (strbuf, F_OK) < 0) - { - if ((fd = fopen (strbuf, "a")) == NULL) - { - return ERR_FILE_CREATE_FAIL; - } - fclose (fd); - } - return retval; -} - - -/* - * dbid, dbpasswd is filled by this function - * caller must provide space for dbid, dbpasswd - */ -int -_ut_get_dbaccess (nvplist *req, char *dbid, char *dbpasswd) -{ - int retval; - char *ip, *port, *dbname; - char _dbmt_error[1024]; - T_DBMT_CON_DBINFO con_dbinfo; - - dbid[0] = dbpasswd[0] = '\0'; - - ip = nv_get_val (req, "_IP"); - port = nv_get_val (req, "_PORT"); - dbname = nv_get_val (req, "dbname"); - - /* read conlist */ - memset (&con_dbinfo, 0, sizeof (T_DBMT_CON_DBINFO)); - if ((retval = - dbmt_con_read_dbinfo (&con_dbinfo, ip, port, dbname, - _dbmt_error)) <= 0) - { - return 0; - } - - /* extract db user info */ - strcpy (dbid, con_dbinfo.uid); - uDecrypt (PASSWD_LENGTH, con_dbinfo.passwd, dbpasswd); - - return 1; -} - - -/* Generate status, note and write to log */ -void -uGenerateStatus (nvplist *req, nvplist *res, int retval, - const char *_dbmt_error) -{ - char strbuf[1024]; - - if ((retval == -1) || (retval == 0)) - { - return; - } - - if ((retval == 1) || (retval == ERR_NO_ERROR)) - { - nv_update_val (res, "status", "success"); - return; - } - - if (retval == ERR_FILE_COMPRESS) - { - nv_update_val (res, "status", "success"); - nv_update_val (res, "note", - "Can't compress the file. Download original file"); - return; - } - - nv_update_val (res, "status", "failure"); - switch (retval) - { - case ERR_GENERAL_ERROR: - sprintf (strbuf, "Unknown general error"); - break; - case ERR_UNDEFINED_TASK: - sprintf (strbuf, "Undefined request - %s", _dbmt_error); - break; - case ERR_DBDIRNAME_NULL: - sprintf (strbuf, "Can not find the directory database(%s) is located", - _dbmt_error); - break; - case ERR_GET_FILE: - sprintf (strbuf, "Can't get requested files"); - break; - case ERR_REQUEST_FORMAT: - sprintf (strbuf, "Invalid request format"); - break; - case ERR_DATABASETXT_OPEN: - sprintf (strbuf, "'%s' open error", ARNIADB_DATABASE_TXT); - break; - case ERR_USER_CAPABILITY: - sprintf (strbuf, "Failed to get user profile for '%s'", _dbmt_error); - break; - case ERR_FILE_INTEGRITY: - sprintf (strbuf, "Password file(%s) integrity failure", _dbmt_error); - break; - case ERR_SYSTEM_CALL: - sprintf (strbuf, "Command returned error : %s", _dbmt_error); - break; - case ERR_PASSWORD_FILE: - sprintf (strbuf, "Password file(%s) open error", _dbmt_error); - break; - case ERR_PARAM_MISSING: - sprintf (strbuf, "Parameter(%s) missing in the request", _dbmt_error); - break; - case ERR_DIR_CREATE_FAIL: - sprintf (strbuf, "Directory(%s) creation failed", _dbmt_error); - break; - case ERR_FILE_OPEN_FAIL: - sprintf (strbuf, "File(%s) open error", _dbmt_error); - break; - case ERR_STANDALONE_MODE: - sprintf (strbuf, "Database(%s) is running in standalone mode", - _dbmt_error); - break; - case ERR_DB_ACTIVE: - sprintf (strbuf, "Database(%s) is active state.", _dbmt_error); - break; - case ERR_DB_INACTIVE: - sprintf (strbuf, "Database(%s) is not active state", _dbmt_error); - break; - case ERR_DB_NONEXISTANT: - sprintf (strbuf, "Database(%s) does not exist", _dbmt_error); - break; - case ERR_DBMTUSER_EXIST: - sprintf (strbuf, "ARNIADB Manager user(%s) already exist", _dbmt_error); - break; - case ERR_DIROPENFAIL: - sprintf (strbuf, "Failed to read directory(%s)", _dbmt_error); - break; - case ERR_PERMISSION: - sprintf (strbuf, "No permission for %s", _dbmt_error); - break; - case ERR_INVALID_TOKEN: - sprintf (strbuf, - "Request is rejected due to invalid token. Please reconnect."); - break; - case ERR_SYSTEM_CALL_CON_DUMP: - sprintf (strbuf, "%s", _dbmt_error); - break; - case ERR_STAT: - sprintf (strbuf, "Failed to get the file information"); - break; - case ERR_OPENDIR: - sprintf (strbuf, "Failed to open the directory"); - break; - case ERR_UNICASCONF_OPEN: - sprintf (strbuf, "Failed to open unicas.conf"); - break; - case ERR_UNICASCONF_PARAM_MISSING: - sprintf (strbuf, "Specified parameter does not exist in unicas.conf"); - break; - case ERR_DBLOGIN_FAIL: - sprintf (strbuf, "Failed to log in to database using id:%s", - _dbmt_error); - break; - case ERR_DBRESTART_FAIL: - sprintf (strbuf, "Failed to restart database(%s)", _dbmt_error); - break; - case ERR_DBUSER_NOTFOUND: - sprintf (strbuf, "Database user (%s) not found", _dbmt_error); - break; - case ERR_DBPASSWD_CLEAR: - sprintf (strbuf, "Failed to clear existing password - %s", _dbmt_error); - break; - case ERR_DBPASSWD_SET: - sprintf (strbuf, "Failed to set new password - %s", _dbmt_error); - break; - case ERR_MEM_ALLOC: - sprintf (strbuf, "Memory allocation error."); - break; - case ERR_TMPFILE_OPEN_FAIL: - sprintf (strbuf, "Temporal file open error."); - break; - case ERR_WITH_MSG: - strcpy_limit (strbuf, _dbmt_error, sizeof (strbuf)); - break; - case ERR_UPA_SYSTEM: - sprintf (strbuf, "Authentication System Error."); - break; - case ERR_TEMPLATE_ALREADY_EXIST: - sprintf (strbuf, "Template (%s) already exist.", _dbmt_error); - break; - case ERR_WARNING: - strcpy_limit (strbuf, _dbmt_error, sizeof (strbuf)); - nv_update_val (res, "status", "warning"); - break; - default: - sprintf (strbuf, "error"); - break; - } - nv_update_val (res, "note", strbuf); - ut_error_log (req, strbuf); -} - - -/* validate token and insert id */ -int -ut_validate_token (nvplist *req) -{ - T_USER_TOKEN_INFO *token_info; - - time_t active_time = 0; - time_t now_time = time (NULL); - - //int retval; - - char *ip, *port, *id, *tok[3]; - char *token, token_content[TOKEN_LENGTH + 1]; - - if (!strcmp (nv_get_val (req, "task"), "login") || - !strcmp (nv_get_val (req, "task"), "getcmsenv")) - { - ut_access_log (req, "task = login or getcmsenv."); - return 1; - } - - if ((token = nv_get_val (req, "token")) == NULL) - { - return 0; - } - ut_access_log (req, "task != login or getcmsenv."); - - uDecrypt (TOKEN_LENGTH, token, token_content); - - if (string_tokenize2 (token_content, tok, 3, ':') < 0) - { - return 0; - } - - ip = tok[0]; - port = tok[1]; - id = tok[2]; - - ut_access_log (req, id); - - token_info = dbmt_user_search_token_info (id); - if (token_info == NULL) - { - ut_access_log (req, "can't find registered token."); - return 0; - } - - if (strcmp (token_info->token, token)) - { - ut_access_log (req, "tokens aren't equal!"); - return 0; - } - - ut_get_token_active_time (&active_time); - - if (now_time - token_info->login_time > active_time) - { - return 0; - } - - token_info->login_time = now_time; - - nv_add_nvp (req, "_IP", ip); - nv_add_nvp (req, "_PORT", port); - nv_add_nvp (req, "_ID", id); - - - /* check if ip is an existing ip */ - //retval = dbmt_con_search (ip, port, cli_ver); - - return 1; -} - -/* - * client ip : client port : dbmt id : pserver pid - * 15 5 8 5 = 33 + 4 = 37 - * 40 - 37 = 8. - * Thus, 3 bytes for checksum - */ -char * -ut_token_generate (char *client_ip, char *client_port, char *dbmt_id, - int proc_id, time_t login_time) -{ - char sbuf[TOKEN_LENGTH + 1]; - char token_string[TOKEN_ENC_LENGTH]; - size_t i, len; - - if ((client_ip == NULL) || (client_port == NULL) || (dbmt_id == NULL)) - { - return NULL; - } - memset (sbuf, 0, TOKEN_LENGTH + 1); - snprintf (sbuf, TOKEN_LENGTH, "%s:%s:%s:%d:%lu", client_ip, client_port, - dbmt_id, proc_id, login_time); - len = strlen (sbuf); - /* insert padding to checksum part */ - for (i = len; i < TOKEN_LENGTH; ++i) - { - sbuf[i] = '*'; - } - sbuf[i] = '\0'; - - uEncrypt (TOKEN_LENGTH, sbuf, token_string); - - return strdup (token_string); -} - -void -_accept_connection (nvplist *cli_request, nvplist *cli_response) -{ - char *pstrbuf; - char *client_ip, *client_port, *client_id, *client_ver; -#ifdef WINDOWS - HANDLE proc_id = (HANDLE) getpid (); -#else - pid_t proc_id = (pid_t) getpid (); -#endif - - time_t login_time = time (NULL); - - client_ip = nv_get_val (cli_request, "_CLIENTIP"); - client_port = nv_get_val (cli_request, "_CLIENTPORT"); - client_id = nv_get_val (cli_request, "id"); - client_ver = nv_get_val (cli_request, "clientver"); - - /* generate token and record new connection to file */ - pstrbuf = - ut_token_generate (client_ip, client_port, client_id, getpid (), - login_time); - nv_add_nvp (cli_response, "token", pstrbuf); - - dbmt_con_add (client_ip, client_port, client_ver, client_id); - - ut_access_log (cli_request, "before add token into token list."); - dbmt_user_new_token_info (client_id, client_ip, client_port, pstrbuf, - proc_id, login_time); - - free (pstrbuf); - return; -} - - -#if defined (WINDOWS) -int -gettimeofday (struct timeval *tp, void *tzp) -{ - struct _timeb tm; - _ftime (&tm); - tp->tv_sec = (long) tm.time; - tp->tv_usec = tm.millitm * 1000; - return 0; -} -#endif - -void -_ut_timeval_diff (struct timeval *start, struct timeval *end, int *res_msec) -{ - int sec, msec; - - sec = end->tv_sec - start->tv_sec; - msec = (end->tv_usec / 1000) - (start->tv_usec / 1000); - *res_msec = sec * 1000 + msec; -} - - -#if defined(WINDOWS) -int -ut_run_child (const char *bin_path, const char *const argv[], int wait_flag, - const char *stdin_file, const char *stdout_file, - const char *stderr_file, int *exit_status) -{ - int new_pid; - STARTUPINFO start_info; - PROCESS_INFORMATION proc_info; - BOOL res; - int i, cmd_arg_len; - char cmd_arg[1024]; - BOOL inherit_flag = FALSE; - HANDLE hStdIn = INVALID_HANDLE_VALUE; - HANDLE hStdOut = INVALID_HANDLE_VALUE; - HANDLE hStdErr = INVALID_HANDLE_VALUE; - - if (exit_status != NULL) - { - *exit_status = 0; - } - - for (i = 0, cmd_arg_len = 0; argv[i]; i++) - { - cmd_arg_len += sprintf (cmd_arg + cmd_arg_len, "\"%s\" ", argv[i]); - } - - GetStartupInfo (&start_info); - start_info.wShowWindow = SW_HIDE; - - if (stdin_file) - { - hStdIn = - CreateFile (stdin_file, GENERIC_READ, FILE_SHARE_READ, NULL, - OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); - if (hStdIn != INVALID_HANDLE_VALUE) - { - SetHandleInformation (hStdIn, HANDLE_FLAG_INHERIT, - HANDLE_FLAG_INHERIT); - start_info.dwFlags = STARTF_USESTDHANDLES; - start_info.hStdInput = hStdIn; - inherit_flag = TRUE; - } - } - if (stdout_file) - { - hStdOut = - CreateFile (stdout_file, GENERIC_WRITE, FILE_SHARE_READ, NULL, - CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); - if (hStdOut != INVALID_HANDLE_VALUE) - { - SetHandleInformation (hStdOut, HANDLE_FLAG_INHERIT, - HANDLE_FLAG_INHERIT); - start_info.dwFlags = STARTF_USESTDHANDLES; - start_info.hStdOutput = hStdOut; - inherit_flag = TRUE; - } - } - if (stderr_file) - { - hStdErr = - CreateFile (stderr_file, GENERIC_WRITE, - FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, - NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); - if (hStdErr != INVALID_HANDLE_VALUE) - { - SetHandleInformation (hStdErr, HANDLE_FLAG_INHERIT, - HANDLE_FLAG_INHERIT); - start_info.dwFlags = STARTF_USESTDHANDLES; - start_info.hStdError = hStdErr; - inherit_flag = TRUE; - } - } - - res = CreateProcess (bin_path, cmd_arg, NULL, NULL, inherit_flag, - CREATE_NO_WINDOW, NULL, NULL, &start_info, &proc_info); - - if (hStdIn != INVALID_HANDLE_VALUE) - { - CloseHandle (hStdIn); - } - if (hStdOut != INVALID_HANDLE_VALUE) - { - CloseHandle (hStdOut); - } - if (hStdErr != INVALID_HANDLE_VALUE) - { - CloseHandle (hStdErr); - } - - if (res == FALSE) - { - return -1; - } - - new_pid = proc_info.dwProcessId; - - if (wait_flag) - { - DWORD status = 0; - //WaitForSingleObject (proc_info.hProcess, INFINITE); - //GetExitCodeProcess (proc_info.hProcess, &status); - if (exit_status != NULL) - { - *exit_status = status; - } - CloseHandle (proc_info.hProcess); - CloseHandle (proc_info.hThread); - return 0; - } - else - { - CloseHandle (proc_info.hProcess); - CloseHandle (proc_info.hThread); - return new_pid; - } -} -#else -int -ut_run_child (const char *bin_path, const char *const argv[], int wait_flag, - const char *stdin_file, const char *stdout_file, - const char *stderr_file, int *exit_status) -{ - int pid; - - if (exit_status != NULL) - { - *exit_status = 0; - } - - if (wait_flag) - { - signal (SIGCHLD, SIG_DFL); - } - else - { - signal (SIGCHLD, SIG_IGN); - } - pid = fork (); - if (pid == 0) - { - FILE *fp; - - close_all_fds (3); - - if (stdin_file != NULL) - { - fp = fopen (stdin_file, "r"); - if (fp != NULL) - { - dup2 (fileno (fp), 0); - fclose (fp); - } - } - if (stdout_file != NULL) - { - unlink (stdout_file); - fp = fopen (stdout_file, "w"); - if (fp != NULL) - { - dup2 (fileno (fp), 1); - fclose (fp); - } - } - if (stderr_file != NULL) - { - unlink (stderr_file); - fp = fopen (stderr_file, "w"); - if (fp != NULL) - { - dup2 (fileno (fp), 2); - fclose (fp); - } - } - - execv (bin_path, (char *const *) argv); - exit (0); - } - - if (pid < 0) - { - return -1; - } - - if (wait_flag) - { - int status = 0; - waitpid (pid, &status, 0); - if (exit_status != NULL) - { - *exit_status = status; - } - return 0; - } - else - { - return pid; - } -} -#endif - -typedef struct _dir_file_node -{ - char *file_name; - struct _dir_file_node *next; - struct _dir_file_node *prev; -} dir_file_node; - -typedef struct _dir_file_list_head -{ - unsigned int file_num; - dir_file_node *head; -} dir_file_list_head; - -static int -add_node_to_list (dir_file_list_head *file_head, const char *file_name) -{ - dir_file_node *file_node; - if (file_head == NULL || file_name == NULL) - { - return -1; - } - - file_node = (dir_file_node *) malloc (sizeof (dir_file_node)); - if (file_node == NULL) - { - return -1; - } - - file_node->file_name = strdup (file_name); - file_node->next = file_head->head; - if (file_head->head) - { - file_head->head->prev = file_node; - } - file_node->prev = NULL; - file_head->head = file_node; - file_head->file_num++; - return 0; -} - -static void -remove_node_from_list (dir_file_list_head *file_head, - dir_file_node *file_node) -{ - if (file_head == NULL || file_node == NULL) - { - return; - } - - if (file_node->prev) - { - file_node->prev->next = file_node->next; - } - else if (file_node->next) - { - file_node->next->prev = NULL; - file_head->head = file_node->next; - } - if (file_node->next) - { - file_node->next->prev = file_node->prev; - } - else if (file_node->prev) - { - file_node->prev->next = NULL; - } - - file_head->file_num--; - return; -} - -static void -free_file_list (dir_file_list_head *file_head) -{ - dir_file_node *pnode, *pnext; - if (file_head == NULL) - { - return; - } - pnode = file_head->head; - while (pnode) - { - pnext = pnode->next; - - if (pnode->file_name) - { - free (pnode->file_name); - } - free (pnode); - pnode = pnext; - } - file_head->head = NULL; - file_head->file_num = 0; - return; -} - - -#if defined(WINDOWS) -static int -scan_dir (const char *scan_path, const char *pattern, - dir_file_list_head *file_list) -{ - WIN32_FIND_DATA FileData; - HANDLE hSearch = NULL; - BOOL finished = FALSE; - char dir_path[256]; - - if (file_list == NULL) - { - return -1; - } - - snprintf (dir_path, 256, "%s/*.*", scan_path); - hSearch = FindFirstFile (dir_path, &FileData); - if (hSearch == INVALID_HANDLE_VALUE) - { - return -1; - } - - while (!finished) - { - if (strstr (FileData.cFileName, pattern)) - { - add_node_to_list (file_list, FileData.cFileName); - } - finished = !FindNextFile (hSearch, &FileData); - } - FindClose (hSearch); - return 0; -} -#else -static int -scan_dir (const char *scan_path, const char *pattern, - dir_file_list_head *file_list) -{ - DIR *dp; - struct dirent *ep; - dp = opendir (scan_path); - if (dp == NULL) - { - return -1; - } - while ((ep = readdir (dp)) != NULL) - { - if (strstr (ep->d_name, pattern)) - { - add_node_to_list (file_list, ep->d_name); - } - } - closedir (dp); - - return 0; -} -#endif - -int -remove_extra_subdir (const char *dirpath, const char *pattern, - unsigned int save_num) -{ - dir_file_list_head file_list = { 0, NULL }; - dir_file_node *pnode, *pnext; - char file_path[260]; - if (scan_dir (dirpath, pattern, &file_list) < 0) - { - return -1; - } - - while (file_list.file_num > save_num) - { - pnode = file_list.head; - pnext = pnode; - while (pnext) - { - if (strcmp (pnode->file_name, pnext->file_name) > 0) - { - pnode = pnext; - } - pnext = pnext->next; - } - snprintf (file_path, 260, "%s/%s", dirpath, pnode->file_name); - uRemoveDir (file_path, REMOVE_DIR_FORCED); - remove_node_from_list (&file_list, pnode); - } - - free_file_list (&file_list); - return 0; -} - -int -IsValidUserName (const char *pUserName) -{ - size_t len = 0; - size_t idx = 0; - if (!pUserName || !*pUserName) - { - return -1; - } - - len = strlen (pUserName); - if (len < 4 || len > 32) - { - return -1; - } - - // If the first char isn't 'a'-'z' or 'A'-'Z', then return error - if (! ((pUserName[0] >= 'a' && pUserName[0] <= 'z') - || (pUserName[0] >= 'A' && pUserName[0] <= 'Z'))) - { - return -1; - } - - // If the char isn't 'a'-'z', 'A'-'Z', '0'-'9' or '_', then return error - for (idx = 1; idx < len; idx++) - { - if (! ((pUserName[idx] >= 'a' && pUserName[idx] <= 'z') - || (pUserName[idx] >= 'A' && pUserName[idx] <= 'Z') - || (pUserName[idx] >= '0' && pUserName[idx] <= '9') - || (pUserName[idx] == '_'))) - { - return -1; - } - } - return 0; -} - -int -ut_get_token_active_time (time_t *active_time) -{ - char file_name[PATH_MAX]; - char line_buf[LINE_MAX]; - FILE *in_file = NULL; - char *pos = NULL; - - file_name[0] = '\0'; - line_buf[0] = '\0'; - - conf_get_dbmt_file (FID_DBMT_CONF, file_name); - in_file = fopen (file_name, "r"); - - if (in_file == NULL) - { - return 1; - } - - *active_time = 0; - while (fgets (line_buf, LINE_MAX, in_file) != NULL) - { - if (line_buf[0] == '#') - { - continue; - } - - if ((pos = strstr (line_buf, "=")) != NULL && - strstr (line_buf, "token_active_time") != NULL) - { - char tmp_str[LINE_MAX]; - strcpy (tmp_str, pos + 1); - - *active_time = atoi (tmp_str); - - break; - } - } - fclose (in_file); - - if (*active_time == 0) - { - *active_time = 7200; - } - - return 0; -} - -int -ut_validate_auth (nvplist *req) -{ - T_USER_AUTH auth_task = 0; - T_USER_AUTH auth_user = 0; - T_DBMT_USER dbmt_user; - T_DBMT_USER_AUTHINFO *auth_info = NULL; - char *task = NULL; - char *user_id = NULL; - char dbmt_error[DBMT_ERROR_MSG_SIZE]; - int num_authinfo = 0; - int i = 0; // loop var - - dbmt_error[0] = '\0'; - - task = nv_get_val (req, "task"); - user_id = nv_get_val (req, "_ID"); - - if (task == NULL) - { - return 0; - } - - if (!strcmp (task, "login") || !strcmp (task, "getcmsenv")) - { - return 1; - } - - if (user_id == NULL) - { - return 0; - } - - if (ut_get_task_info (task, NULL, NULL, &auth_task) == 0) - { - // As the task doesn't exist, this failure will be checked in next step. - return 1; - } - - if (dbmt_user_read (&dbmt_user, dbmt_error) != ERR_NO_ERROR) - { - return 0; - } - - for (i = 0; i < dbmt_user.num_dbmt_user; ++i) - { - if (!strcmp (dbmt_user.user_info[i].user_name, user_id)) - { - auth_info = dbmt_user.user_info[i].authinfo; - num_authinfo = dbmt_user.user_info[i].num_authinfo; - break; - } - } - - for (i = 0; i < num_authinfo; ++i) - { - if (!strcmp (auth_info[i].domain, "user_auth")) - { - auth_user = atoi (auth_info[i].auth); - break; - } - } - - // assign default authority to old users. - if (auth_user == 0) - { - if (!strcmp (user_id, "admin")) - { - auth_user = AU_ADMIN; - } - else - { - auth_user = ALL_AUTHORITY; - } - } - - if (auth_user == AU_ADMIN) - { - return 1; - } - - return (auth_user & auth_task) ? 1 : 0; - -} - -static int -get_short_filename (char *ret_name, int ret_name_len, - char *short_filename) -{ - char *ptr = NULL; - char *path_p = NULL; - unsigned int filename_len = 0; - -#if defined(WINDOWS) - path_p = strrchr (short_filename, '\\'); -#else - path_p = strrchr (short_filename, '/'); -#endif - - if (path_p != NULL) - { - return -1; - } - - if (short_filename == NULL) - { - return -1; - } - - if (ret_name_len <= (int) strlen (short_filename)) - { - return -1; - } - - ptr = strrchr (short_filename, '.'); - if (ptr == NULL) - { - snprintf (ret_name, strlen (short_filename) + 1, short_filename); - return -1; - } - - filename_len = (unsigned int) (ptr - short_filename); - - snprintf (ret_name, filename_len + 1, short_filename); - - return 0; -} - -int -ut_get_filename (char *fullpath, int with_ext, char *ret_filename) -{ - char *filename = NULL; - char short_filename[PATH_MAX]; - - short_filename[0] = '\0'; - - if (fullpath == NULL) - { - return -1; - } - -#if defined(WINDOWS) - filename = strrchr (fullpath, '\\'); -#else - filename = strrchr (fullpath, '/'); -#endif - - if ((filename == NULL) || ((filename + 1) == NULL)) - { - return -1; - } - - if (with_ext == 1) - { - snprintf (ret_filename, PATH_MAX, filename + 1); - return 0; - } - else - { - if (get_short_filename (short_filename, PATH_MAX, filename + 1) != 0) - { - return -1; - } - snprintf (ret_filename, PATH_MAX, short_filename); - } - return 0; -} - - -#if defined(WINDOWS) - -static int -get_cpu_time (__int64 *kernel, __int64 *user, __int64 *idle) -{ - /* this logic allow multi thread init multiple times */ - if (s_symbol_loaded == 0) - { - /* - * kernel32.dll and ntdll.dll is essential DLL about user process. - * when a process started, that means kernel32.dll and ntdll.dll - * already load in process memory space. - * so call LoadLibrary() and FreeLibrary() function once, only - * increase and decrease dll reference counter. this behavior does - * not cause kernel32.dll or ntdll.dll unload from current process. - */ - - /* - * first try find function GetSystemTimes(). Windows OS suport this - * function since Windows XP SP1, Vista, Server 2003 or Server 2008. - */ - HMODULE module = LoadLibraryA ("kernel32.dll"); - s_pfnGetSystemTimes = - (GET_SYSTEM_TIMES) GetProcAddress (module, "GetSystemTimes"); - FreeLibrary (module); - - if (s_pfnGetSystemTimes != NULL) - { - s_symbol_loaded = 1; - } - else - { - /* - * OS may be is Windows 2000 or Windows XP. (does not support Windows 9x/NT) - * try find function NtQuerySystemInformation() - */ - module = LoadLibraryA ("ntdll.dll"); - s_pfnNtQuerySystemInformation = (NT_QUERY_SYSTEM_INFORMATION) - GetProcAddress (module, "NtQuerySystemInformation"); - FreeLibrary (module); - - if (s_pfnNtQuerySystemInformation == NULL) - { - s_symbol_loaded = 3; - } - else - { - s_symbol_loaded = 2; - } - } - } - - if (s_symbol_loaded == 1) - { - FILETIME kernel_time, user_time, idle_time; - ULARGE_INTEGER lk, lu, li; - - s_pfnGetSystemTimes (&idle_time, &kernel_time, &user_time); - - lk.HighPart = kernel_time.dwHighDateTime; - lk.LowPart = kernel_time.dwLowDateTime; - lu.HighPart = user_time.dwHighDateTime; - lu.LowPart = user_time.dwLowDateTime; - li.HighPart = idle_time.dwHighDateTime; - li.LowPart = idle_time.dwLowDateTime; - - /* In win32 system, lk includes "System Idle Process" time, - * so we should exclude it */ - *kernel = lk.QuadPart - li.QuadPart; - *user = lu.QuadPart; - *idle = li.QuadPart; - - return 0; - } - else if (s_symbol_loaded == 2) - { - SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION sppi; - ULONG len; - - s_pfnNtQuerySystemInformation (SystemProcessorPerformanceInformation, - &sppi, sizeof (sppi), &len); - - /* In win32 system, sppi.KernelTime includes "System Idle Process" - * time, so we should exclude it */ - *kernel = sppi.KernelTime.QuadPart - sppi.IdleTime.QuadPart; - *user = sppi.UserTime.QuadPart; - *idle = sppi.IdleTime.QuadPart; - - return 0; - } - - return -1; -} - -BOOL -SetPrivilege (HANDLE hToken, LPCTSTR lpszPrivilege, BOOL bEnablePrivilege) -{ - TOKEN_PRIVILEGES tp; - LUID luid; - - /* receives LUID of privilege */ - if (!LookupPrivilegeValue (NULL, lpszPrivilege, &luid)) - { - return FALSE; - } - - tp.PrivilegeCount = 1; - tp.Privileges[0].Luid = luid; - if (bEnablePrivilege) - { - tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; - } - else - { - tp.Privileges[0].Attributes = 0; - } - - if (!AdjustTokenPrivileges (hToken, FALSE, &tp, - sizeof (TOKEN_PRIVILEGES), NULL, NULL)) - { - return FALSE; - } - - if (GetLastError () == ERROR_NOT_ALL_ASSIGNED) - { - return FALSE; - } - - return TRUE; -} - -int -ut_get_proc_stat (T_CMS_PROC_STAT *stat, int pid) -{ - ULARGE_INTEGER lk, lu; - FILETIME dummy1, dummy2, kt, ut; - PROCESS_MEMORY_COUNTERS pmc; - MEMORYSTATUSEX ms; - HANDLE hProcess = NULL, hToken = NULL; - int ret = 0; - - stat->pid = pid; - if (!OpenThreadToken (GetCurrentThread (), - (TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY), - FALSE, &hToken)) - { - if (GetLastError () == ERROR_NO_TOKEN) - { - if (!ImpersonateSelf (SecurityImpersonation)) - { - return -1; - } - - if (!OpenThreadToken (GetCurrentThread (), - (TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY), - FALSE, &hToken)) - { - return -1; - } - } - else - { - return -1; - } - } - - /* enable SeDebugPrivilege */ - if (!SetPrivilege (hToken, SE_DEBUG_NAME, TRUE)) - { - ret = -1; - goto error_exit; - } - - hProcess = OpenProcess (PROCESS_ALL_ACCESS, FALSE, pid); - if (hProcess == NULL) - { - ret = -1; - goto error_exit; - } - - if (!GetProcessTimes (hProcess, &dummy1, &dummy2, &kt, &ut)) - { - ret = -1; - goto error_exit; - } - - lk.HighPart = kt.dwHighDateTime; - lk.LowPart = kt.dwLowDateTime; - lu.HighPart = ut.dwHighDateTime; - lu.LowPart = ut.dwLowDateTime; - - stat->cpu_kernel = lk.QuadPart; - stat->cpu_user = lu.QuadPart; - - memset (&pmc, 0, sizeof (pmc)); - pmc.cb = sizeof (pmc); - - if (!GetProcessMemoryInfo (hProcess, &pmc, sizeof (pmc))) - { - ret = -1; - goto error_exit; - } - - stat->mem_physical = pmc.WorkingSetSize; - - memset (&ms, 0, sizeof (ms)); - ms.dwLength = sizeof (ms); - - if (!GlobalMemoryStatusEx (&ms)) - { - ret = -1; - goto error_exit; - } - - stat->mem_virtual = ms.ullTotalVirtual - ms.ullAvailVirtual; - -error_exit: - if (hProcess != NULL) - { - CloseHandle (hProcess); - } - if (hToken != NULL) - { - CloseHandle (hToken); - } - return ret; -} - -int -ut_get_host_stat (T_CMS_HOST_STAT *stat, char *_dbmt_error) -{ - __int64 kernel, user, idle; - PERFORMANCE_INFORMATION pi; - - if (stat == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "Invalid parameter: %s.", - "stat"); - return ERR_WITH_MSG; - } - - if (get_cpu_time (&kernel, &user, &idle) != 0) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, - "Failed to get the cpu information."); - return ERR_WITH_MSG; - } - - stat->cpu_kernel = kernel; - stat->cpu_user = user; - stat->cpu_idle = idle; - stat->cpu_iowait = 0; - - memset (&pi, 0, sizeof (pi)); - pi.cb = sizeof (pi); - if (!GetPerformanceInfo (&pi, sizeof (pi))) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, - "Failed to get the memory information."); - return ERR_WITH_MSG; - } - - stat->mem_physical_total = ((__int64) pi.PhysicalTotal) * pi.PageSize; - stat->mem_physical_free = ((__int64) pi.PhysicalAvailable) * pi.PageSize; - stat->mem_swap_total = ((__int64) pi.CommitLimit) * pi.PageSize; - stat->mem_swap_free = - ((__int64) (pi.CommitLimit - pi.CommitTotal)) * pi.PageSize; - - return ERR_NO_ERROR; -} - -#elif defined(AIX) - -int -ut_get_proc_stat (T_CMS_PROC_STAT *stat, int pid) -{ - struct pstatus proc_stat; - struct psinfo proc_psinfo; - char file_name[PATH_MAX]; - int fd = -1; - long int ticks_per_sec = 0; - - file_name[0] = '\0'; - - if (stat == NULL) - { - return -1; - } - - ticks_per_sec = sysconf (_SC_CLK_TCK); - snprintf (file_name, PATH_MAX, "/proc/%d/status", pid); - - fd = open (file_name, O_RDONLY); - if (fd == -1) - { - return -1; - } - if (read (fd, (void *) &proc_stat, sizeof (struct pstatus)) == -1) - { - close (fd); - return -1; - } - close (fd); - - stat->cpu_user = - (uint64_t) ((proc_stat.pr_utime.tv_sec + - proc_stat.pr_utime.tv_nsec * 10e-9) * ticks_per_sec); - stat->cpu_kernel = - (uint64_t) ((proc_stat.pr_stime.tv_sec + - proc_stat.pr_stime.tv_nsec * 10e-9) * ticks_per_sec); - - snprintf (file_name, PATH_MAX, "/proc/%d/psinfo", pid); - - fd = open (file_name, O_RDONLY); - if (fd == -1) - { - return -1; - } - if (read (fd, (void *) &proc_psinfo, sizeof (struct psinfo)) == -1) - { - close (fd); - return -1; - } - close (fd); - - stat->mem_virtual = proc_psinfo.pr_size * 1024; - stat->mem_physical = proc_psinfo.pr_rssize * 1024; - - return 0; -} - -int -ut_get_host_stat (T_CMS_HOST_STAT *stat, char *_dbmt_error) -{ - perfstat_cpu_total_t cpu_stat; - perfstat_memory_total_t mem_info; - - if (stat == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "Invalid parameter: %s.", "stat"); - return ERR_WITH_MSG; - } - if (perfstat_cpu_total (NULL, &cpu_stat, sizeof (perfstat_cpu_total_t), 1) == -1) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, - "Failed to get the cpu information."); - return ERR_WITH_MSG; - } - stat->cpu_user = cpu_stat.user; - stat->cpu_kernel = cpu_stat.sys; - stat->cpu_idle = cpu_stat.idle; - stat->cpu_iowait = cpu_stat.wait; - - if (perfstat_memory_total - (NULL, &mem_info, sizeof (perfstat_memory_total_t), 1) == -1) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, - "Failed to get the memory information."); - return ERR_WITH_MSG; - } - stat->mem_physical_total = mem_info.real_total * 4 * 1024; - stat->mem_physical_free = mem_info.real_free * 4 * 1024; - stat->mem_swap_total = mem_info.pgsp_total * 4 * 1024; - stat->mem_swap_free = mem_info.pgsp_free * 4 * 1024; - - return ERR_NO_ERROR; -} - -#else - -int -ut_get_proc_stat (T_CMS_PROC_STAT *stat, int pid) -{ - long vmem_pages; - long rmem_pages; - char fname[PATH_MAX]; - FILE *cpufp = NULL; - FILE *memfp = NULL; - - vmem_pages = 0; - rmem_pages = 0; - fname[0] = '\0'; - - if (stat == NULL || pid == 0) - { - return -1; - } - - stat->pid = pid; - - snprintf (fname, PATH_MAX - 1, "/proc/%d/stat", (int) pid); - cpufp = fopen (fname, "r"); - if (!cpufp) - { - return -1; - } - - snprintf (fname, PATH_MAX - 1, "/proc/%d/statm", (int) pid); - memfp = fopen (fname, "r"); - if (memfp == NULL) - { - fclose (cpufp); - return -1; - } -#if __WORDSIZE == 64 - fscanf (cpufp, "%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%lu%lu", - &stat->cpu_user, &stat->cpu_kernel); - fscanf (memfp, "%lu%lu", &vmem_pages, &rmem_pages); /* 'size' and 'resident' in stat file */ -#else - fscanf (cpufp, "%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%llu%llu", - &stat->cpu_user, &stat->cpu_kernel); - fscanf (memfp, "%lu%lu", &vmem_pages, &rmem_pages); /* 'size' and 'resident' in stat file */ -#endif - - stat->mem_virtual = vmem_pages * sysconf (_SC_PAGESIZE); - stat->mem_physical = rmem_pages * sysconf (_SC_PAGESIZE); - - fclose (cpufp); - fclose (memfp); - - return 0; -} - -int -ut_get_host_stat (T_CMS_HOST_STAT *stat, char *_dbmt_error) -{ - char linebuf[LINE_MAX]; - char prefix[50]; - uint64_t nice; - uint64_t buffers; - uint64_t cached; - FILE *cpufp = NULL; - FILE *memfp = NULL; - int n_cpuitem = 0; - int n_memitem = 0; - const char *stat_file = "/proc/stat"; - const char *meminfo_file = "/proc/meminfo"; - - linebuf[0] = '\0'; - prefix[0] = '\0'; - - if (stat == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "Invalid parameter: %s.", "stat"); - return ERR_WITH_MSG; - } - cpufp = fopen (stat_file, "r"); - if (cpufp == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "stat_file"); - return ERR_FILE_OPEN_FAIL; - } - memfp = fopen (meminfo_file, "r"); - if (memfp == NULL) - { - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "meminfo_file"); - return ERR_FILE_OPEN_FAIL; - } - - while (fgets (linebuf, sizeof (linebuf), cpufp)) - { - sscanf (linebuf, "%49s", prefix); - if (!strcmp (prefix, "cpu")) - { -#if __WORDSIZE == 64 - sscanf (linebuf, "%*s%lu%lu%lu%lu%lu", &stat->cpu_user, &nice, - &stat->cpu_kernel, &stat->cpu_idle, &stat->cpu_iowait); -#else - sscanf (linebuf, "%*s%llu%llu%llu%llu%llu", &stat->cpu_user, &nice, - &stat->cpu_kernel, &stat->cpu_idle, &stat->cpu_iowait); -#endif - - stat->cpu_user += nice; - n_cpuitem++; - break; - } - } - if (n_cpuitem != 1) - { - goto error_handle; - } - - while (fgets (linebuf, sizeof (linebuf), memfp)) - { - sscanf (linebuf, "%49s", prefix); - if (!strcmp (prefix, "MemTotal:")) - { -#if __WORDSIZE == 64 - sscanf (linebuf, "%*s%lu", &stat->mem_physical_total); -#else - sscanf (linebuf, "%*s%llu", &stat->mem_physical_total); -#endif - n_memitem++; - } - if (!strcmp (prefix, "MemFree:")) - { -#if __WORDSIZE == 64 - sscanf (linebuf, "%*s%lu", &stat->mem_physical_free); -#else - sscanf (linebuf, "%*s%llu", &stat->mem_physical_free); -#endif - n_memitem++; - } - if (!strcmp (prefix, "Buffers:")) - { -#if __WORDSIZE == 64 - sscanf (linebuf, "%*s%lu", &buffers); -#else - sscanf (linebuf, "%*s%llu", &buffers); -#endif - } - if (!strcmp (prefix, "Cached:")) - { -#if __WORDSIZE == 64 - sscanf (linebuf, "%*s%lu", &cached); -#else - sscanf (linebuf, "%*s%llu", &cached); -#endif - } - if (!strcmp (prefix, "SwapTotal:")) - { -#if __WORDSIZE == 64 - sscanf (linebuf, "%*s%lu", &stat->mem_swap_total); -#else - sscanf (linebuf, "%*s%llu", &stat->mem_swap_total); -#endif - n_memitem++; - } - if (!strcmp (prefix, "SwapFree:")) - { -#if __WORDSIZE == 64 - sscanf (linebuf, "%*s%lu", &stat->mem_swap_free); -#else - sscanf (linebuf, "%*s%llu", &stat->mem_swap_free); -#endif - n_memitem++; - } - } - if (n_memitem != 4) - { - goto error_handle; - } - - stat->mem_physical_free += (buffers + cached); - - stat->mem_physical_total *= 1024; - stat->mem_physical_free *= 1024; - stat->mem_swap_total *= 1024; - stat->mem_swap_free *= 1024; - - fclose (cpufp); - fclose (memfp); - return ERR_NO_ERROR; - -error_handle: - snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "read host info error."); - fclose (cpufp); - fclose (memfp); - return ERR_WITH_MSG; -} - -#endif // WINDOWS - -int -ut_record_arniadb_utility_log_stderr (const char *msg) -{ - if (msg == NULL) - { - return -1; - } -#if !defined(WINDOWS) - fprintf (stderr, msg); -#endif - cm_util_log_write_errstr (msg); - - return 0; -} - -int -ut_record_arniadb_utility_log_stdout (const char *msg) -{ - if (msg == NULL) - { - return -1; - } -#if !defined(WINDOWS) - fprintf (stdout, msg); -#endif - cm_util_log_write_errstr (msg); - - return 0; -} diff --git a/server/src/cm_server_util.h b/server/src/cm_server_util.h deleted file mode 100644 index 23c1992..0000000 --- a/server/src/cm_server_util.h +++ /dev/null @@ -1,219 +0,0 @@ -/* - * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. - * - * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/* - * cm_server_util.h - - */ - -#ifndef _CM_SERVER_UTIL_H_ -#define _CM_SERVER_UTIL_H_ - -#include "cm_porting.h" -#include "cm_dep.h" -#include "cm_cmd_exec.h" -#include "cm_job_task.h" - -#ifndef WINDOWS -#include -#include -#include -#include -#include -#else -#ifndef uint64_t -typedef unsigned __int64 uint64_t; -#endif -#endif - -#define makestring1(x) #x -#define makestring(x) makestring1(x) - -#define TOKEN_LENGTH 128 /* multiple of 8 */ -#define TOKEN_ENC_LENGTH (TOKEN_LENGTH * 2 + 1) -#define PASSWD_LENGTH 32 -#define PASSWD_ENC_LENGTH (PASSWD_LENGTH * 2 + 1) - -#define REMOVE_DIR_FORCED 1 -#define REMOVE_EMPTY_DIR 0 - -#define MAX_AUTOQUERY_SCRIPT_SIZE 4095 -#define MAX_JOB_CONFIG_FILE_LINE_LENGTH (4096 + 256) - -#define BYTES_IN_K (1024) -#define BYTES_IN_M (1024 * 1024) -#define BYTES_IN_G (1024 * 1024 * 1024) - -#define RSA_KEY_SIZE 1024 - -#ifdef _DEBUG_ -#include "deb.h" -#define MALLOC(p) debug_malloc(p) -#else -#define MALLOC(p) malloc(p) -#endif - -#define FREE_MEM(PTR) \ - do { \ - if (PTR) { \ - free(PTR); \ - PTR = 0; \ - } \ - } while (0) - -#define REALLOC(PTR, SIZE) \ - (PTR == NULL) ? malloc(SIZE) : realloc(PTR, SIZE) - -#ifndef MAX -#define MAX(x, y) (((x) > (y)) ? (x) : (y)) -#endif - -#ifndef MIN -#define MIN(x, y) (((x) < (y)) ? (x) : (y)) -#endif - -#define MAKE_MUTIPLE_EIGHT(num) (((num) + (8) - 1) & ~((8) - 1)) - -#ifdef AIX -//the size of stack per thread -#define AIX_STACKSIZE_PER_THREAD (10*1024*1024) -#endif - -typedef enum -{ - TIME_STR_FMT_DATE = NV_ADD_DATE, - TIME_STR_FMT_TIME = NV_ADD_TIME, - TIME_STR_FMT_DATE_TIME = NV_ADD_DATE_TIME -} T_TIME_STR_FMT_TYPE; - -typedef struct -{ - uint64_t cpu_user; - uint64_t cpu_kernel; - uint64_t cpu_idle; - uint64_t cpu_iowait; - uint64_t mem_physical_total; - uint64_t mem_physical_free; - uint64_t mem_swap_total; - uint64_t mem_swap_free; -} T_CMS_HOST_STAT; - -typedef struct -{ - int pid; - uint64_t cpu_kernel; - uint64_t cpu_user; - uint64_t mem_physical; - uint64_t mem_virtual; /* size item in statm file */ -} T_CMS_PROC_STAT; - -int _op_check_is_localhost (char *token, char *tmpdbname); -void append_host_to_dbname (char *name_buf, const char *dbname, - int buf_len); -void *increase_capacity (void *ptr, int block_size, int old_count, - int new_count); -char *strcpy_limit (char *dest, const char *src, int buf_len); -int ut_getdelim (char **lineptr, int *n, int delimiter, FILE *fp); -int ut_getline (char **lineptr, int *n, FILE *fp); -void ut_error_log (nvplist *req, const char *errmsg); -void ut_access_log (nvplist *req, const char *msg); -void uRemoveCRLF (char *str); -int uStringEqual (const char *str1, const char *str2); -int uStringEqualIgnoreCase (const char *str1, const char *str2); -int ut_gettaskcode (char *task); -int ut_send_response (SOCKET fd, nvplist *res); -int ut_receive_request (SOCKET fd, nvplist *req); -void ut_daemon_start (void); -void ut_dump_file_to_string (char *string, char *fname); -int uRetrieveDBDirectory (const char *dbname, char *target); -int _isRegisteredDB (char *); -//int uReadDBnfo (char *); -void uWriteDBnfo (void); -void uWriteDBnfo2 (T_SERVER_STATUS_RESULT *cmd_res); -int ut_get_dblist (nvplist *res, char dbdir_flag); -int uCreateLockFile (char *filename); -void uRemoveLockFile (int fd); -int uCreateDir (char *path); -int folder_copy (const char *src_dir, const char *dest_dir); -int uRemoveDir (char *dir, int remove_file_in_dir); -int string_tokenize_accept_laststring_space (char *str, char *tok[], - int num_tok); -int make_version_info (const char *cli_ver, int *major_ver, int *minor_ver); -int file_copy (char *src_file, char *dest_file); -int move_file (char *src_file, char *dest_file); -void close_all_fds (int init_fd); -char *ut_trim (char *str); -void server_fd_clear (fd_set srv_fds); -int ut_write_pid (char *pid_file); -int ut_disk_free_space (char *path); -char *ip2str (unsigned char *ip, char *ip_str); -int string_tokenize (char *str, char *tok[], int num_tok); -int string_tokenize2 (char *str, char *tok[], int num_tok, int c); -int ut_get_task_info (const char *task, char *access_log_flag, - T_TASK_FUNC *task_func, T_USER_AUTH *auth); -char *time_to_str (time_t t, const char *fmt, char *buf, int type); -int read_from_socket (SOCKET fd, char *buf, int size); -int write_to_socket (SOCKET fd, const char *buf, int size); -int is_cmserver_process (int pid, const char *module_name); -int make_default_env (void); -#if defined(WINDOWS) -void remove_end_of_dir_ch (char *path); -#endif - -#if defined(WINDOWS) -#define popen _popen -#define pclose _pclose -int kill (int pid, int signo); -void unix_style_path (char *path); -char *nt_style_path (char *path, char *new_path_buf); -#endif - -int _ut_get_dbaccess (nvplist *req, char *dbid, char *dbpasswd); -void uGenerateStatus (nvplist *req, nvplist *res, int retval, - const char *_dbmt_error); -int ut_validate_token (nvplist *req); -void _ut_timeval_diff (struct timeval *start, struct timeval *end, - int *res_msec); -char *ut_token_generate (char *client_ip, char *client_port, - char *dbmt_id, int proc_id, time_t login_time); -void _accept_connection (nvplist *cli_request, nvplist *cli_response); -#if defined(WINDOWS) -int gettimeofday (struct timeval *tp, void *tzp); -#endif -int ut_run_child (const char *bin_path, const char *const argv[], - int wait_flag, const char *stdin_file, - const char *stdout_file, const char *stderr_file, int *exit_status); - -int IsValidUserName (const char *pUserName); -int ut_validate_auth (nvplist *req); -int ut_get_token_active_time (time_t *active_time); -int remove_extra_subdir (const char *dirpath, const char *pattern, - unsigned int save_num); -int ut_get_filename (char *fullpath, int with_ext, char *ret_filename); -int ut_get_host_stat (T_CMS_HOST_STAT *stat, char *_dbmt_error); -int ut_get_proc_stat (T_CMS_PROC_STAT *stat, int pid); -int ut_record_arniadb_utility_log_stderr (const char *msg); -int ut_record_arniadb_utility_log_stdout (const char *msg); -int run_child_linux (const char *pname, const char *const argv[], int wait_flag, - const char *stdin_file, char *stdout_file, char *stderr_file, - int *exit_status); -void write_manager_access_log (const char *protocol_str, const char *msg); -void write_manager_error_log (const char *protocol_str, const char *msg); - -#endif /* _CM_SERVER_UTIL_H_ */ diff --git a/server/src/cm_text_encryption.c b/server/src/cm_text_encryption.c deleted file mode 100644 index 2026a85..0000000 --- a/server/src/cm_text_encryption.c +++ /dev/null @@ -1,291 +0,0 @@ -/* - * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. - * - * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/* - * tea.c - - */ - -#ident "$Id$" - -#include -#include -#include -#include - -#include "cm_porting.h" -#include "cm_text_encryption.h" - -#if (defined(SOLARIS) && !defined(SOLARIS_X86)) || defined(HPUX) || defined(AIX) -#define BYTE_ORDER_BIG_ENDIAN -#elif defined(WINDOWS) || defined(LINUX) || defined(OSF1) || defined(ALPHA_LINUX) || defined(UNIXWARE7) || defined(SOLARIS_X86) -#ifdef BYTE_ORDER_BIG_ENDIAN -#error BYTE_ORDER_BIG_ENDIAN defined -#endif -#else -#error PLATFORM NOT DEFINED -#endif - -static void tea_encrypt (unsigned int key[], int len, char *buf); -static void tea_decrypt (unsigned int key[], int len, char *buf); -static void _encrypt (unsigned int k[], unsigned int text[]); -static void _decrypt (unsigned int k[], unsigned int text[]); -static char ut_get_hexval (char c); -static void array_init_random_value (char *arr, int arrsize); -static int big_endian_int (int from); - -static unsigned int key[4] = { 1, 2, 3, 4 }; /* key for tea encryption algorithm */ - -/* - * DESCRIPTION - * The uEncrypt() function encrypts the src string and converts - * the binary result to the string of hexadecimal representation. - * Since one byte is represented as two hexadecimal digit, 'trg' must - * have twice the space of 'src'. - * NOTE - * - 'len' must be multiple of 8. - * - size of 'trg' must be at lease twice the 'src' - * - 'src' must have the length equal to 'len' - */ -void -uEncrypt (int len, const char *src, char *trg) -{ - char *encstr = NULL; - char strbuf[10]; - int i; - - if (src == NULL) - { - src = ""; - } - - if ((encstr = (char *) malloc (len + 1)) == NULL) - { - return; - } - - array_init_random_value (encstr, sizeof (encstr)); - strcpy (encstr, src); - - tea_encrypt (key, len, encstr); - for (i = 0; i < len; ++i) - { - sprintf (strbuf, "%08x", encstr[i]); - trg[i * 2] = strbuf[6]; - trg[i * 2 + 1] = strbuf[7]; - } - trg[i * 2] = '\0'; - - free (encstr); -} - -/* - * DESCRIPTION - * The uDecrypt() function decrypts the src string and converts - * the string of hexadecimal string into its original values. - * NOTE - * - size of 'src' must be at least twice the 'trg' - * - size of 'trg' must be equal to 'len' - */ -void -uDecrypt (int len, const char *src, char *trg) -{ - int i; - char v1, v2; - char *hexacode = NULL; - - if (src == NULL || src[0] == '\0') - { - trg[0] = '\0'; - return; - } - - if ((hexacode = (char *) malloc (len * 2 + 1)) == NULL) - { - return; - } - - memset (hexacode, 0, sizeof (hexacode)); - strcpy (hexacode, src); - - for (i = 0; i < len; ++i) - { - v1 = ut_get_hexval (hexacode[i * 2]); - v2 = ut_get_hexval (hexacode[i * 2 + 1]); - v1 = v1 << 4; - trg[i] = (unsigned char) v1 | (unsigned char) v2; - } - tea_decrypt (key, len, trg); - trg[len] = '\0'; - - free (hexacode); -} - -/* This function assumes that unsigned_int is 4 bytes int. - En/Decryption processes 8 bytes at a time. - Although this function encrypts any length of text, - parameter text must have space size in multiple of 8 because this - function returns encryption in multiple of 8 bytes */ -static void -tea_encrypt (unsigned int key[], int len, char *text) -{ - unsigned int ulbuf[2]; - - while (len > 0) - { - if ((size_t) len < sizeof (ulbuf)) - { - memset (ulbuf, ' ', sizeof (ulbuf)); - memcpy (ulbuf, text, len); - _encrypt (key, ulbuf); - memcpy (text, ulbuf, len); - break; - } - else - { - memcpy (ulbuf, text, sizeof (ulbuf)); - _encrypt (key, ulbuf); - memcpy (text, ulbuf, sizeof (ulbuf)); - } - len -= sizeof (ulbuf); - text += sizeof (ulbuf); - } -} - -/* text parameter must hold encryption of 8-byte multiple size which was - returned from previous tea_encrypt() call */ -static void -tea_decrypt (unsigned int key[], int len, char *text) -{ - unsigned int ulbuf[2]; - - while (len > 0) - { - if ((size_t) len < sizeof (ulbuf)) - { - memset (ulbuf, ' ', sizeof (ulbuf)); - /*memcpy(ulbuf,text,len); */ - memcpy (ulbuf, text, sizeof (ulbuf)); - _decrypt (key, ulbuf); - memcpy (text, ulbuf, len); - break; - } - else - { - memcpy (ulbuf, text, sizeof (ulbuf)); - _decrypt (key, ulbuf); - memcpy (text, ulbuf, sizeof (ulbuf)); - } - len -= sizeof (ulbuf); - text += sizeof (ulbuf); - } -} - -static void -_encrypt (unsigned int k[], unsigned int text[]) -{ - unsigned int y = big_endian_int (text[0]); - unsigned int z = big_endian_int (text[1]); - unsigned int delta = 0x9e3779b9; - unsigned int sum = 0; - int n; - - for (n = 0; n < 32; n++) - { - sum += delta; - y += ((z << 4) + k[0]) ^ (z + sum) ^ ((z >> 5) + k[1]); - z += ((y << 4) + k[2]) ^ (y + sum) ^ ((y >> 5) + k[3]); - } - text[0] = big_endian_int (y); - text[1] = big_endian_int (z); -} - -static void -_decrypt (unsigned int k[], unsigned int text[]) -{ - unsigned int y = big_endian_int (text[0]); - unsigned int z = big_endian_int (text[1]); - unsigned int delta = 0x9e3779b9; - unsigned int sum = delta << 5; - int n; - - for (n = 0; n < 32; n++) - { - z -= ((y << 4) + k[2]) ^ (y + sum) ^ ((y >> 5) + k[3]); - y -= ((z << 4) + k[0]) ^ (z + sum) ^ ((z >> 5) + k[1]); - sum -= delta; - } - text[0] = big_endian_int (y); - text[1] = big_endian_int (z); -} - -static char -ut_get_hexval (char c) -{ - if (c >= '0' && c <= '9') - { - return (c - '0'); - } - - if (c >= 'a' && c <= 'f') - { - return (c - 'a' + 10); - } - - return (c - 'A' + 10); /* c >= 'A' && c <= 'F' */ -} - -static void -array_init_random_value (char *arr, int arrsize) -{ - int i; - static unsigned int seed = 0; - - if (seed == 0) - { - seed = (unsigned int) time (NULL); - srand (seed); - } - - for (i = 0; i < arrsize; i++) - { - arr[i] = rand () % 100; - } -} - -static int -big_endian_int (int from) -{ -#ifdef BYTE_ORDER_BIG_ENDIAN - return from; -#else - int to; - char *p, *q; - - p = (char *) &from; - q = (char *) &to; - - q[0] = p[3]; - q[1] = p[2]; - q[2] = p[1]; - q[3] = p[0]; - - return to; -#endif -} diff --git a/server/src/cm_text_encryption.h b/server/src/cm_text_encryption.h deleted file mode 100644 index ccaf13f..0000000 --- a/server/src/cm_text_encryption.h +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. - * - * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/* - * cm_text_encryption.h - - */ - -#ifndef _CM_TEXT_ENCRYPTION_H_ -#define _CM_TEXT_ENCRYPTION_H_ -#ifdef __cplusplus -extern "C" -{ -#endif -#ident "$Id$" - -void uEncrypt (int len, const char *src, char *trg); -void uDecrypt (int len, const char *src, char *trg); -#ifdef __cplusplus -} -#endif -#endif /* _CM_TEXT_ENCRYPTION_H_ */ diff --git a/server/src/cm_user.cpp b/server/src/cm_user.cpp deleted file mode 100644 index 47bd8a7..0000000 --- a/server/src/cm_user.cpp +++ /dev/null @@ -1,711 +0,0 @@ -/* - * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. - * - * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/* - * cm_user.cpp - - */ - -#include -#include -#include - -#if defined(WINDOWS) -#include -#else -#include -#endif - -#include "cm_porting.h" -#include "cm_config.h" -#include "cm_server_util.h" -#include "cm_user.h" - -#define ARNIADB_PASS_OPEN_TAG "<<<:" -#define ARNIADB_PASS_OPEN_TAG_LEN strlen(ARNIADB_PASS_OPEN_TAG) -#define ARNIADB_PASS_CLOSE_TAG ">>>:" -#define ARNIADB_PASS_CLOSE_TAG_LEN strlen(ARNIADB_PASS_CLOSE_TAG) - - -T_USER_TOKEN_INFO *user_token_info = NULL; - -int -dbmt_user_read (T_DBMT_USER *dbmt_user, char *_dbmt_error) -{ - T_DBMT_USER_INFO *user_info = NULL; - T_DBMT_USER_DBINFO *user_dbinfo = NULL; - T_DBMT_USER_AUTHINFO *user_authinfo = NULL; - int num_dbmt_user = 0; - int num_dbinfo = 0; - int num_authinfo = 0; - char *authinfo[2]; - char *dbinfo[4]; - FILE *fp = NULL; - char strbuf[1024]; - char cur_user[DBMT_USER_NAME_LEN]; - int retval = ERR_NO_ERROR; - int lock_fd; - - memset (dbmt_user, 0, sizeof (T_DBMT_USER)); - - lock_fd = uCreateLockFile (conf_get_dbmt_file (FID_LOCK_DBMT_PASS, strbuf)); - if (lock_fd < 0) - { - return ERR_TMPFILE_OPEN_FAIL; - } - - fp = fopen (conf_get_dbmt_file (FID_DBMT_ARNIADB_PASS, strbuf), "r"); - if (fp == NULL) - { - strcpy (_dbmt_error, - conf_get_dbmt_file2 (FID_DBMT_ARNIADB_PASS, strbuf)); - retval = ERR_FILE_OPEN_FAIL; - goto read_dbmt_user_error; - } - - memset (cur_user, 0, sizeof (cur_user)); - while (fgets (strbuf, sizeof (strbuf), fp)) - { - ut_trim (strbuf); - if (strncmp (strbuf, ARNIADB_PASS_OPEN_TAG, ARNIADB_PASS_OPEN_TAG_LEN) == 0) - { - snprintf (cur_user, sizeof (cur_user) - 1, "%s", strbuf + ARNIADB_PASS_OPEN_TAG_LEN); - if (cur_user[0] == '\0') - { - continue; - } - - user_info = - (T_DBMT_USER_INFO *) increase_capacity (user_info, - sizeof (T_DBMT_USER_INFO), num_dbmt_user, - num_dbmt_user + 1); - if (user_info == NULL) - { - retval = ERR_MEM_ALLOC; - goto read_dbmt_user_error; - } - num_dbmt_user++; - - /* user name set */ - strcpy_limit (user_info[num_dbmt_user - 1].user_name, cur_user, - DBMT_USER_NAME_LEN); - if (user_dbinfo != NULL) - { - free (user_dbinfo); - user_dbinfo = NULL; - } - num_dbinfo = 0; - num_authinfo = 0; - continue; - } - - if (cur_user[0] == '\0') - { - continue; - } - - if (strncmp (strbuf, ARNIADB_PASS_CLOSE_TAG, ARNIADB_PASS_CLOSE_TAG_LEN) == 0) - { - if (strcmp (strbuf + ARNIADB_PASS_CLOSE_TAG_LEN, cur_user) != 0) - { - strcpy (_dbmt_error, conf_get_dbmt_file2 (FID_DBMT_ARNIADB_PASS, - strbuf)); - retval = ERR_FILE_INTEGRITY; - goto read_dbmt_user_error; - } - if (user_info != NULL) - { - user_info[num_dbmt_user - 1].dbinfo = user_dbinfo; - user_dbinfo = NULL; - user_info[num_dbmt_user - 1].num_dbinfo = num_dbinfo; - - user_info[num_dbmt_user - 1].authinfo = user_authinfo; - user_authinfo = NULL; - user_info[num_dbmt_user - 1].num_authinfo = num_authinfo; - } - cur_user[0] = '\0'; - } - else - { - /* get authority info and database info */ - if (string_tokenize2 (strbuf, authinfo, 2, ':') < 0) - { - continue; - } - else - { - if ((strcmp (authinfo[0], "dbc") == 0) - || (strcmp (authinfo[0], "dbo") == 0) - || (strcmp (authinfo[0], "brk") == 0) - || (strcmp (authinfo[0], "mon") == 0) - || (strcmp (authinfo[0], "job") == 0) - || (strcmp (authinfo[0], "var") == 0) - || (strcmp (authinfo[0], "user_auth") == 0) - || (strcmp (authinfo[0], "admin") == 0) || - // for old cmdb.pass file. - (strcmp (authinfo[0], "unicas") == 0) - || (strcmp (authinfo[0], "dbcreate") == 0) - || (strcmp (authinfo[0], "statusmonitorauth") == 0)) - { - T_DBMT_USER_AUTHINFO tmp_authinfo; - memset (&tmp_authinfo, 0, sizeof (T_DBMT_USER_AUTHINFO)); - - dbmt_user_set_authinfo (&tmp_authinfo, authinfo[0], authinfo[1]); - - user_authinfo = - (T_DBMT_USER_AUTHINFO *) increase_capacity (user_authinfo, - sizeof (T_DBMT_USER_AUTHINFO), - num_authinfo, num_authinfo + 1); - if (user_authinfo == NULL) - { - retval = ERR_MEM_ALLOC; - goto read_dbmt_user_error; - } - num_authinfo++; - user_authinfo[num_authinfo - 1] = tmp_authinfo; - } - else - { - T_DBMT_USER_DBINFO tmp_dbinfo; - memset (&tmp_dbinfo, 0, sizeof (T_DBMT_USER_DBINFO)); - - if (string_tokenize2 (authinfo[1], dbinfo, 3, ';') < 0) - { - continue; - } - - /* 8.3.0 cmdb.pass not store dbpasswd. For compatibility, - * check if use older version cmdb.pass */ - char *separator; - separator = dbinfo[3] = strchr (dbinfo[2], ';'); - if (separator != NULL) - { - *separator = '\0'; - dbinfo[3] = separator + 1; - dbmt_user_set_dbinfo (&tmp_dbinfo, authinfo[0], - dbinfo[0], dbinfo[1], dbinfo[3]); - } - else - { - dbmt_user_set_dbinfo (&tmp_dbinfo, authinfo[0], - dbinfo[0], dbinfo[1], dbinfo[2]); - } - - user_dbinfo = - (T_DBMT_USER_DBINFO *) increase_capacity (user_dbinfo, - sizeof (T_DBMT_USER_DBINFO), - num_dbinfo, num_dbinfo + 1); - if (user_dbinfo == NULL) - { - retval = ERR_MEM_ALLOC; - goto read_dbmt_user_error; - } - num_dbinfo++; - user_dbinfo[num_dbinfo - 1] = tmp_dbinfo; - } - } - } - } - fclose (fp); - fp = NULL; - - if (user_dbinfo != NULL) - { - free (user_dbinfo); - user_dbinfo = NULL; - } - if (user_authinfo != NULL) - { - free (user_authinfo); - user_authinfo = NULL; - } - - if (num_dbmt_user < 1) - { - strcpy (_dbmt_error, - conf_get_dbmt_file2 (FID_DBMT_ARNIADB_PASS, strbuf)); - retval = ERR_FILE_INTEGRITY; - goto read_dbmt_user_error; - } - - dbmt_user->num_dbmt_user = num_dbmt_user; - dbmt_user->user_info = user_info; - - fp = fopen (conf_get_dbmt_file (FID_DBMT_PASS, strbuf), "r"); - if (fp == NULL) - { - strcpy (_dbmt_error, conf_get_dbmt_file2 (FID_DBMT_PASS, strbuf)); - retval = ERR_FILE_OPEN_FAIL; - goto read_dbmt_user_error; - } - - while (fgets (strbuf, sizeof (strbuf), fp)) - { - char *tok[2]; - int i; - - ut_trim (strbuf); - if (string_tokenize2 (strbuf, tok, 2, ':') < 0) - { - continue; - } - for (i = 0; i < dbmt_user->num_dbmt_user; i++) - { - if (strcmp (tok[0], dbmt_user->user_info[i].user_name) == 0) - { - snprintf (dbmt_user->user_info[i].user_passwd, - sizeof (dbmt_user->user_info[i].user_passwd) - 1, - "%s", tok[1]); - break; - } - } - } - fclose (fp); - - uRemoveLockFile (lock_fd); - return ERR_NO_ERROR; - -read_dbmt_user_error: - if (fp != NULL) - { - fclose (fp); - } - if (user_info != NULL) - { - free (user_info); - } - if (user_authinfo != NULL) - { - free (user_authinfo); - } - if (user_dbinfo != NULL) - { - free (user_dbinfo); - } - dbmt_user_free (dbmt_user); - uRemoveLockFile (lock_fd); - - return retval; -} - -void -dbmt_user_free (T_DBMT_USER *dbmt_user) -{ - int i; - - if (dbmt_user->user_info) - { - for (i = 0; i < dbmt_user->num_dbmt_user; i++) - { - if (dbmt_user->user_info[i].dbinfo) - { - free (dbmt_user->user_info[i].dbinfo); - } - if (dbmt_user->user_info[i].authinfo) - { - free (dbmt_user->user_info[i].authinfo); - } - } - free (dbmt_user->user_info); - } -} - -int -dbmt_user_write_auth (T_DBMT_USER *dbmt_user, char *_dbmt_error) -{ - FILE *fp; - char tmpfile[512]; - int i, j; - char strbuf[1024]; - int lock_fd; - -#if !defined (DO_NOT_USE_ARNIADBENV) - sprintf (tmpfile, "%s/tmp/DBMT_util_pass.%d", sco.szArniadb, (int) getpid ()); -#else - sprintf (tmpfile, "%s/DBMT_util_pass.%d", ARNIADB_TMPDIR, (int) getpid ()); -#endif - fp = fopen (tmpfile, "w"); - if (fp == NULL) - { - return ERR_TMPFILE_OPEN_FAIL; - } - for (i = 0; i < dbmt_user->num_dbmt_user; i++) - { - if (dbmt_user->user_info[i].user_name[0] == '\0') - { - continue; - } - - fprintf (fp, "%s%s\n", ARNIADB_PASS_OPEN_TAG, - dbmt_user->user_info[i].user_name); - for (j = 0; j < dbmt_user->user_info[i].num_authinfo; j++) - { - if (dbmt_user->user_info[i].authinfo[j].domain[0] == '\0') - { - continue; - } - fprintf (fp, "%s:%s\n", dbmt_user->user_info[i].authinfo[j].domain, - dbmt_user->user_info[i].authinfo[j].auth); - } - for (j = 0; j < dbmt_user->user_info[i].num_dbinfo; j++) - { - if (dbmt_user->user_info[i].dbinfo[j].dbname[0] == '\0') - { - continue; - } - fprintf (fp, "%s:%s;%s;%s\n", - dbmt_user->user_info[i].dbinfo[j].dbname, - dbmt_user->user_info[i].dbinfo[j].auth, - dbmt_user->user_info[i].dbinfo[j].uid, - dbmt_user->user_info[i].dbinfo[j].broker_address); - } - fprintf (fp, "%s%s\n", ARNIADB_PASS_CLOSE_TAG, - dbmt_user->user_info[i].user_name); - } - fclose (fp); - - lock_fd = uCreateLockFile (conf_get_dbmt_file (FID_LOCK_DBMT_PASS, strbuf)); - if (lock_fd < 0) - { - unlink (tmpfile); - return ERR_TMPFILE_OPEN_FAIL; - } - move_file (tmpfile, conf_get_dbmt_file (FID_DBMT_ARNIADB_PASS, strbuf)); - uRemoveLockFile (lock_fd); - - return ERR_NO_ERROR; -} - -void -dbmt_user_set_dbinfo (T_DBMT_USER_DBINFO *dbinfo, const char *dbname, - const char *auth, const char *uid, - const char *broker_address) -{ - strcpy_limit (dbinfo->dbname, dbname, sizeof (dbinfo->dbname)); - strcpy_limit (dbinfo->auth, auth, sizeof (dbinfo->auth)); - strcpy_limit (dbinfo->uid, uid, sizeof (dbinfo->uid)); - if (broker_address == NULL) - { - dbinfo->broker_address[0] = '\0'; - } - else - { - strcpy_limit (dbinfo->broker_address, broker_address, - sizeof (dbinfo->broker_address)); - } -} - -void -dbmt_user_set_authinfo (T_DBMT_USER_AUTHINFO *authinfo, const char *domain, - const char *auth) -{ - strcpy_limit (authinfo->domain, domain, sizeof (authinfo->domain)); - strcpy_limit (authinfo->auth, auth, sizeof (authinfo->auth)); -} - -void -dbmt_user_set_userinfo (T_DBMT_USER_INFO *usrinfo, const char *user_name, - const char *user_passwd, int num_authinfo, - T_DBMT_USER_AUTHINFO *authinfo, int num_dbinfo, - T_DBMT_USER_DBINFO *dbinfo) -{ - strcpy_limit (usrinfo->user_name, user_name, sizeof (usrinfo->user_name)); - strcpy_limit (usrinfo->user_passwd, user_passwd, sizeof (usrinfo->user_passwd)); - usrinfo->num_authinfo = num_authinfo; - usrinfo->authinfo = authinfo; - usrinfo->num_dbinfo = num_dbinfo; - usrinfo->dbinfo = dbinfo; -} - -int -dbmt_user_search (T_DBMT_USER_INFO *user_info, const char *dbname) -{ - int i; - - for (i = 0; i < user_info->num_dbinfo; i++) - { - if (strcmp (user_info->dbinfo[i].dbname, dbname) == 0) - { - return i; - } - } - - return -1; -} - -int -dbmt_user_write_pass (T_DBMT_USER *dbmt_user, char *_dbmt_error) -{ - char tmpfile[512], strbuf[1024]; - FILE *fp; - int i, lock_fd; - -#if !defined (DO_NOT_USE_ARNIADBENV) - sprintf (tmpfile, "%s/tmp/DBMT_util_pass.%d", sco.szArniadb, (int) getpid ()); -#else - sprintf (tmpfile, "%s/DBMT_util_pass.%d", ARNIADB_TMPDIR, (int) getpid ()); -#endif - - fp = fopen (tmpfile, "w"); - if (fp == NULL) - { - return ERR_TMPFILE_OPEN_FAIL; - } - for (i = 0; i < dbmt_user->num_dbmt_user; i++) - { - if (dbmt_user->user_info[i].user_name[0] == '\0') - { - continue; - } - fprintf (fp, "%s:%s\n", dbmt_user->user_info[i].user_name, - dbmt_user->user_info[i].user_passwd); - } - fclose (fp); - - lock_fd = uCreateLockFile (conf_get_dbmt_file (FID_LOCK_DBMT_PASS, strbuf)); - if (lock_fd < 0) - { - unlink (tmpfile); - return ERR_TMPFILE_OPEN_FAIL; - } - move_file (tmpfile, conf_get_dbmt_file (FID_DBMT_PASS, strbuf)); - uRemoveLockFile (lock_fd); - - return ERR_NO_ERROR; -} - -void -dbmt_user_db_delete (T_DBMT_USER *dbmt_user, char *dbname) -{ - int i, j; - - for (i = 0; i < dbmt_user->num_dbmt_user; i++) - { - for (j = 0; j < dbmt_user->user_info[i].num_dbinfo; j++) - { - if (strcmp (dbmt_user->user_info[i].dbinfo[j].dbname, dbname) == 0) - { - dbmt_user->user_info[i].dbinfo[j].dbname[0] = '\0'; - } - } - } -} - -int -dbmt_user_add_dbinfo (T_DBMT_USER_INFO *usrinfo, T_DBMT_USER_DBINFO *dbinfo) -{ - int i = usrinfo->num_dbinfo; - - usrinfo->dbinfo = - (T_DBMT_USER_DBINFO *) increase_capacity (usrinfo->dbinfo, - sizeof (T_DBMT_USER_DBINFO), - i, i + 1); - if (usrinfo->dbinfo == NULL) - { - return ERR_MEM_ALLOC; - } - i++; - usrinfo->num_dbinfo = i; - for (i--; i >= 1; i--) - { - usrinfo->dbinfo[i] = usrinfo->dbinfo[i - 1]; - } - usrinfo->dbinfo[0] = *dbinfo; - - return ERR_NO_ERROR; -} - -int -dbmt_user_new_token_info (const char *user_id, - const char *user_ip, - const char *user_port, const char *token_enc, -#ifdef WINDOWS - HANDLE proc_id, -#else - pid_t proc_id, -#endif - time_t login_time) -{ - T_USER_TOKEN_INFO *end_node; - T_USER_TOKEN_INFO *new_node; - - if (! (new_node = dbmt_user_search_token_info (user_id))) - { - new_node = (T_USER_TOKEN_INFO *) malloc (sizeof (T_USER_TOKEN_INFO)); - if (new_node == NULL) - { - return ERR_MEM_ALLOC; - } - - if (user_token_info == NULL) - { - end_node = user_token_info = new_node; - } - else - { - end_node = user_token_info->prev; - } - end_node->next = new_node; - new_node->next = user_token_info; - new_node->prev = end_node; - user_token_info->prev = new_node; - } - - strncpy (new_node->user_id, user_id, DBMT_USER_NAME_LEN); - strncpy (new_node->user_ip, user_ip, 20); - strncpy (new_node->user_port, user_port, 10); - strncpy (new_node->token, token_enc, TOKEN_ENC_LENGTH); - new_node->proc_id = proc_id; - new_node->login_time = login_time; - - return ERR_NO_ERROR; -} - -T_USER_TOKEN_INFO * -dbmt_user_search_token_info (const char *user_id) -{ - T_USER_TOKEN_INFO *head = user_token_info; - - if (user_id == NULL) - { - return NULL; - } - - if (head == NULL) - { - ut_access_log (NULL, "user_token_info is null."); - return NULL; - } - - do - { - if (!strcmp (head->user_id, user_id)) - { - return head; - } - - head = head->next; - - } - while (head != user_token_info); - - return NULL; -} - -T_USER_TOKEN_INFO * -dbmt_user_search_token_info_by_token (const char *token) -{ - T_USER_TOKEN_INFO *head = user_token_info; - - if (token == NULL) - { - return NULL; - } - - if (head == NULL) - { - ut_access_log (NULL, "user_token_info is null."); - return NULL; - } - - do - { - if (!strcmp (head->token, token)) - { - return head; - } - - head = head->next; - - } - while (head != user_token_info); - - return NULL; - -} - -T_USER_TOKEN_INFO * -dbmt_user_delete_token_info (const char *user_id) -{ - T_USER_TOKEN_INFO *removed_node = NULL; - - if (user_id == NULL) - { - return NULL; - } - - - if ((removed_node = dbmt_user_search_token_info (user_id)) == NULL) - { - return NULL; - } - - if (removed_node == user_token_info) - { - if (user_token_info->next != user_token_info) - { - user_token_info = user_token_info->next; - } - else - { - user_token_info = NULL; - } - } - - removed_node->prev->next = removed_node->next; - removed_node->next->prev = removed_node->prev; - - return removed_node; - -} - -T_USER_TOKEN_INFO * -dbmt_user_delete_token_info_by_token (const char *token) -{ - T_USER_TOKEN_INFO *removed_node = NULL; - - if (token == NULL) - { - return NULL; - } - - if ((removed_node = dbmt_user_search_token_info_by_token (token)) == NULL) - { - return NULL; - } - - if (removed_node == user_token_info) - { - if (user_token_info->next != user_token_info) - { - user_token_info = user_token_info->next; - } - else - { - user_token_info = NULL; - } - - } - - removed_node->prev->next = removed_node->next; - removed_node->next->prev = removed_node->prev; - - return removed_node; - -} diff --git a/server/src/cm_user.h b/server/src/cm_user.h deleted file mode 100644 index 6165284..0000000 --- a/server/src/cm_user.h +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. - * - * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/* - * cm_user.h - - */ - -#ifndef _CM_USER_H_ -#define _CM_USER_H_ - -#define DBMT_USER_NAME_LEN 64 - -typedef struct -{ - char dbname[DBMT_USER_NAME_LEN]; - char auth[16]; - char uid[32]; - char broker_address[64]; -} T_DBMT_USER_DBINFO; - -typedef struct -{ - char domain[DBMT_USER_NAME_LEN]; - char auth[16]; -} T_DBMT_USER_AUTHINFO; - -typedef struct -{ - char user_name[DBMT_USER_NAME_LEN]; - char user_passwd[80]; - int num_authinfo; - int num_dbinfo; - T_DBMT_USER_AUTHINFO *authinfo; - T_DBMT_USER_DBINFO *dbinfo; -} T_DBMT_USER_INFO; - -typedef struct -{ - int num_dbmt_user; - T_DBMT_USER_INFO *user_info; -} T_DBMT_USER; - -typedef struct T_USER_TOKEN_INFO T_USER_TOKEN_INFO; - -struct T_USER_TOKEN_INFO -{ - char user_id[DBMT_USER_NAME_LEN]; - char user_ip[20]; - char user_port[10]; -#ifdef WINDOWS - HANDLE proc_id; -#else - pid_t proc_id; -#endif - time_t login_time; - - char token[TOKEN_ENC_LENGTH]; - - T_USER_TOKEN_INFO *next; - T_USER_TOKEN_INFO *prev; - -}; - -int dbmt_user_read (T_DBMT_USER *dbmt_user, char *_dbmt_error); -void dbmt_user_free (T_DBMT_USER *dbmt_user); -int dbmt_user_write_auth (T_DBMT_USER *dbmt_user, char *_dbmt_error); -int dbmt_user_write_pass (T_DBMT_USER *dbmt_user, char *_dbmt_error); -void dbmt_user_set_dbinfo (T_DBMT_USER_DBINFO *dbinfo, const char *dbname, - const char *auth, const char *uid, const char *broker_address); -void dbmt_user_set_authinfo (T_DBMT_USER_AUTHINFO *authinfo, - const char *domain, const char *auth); -void dbmt_user_set_userinfo (T_DBMT_USER_INFO *usrinfo, - const char *user_name, const char *user_passwd, - int num_authinfo, T_DBMT_USER_AUTHINFO *authinfo, - int num_dbinfo, T_DBMT_USER_DBINFO *dbinfo); -int dbmt_user_search (T_DBMT_USER_INFO *user_info, const char *dbname); -void dbmt_user_db_delete (T_DBMT_USER *dbmt_user, char *dbname); -int dbmt_user_add_dbinfo (T_DBMT_USER_INFO *usrinfo, - T_DBMT_USER_DBINFO *dbinfo); - -int dbmt_user_new_token_info (const char *user_id, - const char *user_ip, const char *user_port, - const char *token_enc, -#ifdef WINDOWS - HANDLE proc_id, -#else - pid_t proc_id, -#endif - time_t login_time); - -T_USER_TOKEN_INFO *dbmt_user_search_token_info (const char *user_id); -T_USER_TOKEN_INFO *dbmt_user_search_token_info_by_token (const char *token); -T_USER_TOKEN_INFO *dbmt_user_delete_token_info (const char *user_id); -T_USER_TOKEN_INFO *dbmt_user_delete_token_info_by_token (const char *token); - -#endif /* _CM_USER_H_ */ diff --git a/server/src/cm_win_wsa.c b/server/src/cm_win_wsa.c deleted file mode 100644 index 6498801..0000000 --- a/server/src/cm_win_wsa.c +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. - * - * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/* - * wsa_init.c - - */ - -#ident "$Id$" - -#include -#include - -int -wsa_initialize () -{ - WORD wVersionRequested; - WSADATA wsaData; - int err; - - wVersionRequested = MAKEWORD (1, 1); - - err = WSAStartup (wVersionRequested, &wsaData); - - if (err != 0) - { - return -1; - } - - /* Confirm that the Windows Sockets DLL supports 1.1. */ - /* Note that if the DLL supports versions greater */ - /* than 1.1 in addition to 1.1, it will still return */ - /* 1.1 in wVersion since that is the version we */ - /* requested. */ - if (LOBYTE (wsaData.wVersion) != 1 || HIBYTE (wsaData.wVersion) != 1) - { - WSACleanup (); - return -1; - } - /* The Windows Sockets DLL is acceptable. Proceed. */ - - - /* Make sure that the version requested is >= 1.1. */ - /* The low byte is the major version and the high */ - /* byte is the minor version. */ - if (LOBYTE (wVersionRequested) < 1 || - (LOBYTE (wVersionRequested) == 1 && HIBYTE (wVersionRequested) < 1)) - { - return -1; - } - /* Since we only support 1.1, set both wVersion and */ - /* wHighVersion to 1.1. */ - /* - lpWsaData->wVersion = MAKEWORD( 1, 1 ); - lpWsaData->wHighVersion = MAKEWORD( 1, 1 ); - */ - - return 0; -} diff --git a/server/src/cm_win_wsa.h b/server/src/cm_win_wsa.h deleted file mode 100644 index 140227a..0000000 --- a/server/src/cm_win_wsa.h +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. - * - * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - - -/* - * cm_wsa_init.h - - */ - -#ifndef _CM_WSA_INIT_H_ -#define _CM_WSA_INIT_H_ - -#ident "$Id$" - -/* - * IMPORTED SYSTEM HEADER FILES - */ - -/* - * IMPORTED OTHER HEADER FILES - */ - -/* - * EXPORTED DEFINITIONS - */ - -/* - * EXPORTED TYPE DEFINITIONS - */ - -/* - * EXPORTED FUNCTION PROTOTYPES - */ -#ifdef __cplusplus -extern "C" -{ -#endif - -int wsa_initialize (); - -#ifdef __cplusplus -} -#endif -/* - * EXPORTED VARIABLES - */ - -#endif /* _CM_WSA_INIT_H_ */ diff --git a/server/test/Makefile b/server/test/Makefile index 60d6cec..44f59d9 100644 --- a/server/test/Makefile +++ b/server/test/Makefile @@ -1,9 +1,9 @@ CUR_PATH=$(shell /bin/pwd) -COVERAGE_PATH=../cmserver/ +COVERAGE_PATH=../amserver/ test: python test_cci.py - /usr/bin/php -q test_tasks.php ./log/test_cmserver.xml + /usr/bin/php -q test_tasks.php ./log/test_amserver.xml g++ -o sendfile sendfile.cpp ./sendfile task_test_case/jobfile task_test_case/jobfile.zip python test_tasks.py diff --git a/server/test/cm_mon_data/dump_data.py b/server/test/cm_mon_data/dump_data.py deleted file mode 100644 index eef9a4d..0000000 --- a/server/test/cm_mon_data/dump_data.py +++ /dev/null @@ -1,113 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -import struct -import json -import time -import sys - - -metric = "vol_freespace" -dtype = "monthly" -bname = "query_editor" -dbname = "demodb" -volname = "demodb" - -# globe -dpath = "/home/liuhj/ARNIADB/var/manager/mon_data/" - - -def dump_mod_data(filename, pos, size): - data = [] - fp = open(filename, "rb") - fp.seek(pos, 0) - for i in range(size): - a, = struct.unpack("i", fp.read(4)) - data.append(a) - return data - -def dump_daily(mon_file, meta, m_len, m_idx, blk_idx): - pos = blk_idx * (3600*24/meta["k_interval"] + 24*30 + 365) * m_len * 4 - daily_data = dump_mod_data(mon_file, pos, 3600 * 24 / meta["k_interval"] * m_len) - - sec = int(time.time()) - - read_idx = (sec % (3600 * 24))/meta["k_interval"] - - for i in range(read_idx): - #print daily_data[i*m_len + m_idx], - #print "read_idx:" + str(i), - for j in range(m_len): - print daily_data[i*m_len + j], - print "\n", - - # daily diff - #prev = daily_data[m_idx] - #for i in range(1, read_idx): - # now = daily_data[i*m_len + m_idx] - # print (now - prev)/meta["k_interval"], - # if now < prev: - # print i, now, prev - # raw_input() - # prev = now - -def dump_monthly(mon_file, meta, m_len, m_idx, blk_idx): - pos = (blk_idx * (3600*24/meta["k_interval"] + 24*30 + 365) + 3600*24/meta["k_interval"]) * m_len * 4 - dump_data = dump_mod_data(mon_file, pos, 30*24*m_len) - sec = int(time.time()) - read_idx = (sec % (30 *3600 * 24))/3600 - #for i in range(read_idx): - for i in range(30 * 24): - for j in range(m_len): - print dump_data[i*m_len + j], - print "\n", - #print dump_data[i*m_len + m_idx], - #print i, dump_data[i*m_len + m_idx] - -def dump_yearly(mon_file, meta, m_len, m_idx, blk_idx): - pos = (blk_idx * (3600*24/meta["k_interval"] + 24*30 + 365) + 3600*24/meta["k_interval"] + 30 * 24) * m_len * 4 - dump_data = dump_mod_data(mon_file, pos, 365*m_len) - sec = int(time.time()) - read_idx = (sec % (365 * 3600 * 24))/(3600 * 24) - for i in range(read_idx): - print i, dump_data[i*m_len + m_idx] - - -if __name__ == '__main__': - meta = json.load(open(dpath + "meta.json", "r")) - if "os_" == metric[0:3]: - mon_file = dpath + "os_mon" - blk_idx = 0 - m_idx = meta["k_os_metrics"][metric] - m_len = len(meta["k_os_metrics"]) - elif "broker_" == metric[0:7]: - mon_file = dpath + "broker_mon" - blk_idx = meta["k_broker_rrd"][bname + "_idx"] - m_idx = meta["k_broker_metrics"][metric] - m_len = len(meta["k_broker_metrics"]) - elif "db_" == metric[0:3]: - mon_file = dpath + "db_mon" - blk_idx = meta["k_db_rrd"][dbname + "_idx"] - m_idx = meta["k_db_metrics"][metric] - m_len = len(meta["k_db_metrics"]) - elif "vol_" == metric[0:4]: - mon_file = dpath + "vol_mon" - blk_idx = meta["k_db_rrd"][dbname + "_vol"][volname] - m_idx = 0 - m_len = 2 - else: - print "metric is needed" - sys.exit(1) - - if dtype == "daily": - dump_daily(mon_file, meta, m_len, m_idx, blk_idx) - - elif dtype == "monthly": - dump_monthly(mon_file, meta, m_len, m_idx, blk_idx) - elif dtype == "yearly": - dump_yearly(mon_file, meta, m_len, m_idx, blk_idx) - else: - print "dtype is needed" - sys.exit(1) - - diff --git a/server/test/hudsonbuild.sh b/server/test/hudsonbuild.sh index d929171..29f2050 100644 --- a/server/test/hudsonbuild.sh +++ b/server/test/hudsonbuild.sh @@ -5,14 +5,14 @@ mkdir -p log arn_js stop arn_auto stop -valgrind --leak-check=full --log-file=./log/cmserver_auto.valgrind.log arn_auto start -valgrind --leak-check=full --log-file=./log/cmserver_js.valgrind.log arn_js start +valgrind --leak-check=full --log-file=./log/amserver_auto.valgrind.log arn_auto start +valgrind --leak-check=full --log-file=./log/amserver_js.valgrind.log arn_js start -arn_cmserver stop +arn_amserver stop sleep 3 -valgrind --leak-check=full --log-file=./log/cmserver_cmserver.valgrind.log arn_cmserver start +valgrind --leak-check=full --log-file=./log/amserver_amserver.valgrind.log arn_amserver start -sed -i -e '/invalid file descriptor .* in syscall close/d' -e '/to select an alternative log fd/d' ./log/cmserver_*.valgrind.log* +sed -i -e '/invalid file descriptor .* in syscall close/d' -e '/to select an alternative log fd/d' ./log/amserver_*.valgrind.log* arniadb deletedb anotherdb #remove legacy test database arniadb deletedb alatestdb #remove legacy test database diff --git a/server/test/task_list.txt b/server/test/task_list.txt index b4f3f7a..20ce992 100644 --- a/server/test/task_list.txt +++ b/server/test/task_list.txt @@ -4,7 +4,7 @@ setdbmtpasswd_admin login_errver setloglevel -getcmsenv +getamsenv getprocstat getsysdiskinfo startinfo diff --git a/server/test/task_test_case_json/getcmsenv.txt b/server/test/task_test_case_json/getcmsenv.txt deleted file mode 100644 index c3f9261..0000000 --- a/server/test/task_test_case_json/getcmsenv.txt +++ /dev/null @@ -1,2 +0,0 @@ -{"task":"getcmsenv", -"token":"cdfb4c5717170c5e9c6856b4d1c61ee8132bcc7d82bd609066ed9ece2554c47f7926f07dd201b6aa"} \ No newline at end of file diff --git a/server/test/task_test_config/cm_conf/arniadb_broker.conf b/server/test/task_test_config/cm_conf/arniadb_broker.conf deleted file mode 100644 index 0ef306f..0000000 --- a/server/test/task_test_config/cm_conf/arniadb_broker.conf +++ /dev/null @@ -1,50 +0,0 @@ - -# -# Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. -# -# 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; version 2 of the License. -# -# 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 Street, Fifth Floor, Boston, MA 02110-1301, USA -# - -[broker] -MASTER_SHM_ID =30001 -ADMIN_LOG_FILE =log/broker/arniadb_broker.log - -[%query_editor] -SERVICE =ON -BROKER_PORT =30000 -MIN_NUM_APPL_SERVER =5 -MAX_NUM_APPL_SERVER =40 -APPL_SERVER_SHM_ID =30000 -LOG_DIR =log/broker/sql_log -ERROR_LOG_DIR =log/broker/error_log -SQL_LOG =ON -TIME_TO_KILL =120 -SESSION_TIMEOUT =300 -KEEP_CONNECTION =AUTO -CCI_DEFAULT_AUTOCOMMIT =ON - -[%BROKER1] -SERVICE =ON -BROKER_PORT =33000 -MIN_NUM_APPL_SERVER =5 -MAX_NUM_APPL_SERVER =40 -APPL_SERVER_SHM_ID =33000 -LOG_DIR =log/broker/sql_log -ERROR_LOG_DIR =log/broker/error_log -SQL_LOG =ON -TIME_TO_KILL =120 -SESSION_TIMEOUT =300 -KEEP_CONNECTION =AUTO -CCI_DEFAULT_AUTOCOMMIT =ON - diff --git a/server/test/task_test_config/cm_conf/autoaddvoldb.conf b/server/test/task_test_config/cm_conf/autoaddvoldb.conf deleted file mode 100644 index 7c1c989..0000000 --- a/server/test/task_test_config/cm_conf/autoaddvoldb.conf +++ /dev/null @@ -1,4 +0,0 @@ -# -demodb ON 2 200 ON 2 200 -demodb ON 2 200 ON 2 200 -destinationdb ON 2 200 ON 2 200 \ No newline at end of file diff --git a/server/test/task_test_config/cm_conf/autobackupdb.conf b/server/test/task_test_config/cm_conf/autobackupdb.conf deleted file mode 100644 index fe75fa4..0000000 --- a/server/test/task_test_config/cm_conf/autobackupdb.conf +++ /dev/null @@ -1,14 +0,0 @@ -#db-name bk-id path peroid date time level -testdb1 1 log Weekly Saturday 0 0 ON ON ON ON y y 0 1 -testdb1 1 log Weekly Sunday 0 0 ON ON ON ON y y 0 1 -testdb1 1 log Weekly Monday 0 0 ON ON ON ON y y 0 1 -testdb1 1 log Weekly Tuesday 0 0 ON ON ON ON y y 0 1 -testdb1 1 log Weekly Wednesday 0 0 ON ON ON ON y y 0 1 -testdb1 1 log Weekly Thursday 0 0 ON ON ON ON y y 0 1 -testdb1 1 log Weekly Friday 0 0 ON ON ON ON y y 0 1 -testdb1 1 log Weekly Otherday 0 0 ON ON ON ON y y 0 1 -testdb3 1 log Monthly 1 0 0 ON ON ON ON y y 0 1 -testdb3 1 log Daily nothing 0 0 ON ON ON ON y y 0 1 -testdb3 1 log Hourly 1 0 0 ON ON ON ON y y 0 1 -testdb3 1 log Special 1 0 0 ON ON ON ON y y 0 1 -testdb3 1 log Other 1 0 0 ON ON ON ON y y 0 1 diff --git a/server/test/task_test_config/cm_conf/autoexecquery.conf b/server/test/task_test_config/cm_conf/autoexecquery.conf deleted file mode 100644 index 7d25a11..0000000 --- a/server/test/task_test_config/cm_conf/autoexecquery.conf +++ /dev/null @@ -1,11 +0,0 @@ -# -test1 1 dba "" admin WEEK SUN "select * form code;" -test1 1 dba 1 admin WEEK MON "select * form code;" -test1 1 dba 1 admin WEEK TUE "select * form code;" -test1 1 dba 1 admin WEEK WED "select * form code;" -test1 1 dba 1 admin WEEK THU "select * form code;" -test1 1 dba 1 admin WEEK FRI "select * form code;" -test1 1 dba 1 yifan WEEK SAT "select * form code;" -test1 1 dba 1 admin ONE MON "select * form code;" -test1 1 dba 1 admin DAY MON "select * form code;" -test1 1 dba 1 admin MONTH 1 "select * form code;" \ No newline at end of file diff --git a/server/test/task_test_config/cm_conf/autohistory.conf b/server/test/task_test_config/cm_conf/autohistory.conf deleted file mode 100644 index 45c5963..0000000 --- a/server/test/task_test_config/cm_conf/autohistory.conf +++ /dev/null @@ -1,2 +0,0 @@ -#switch start time - end time mem cpu -ON 2012 6 10 0 0 0 2012 6 11 0 0 0 100.0 100.0 \ No newline at end of file diff --git a/server/test/task_test_config/cm_conf/cm.conf b/server/test/task_test_config/cm_conf/cm.conf deleted file mode 100644 index 7f35e03..0000000 --- a/server/test/task_test_config/cm_conf/cm.conf +++ /dev/null @@ -1,48 +0,0 @@ -# cm.conf -# -- ARNIADB database management tool server configuration file -# -# -# When server starts, it looks for the environment variable -# 'ARNIADB_MANAGER' and use it to locate this file. It is assumed that -# 'ARNIADB_MANAGER' is the root directory of all ARNIADB Manager related files. -# - -# -# Port number designation -# -cm_port=8001 -port_job_server=8002 -port_auto_server=8001 -# -# Monitoring interval setting -# -monitor_interval=1 - -# -# Allowing Multiple connection with one ARNIADB Manager user. -# -allow_user_multi_connection=YES -allow_user_multi_connection=NO - -auto_start_broker=yes -auto_start_broker=no - -concurrent_thread_num=8 -concurrent_thread_num=100 - -support_web_manager=1 - -############################### -# diagnostics parameter -############################### -# -# turn on/off diag -# -#execute_diag=ON - -# -# server long query time (sec) -# -server_long_query_time=10 - -error_log=log/arniadb_error.log diff --git a/server/test/task_test_config/cm_conf/cm.pass b/server/test/task_test_config/cm_conf/cm.pass deleted file mode 100644 index 58ecec1..0000000 --- a/server/test/task_test_config/cm_conf/cm.pass +++ /dev/null @@ -1 +0,0 @@ -admin:6e85f0f80f030451dc9e98851098dfb2 diff --git a/server/test/test_cci.py b/server/test/test_cci.py index f8af68c..3aacd39 100644 --- a/server/test/test_cci.py +++ b/server/test/test_cci.py @@ -3,7 +3,7 @@ import json import struct -cmsip="localhost" +amsip="localhost" port=8003 url="/cci" @@ -41,7 +41,7 @@ def exec_task(ip, port, url, body): def do_task(task): json_cci["task"] = task - response = exec_task(cmsip, port, url, str(json.dumps(json_cci))) + response = exec_task(amsip, port, url, str(json.dumps(json_cci))) return response do_task("unknowntask") diff --git a/server/test/test_tasks.php b/server/test/test_tasks.php index 844aaa1..ad37adb 100644 --- a/server/test/test_tasks.php +++ b/server/test/test_tasks.php @@ -497,7 +497,7 @@ function print_test_suites($ntests, $ntests_failed, $time_elapsed, $result_arr) { global $outfp; - $classname = "CMSERVER_TEST"; + $classname = "AMSERVER_TEST"; fwrite($outfp, ""); diff --git a/server/test/test_tasks.py b/server/test/test_tasks.py index 8336532..97154e8 100644 --- a/server/test/test_tasks.py +++ b/server/test/test_tasks.py @@ -22,8 +22,8 @@ def findport(): continue return line[idx:][idx1+1:idx2] -#cmsip="192.168.0.1" -cmsip="localhost" +#amsip="192.168.0.1" +amsip="localhost" port=int(findport()) url="/cm_api" testdir="task_test_case_json/" @@ -52,7 +52,7 @@ def do_one_job(taskfile, token): if list == type(request): for req in request: req["token"] = token - response = exec_task(cmsip, port, url, json.dumps(req)) + response = exec_task(amsip, port, url, json.dumps(req)) data=json.loads(response.decode()) if data["status"] == "failure": print (data["task"] + " : " + '\033[31m{0}\033[0m'.format(data["note"])) @@ -61,7 +61,7 @@ def do_one_job(taskfile, token): else: req = request req["token"] = token - response = exec_task(cmsip, port, url, json.dumps(req)) + response = exec_task(amsip, port, url, json.dumps(req)) data=json.loads(response.decode()) if data["status"] == "failure": print (data["task"] + " : " + '\033[31m{0}\033[0m'.format(data["note"])) @@ -90,7 +90,7 @@ def init_env(): request = load_task(testdir+"/login.txt") passwd = raw_input("Please input the passwd for %s: " %(request["id"])) request["password"] = passwd - response = exec_task(cmsip, port, url, json.dumps(request)) + response = exec_task(amsip, port, url, json.dumps(request)) data=json.loads(response.decode()) if data["status"] == "failure": print (data["task"] + " : " + '\033[31m{0}\033[0m'.format(data["note"])) @@ -108,4 +108,4 @@ def init_env(): #do_one_job("task_json/renamedb.txt", token) do_all_jobs(token) -exec_task(cmsip, port, "/upload", "") +exec_task(amsip, port, "/upload", "") diff --git a/server/win/arn_manager/arn_manager.vcproj b/server/win/arn_manager/arn_manager.vcproj index a7fe77f..64d8ba6 100644 --- a/server/win/arn_manager/arn_manager.vcproj +++ b/server/win/arn_manager/arn_manager.vcproj @@ -65,7 +65,7 @@ /> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/server/win/cm_admin/resource.h b/server/win/cm_admin/resource.h deleted file mode 100644 index b33ffd3..0000000 --- a/server/win/cm_admin/resource.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. - * - * 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; version 2 of the License. - * - * 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 Street, Fifth Floor, Boston, MA 02110-1301, USA - * - */ - -//{{NO_DEPENDENCIES}} -// Microsoft Visual C++ generated include file. -// Used by version.rc - -// ´ÙÀ½Àº »õ °³Ã¼¿¡ »ç¿ëÇÒ ±âº»°ªÀÔ´Ï´Ù. -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 101 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1001 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif diff --git a/server/win/cm_admin/version.rc b/server/win/cm_admin/version.rc deleted file mode 100644 index 22405bb..0000000 --- a/server/win/cm_admin/version.rc +++ /dev/null @@ -1,103 +0,0 @@ -// Microsoft Visual C++ generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "afxres.h" -#include "../version.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// Çѱ¹¾î resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_KOR) -#ifdef _WIN32 -LANGUAGE LANG_KOREAN, SUBLANG_DEFAULT -#pragma code_page(949) -#endif //_WIN32 - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE -BEGIN - "#include ""afxres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION MAJOR_VERSION,MINOR_VERSION,PATCH_VERSION,BUILD_SERIAL_NUMBER - PRODUCTVERSION MAJOR_VERSION,MINOR_VERSION,PATCH_VERSION,BUILD_SERIAL_NUMBER - FILEFLAGSMASK 0x17L -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x4L - FILETYPE 0x1L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "041204b0" - BEGIN - VALUE "CompanyName", "Search Solution Corporation" - VALUE "FileDescription", "ARNIADB Management Server" - VALUE "FileVersion", VERSION_STRING - VALUE "InternalName", "ARNIADB Management Server" - VALUE "LegalCopyright", "Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution." - VALUE "OriginalFilename", "cm_admin.exe" - VALUE "ProductName", "ARNIADB Management Server" - VALUE "ProductVersion", VERSION_STRING - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x412, 1200 - END -END - -#endif // Çѱ¹¾î resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - diff --git a/server/win/cmserver.sln b/server/win/cmserver.sln deleted file mode 100644 index ce5210f..0000000 --- a/server/win/cmserver.sln +++ /dev/null @@ -1,63 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "install", "install\install.vcproj", "{4767EEE0-220E-4FDE-8788-0E8BAE173CE1}" - ProjectSection(ProjectDependencies) = postProject - {9A6A101D-4569-4BC7-9010-9E4554D7E945} = {9A6A101D-4569-4BC7-9010-9E4554D7E945} - {1E764BE7-D450-4166-8F62-4FD1967F5AD8} = {1E764BE7-D450-4166-8F62-4FD1967F5AD8} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "arn_manager", "arn_manager\arn_manager.vcproj", "{1E764BE7-D450-4166-8F62-4FD1967F5AD8}" - ProjectSection(ProjectDependencies) = postProject - {FB6ECD68-F1C6-42A7-8EB7-5BCBF151D718} = {FB6ECD68-F1C6-42A7-8EB7-5BCBF151D718} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "jsoncpp", "..\external\jsoncpp\vs\jsoncpp.vcproj", "{FB6ECD68-F1C6-42A7-8EB7-5BCBF151D718}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "cm_admin", "cm_admin\cm_admin.vcproj", "{9A6A101D-4569-4BC7-9010-9E4554D7E945}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Win32 = Debug|Win32 - Debug|x64 = Debug|x64 - Release|Win32 = Release|Win32 - Release|x64 = Release|x64 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {4767EEE0-220E-4FDE-8788-0E8BAE173CE1}.Debug|Win32.ActiveCfg = Debug|Win32 - {4767EEE0-220E-4FDE-8788-0E8BAE173CE1}.Debug|Win32.Build.0 = Debug|Win32 - {4767EEE0-220E-4FDE-8788-0E8BAE173CE1}.Debug|x64.ActiveCfg = Debug|x64 - {4767EEE0-220E-4FDE-8788-0E8BAE173CE1}.Debug|x64.Build.0 = Debug|x64 - {4767EEE0-220E-4FDE-8788-0E8BAE173CE1}.Release|Win32.ActiveCfg = Release|Win32 - {4767EEE0-220E-4FDE-8788-0E8BAE173CE1}.Release|Win32.Build.0 = Release|Win32 - {4767EEE0-220E-4FDE-8788-0E8BAE173CE1}.Release|x64.ActiveCfg = Release|x64 - {4767EEE0-220E-4FDE-8788-0E8BAE173CE1}.Release|x64.Build.0 = Release|x64 - {1E764BE7-D450-4166-8F62-4FD1967F5AD8}.Debug|Win32.ActiveCfg = Debug|Win32 - {1E764BE7-D450-4166-8F62-4FD1967F5AD8}.Debug|Win32.Build.0 = Debug|Win32 - {1E764BE7-D450-4166-8F62-4FD1967F5AD8}.Debug|x64.ActiveCfg = Debug|x64 - {1E764BE7-D450-4166-8F62-4FD1967F5AD8}.Debug|x64.Build.0 = Debug|x64 - {1E764BE7-D450-4166-8F62-4FD1967F5AD8}.Release|Win32.ActiveCfg = Release|Win32 - {1E764BE7-D450-4166-8F62-4FD1967F5AD8}.Release|Win32.Build.0 = Release|Win32 - {1E764BE7-D450-4166-8F62-4FD1967F5AD8}.Release|x64.ActiveCfg = Release|x64 - {1E764BE7-D450-4166-8F62-4FD1967F5AD8}.Release|x64.Build.0 = Release|x64 - {FB6ECD68-F1C6-42A7-8EB7-5BCBF151D718}.Debug|Win32.ActiveCfg = Debug|Win32 - {FB6ECD68-F1C6-42A7-8EB7-5BCBF151D718}.Debug|Win32.Build.0 = Debug|Win32 - {FB6ECD68-F1C6-42A7-8EB7-5BCBF151D718}.Debug|x64.ActiveCfg = Debug|x64 - {FB6ECD68-F1C6-42A7-8EB7-5BCBF151D718}.Debug|x64.Build.0 = Debug|x64 - {FB6ECD68-F1C6-42A7-8EB7-5BCBF151D718}.Release|Win32.ActiveCfg = Release|Win32 - {FB6ECD68-F1C6-42A7-8EB7-5BCBF151D718}.Release|Win32.Build.0 = Release|Win32 - {FB6ECD68-F1C6-42A7-8EB7-5BCBF151D718}.Release|x64.ActiveCfg = Release|x64 - {FB6ECD68-F1C6-42A7-8EB7-5BCBF151D718}.Release|x64.Build.0 = Release|x64 - {9A6A101D-4569-4BC7-9010-9E4554D7E945}.Debug|Win32.ActiveCfg = Debug|Win32 - {9A6A101D-4569-4BC7-9010-9E4554D7E945}.Debug|Win32.Build.0 = Debug|Win32 - {9A6A101D-4569-4BC7-9010-9E4554D7E945}.Debug|x64.ActiveCfg = Debug|x64 - {9A6A101D-4569-4BC7-9010-9E4554D7E945}.Debug|x64.Build.0 = Debug|x64 - {9A6A101D-4569-4BC7-9010-9E4554D7E945}.Release|Win32.ActiveCfg = Release|Win32 - {9A6A101D-4569-4BC7-9010-9E4554D7E945}.Release|Win32.Build.0 = Release|Win32 - {9A6A101D-4569-4BC7-9010-9E4554D7E945}.Release|x64.ActiveCfg = Release|x64 - {9A6A101D-4569-4BC7-9010-9E4554D7E945}.Release|x64.Build.0 = Release|x64 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/server/win/install/install.bat b/server/win/install/install.bat index cc0abb8..a759d61 100644 --- a/server/win/install/install.bat +++ b/server/win/install/install.bat @@ -14,12 +14,12 @@ mkdir %DEST_DIR%\conf copy %SRC_DIR%\*.exe %DEST_DIR%\bin copy %SRC_DIR%\*.pdb %DEST_DIR%\bin -copy %SRC_DIR%\..\..\cmserver\conf\*.conf %DEST_DIR%\conf -copy %SRC_DIR%\..\..\cmserver\conf\*.pass %DEST_DIR%\conf -copy %SRC_DIR%\..\..\cmserver\conf\cm_ssl_cert.* %DEST_DIR%\conf +copy %SRC_DIR%\..\..\amserver\conf\*.conf %DEST_DIR%\conf +copy %SRC_DIR%\..\..\amserver\conf\*.pass %DEST_DIR%\conf +copy %SRC_DIR%\..\..\amserver\conf\cm_ssl_cert.* %DEST_DIR%\conf if errorlevel 1 ( exit /b 0 ) -exit /b %errorlevel% \ No newline at end of file +exit /b %errorlevel% diff --git a/server/win/install/install.vcproj b/server/win/install/install.vcproj index af3e304..05bf334 100644 --- a/server/win/install/install.vcproj +++ b/server/win/install/install.vcproj @@ -28,9 +28,9 @@ > Date: Sat, 16 Oct 2021 17:12:12 +0300 Subject: [PATCH 03/12] add ams --- .idea/arniadb-manager-server.iml | 9 + docs/api/getamsenv.md | 20 + server/amserver/Makefile.am | 62 + server/amserver/conf/Makefile.am | 23 + server/amserver/conf/am.conf | 67 + server/amserver/conf/am.pass | 1 + server/amserver/conf/am_ssl_cert.crt | 14 + server/amserver/conf/am_ssl_cert.key | 15 + server/amserver/conf/autoaddvoldb.conf | 0 server/amserver/conf/autobackupdb.conf | 0 server/amserver/conf/autoexecquery.conf | 0 server/amserver/conf/autohistory.conf | 0 server/amserver/conf/cmdb.pass | 4 + .../amserver/conf/diagactivitytemplate.conf | 0 server/amserver/conf/diagstatustemplate.conf | 9 + server/build_ams_env.sh | 70 + .../openssl/linux_32/include/openssl/ams.h | 501 + .../openssl/linux_64/include/openssl/ams.h | 339 + .../openssl/linux_64/include/openssl/amserr.h | 202 + .../openssl/win_32/include/openssl/ams.h | 501 + .../openssl/win_64/include/openssl/ams.h | 501 + server/src/am_auto_task.cpp | 218 + server/src/am_auto_task.h | 47 + server/src/am_autojob.cpp | 1701 ++ server/src/am_autojob.h | 82 + server/src/am_cci_interface.cpp | 1655 ++ server/src/am_cci_interface.h | 53 + server/src/am_cmd.cpp | 83 + server/src/am_cmd_exec.cpp | 1406 ++ server/src/am_cmd_exec.h | 279 + server/src/am_cmd_task.cpp | 1490 ++ server/src/am_cmd_task.h | 61 + server/src/am_cmd_util.cpp | 282 + server/src/am_cmd_util.h | 123 + server/src/am_compress.h | 6747 +++++++ server/src/am_config.cpp | 809 + server/src/am_config.h | 629 + server/src/am_connect_info.cpp | 547 + server/src/am_connect_info.h | 62 + server/src/am_http_server.cpp | 664 + server/src/am_http_server.h | 112 + server/src/am_httpd.cpp | 921 + server/src/am_job_task.cpp | 16143 ++++++++++++++++ server/src/am_job_task.h | 439 + server/src/am_log.h | 515 + server/src/am_mailer.h | 1913 ++ server/src/am_mon_stat.cpp | 1943 ++ server/src/am_mon_stat.h | 114 + server/src/am_porting.h | 339 + server/src/am_server_autoupdate.cpp | 386 + server/src/am_server_autoupdate.h | 24 + server/src/am_server_extend_interface.cpp | 2707 +++ server/src/am_server_extend_interface.h | 101 + server/src/am_server_interface.cpp | 757 + server/src/am_server_interface.h | 33 + server/src/am_server_stat.c | 463 + server/src/am_server_stat.h | 99 + server/src/am_server_util.cpp | 3790 ++++ server/src/am_server_util.h | 219 + server/src/am_text_encryption.c | 291 + server/src/am_text_encryption.h | 38 + server/src/am_user.cpp | 711 + server/src/am_user.h | 113 + server/src/am_win_wsa.c | 75 + server/src/am_win_wsa.h | 63 + server/test/am_mon_data/dump_data.py | 113 + server/test/task_test_case_json/getamsenv.txt | 2 + server/test/task_test_config/am_conf/am.conf | 48 + server/test/task_test_config/am_conf/am.pass | 1 + .../am_conf/arniadb_broker.conf | 50 + .../am_conf/autoaddvoldb.conf | 4 + .../am_conf/autobackupdb.conf | 14 + .../am_conf/autoexecquery.conf | 11 + .../task_test_config/am_conf/autohistory.conf | 2 + server/win/am_admin/am_admin.vcproj | 411 + server/win/am_admin/resource.h | 32 + server/win/am_admin/version.rc | 103 + server/win/amserver.sln | 63 + 78 files changed, 52439 insertions(+) create mode 100644 .idea/arniadb-manager-server.iml create mode 100644 docs/api/getamsenv.md create mode 100644 server/amserver/Makefile.am create mode 100644 server/amserver/conf/Makefile.am create mode 100644 server/amserver/conf/am.conf create mode 100644 server/amserver/conf/am.pass create mode 100644 server/amserver/conf/am_ssl_cert.crt create mode 100644 server/amserver/conf/am_ssl_cert.key create mode 100644 server/amserver/conf/autoaddvoldb.conf create mode 100644 server/amserver/conf/autobackupdb.conf create mode 100644 server/amserver/conf/autoexecquery.conf create mode 100644 server/amserver/conf/autohistory.conf create mode 100644 server/amserver/conf/cmdb.pass create mode 100644 server/amserver/conf/diagactivitytemplate.conf create mode 100644 server/amserver/conf/diagstatustemplate.conf create mode 100644 server/build_ams_env.sh create mode 100644 server/external/openssl/linux_32/include/openssl/ams.h create mode 100644 server/external/openssl/linux_64/include/openssl/ams.h create mode 100644 server/external/openssl/linux_64/include/openssl/amserr.h create mode 100644 server/external/openssl/win_32/include/openssl/ams.h create mode 100644 server/external/openssl/win_64/include/openssl/ams.h create mode 100644 server/src/am_auto_task.cpp create mode 100644 server/src/am_auto_task.h create mode 100644 server/src/am_autojob.cpp create mode 100644 server/src/am_autojob.h create mode 100644 server/src/am_cci_interface.cpp create mode 100644 server/src/am_cci_interface.h create mode 100644 server/src/am_cmd.cpp create mode 100644 server/src/am_cmd_exec.cpp create mode 100644 server/src/am_cmd_exec.h create mode 100644 server/src/am_cmd_task.cpp create mode 100644 server/src/am_cmd_task.h create mode 100644 server/src/am_cmd_util.cpp create mode 100644 server/src/am_cmd_util.h create mode 100644 server/src/am_compress.h create mode 100644 server/src/am_config.cpp create mode 100644 server/src/am_config.h create mode 100644 server/src/am_connect_info.cpp create mode 100644 server/src/am_connect_info.h create mode 100644 server/src/am_http_server.cpp create mode 100644 server/src/am_http_server.h create mode 100644 server/src/am_httpd.cpp create mode 100644 server/src/am_job_task.cpp create mode 100644 server/src/am_job_task.h create mode 100644 server/src/am_log.h create mode 100644 server/src/am_mailer.h create mode 100644 server/src/am_mon_stat.cpp create mode 100644 server/src/am_mon_stat.h create mode 100644 server/src/am_porting.h create mode 100644 server/src/am_server_autoupdate.cpp create mode 100644 server/src/am_server_autoupdate.h create mode 100644 server/src/am_server_extend_interface.cpp create mode 100644 server/src/am_server_extend_interface.h create mode 100644 server/src/am_server_interface.cpp create mode 100644 server/src/am_server_interface.h create mode 100644 server/src/am_server_stat.c create mode 100644 server/src/am_server_stat.h create mode 100644 server/src/am_server_util.cpp create mode 100644 server/src/am_server_util.h create mode 100644 server/src/am_text_encryption.c create mode 100644 server/src/am_text_encryption.h create mode 100644 server/src/am_user.cpp create mode 100644 server/src/am_user.h create mode 100644 server/src/am_win_wsa.c create mode 100644 server/src/am_win_wsa.h create mode 100644 server/test/am_mon_data/dump_data.py create mode 100644 server/test/task_test_case_json/getamsenv.txt create mode 100644 server/test/task_test_config/am_conf/am.conf create mode 100644 server/test/task_test_config/am_conf/am.pass create mode 100644 server/test/task_test_config/am_conf/arniadb_broker.conf create mode 100644 server/test/task_test_config/am_conf/autoaddvoldb.conf create mode 100644 server/test/task_test_config/am_conf/autobackupdb.conf create mode 100644 server/test/task_test_config/am_conf/autoexecquery.conf create mode 100644 server/test/task_test_config/am_conf/autohistory.conf create mode 100644 server/win/am_admin/am_admin.vcproj create mode 100644 server/win/am_admin/resource.h create mode 100644 server/win/am_admin/version.rc create mode 100644 server/win/amserver.sln diff --git a/.idea/arniadb-manager-server.iml b/.idea/arniadb-manager-server.iml new file mode 100644 index 0000000..d6ebd48 --- /dev/null +++ b/.idea/arniadb-manager-server.iml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/docs/api/getamsenv.md b/docs/api/getamsenv.md new file mode 100644 index 0000000..e0b269e --- /dev/null +++ b/docs/api/getamsenv.md @@ -0,0 +1,20 @@ +# getamsenv + +Get databases' information in arniadb. + +## Request Json Syntax + +| **Key** | **Description** | +| --- | --- | +| task | task name | +| token | token string encrypted. | + + +## Request Sample + +``` +{ + "task":"getamsenv", + "token":"4504b930fc1be99bf5dfd31fc5799faaa3f117fb903f397de087cd3544165d857926f07dd201b6aa" + } +``` diff --git a/server/amserver/Makefile.am b/server/amserver/Makefile.am new file mode 100644 index 0000000..df2ccc0 --- /dev/null +++ b/server/amserver/Makefile.am @@ -0,0 +1,62 @@ + +# +# Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. +# +# 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 Street, Fifth Floor, Boston, MA 02110-1301 USA +# + + +SUBDIRS = conf + +SRC = $(top_srcdir)/src +DBMT_DIR = $(SRC) + +INCLUDES = @SRC_INC@ +DEFS += @SYS_DEFS@ @VERSION_DEFS@ @COMMON_DEFS@ +LIBS += @SYS_LIBS@ + +bin_PROGRAMS = cm_admin arn_manager + +cm_admin_SOURCES = \ + $(DBMT_DIR)/cm_text_encryption.c \ + $(DBMT_DIR)/cm_config.cpp \ + $(DBMT_DIR)/cm_server_util.cpp \ + $(DBMT_DIR)/cm_user.cpp \ + $(DBMT_DIR)/cm_cmd.cpp \ + $(DBMT_DIR)/cm_cmd_util.cpp \ + $(DBMT_DIR)/cm_connect_info.cpp \ + $(DBMT_DIR)/cm_cmd_task.cpp +cm_admin_CFLAGS = -D_FILE_OFFSET_BITS=64 +cm_admin_LDFLAGS = @CMDEP_LIB@ -D_FILE_OFFSET_BITS=64 + +arn_manager_SOURCES = \ + $(DBMT_DIR)/cm_server_util.cpp \ + $(DBMT_DIR)/cm_autojob.cpp \ + $(DBMT_DIR)/cm_text_encryption.c \ + $(DBMT_DIR)/cm_config.cpp \ + $(DBMT_DIR)/cm_job_task.cpp \ + $(DBMT_DIR)/cm_cmd_exec.cpp \ + $(DBMT_DIR)/cm_connect_info.cpp \ + $(DBMT_DIR)/cm_auto_task.cpp \ + $(DBMT_DIR)/cm_httpd.cpp \ + $(DBMT_DIR)/cm_mon_stat.cpp \ + $(DBMT_DIR)/cm_user.cpp \ + $(DBMT_DIR)/cm_http_server.cpp \ + $(DBMT_DIR)/cm_server_extend_interface.cpp \ + $(DBMT_DIR)/cm_server_interface.cpp \ + $(DBMT_DIR)/cm_cci_interface.cpp \ + $(DBMT_DIR)/cm_server_autoupdate.cpp +arn_manager_CPPFLAGS = $(AM_CFLAGS) -DFSERVER_SLAVE -DJSON_SUPPORT -DEVENT__HAVE_OPENSSL -D_FILE_OFFSET_BITS=64 @EXTERNAL_INC@ +arn_manager_LDFLAGS = -larniadbcs @AMSTAT_LIB@ @CMDEP_LIB@ @EXTERNAL_LIB@ -lrt -lcascci diff --git a/server/amserver/conf/Makefile.am b/server/amserver/conf/Makefile.am new file mode 100644 index 0000000..cb61221 --- /dev/null +++ b/server/amserver/conf/Makefile.am @@ -0,0 +1,23 @@ + +# +# Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. +# +# 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; version 2 of the License. +# +# 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 Street, Fifth Floor, Boston, MA 02110-1301, USA +# + + +confdir = ${prefix}/conf +dist_conf_DATA = autohistory.conf cmdb.pass autoaddvoldb.conf diagactivitytemplate.conf autobackupdb.conf cm.conf diagstatustemplate.conf autoexecquery.conf cm.pass \ + cm_ssl_cert.crt cm_ssl_cert.key + diff --git a/server/amserver/conf/am.conf b/server/amserver/conf/am.conf new file mode 100644 index 0000000..86af47a --- /dev/null +++ b/server/amserver/conf/am.conf @@ -0,0 +1,67 @@ +# cm.conf +# -- ARNIADB database management tool server configuration file +# +# +# When server starts, it looks for the environment variable +# 'ARNIADB_MANAGER' and use it to locate this file. It is assumed that +# 'ARNIADB_MANAGER' is the root directory of all ARNIADB Manager related files. +# +# Manager server section - a section for 'arniadb service' command +# Common section - properties for ARNIADB Manager Server +# This section will be applied before starting manager server. +[cm] +# +# Port number designation +# A port for the connection between ARNIADB Manager server and Client. +# ARNIADB Manager server uses the value cm_port. +# The default value is 8001. +# +cm_port=8001 + +# +# AMS Process Monitoring interval setting +# +cm_process_monitor_interval=5 + +# +# Allowing Multiple connection with one ARNIADB Manager user. +# +allow_user_multi_connection=YES + +############################### +# diagnostics parameter +############################### +# +# turn ON/OFF diag +# +#execute_diag=ON + +# +# server long query time (sec) +# +server_long_query_time=10 + +# +# Auto jobs execution timeout (sec) +# Default value: 43200 (12 hours) +# Minimum value: 60 +auto_job_timeout=43200 + +# +# Define token active time(session timeout), default value is 7200. +# +#token_active_time=7200 + +# +# support monitoring statistic (YES/NO), default NO +# If you want to use the advanced monitoring feature on ARNIADB Manager, +# you should set this value to YES. +# +support_mon_statistic=NO + +# +# max log file number: default 10 +# When the log files is more than max_log_files, +# The oldest log will be removed. +# +max_log_files=10 diff --git a/server/amserver/conf/am.pass b/server/amserver/conf/am.pass new file mode 100644 index 0000000..58ecec1 --- /dev/null +++ b/server/amserver/conf/am.pass @@ -0,0 +1 @@ +admin:6e85f0f80f030451dc9e98851098dfb2 diff --git a/server/amserver/conf/am_ssl_cert.crt b/server/amserver/conf/am_ssl_cert.crt new file mode 100644 index 0000000..a72d8d3 --- /dev/null +++ b/server/amserver/conf/am_ssl_cert.crt @@ -0,0 +1,14 @@ +-----BEGIN CERTIFICATE----- +MIICDzCCAXgCCQDO8wrRT6KVNzANBgkqhkiG9w0BAQUFADBMMQswCQYDVQQGEwJD +TjESMBAGA1UECBMJQmVya3NoaXJlMRAwDgYDVQQHEwdOZXdidXJ5MRcwFQYDVQQK +Ew5NeSBDb21wYW55IEx0ZDAeFw0xMjAzMDcwNzIwMDdaFw0xMzAzMDcwNzIwMDda +MEwxCzAJBgNVBAYTAkNOMRIwEAYDVQQIEwlCZXJrc2hpcmUxEDAOBgNVBAcTB05l +d2J1cnkxFzAVBgNVBAoTDk15IENvbXBhbnkgTHRkMIGfMA0GCSqGSIb3DQEBAQUA +A4GNADCBiQKBgQDyhIO7i4Xitj43+7VOyhez8FOQGafRfAlIzIoGKTF3WbmQB2ir +LTfs1vCPb28G40t49yFAxb/4XbKRlRhmVfHDqIrcZoPVDJ/01hfYPEzzOy02XEBH +x0jUqfbVkuS1Wr59afcqzciY2oQ1GrBAFvwwJiagDWfE8D9F+bSPyTF7jQIDAQAB +MA0GCSqGSIb3DQEBBQUAA4GBAIUq4xzJ8FS+ArVPYP+8Rf0OciSpdOYngeT4xWox +2AQdgTRs+1DS0M3jePqztPYc88acPGQrpkLeZqu2ICK5FMdEHBA8kPVCpJne7Oqh +Tqdc6j0MIYUVBN8cxQKO1XhTrh6qz26nDF4erXzt2txiPRhKqR4Tw0ekSkUeUHqb +DnWR +-----END CERTIFICATE----- diff --git a/server/amserver/conf/am_ssl_cert.key b/server/amserver/conf/am_ssl_cert.key new file mode 100644 index 0000000..62fec17 --- /dev/null +++ b/server/amserver/conf/am_ssl_cert.key @@ -0,0 +1,15 @@ +-----BEGIN RSA PRIVATE KEY----- +MIICXQIBAAKBgQDyhIO7i4Xitj43+7VOyhez8FOQGafRfAlIzIoGKTF3WbmQB2ir +LTfs1vCPb28G40t49yFAxb/4XbKRlRhmVfHDqIrcZoPVDJ/01hfYPEzzOy02XEBH +x0jUqfbVkuS1Wr59afcqzciY2oQ1GrBAFvwwJiagDWfE8D9F+bSPyTF7jQIDAQAB +AoGBALPC6epgNzOfJmtU1kW6ousr3qTXf39V04P0qPJ8IkB3b4aFF16au/OANvv6 ++289l7noZOugKPWubihfPaDNX8/YgWDT35tbwnu8ObL46oOGdChhTkoe0wqYmkXq +U2WVIpjip+f60AZYxDL5EDFrUvnBeG1QX9kRahiGbi8vTbZ5AkEA+T2fW47Bovnu +pTNP4uzKahjEt0Xu4sr4lvZ/r+24p23OgPtIU5Rajt7LUoNoRDW898Ht1v4iSFjP +FbeEP4NMSwJBAPkYN2skC4WRtMnsHWuMgiWD9evP4rcJwb9wBcKfNmnPXELk9RY2 +o+pkmwxyDhhV4TQNXsPe/Oat7fSTBGe0wIcCQQCsakyK8b5SF8NW1KA2wsdjja7H +ecE/cll1VSAPe8t5RyTLZQkriDz9CHJuqii+xs3qNmVpjHP6yDS5OTJrHVDxAkAp +lq96BfSegmtK408uK7F3Dgc7LeROZySgD9YGXoq5M9PVn2CEKu9HLTDt7QUJbx1A +kZLm5Q4YfaWjFgDAR991AkBysGv1IfMuTXJ+zEHfFzykwKB/f7q+JfmkrxalWbuL +pQkRp+3VqXPtHm8LR2yeOhk6c3mEi8EJBlFH8J0cixoz +-----END RSA PRIVATE KEY----- diff --git a/server/amserver/conf/autoaddvoldb.conf b/server/amserver/conf/autoaddvoldb.conf new file mode 100644 index 0000000..e69de29 diff --git a/server/amserver/conf/autobackupdb.conf b/server/amserver/conf/autobackupdb.conf new file mode 100644 index 0000000..e69de29 diff --git a/server/amserver/conf/autoexecquery.conf b/server/amserver/conf/autoexecquery.conf new file mode 100644 index 0000000..e69de29 diff --git a/server/amserver/conf/autohistory.conf b/server/amserver/conf/autohistory.conf new file mode 100644 index 0000000..e69de29 diff --git a/server/amserver/conf/cmdb.pass b/server/amserver/conf/cmdb.pass new file mode 100644 index 0000000..3cf35aa --- /dev/null +++ b/server/amserver/conf/cmdb.pass @@ -0,0 +1,4 @@ +<<<:admin +unicas:admin +dbcreate:admin +>>>:admin diff --git a/server/amserver/conf/diagactivitytemplate.conf b/server/amserver/conf/diagactivitytemplate.conf new file mode 100644 index 0000000..e69de29 diff --git a/server/amserver/conf/diagstatustemplate.conf b/server/amserver/conf/diagstatustemplate.conf new file mode 100644 index 0000000..af78492 --- /dev/null +++ b/server/amserver/conf/diagstatustemplate.conf @@ -0,0 +1,9 @@ +<<< +broker_template +status monitor template of broker + +1 +cas_st_request 1 0.1 +cas_st_transaction 7 0.1 +cas_st_active_session 3 0.1 +>>> diff --git a/server/build_ams_env.sh b/server/build_ams_env.sh new file mode 100644 index 0000000..4196b42 --- /dev/null +++ b/server/build_ams_env.sh @@ -0,0 +1,70 @@ +#!/bin/bash + +if [ -z $JAVA_HOME ] +then + echo "WE NEED JAVA_HOME";exit 1; +fi + +yum install ant + +#build libevent +wget http://cloud.github.com/downloads/libevent/libevent/libevent-2.0.18-stable.tar.gz +tar zxvf libevent-2.0.18-stable.tar.gz +cd libevent-2.0.18-stable +./configure;make;make install + +cd .. + +#build jsoncpp +wget http://nchc.dl.sourceforge.net/project/jsoncpp/jsoncpp/0.5.0/jsoncpp-src-0.5.0.tar.gz +tar zxvf jsoncpp-src-0.5.0.tar.gz +cd jsoncpp-src-0.5.0 +g++ -o src/lib_json/json_reader.o -c -Wall -Iinclude src/lib_json/json_reader.cpp +g++ -o src/lib_json/json_value.o -c -Wall -Iinclude src/lib_json/json_value.cpp +g++ -o src/lib_json/json_writer.o -c -Wall -Iinclude src/lib_json/json_writer.cpp +ar rc src/lib_json/libjson.a src/lib_json/json_reader.o src/lib_json/json_value.o src/lib_json/json_writer.o +ranlib src/lib_json/libjson.a +cp -r include/json /usr/local/include +cp src/lib_json/libjson.a /usr/local/lib + +cd .. + +#build arniadb +wget ftp://ftp.arniadb.org/ARNIADB_Engine/8.4.1/Linux/ARNIADB-8.4.1.2032.src.tar.gz +tar xzvf ARNIADB-8.4.1.2032.src.tar.gz + +cd arniadb-8.4.1.2032 +./configure --enable-64bit --enable-debug +make +make install + +#configure arniadb env + +cat >> .arniadb.sh << EOF +#!/bin/bash +ARNIADB=/root/arniadb +ARNIADB_DATABASES=/root/arniadb/databases +ARNIADB_LANG=en_US +ld_lib_path=`printenv LD_LIBRARY_PATH` +if [ "$ld_lib_path" = "" ] +then +LD_LIBRARY_PATH=$ARNIADB/lib +else +LD_LIBRARY_PATH=$ARNIADB/lib:$LD_LIBRARY_PATH +fi +SHLIB_PATH=$LD_LIBRARY_PATH +LIBPATH=$LD_LIBRARY_PATH +PATH=$ARNIADB/bin:$ARNIADB/arniadbmanager:$PATH +export ARNIADB +export ARNIADB_DATABASES +export ARNIADB_LANG +export LD_LIBRARY_PATH +export SHLIB_PATH +export LIBPATH +export PATH +EOF +chmod +x .arniadb.sh +./.arniadb.sh + +mkdir $ARNIADB_DATABASES + diff --git a/server/external/openssl/linux_32/include/openssl/ams.h b/server/external/openssl/linux_32/include/openssl/ams.h new file mode 100644 index 0000000..35b6bd0 --- /dev/null +++ b/server/external/openssl/linux_32/include/openssl/ams.h @@ -0,0 +1,501 @@ +/* crypto/ams/ams.h */ +/* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL + * project. + */ +/* ==================================================================== + * Copyright (c) 2008 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * licensing@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + */ + + +#ifndef HEADER_AMS_H +#define HEADER_AMS_H + +#include + +#ifdef OPENSSL_NO_AMS +#error AMS is disabled. +#endif + +#ifdef __cplusplus +extern "C" { +#endif + + +typedef struct AMS_ContentInfo_st AMS_ContentInfo; +typedef struct AMS_SignerInfo_st AMS_SignerInfo; +typedef struct AMS_CertificateChoices AMS_CertificateChoices; +typedef struct AMS_RevocationInfoChoice_st AMS_RevocationInfoChoice; +typedef struct AMS_RecipientInfo_st AMS_RecipientInfo; +typedef struct AMS_ReceiptRequest_st AMS_ReceiptRequest; +typedef struct AMS_Receipt_st AMS_Receipt; + +DECLARE_STACK_OF(AMS_SignerInfo) +DECLARE_STACK_OF(GENERAL_NAMES) +DECLARE_ASN1_FUNCTIONS(AMS_ContentInfo) +DECLARE_ASN1_FUNCTIONS(AMS_ReceiptRequest) +DECLARE_ASN1_PRINT_FUNCTION(AMS_ContentInfo) + +#define AMS_SIGNERINFO_ISSUER_SERIAL 0 +#define AMS_SIGNERINFO_KEYIDENTIFIER 1 + +#define AMS_RECIPINFO_TRANS 0 +#define AMS_RECIPINFO_AGREE 1 +#define AMS_RECIPINFO_KEK 2 +#define AMS_RECIPINFO_PASS 3 +#define AMS_RECIPINFO_OTHER 4 + +/* S/MIME related flags */ + +#define AMS_TEXT 0x1 +#define AMS_NOCERTS 0x2 +#define AMS_NO_CONTENT_VERIFY 0x4 +#define AMS_NO_ATTR_VERIFY 0x8 +#define AMS_NOSIGS \ + (AMS_NO_CONTENT_VERIFY|AMS_NO_ATTR_VERIFY) +#define AMS_NOINTERN 0x10 +#define AMS_NO_SIGNER_CERT_VERIFY 0x20 +#define AMS_NOVERIFY 0x20 +#define AMS_DETACHED 0x40 +#define AMS_BINARY 0x80 +#define AMS_NOATTR 0x100 +#define AMS_NOSMIMECAP 0x200 +#define AMS_NOOLDMIMETYPE 0x400 +#define AMS_CRLFEOL 0x800 +#define AMS_STREAM 0x1000 +#define AMS_NOCRL 0x2000 +#define AMS_PARTIAL 0x4000 +#define AMS_REUSE_DIGEST 0x8000 +#define AMS_USE_KEYID 0x10000 +#define AMS_DEBUG_DECRYPT 0x20000 + +const ASN1_OBJECT *AMS_get0_type(AMS_ContentInfo *ams); + +BIO *AMS_dataInit(AMS_ContentInfo *ams, BIO *icont); +int AMS_dataFinal(AMS_ContentInfo *ams, BIO *bio); + +ASN1_OCTET_STRING **AMS_get0_content(AMS_ContentInfo *ams); +int AMS_is_detached(AMS_ContentInfo *ams); +int AMS_set_detached(AMS_ContentInfo *ams, int detached); + +#ifdef HEADER_PEM_H +DECLARE_PEM_rw_const(AMS, AMS_ContentInfo) +#endif + +int AMS_stream(unsigned char ***boundary, AMS_ContentInfo *ams); +AMS_ContentInfo *d2i_AMS_bio(BIO *bp, AMS_ContentInfo **ams); +int i2d_AMS_bio(BIO *bp, AMS_ContentInfo *ams); + +BIO *BIO_new_AMS(BIO *out, AMS_ContentInfo *ams); +int i2d_AMS_bio_stream(BIO *out, AMS_ContentInfo *ams, BIO *in, int flags); +int PEM_write_bio_AMS_stream(BIO *out, AMS_ContentInfo *ams, BIO *in, int flags); +AMS_ContentInfo *SMIME_read_AMS(BIO *bio, BIO **bcont); +int SMIME_write_AMS(BIO *bio, AMS_ContentInfo *ams, BIO *data, int flags); + +int AMS_final(AMS_ContentInfo *ams, BIO *data, BIO *dcont, unsigned int flags); + +AMS_ContentInfo *AMS_sign(X509 *signcert, EVP_PKEY *pkey, STACK_OF(X509) *certs, + BIO *data, unsigned int flags); + +AMS_ContentInfo *AMS_sign_receipt(AMS_SignerInfo *si, + X509 *signcert, EVP_PKEY *pkey, + STACK_OF(X509) *certs, + unsigned int flags); + +int AMS_data(AMS_ContentInfo *ams, BIO *out, unsigned int flags); +AMS_ContentInfo *AMS_data_create(BIO *in, unsigned int flags); + +int AMS_digest_verify(AMS_ContentInfo *ams, BIO *dcont, BIO *out, + unsigned int flags); +AMS_ContentInfo *AMS_digest_create(BIO *in, const EVP_MD *md, + unsigned int flags); + +int AMS_EncryptedData_decrypt(AMS_ContentInfo *ams, + const unsigned char *key, size_t keylen, + BIO *dcont, BIO *out, unsigned int flags); + +AMS_ContentInfo *AMS_EncryptedData_encrypt(BIO *in, const EVP_CIPHER *cipher, + const unsigned char *key, size_t keylen, + unsigned int flags); + +int AMS_EncryptedData_set1_key(AMS_ContentInfo *ams, const EVP_CIPHER *ciph, + const unsigned char *key, size_t keylen); + +int AMS_verify(AMS_ContentInfo *ams, STACK_OF(X509) *certs, + X509_STORE *store, BIO *dcont, BIO *out, unsigned int flags); + +int AMS_verify_receipt(AMS_ContentInfo *rams, AMS_ContentInfo *oams, + STACK_OF(X509) *certs, + X509_STORE *store, unsigned int flags); + +STACK_OF(X509) *AMS_get0_signers(AMS_ContentInfo *ams); + +AMS_ContentInfo *AMS_encrypt(STACK_OF(X509) *certs, BIO *in, + const EVP_CIPHER *cipher, unsigned int flags); + +int AMS_decrypt(AMS_ContentInfo *ams, EVP_PKEY *pkey, X509 *cert, + BIO *dcont, BIO *out, + unsigned int flags); + +int AMS_decrypt_set1_pkey(AMS_ContentInfo *ams, EVP_PKEY *pk, X509 *cert); +int AMS_decrypt_set1_key(AMS_ContentInfo *ams, + unsigned char *key, size_t keylen, + unsigned char *id, size_t idlen); +int AMS_decrypt_set1_password(AMS_ContentInfo *ams, + unsigned char *pass, ossl_ssize_t passlen); + +STACK_OF(AMS_RecipientInfo) *AMS_get0_RecipientInfos(AMS_ContentInfo *ams); +int AMS_RecipientInfo_type(AMS_RecipientInfo *ri); +AMS_ContentInfo *AMS_EnvelopedData_create(const EVP_CIPHER *cipher); +AMS_RecipientInfo *AMS_add1_recipient_cert(AMS_ContentInfo *ams, + X509 *recip, unsigned int flags); +int AMS_RecipientInfo_set0_pkey(AMS_RecipientInfo *ri, EVP_PKEY *pkey); +int AMS_RecipientInfo_ktri_cert_cmp(AMS_RecipientInfo *ri, X509 *cert); +int AMS_RecipientInfo_ktri_get0_algs(AMS_RecipientInfo *ri, + EVP_PKEY **pk, X509 **recip, + X509_ALGOR **palg); +int AMS_RecipientInfo_ktri_get0_signer_id(AMS_RecipientInfo *ri, + ASN1_OCTET_STRING **keyid, + X509_NAME **issuer, ASN1_INTEGER **sno); + +AMS_RecipientInfo *AMS_add0_recipient_key(AMS_ContentInfo *ams, int nid, + unsigned char *key, size_t keylen, + unsigned char *id, size_t idlen, + ASN1_GENERALIZEDTIME *date, + ASN1_OBJECT *otherTypeId, + ASN1_TYPE *otherType); + +int AMS_RecipientInfo_kekri_get0_id(AMS_RecipientInfo *ri, + X509_ALGOR **palg, + ASN1_OCTET_STRING **pid, + ASN1_GENERALIZEDTIME **pdate, + ASN1_OBJECT **potherid, + ASN1_TYPE **pothertype); + +int AMS_RecipientInfo_set0_key(AMS_RecipientInfo *ri, + unsigned char *key, size_t keylen); + +int AMS_RecipientInfo_kekri_id_cmp(AMS_RecipientInfo *ri, + const unsigned char *id, size_t idlen); + +int AMS_RecipientInfo_set0_password(AMS_RecipientInfo *ri, + unsigned char *pass, + ossl_ssize_t passlen); + +AMS_RecipientInfo *AMS_add0_recipient_password(AMS_ContentInfo *ams, + int iter, int wrap_nid, int pbe_nid, + unsigned char *pass, + ossl_ssize_t passlen, + const EVP_CIPHER *kekciph); + +int AMS_RecipientInfo_decrypt(AMS_ContentInfo *ams, AMS_RecipientInfo *ri); + +int AMS_uncompress(AMS_ContentInfo *ams, BIO *dcont, BIO *out, + unsigned int flags); +AMS_ContentInfo *AMS_compress(BIO *in, int comp_nid, unsigned int flags); + +int AMS_set1_eContentType(AMS_ContentInfo *ams, const ASN1_OBJECT *oid); +const ASN1_OBJECT *AMS_get0_eContentType(AMS_ContentInfo *ams); + +AMS_CertificateChoices *AMS_add0_CertificateChoices(AMS_ContentInfo *ams); +int AMS_add0_cert(AMS_ContentInfo *ams, X509 *cert); +int AMS_add1_cert(AMS_ContentInfo *ams, X509 *cert); +STACK_OF(X509) *AMS_get1_certs(AMS_ContentInfo *ams); + +AMS_RevocationInfoChoice *AMS_add0_RevocationInfoChoice(AMS_ContentInfo *ams); +int AMS_add0_crl(AMS_ContentInfo *ams, X509_CRL *crl); +int AMS_add1_crl(AMS_ContentInfo *ams, X509_CRL *crl); +STACK_OF(X509_CRL) *AMS_get1_crls(AMS_ContentInfo *ams); + +int AMS_SignedData_init(AMS_ContentInfo *ams); +AMS_SignerInfo *AMS_add1_signer(AMS_ContentInfo *ams, + X509 *signer, EVP_PKEY *pk, const EVP_MD *md, + unsigned int flags); +STACK_OF(AMS_SignerInfo) *AMS_get0_SignerInfos(AMS_ContentInfo *ams); + +void AMS_SignerInfo_set1_signer_cert(AMS_SignerInfo *si, X509 *signer); +int AMS_SignerInfo_get0_signer_id(AMS_SignerInfo *si, + ASN1_OCTET_STRING **keyid, + X509_NAME **issuer, ASN1_INTEGER **sno); +int AMS_SignerInfo_cert_cmp(AMS_SignerInfo *si, X509 *cert); +int AMS_set1_signers_certs(AMS_ContentInfo *ams, STACK_OF(X509) *certs, + unsigned int flags); +void AMS_SignerInfo_get0_algs(AMS_SignerInfo *si, EVP_PKEY **pk, X509 **signer, + X509_ALGOR **pdig, X509_ALGOR **psig); +int AMS_SignerInfo_sign(AMS_SignerInfo *si); +int AMS_SignerInfo_verify(AMS_SignerInfo *si); +int AMS_SignerInfo_verify_content(AMS_SignerInfo *si, BIO *chain); + +int AMS_add_smimecap(AMS_SignerInfo *si, STACK_OF(X509_ALGOR) *algs); +int AMS_add_simple_smimecap(STACK_OF(X509_ALGOR) **algs, + int algnid, int keysize); +int AMS_add_standard_smimecap(STACK_OF(X509_ALGOR) **smcap); + +int AMS_signed_get_attr_count(const AMS_SignerInfo *si); +int AMS_signed_get_attr_by_NID(const AMS_SignerInfo *si, int nid, + int lastpos); +int AMS_signed_get_attr_by_OBJ(const AMS_SignerInfo *si, ASN1_OBJECT *obj, + int lastpos); +X509_ATTRIBUTE *AMS_signed_get_attr(const AMS_SignerInfo *si, int loc); +X509_ATTRIBUTE *AMS_signed_delete_attr(AMS_SignerInfo *si, int loc); +int AMS_signed_add1_attr(AMS_SignerInfo *si, X509_ATTRIBUTE *attr); +int AMS_signed_add1_attr_by_OBJ(AMS_SignerInfo *si, + const ASN1_OBJECT *obj, int type, + const void *bytes, int len); +int AMS_signed_add1_attr_by_NID(AMS_SignerInfo *si, + int nid, int type, + const void *bytes, int len); +int AMS_signed_add1_attr_by_txt(AMS_SignerInfo *si, + const char *attrname, int type, + const void *bytes, int len); +void *AMS_signed_get0_data_by_OBJ(AMS_SignerInfo *si, ASN1_OBJECT *oid, + int lastpos, int type); + +int AMS_unsigned_get_attr_count(const AMS_SignerInfo *si); +int AMS_unsigned_get_attr_by_NID(const AMS_SignerInfo *si, int nid, + int lastpos); +int AMS_unsigned_get_attr_by_OBJ(const AMS_SignerInfo *si, ASN1_OBJECT *obj, + int lastpos); +X509_ATTRIBUTE *AMS_unsigned_get_attr(const AMS_SignerInfo *si, int loc); +X509_ATTRIBUTE *AMS_unsigned_delete_attr(AMS_SignerInfo *si, int loc); +int AMS_unsigned_add1_attr(AMS_SignerInfo *si, X509_ATTRIBUTE *attr); +int AMS_unsigned_add1_attr_by_OBJ(AMS_SignerInfo *si, + const ASN1_OBJECT *obj, int type, + const void *bytes, int len); +int AMS_unsigned_add1_attr_by_NID(AMS_SignerInfo *si, + int nid, int type, + const void *bytes, int len); +int AMS_unsigned_add1_attr_by_txt(AMS_SignerInfo *si, + const char *attrname, int type, + const void *bytes, int len); +void *AMS_unsigned_get0_data_by_OBJ(AMS_SignerInfo *si, ASN1_OBJECT *oid, + int lastpos, int type); + +#ifdef HEADER_X509V3_H + +int AMS_get1_ReceiptRequest(AMS_SignerInfo *si, AMS_ReceiptRequest **prr); +AMS_ReceiptRequest *AMS_ReceiptRequest_create0(unsigned char *id, int idlen, + int allorfirst, + STACK_OF(GENERAL_NAMES) *receiptList, + STACK_OF(GENERAL_NAMES) *receiptsTo); +int AMS_add1_ReceiptRequest(AMS_SignerInfo *si, AMS_ReceiptRequest *rr); +void AMS_ReceiptRequest_get0_values(AMS_ReceiptRequest *rr, + ASN1_STRING **pcid, + int *pallorfirst, + STACK_OF(GENERAL_NAMES) **plist, + STACK_OF(GENERAL_NAMES) **prto); + +#endif + +/* BEGIN ERROR CODES */ +/* The following lines are auto generated by the script mkerr.pl. Any changes + * made after this point may be overwritten when the script is next run. + */ +void ERR_load_AMS_strings(void); + +/* Error codes for the AMS functions. */ + +/* Function codes. */ +#define AMS_F_CHECK_CONTENT 99 +#define AMS_F_AMS_ADD0_CERT 164 +#define AMS_F_AMS_ADD0_RECIPIENT_KEY 100 +#define AMS_F_AMS_ADD0_RECIPIENT_PASSWORD 165 +#define AMS_F_AMS_ADD1_RECEIPTREQUEST 158 +#define AMS_F_AMS_ADD1_RECIPIENT_CERT 101 +#define AMS_F_AMS_ADD1_SIGNER 102 +#define AMS_F_AMS_ADD1_SIGNINGTIME 103 +#define AMS_F_AMS_COMPRESS 104 +#define AMS_F_AMS_COMPRESSEDDATA_CREATE 105 +#define AMS_F_AMS_COMPRESSEDDATA_INIT_BIO 106 +#define AMS_F_AMS_COPY_CONTENT 107 +#define AMS_F_AMS_COPY_MESSAGEDIGEST 108 +#define AMS_F_AMS_DATA 109 +#define AMS_F_AMS_DATAFINAL 110 +#define AMS_F_AMS_DATAINIT 111 +#define AMS_F_AMS_DECRYPT 112 +#define AMS_F_AMS_DECRYPT_SET1_KEY 113 +#define AMS_F_AMS_DECRYPT_SET1_PASSWORD 166 +#define AMS_F_AMS_DECRYPT_SET1_PKEY 114 +#define AMS_F_AMS_DIGESTALGORITHM_FIND_CTX 115 +#define AMS_F_AMS_DIGESTALGORITHM_INIT_BIO 116 +#define AMS_F_AMS_DIGESTEDDATA_DO_FINAL 117 +#define AMS_F_AMS_DIGEST_VERIFY 118 +#define AMS_F_AMS_ENCODE_RECEIPT 161 +#define AMS_F_AMS_ENCRYPT 119 +#define AMS_F_AMS_ENCRYPTEDCONTENT_INIT_BIO 120 +#define AMS_F_AMS_ENCRYPTEDDATA_DECRYPT 121 +#define AMS_F_AMS_ENCRYPTEDDATA_ENCRYPT 122 +#define AMS_F_AMS_ENCRYPTEDDATA_SET1_KEY 123 +#define AMS_F_AMS_ENVELOPEDDATA_CREATE 124 +#define AMS_F_AMS_ENVELOPEDDATA_INIT_BIO 125 +#define AMS_F_AMS_ENVELOPED_DATA_INIT 126 +#define AMS_F_AMS_FINAL 127 +#define AMS_F_AMS_GET0_CERTIFICATE_CHOICES 128 +#define AMS_F_AMS_GET0_CONTENT 129 +#define AMS_F_AMS_GET0_ECONTENT_TYPE 130 +#define AMS_F_AMS_GET0_ENVELOPED 131 +#define AMS_F_AMS_GET0_REVOCATION_CHOICES 132 +#define AMS_F_AMS_GET0_SIGNED 133 +#define AMS_F_AMS_MSGSIGDIGEST_ADD1 162 +#define AMS_F_AMS_RECEIPTREQUEST_CREATE0 159 +#define AMS_F_AMS_RECEIPT_VERIFY 160 +#define AMS_F_AMS_RECIPIENTINFO_DECRYPT 134 +#define AMS_F_AMS_RECIPIENTINFO_KEKRI_DECRYPT 135 +#define AMS_F_AMS_RECIPIENTINFO_KEKRI_ENCRYPT 136 +#define AMS_F_AMS_RECIPIENTINFO_KEKRI_GET0_ID 137 +#define AMS_F_AMS_RECIPIENTINFO_KEKRI_ID_CMP 138 +#define AMS_F_AMS_RECIPIENTINFO_KTRI_CERT_CMP 139 +#define AMS_F_AMS_RECIPIENTINFO_KTRI_DECRYPT 140 +#define AMS_F_AMS_RECIPIENTINFO_KTRI_ENCRYPT 141 +#define AMS_F_AMS_RECIPIENTINFO_KTRI_GET0_ALGS 142 +#define AMS_F_AMS_RECIPIENTINFO_KTRI_GET0_SIGNER_ID 143 +#define AMS_F_AMS_RECIPIENTINFO_PWRI_CRYPT 167 +#define AMS_F_AMS_RECIPIENTINFO_SET0_KEY 144 +#define AMS_F_AMS_RECIPIENTINFO_SET0_PASSWORD 168 +#define AMS_F_AMS_RECIPIENTINFO_SET0_PKEY 145 +#define AMS_F_AMS_SET1_SIGNERIDENTIFIER 146 +#define AMS_F_AMS_SET_DETACHED 147 +#define AMS_F_AMS_SIGN 148 +#define AMS_F_AMS_SIGNED_DATA_INIT 149 +#define AMS_F_AMS_SIGNERINFO_CONTENT_SIGN 150 +#define AMS_F_AMS_SIGNERINFO_SIGN 151 +#define AMS_F_AMS_SIGNERINFO_VERIFY 152 +#define AMS_F_AMS_SIGNERINFO_VERIFY_CERT 153 +#define AMS_F_AMS_SIGNERINFO_VERIFY_CONTENT 154 +#define AMS_F_AMS_SIGN_RECEIPT 163 +#define AMS_F_AMS_STREAM 155 +#define AMS_F_AMS_UNCOMPRESS 156 +#define AMS_F_AMS_VERIFY 157 + +/* Reason codes. */ +#define AMS_R_ADD_SIGNER_ERROR 99 +#define AMS_R_CERTIFICATE_ALREADY_PRESENT 175 +#define AMS_R_CERTIFICATE_HAS_NO_KEYID 160 +#define AMS_R_CERTIFICATE_VERIFY_ERROR 100 +#define AMS_R_CIPHER_INITIALISATION_ERROR 101 +#define AMS_R_CIPHER_PARAMETER_INITIALISATION_ERROR 102 +#define AMS_R_AMS_DATAFINAL_ERROR 103 +#define AMS_R_AMS_LIB 104 +#define AMS_R_CONTENTIDENTIFIER_MISMATCH 170 +#define AMS_R_CONTENT_NOT_FOUND 105 +#define AMS_R_CONTENT_TYPE_MISMATCH 171 +#define AMS_R_CONTENT_TYPE_NOT_COMPRESSED_DATA 106 +#define AMS_R_CONTENT_TYPE_NOT_ENVELOPED_DATA 107 +#define AMS_R_CONTENT_TYPE_NOT_SIGNED_DATA 108 +#define AMS_R_CONTENT_VERIFY_ERROR 109 +#define AMS_R_CTRL_ERROR 110 +#define AMS_R_CTRL_FAILURE 111 +#define AMS_R_DECRYPT_ERROR 112 +#define AMS_R_DIGEST_ERROR 161 +#define AMS_R_ERROR_GETTING_PUBLIC_KEY 113 +#define AMS_R_ERROR_READING_MESSAGEDIGEST_ATTRIBUTE 114 +#define AMS_R_ERROR_SETTING_KEY 115 +#define AMS_R_ERROR_SETTING_RECIPIENTINFO 116 +#define AMS_R_INVALID_ENCRYPTED_KEY_LENGTH 117 +#define AMS_R_INVALID_KEY_ENCRYPTION_PARAMETER 176 +#define AMS_R_INVALID_KEY_LENGTH 118 +#define AMS_R_MD_BIO_INIT_ERROR 119 +#define AMS_R_MESSAGEDIGEST_ATTRIBUTE_WRONG_LENGTH 120 +#define AMS_R_MESSAGEDIGEST_WRONG_LENGTH 121 +#define AMS_R_MSGSIGDIGEST_ERROR 172 +#define AMS_R_MSGSIGDIGEST_VERIFICATION_FAILURE 162 +#define AMS_R_MSGSIGDIGEST_WRONG_LENGTH 163 +#define AMS_R_NEED_ONE_SIGNER 164 +#define AMS_R_NOT_A_SIGNED_RECEIPT 165 +#define AMS_R_NOT_ENCRYPTED_DATA 122 +#define AMS_R_NOT_KEK 123 +#define AMS_R_NOT_KEY_TRANSPORT 124 +#define AMS_R_NOT_PWRI 177 +#define AMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE 125 +#define AMS_R_NO_CIPHER 126 +#define AMS_R_NO_CONTENT 127 +#define AMS_R_NO_CONTENT_TYPE 173 +#define AMS_R_NO_DEFAULT_DIGEST 128 +#define AMS_R_NO_DIGEST_SET 129 +#define AMS_R_NO_KEY 130 +#define AMS_R_NO_KEY_OR_CERT 174 +#define AMS_R_NO_MATCHING_DIGEST 131 +#define AMS_R_NO_MATCHING_RECIPIENT 132 +#define AMS_R_NO_MATCHING_SIGNATURE 166 +#define AMS_R_NO_MSGSIGDIGEST 167 +#define AMS_R_NO_PASSWORD 178 +#define AMS_R_NO_PRIVATE_KEY 133 +#define AMS_R_NO_PUBLIC_KEY 134 +#define AMS_R_NO_RECEIPT_REQUEST 168 +#define AMS_R_NO_SIGNERS 135 +#define AMS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE 136 +#define AMS_R_RECEIPT_DECODE_ERROR 169 +#define AMS_R_RECIPIENT_ERROR 137 +#define AMS_R_SIGNER_CERTIFICATE_NOT_FOUND 138 +#define AMS_R_SIGNFINAL_ERROR 139 +#define AMS_R_SMIME_TEXT_ERROR 140 +#define AMS_R_STORE_INIT_ERROR 141 +#define AMS_R_TYPE_NOT_COMPRESSED_DATA 142 +#define AMS_R_TYPE_NOT_DATA 143 +#define AMS_R_TYPE_NOT_DIGESTED_DATA 144 +#define AMS_R_TYPE_NOT_ENCRYPTED_DATA 145 +#define AMS_R_TYPE_NOT_ENVELOPED_DATA 146 +#define AMS_R_UNABLE_TO_FINALIZE_CONTEXT 147 +#define AMS_R_UNKNOWN_CIPHER 148 +#define AMS_R_UNKNOWN_DIGEST_ALGORIHM 149 +#define AMS_R_UNKNOWN_ID 150 +#define AMS_R_UNSUPPORTED_COMPRESSION_ALGORITHM 151 +#define AMS_R_UNSUPPORTED_CONTENT_TYPE 152 +#define AMS_R_UNSUPPORTED_KEK_ALGORITHM 153 +#define AMS_R_UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM 179 +#define AMS_R_UNSUPPORTED_RECIPIENT_TYPE 154 +#define AMS_R_UNSUPPORTED_RECPIENTINFO_TYPE 155 +#define AMS_R_UNSUPPORTED_TYPE 156 +#define AMS_R_UNWRAP_ERROR 157 +#define AMS_R_UNWRAP_FAILURE 180 +#define AMS_R_VERIFICATION_FAILURE 158 +#define AMS_R_WRAP_ERROR 159 + +#ifdef __cplusplus +} +#endif +#endif diff --git a/server/external/openssl/linux_64/include/openssl/ams.h b/server/external/openssl/linux_64/include/openssl/ams.h new file mode 100644 index 0000000..672aa68 --- /dev/null +++ b/server/external/openssl/linux_64/include/openssl/ams.h @@ -0,0 +1,339 @@ +/* + * Copyright 2008-2019 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_AMS_H +# define HEADER_AMS_H + +# include + +# ifndef OPENSSL_NO_AMS +# include +# include +# include +# ifdef __cplusplus +extern "C" { +# endif + +typedef struct AMS_ContentInfo_st AMS_ContentInfo; +typedef struct AMS_SignerInfo_st AMS_SignerInfo; +typedef struct AMS_CertificateChoices AMS_CertificateChoices; +typedef struct AMS_RevocationInfoChoice_st AMS_RevocationInfoChoice; +typedef struct AMS_RecipientInfo_st AMS_RecipientInfo; +typedef struct AMS_ReceiptRequest_st AMS_ReceiptRequest; +typedef struct AMS_Receipt_st AMS_Receipt; +typedef struct AMS_RecipientEncryptedKey_st AMS_RecipientEncryptedKey; +typedef struct AMS_OtherKeyAttribute_st AMS_OtherKeyAttribute; + +DEFINE_STACK_OF(AMS_SignerInfo) +DEFINE_STACK_OF(AMS_RecipientEncryptedKey) +DEFINE_STACK_OF(AMS_RecipientInfo) +DEFINE_STACK_OF(AMS_RevocationInfoChoice) +DECLARE_ASN1_FUNCTIONS(AMS_ContentInfo) +DECLARE_ASN1_FUNCTIONS(AMS_ReceiptRequest) +DECLARE_ASN1_PRINT_FUNCTION(AMS_ContentInfo) + +# define AMS_SIGNERINFO_ISSUER_SERIAL 0 +# define AMS_SIGNERINFO_KEYIDENTIFIER 1 + +# define AMS_RECIPINFO_NONE -1 +# define AMS_RECIPINFO_TRANS 0 +# define AMS_RECIPINFO_AGREE 1 +# define AMS_RECIPINFO_KEK 2 +# define AMS_RECIPINFO_PASS 3 +# define AMS_RECIPINFO_OTHER 4 + +/* S/MIME related flags */ + +# define AMS_TEXT 0x1 +# define AMS_NOCERTS 0x2 +# define AMS_NO_CONTENT_VERIFY 0x4 +# define AMS_NO_ATTR_VERIFY 0x8 +# define AMS_NOSIGS \ + (AMS_NO_CONTENT_VERIFY|AMS_NO_ATTR_VERIFY) +# define AMS_NOINTERN 0x10 +# define AMS_NO_SIGNER_CERT_VERIFY 0x20 +# define AMS_NOVERIFY 0x20 +# define AMS_DETACHED 0x40 +# define AMS_BINARY 0x80 +# define AMS_NOATTR 0x100 +# define AMS_NOSMIMECAP 0x200 +# define AMS_NOOLDMIMETYPE 0x400 +# define AMS_CRLFEOL 0x800 +# define AMS_STREAM 0x1000 +# define AMS_NOCRL 0x2000 +# define AMS_PARTIAL 0x4000 +# define AMS_REUSE_DIGEST 0x8000 +# define AMS_USE_KEYID 0x10000 +# define AMS_DEBUG_DECRYPT 0x20000 +# define AMS_KEY_PARAM 0x40000 +# define AMS_ASCIICRLF 0x80000 + +const ASN1_OBJECT *AMS_get0_type(const AMS_ContentInfo *ams); + +BIO *AMS_dataInit(AMS_ContentInfo *ams, BIO *icont); +int AMS_dataFinal(AMS_ContentInfo *ams, BIO *bio); + +ASN1_OCTET_STRING **AMS_get0_content(AMS_ContentInfo *ams); +int AMS_is_detached(AMS_ContentInfo *ams); +int AMS_set_detached(AMS_ContentInfo *ams, int detached); + +# ifdef HEADER_PEM_H +DECLARE_PEM_rw_const(AMS, AMS_ContentInfo) +# endif +int AMS_stream(unsigned char ***boundary, AMS_ContentInfo *ams); +AMS_ContentInfo *d2i_AMS_bio(BIO *bp, AMS_ContentInfo **ams); +int i2d_AMS_bio(BIO *bp, AMS_ContentInfo *ams); + +BIO *BIO_new_AMS(BIO *out, AMS_ContentInfo *ams); +int i2d_AMS_bio_stream(BIO *out, AMS_ContentInfo *ams, BIO *in, int flags); +int PEM_write_bio_AMS_stream(BIO *out, AMS_ContentInfo *ams, BIO *in, + int flags); +AMS_ContentInfo *SMIME_read_AMS(BIO *bio, BIO **bcont); +int SMIME_write_AMS(BIO *bio, AMS_ContentInfo *ams, BIO *data, int flags); + +int AMS_final(AMS_ContentInfo *ams, BIO *data, BIO *dcont, + unsigned int flags); + +AMS_ContentInfo *AMS_sign(X509 *signcert, EVP_PKEY *pkey, + STACK_OF(X509) *certs, BIO *data, + unsigned int flags); + +AMS_ContentInfo *AMS_sign_receipt(AMS_SignerInfo *si, + X509 *signcert, EVP_PKEY *pkey, + STACK_OF(X509) *certs, unsigned int flags); + +int AMS_data(AMS_ContentInfo *ams, BIO *out, unsigned int flags); +AMS_ContentInfo *AMS_data_create(BIO *in, unsigned int flags); + +int AMS_digest_verify(AMS_ContentInfo *ams, BIO *dcont, BIO *out, + unsigned int flags); +AMS_ContentInfo *AMS_digest_create(BIO *in, const EVP_MD *md, + unsigned int flags); + +int AMS_EncryptedData_decrypt(AMS_ContentInfo *ams, + const unsigned char *key, size_t keylen, + BIO *dcont, BIO *out, unsigned int flags); + +AMS_ContentInfo *AMS_EncryptedData_encrypt(BIO *in, const EVP_CIPHER *cipher, + const unsigned char *key, + size_t keylen, unsigned int flags); + +int AMS_EncryptedData_set1_key(AMS_ContentInfo *ams, const EVP_CIPHER *ciph, + const unsigned char *key, size_t keylen); + +int AMS_verify(AMS_ContentInfo *ams, STACK_OF(X509) *certs, + X509_STORE *store, BIO *dcont, BIO *out, unsigned int flags); + +int AMS_verify_receipt(AMS_ContentInfo *rams, AMS_ContentInfo *oams, + STACK_OF(X509) *certs, + X509_STORE *store, unsigned int flags); + +STACK_OF(X509) *AMS_get0_signers(AMS_ContentInfo *ams); + +AMS_ContentInfo *AMS_encrypt(STACK_OF(X509) *certs, BIO *in, + const EVP_CIPHER *cipher, unsigned int flags); + +int AMS_decrypt(AMS_ContentInfo *ams, EVP_PKEY *pkey, X509 *cert, + BIO *dcont, BIO *out, unsigned int flags); + +int AMS_decrypt_set1_pkey(AMS_ContentInfo *ams, EVP_PKEY *pk, X509 *cert); +int AMS_decrypt_set1_key(AMS_ContentInfo *ams, + unsigned char *key, size_t keylen, + const unsigned char *id, size_t idlen); +int AMS_decrypt_set1_password(AMS_ContentInfo *ams, + unsigned char *pass, ossl_ssize_t passlen); + +STACK_OF(AMS_RecipientInfo) *AMS_get0_RecipientInfos(AMS_ContentInfo *ams); +int AMS_RecipientInfo_type(AMS_RecipientInfo *ri); +EVP_PKEY_CTX *AMS_RecipientInfo_get0_pkey_ctx(AMS_RecipientInfo *ri); +AMS_ContentInfo *AMS_EnvelopedData_create(const EVP_CIPHER *cipher); +AMS_RecipientInfo *AMS_add1_recipient_cert(AMS_ContentInfo *ams, + X509 *recip, unsigned int flags); +int AMS_RecipientInfo_set0_pkey(AMS_RecipientInfo *ri, EVP_PKEY *pkey); +int AMS_RecipientInfo_ktri_cert_cmp(AMS_RecipientInfo *ri, X509 *cert); +int AMS_RecipientInfo_ktri_get0_algs(AMS_RecipientInfo *ri, + EVP_PKEY **pk, X509 **recip, + X509_ALGOR **palg); +int AMS_RecipientInfo_ktri_get0_signer_id(AMS_RecipientInfo *ri, + ASN1_OCTET_STRING **keyid, + X509_NAME **issuer, + ASN1_INTEGER **sno); + +AMS_RecipientInfo *AMS_add0_recipient_key(AMS_ContentInfo *ams, int nid, + unsigned char *key, size_t keylen, + unsigned char *id, size_t idlen, + ASN1_GENERALIZEDTIME *date, + ASN1_OBJECT *otherTypeId, + ASN1_TYPE *otherType); + +int AMS_RecipientInfo_kekri_get0_id(AMS_RecipientInfo *ri, + X509_ALGOR **palg, + ASN1_OCTET_STRING **pid, + ASN1_GENERALIZEDTIME **pdate, + ASN1_OBJECT **potherid, + ASN1_TYPE **pothertype); + +int AMS_RecipientInfo_set0_key(AMS_RecipientInfo *ri, + unsigned char *key, size_t keylen); + +int AMS_RecipientInfo_kekri_id_cmp(AMS_RecipientInfo *ri, + const unsigned char *id, size_t idlen); + +int AMS_RecipientInfo_set0_password(AMS_RecipientInfo *ri, + unsigned char *pass, + ossl_ssize_t passlen); + +AMS_RecipientInfo *AMS_add0_recipient_password(AMS_ContentInfo *ams, + int iter, int wrap_nid, + int pbe_nid, + unsigned char *pass, + ossl_ssize_t passlen, + const EVP_CIPHER *kekciph); + +int AMS_RecipientInfo_decrypt(AMS_ContentInfo *ams, AMS_RecipientInfo *ri); +int AMS_RecipientInfo_encrypt(AMS_ContentInfo *ams, AMS_RecipientInfo *ri); + +int AMS_uncompress(AMS_ContentInfo *ams, BIO *dcont, BIO *out, + unsigned int flags); +AMS_ContentInfo *AMS_compress(BIO *in, int comp_nid, unsigned int flags); + +int AMS_set1_eContentType(AMS_ContentInfo *ams, const ASN1_OBJECT *oid); +const ASN1_OBJECT *AMS_get0_eContentType(AMS_ContentInfo *ams); + +AMS_CertificateChoices *AMS_add0_CertificateChoices(AMS_ContentInfo *ams); +int AMS_add0_cert(AMS_ContentInfo *ams, X509 *cert); +int AMS_add1_cert(AMS_ContentInfo *ams, X509 *cert); +STACK_OF(X509) *AMS_get1_certs(AMS_ContentInfo *ams); + +AMS_RevocationInfoChoice *AMS_add0_RevocationInfoChoice(AMS_ContentInfo *ams); +int AMS_add0_crl(AMS_ContentInfo *ams, X509_CRL *crl); +int AMS_add1_crl(AMS_ContentInfo *ams, X509_CRL *crl); +STACK_OF(X509_CRL) *AMS_get1_crls(AMS_ContentInfo *ams); + +int AMS_SignedData_init(AMS_ContentInfo *ams); +AMS_SignerInfo *AMS_add1_signer(AMS_ContentInfo *ams, + X509 *signer, EVP_PKEY *pk, const EVP_MD *md, + unsigned int flags); +EVP_PKEY_CTX *AMS_SignerInfo_get0_pkey_ctx(AMS_SignerInfo *si); +EVP_MD_CTX *AMS_SignerInfo_get0_md_ctx(AMS_SignerInfo *si); +STACK_OF(AMS_SignerInfo) *AMS_get0_SignerInfos(AMS_ContentInfo *ams); + +void AMS_SignerInfo_set1_signer_cert(AMS_SignerInfo *si, X509 *signer); +int AMS_SignerInfo_get0_signer_id(AMS_SignerInfo *si, + ASN1_OCTET_STRING **keyid, + X509_NAME **issuer, ASN1_INTEGER **sno); +int AMS_SignerInfo_cert_cmp(AMS_SignerInfo *si, X509 *cert); +int AMS_set1_signers_certs(AMS_ContentInfo *ams, STACK_OF(X509) *certs, + unsigned int flags); +void AMS_SignerInfo_get0_algs(AMS_SignerInfo *si, EVP_PKEY **pk, + X509 **signer, X509_ALGOR **pdig, + X509_ALGOR **psig); +ASN1_OCTET_STRING *AMS_SignerInfo_get0_signature(AMS_SignerInfo *si); +int AMS_SignerInfo_sign(AMS_SignerInfo *si); +int AMS_SignerInfo_verify(AMS_SignerInfo *si); +int AMS_SignerInfo_verify_content(AMS_SignerInfo *si, BIO *chain); + +int AMS_add_smimecap(AMS_SignerInfo *si, STACK_OF(X509_ALGOR) *algs); +int AMS_add_simple_smimecap(STACK_OF(X509_ALGOR) **algs, + int algnid, int keysize); +int AMS_add_standard_smimecap(STACK_OF(X509_ALGOR) **smcap); + +int AMS_signed_get_attr_count(const AMS_SignerInfo *si); +int AMS_signed_get_attr_by_NID(const AMS_SignerInfo *si, int nid, + int lastpos); +int AMS_signed_get_attr_by_OBJ(const AMS_SignerInfo *si, const ASN1_OBJECT *obj, + int lastpos); +X509_ATTRIBUTE *AMS_signed_get_attr(const AMS_SignerInfo *si, int loc); +X509_ATTRIBUTE *AMS_signed_delete_attr(AMS_SignerInfo *si, int loc); +int AMS_signed_add1_attr(AMS_SignerInfo *si, X509_ATTRIBUTE *attr); +int AMS_signed_add1_attr_by_OBJ(AMS_SignerInfo *si, + const ASN1_OBJECT *obj, int type, + const void *bytes, int len); +int AMS_signed_add1_attr_by_NID(AMS_SignerInfo *si, + int nid, int type, + const void *bytes, int len); +int AMS_signed_add1_attr_by_txt(AMS_SignerInfo *si, + const char *attrname, int type, + const void *bytes, int len); +void *AMS_signed_get0_data_by_OBJ(AMS_SignerInfo *si, const ASN1_OBJECT *oid, + int lastpos, int type); + +int AMS_unsigned_get_attr_count(const AMS_SignerInfo *si); +int AMS_unsigned_get_attr_by_NID(const AMS_SignerInfo *si, int nid, + int lastpos); +int AMS_unsigned_get_attr_by_OBJ(const AMS_SignerInfo *si, + const ASN1_OBJECT *obj, int lastpos); +X509_ATTRIBUTE *AMS_unsigned_get_attr(const AMS_SignerInfo *si, int loc); +X509_ATTRIBUTE *AMS_unsigned_delete_attr(AMS_SignerInfo *si, int loc); +int AMS_unsigned_add1_attr(AMS_SignerInfo *si, X509_ATTRIBUTE *attr); +int AMS_unsigned_add1_attr_by_OBJ(AMS_SignerInfo *si, + const ASN1_OBJECT *obj, int type, + const void *bytes, int len); +int AMS_unsigned_add1_attr_by_NID(AMS_SignerInfo *si, + int nid, int type, + const void *bytes, int len); +int AMS_unsigned_add1_attr_by_txt(AMS_SignerInfo *si, + const char *attrname, int type, + const void *bytes, int len); +void *AMS_unsigned_get0_data_by_OBJ(AMS_SignerInfo *si, ASN1_OBJECT *oid, + int lastpos, int type); + +int AMS_get1_ReceiptRequest(AMS_SignerInfo *si, AMS_ReceiptRequest **prr); +AMS_ReceiptRequest *AMS_ReceiptRequest_create0(unsigned char *id, int idlen, + int allorfirst, + STACK_OF(GENERAL_NAMES) + *receiptList, STACK_OF(GENERAL_NAMES) + *receiptsTo); +int AMS_add1_ReceiptRequest(AMS_SignerInfo *si, AMS_ReceiptRequest *rr); +void AMS_ReceiptRequest_get0_values(AMS_ReceiptRequest *rr, + ASN1_STRING **pcid, + int *pallorfirst, + STACK_OF(GENERAL_NAMES) **plist, + STACK_OF(GENERAL_NAMES) **prto); +int AMS_RecipientInfo_kari_get0_alg(AMS_RecipientInfo *ri, + X509_ALGOR **palg, + ASN1_OCTET_STRING **pukm); +STACK_OF(AMS_RecipientEncryptedKey) +*AMS_RecipientInfo_kari_get0_reks(AMS_RecipientInfo *ri); + +int AMS_RecipientInfo_kari_get0_orig_id(AMS_RecipientInfo *ri, + X509_ALGOR **pubalg, + ASN1_BIT_STRING **pubkey, + ASN1_OCTET_STRING **keyid, + X509_NAME **issuer, + ASN1_INTEGER **sno); + +int AMS_RecipientInfo_kari_orig_id_cmp(AMS_RecipientInfo *ri, X509 *cert); + +int AMS_RecipientEncryptedKey_get0_id(AMS_RecipientEncryptedKey *rek, + ASN1_OCTET_STRING **keyid, + ASN1_GENERALIZEDTIME **tm, + AMS_OtherKeyAttribute **other, + X509_NAME **issuer, ASN1_INTEGER **sno); +int AMS_RecipientEncryptedKey_cert_cmp(AMS_RecipientEncryptedKey *rek, + X509 *cert); +int AMS_RecipientInfo_kari_set0_pkey(AMS_RecipientInfo *ri, EVP_PKEY *pk); +EVP_CIPHER_CTX *AMS_RecipientInfo_kari_get0_ctx(AMS_RecipientInfo *ri); +int AMS_RecipientInfo_kari_decrypt(AMS_ContentInfo *ams, + AMS_RecipientInfo *ri, + AMS_RecipientEncryptedKey *rek); + +int AMS_SharedInfo_encode(unsigned char **pder, X509_ALGOR *kekalg, + ASN1_OCTET_STRING *ukm, int keylen); + +/* Backward compatibility for spelling errors. */ +# define AMS_R_UNKNOWN_DIGEST_ALGORITM AMS_R_UNKNOWN_DIGEST_ALGORITHM +# define AMS_R_UNSUPPORTED_RECPIENTINFO_TYPE \ + AMS_R_UNSUPPORTED_RECIPIENTINFO_TYPE + +# ifdef __cplusplus +} +# endif +# endif +#endif diff --git a/server/external/openssl/linux_64/include/openssl/amserr.h b/server/external/openssl/linux_64/include/openssl/amserr.h new file mode 100644 index 0000000..253fa92 --- /dev/null +++ b/server/external/openssl/linux_64/include/openssl/amserr.h @@ -0,0 +1,202 @@ +/* + * Generated by util/mkerr.pl DO NOT EDIT + * Copyright 1995-2019 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_AMSERR_H +# define HEADER_AMSERR_H + +# ifndef HEADER_SYMHACKS_H +# include +# endif + +# include + +# ifndef OPENSSL_NO_AMS + +# ifdef __cplusplus +extern "C" +# endif +int ERR_load_AMS_strings(void); + +/* + * AMS function codes. + */ +# define AMS_F_CHECK_CONTENT 99 +# define AMS_F_AMS_ADD0_CERT 164 +# define AMS_F_AMS_ADD0_RECIPIENT_KEY 100 +# define AMS_F_AMS_ADD0_RECIPIENT_PASSWORD 165 +# define AMS_F_AMS_ADD1_RECEIPTREQUEST 158 +# define AMS_F_AMS_ADD1_RECIPIENT_CERT 101 +# define AMS_F_AMS_ADD1_SIGNER 102 +# define AMS_F_AMS_ADD1_SIGNINGTIME 103 +# define AMS_F_AMS_COMPRESS 104 +# define AMS_F_AMS_COMPRESSEDDATA_CREATE 105 +# define AMS_F_AMS_COMPRESSEDDATA_INIT_BIO 106 +# define AMS_F_AMS_COPY_CONTENT 107 +# define AMS_F_AMS_COPY_MESSAGEDIGEST 108 +# define AMS_F_AMS_DATA 109 +# define AMS_F_AMS_DATAFINAL 110 +# define AMS_F_AMS_DATAINIT 111 +# define AMS_F_AMS_DECRYPT 112 +# define AMS_F_AMS_DECRYPT_SET1_KEY 113 +# define AMS_F_AMS_DECRYPT_SET1_PASSWORD 166 +# define AMS_F_AMS_DECRYPT_SET1_PKEY 114 +# define AMS_F_AMS_DIGESTALGORITHM_FIND_CTX 115 +# define AMS_F_AMS_DIGESTALGORITHM_INIT_BIO 116 +# define AMS_F_AMS_DIGESTEDDATA_DO_FINAL 117 +# define AMS_F_AMS_DIGEST_VERIFY 118 +# define AMS_F_AMS_ENCODE_RECEIPT 161 +# define AMS_F_AMS_ENCRYPT 119 +# define AMS_F_AMS_ENCRYPTEDCONTENT_INIT 179 +# define AMS_F_AMS_ENCRYPTEDCONTENT_INIT_BIO 120 +# define AMS_F_AMS_ENCRYPTEDDATA_DECRYPT 121 +# define AMS_F_AMS_ENCRYPTEDDATA_ENCRYPT 122 +# define AMS_F_AMS_ENCRYPTEDDATA_SET1_KEY 123 +# define AMS_F_AMS_ENVELOPEDDATA_CREATE 124 +# define AMS_F_AMS_ENVELOPEDDATA_INIT_BIO 125 +# define AMS_F_AMS_ENVELOPED_DATA_INIT 126 +# define AMS_F_AMS_ENV_ASN1_CTRL 171 +# define AMS_F_AMS_FINAL 127 +# define AMS_F_AMS_GET0_CERTIFICATE_CHOICES 128 +# define AMS_F_AMS_GET0_CONTENT 129 +# define AMS_F_AMS_GET0_ECONTENT_TYPE 130 +# define AMS_F_AMS_GET0_ENVELOPED 131 +# define AMS_F_AMS_GET0_REVOCATION_CHOICES 132 +# define AMS_F_AMS_GET0_SIGNED 133 +# define AMS_F_AMS_MSGSIGDIGEST_ADD1 162 +# define AMS_F_AMS_RECEIPTREQUEST_CREATE0 159 +# define AMS_F_AMS_RECEIPT_VERIFY 160 +# define AMS_F_AMS_RECIPIENTINFO_DECRYPT 134 +# define AMS_F_AMS_RECIPIENTINFO_ENCRYPT 169 +# define AMS_F_AMS_RECIPIENTINFO_KARI_ENCRYPT 178 +# define AMS_F_AMS_RECIPIENTINFO_KARI_GET0_ALG 175 +# define AMS_F_AMS_RECIPIENTINFO_KARI_GET0_ORIG_ID 173 +# define AMS_F_AMS_RECIPIENTINFO_KARI_GET0_REKS 172 +# define AMS_F_AMS_RECIPIENTINFO_KARI_ORIG_ID_CMP 174 +# define AMS_F_AMS_RECIPIENTINFO_KEKRI_DECRYPT 135 +# define AMS_F_AMS_RECIPIENTINFO_KEKRI_ENCRYPT 136 +# define AMS_F_AMS_RECIPIENTINFO_KEKRI_GET0_ID 137 +# define AMS_F_AMS_RECIPIENTINFO_KEKRI_ID_CMP 138 +# define AMS_F_AMS_RECIPIENTINFO_KTRI_CERT_CMP 139 +# define AMS_F_AMS_RECIPIENTINFO_KTRI_DECRYPT 140 +# define AMS_F_AMS_RECIPIENTINFO_KTRI_ENCRYPT 141 +# define AMS_F_AMS_RECIPIENTINFO_KTRI_GET0_ALGS 142 +# define AMS_F_AMS_RECIPIENTINFO_KTRI_GET0_SIGNER_ID 143 +# define AMS_F_AMS_RECIPIENTINFO_PWRI_CRYPT 167 +# define AMS_F_AMS_RECIPIENTINFO_SET0_KEY 144 +# define AMS_F_AMS_RECIPIENTINFO_SET0_PASSWORD 168 +# define AMS_F_AMS_RECIPIENTINFO_SET0_PKEY 145 +# define AMS_F_AMS_SD_ASN1_CTRL 170 +# define AMS_F_AMS_SET1_IAS 176 +# define AMS_F_AMS_SET1_KEYID 177 +# define AMS_F_AMS_SET1_SIGNERIDENTIFIER 146 +# define AMS_F_AMS_SET_DETACHED 147 +# define AMS_F_AMS_SIGN 148 +# define AMS_F_AMS_SIGNED_DATA_INIT 149 +# define AMS_F_AMS_SIGNERINFO_CONTENT_SIGN 150 +# define AMS_F_AMS_SIGNERINFO_SIGN 151 +# define AMS_F_AMS_SIGNERINFO_VERIFY 152 +# define AMS_F_AMS_SIGNERINFO_VERIFY_CERT 153 +# define AMS_F_AMS_SIGNERINFO_VERIFY_CONTENT 154 +# define AMS_F_AMS_SIGN_RECEIPT 163 +# define AMS_F_AMS_SI_CHECK_ATTRIBUTES 183 +# define AMS_F_AMS_STREAM 155 +# define AMS_F_AMS_UNCOMPRESS 156 +# define AMS_F_AMS_VERIFY 157 +# define AMS_F_KEK_UNWRAP_KEY 180 + +/* + * AMS reason codes. + */ +# define AMS_R_ADD_SIGNER_ERROR 99 +# define AMS_R_ATTRIBUTE_ERROR 161 +# define AMS_R_CERTIFICATE_ALREADY_PRESENT 175 +# define AMS_R_CERTIFICATE_HAS_NO_KEYID 160 +# define AMS_R_CERTIFICATE_VERIFY_ERROR 100 +# define AMS_R_CIPHER_INITIALISATION_ERROR 101 +# define AMS_R_CIPHER_PARAMETER_INITIALISATION_ERROR 102 +# define AMS_R_AMS_DATAFINAL_ERROR 103 +# define AMS_R_AMS_LIB 104 +# define AMS_R_CONTENTIDENTIFIER_MISMATCH 170 +# define AMS_R_CONTENT_NOT_FOUND 105 +# define AMS_R_CONTENT_TYPE_MISMATCH 171 +# define AMS_R_CONTENT_TYPE_NOT_COMPRESSED_DATA 106 +# define AMS_R_CONTENT_TYPE_NOT_ENVELOPED_DATA 107 +# define AMS_R_CONTENT_TYPE_NOT_SIGNED_DATA 108 +# define AMS_R_CONTENT_VERIFY_ERROR 109 +# define AMS_R_CTRL_ERROR 110 +# define AMS_R_CTRL_FAILURE 111 +# define AMS_R_DECRYPT_ERROR 112 +# define AMS_R_ERROR_GETTING_PUBLIC_KEY 113 +# define AMS_R_ERROR_READING_MESSAGEDIGEST_ATTRIBUTE 114 +# define AMS_R_ERROR_SETTING_KEY 115 +# define AMS_R_ERROR_SETTING_RECIPIENTINFO 116 +# define AMS_R_INVALID_ENCRYPTED_KEY_LENGTH 117 +# define AMS_R_INVALID_KEY_ENCRYPTION_PARAMETER 176 +# define AMS_R_INVALID_KEY_LENGTH 118 +# define AMS_R_MD_BIO_INIT_ERROR 119 +# define AMS_R_MESSAGEDIGEST_ATTRIBUTE_WRONG_LENGTH 120 +# define AMS_R_MESSAGEDIGEST_WRONG_LENGTH 121 +# define AMS_R_MSGSIGDIGEST_ERROR 172 +# define AMS_R_MSGSIGDIGEST_VERIFICATION_FAILURE 162 +# define AMS_R_MSGSIGDIGEST_WRONG_LENGTH 163 +# define AMS_R_NEED_ONE_SIGNER 164 +# define AMS_R_NOT_A_SIGNED_RECEIPT 165 +# define AMS_R_NOT_ENCRYPTED_DATA 122 +# define AMS_R_NOT_KEK 123 +# define AMS_R_NOT_KEY_AGREEMENT 181 +# define AMS_R_NOT_KEY_TRANSPORT 124 +# define AMS_R_NOT_PWRI 177 +# define AMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE 125 +# define AMS_R_NO_CIPHER 126 +# define AMS_R_NO_CONTENT 127 +# define AMS_R_NO_CONTENT_TYPE 173 +# define AMS_R_NO_DEFAULT_DIGEST 128 +# define AMS_R_NO_DIGEST_SET 129 +# define AMS_R_NO_KEY 130 +# define AMS_R_NO_KEY_OR_CERT 174 +# define AMS_R_NO_MATCHING_DIGEST 131 +# define AMS_R_NO_MATCHING_RECIPIENT 132 +# define AMS_R_NO_MATCHING_SIGNATURE 166 +# define AMS_R_NO_MSGSIGDIGEST 167 +# define AMS_R_NO_PASSWORD 178 +# define AMS_R_NO_PRIVATE_KEY 133 +# define AMS_R_NO_PUBLIC_KEY 134 +# define AMS_R_NO_RECEIPT_REQUEST 168 +# define AMS_R_NO_SIGNERS 135 +# define AMS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE 136 +# define AMS_R_RECEIPT_DECODE_ERROR 169 +# define AMS_R_RECIPIENT_ERROR 137 +# define AMS_R_SIGNER_CERTIFICATE_NOT_FOUND 138 +# define AMS_R_SIGNFINAL_ERROR 139 +# define AMS_R_SMIME_TEXT_ERROR 140 +# define AMS_R_STORE_INIT_ERROR 141 +# define AMS_R_TYPE_NOT_COMPRESSED_DATA 142 +# define AMS_R_TYPE_NOT_DATA 143 +# define AMS_R_TYPE_NOT_DIGESTED_DATA 144 +# define AMS_R_TYPE_NOT_ENCRYPTED_DATA 145 +# define AMS_R_TYPE_NOT_ENVELOPED_DATA 146 +# define AMS_R_UNABLE_TO_FINALIZE_CONTEXT 147 +# define AMS_R_UNKNOWN_CIPHER 148 +# define AMS_R_UNKNOWN_DIGEST_ALGORITHM 149 +# define AMS_R_UNKNOWN_ID 150 +# define AMS_R_UNSUPPORTED_COMPRESSION_ALGORITHM 151 +# define AMS_R_UNSUPPORTED_CONTENT_TYPE 152 +# define AMS_R_UNSUPPORTED_KEK_ALGORITHM 153 +# define AMS_R_UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM 179 +# define AMS_R_UNSUPPORTED_RECIPIENTINFO_TYPE 155 +# define AMS_R_UNSUPPORTED_RECIPIENT_TYPE 154 +# define AMS_R_UNSUPPORTED_TYPE 156 +# define AMS_R_UNWRAP_ERROR 157 +# define AMS_R_UNWRAP_FAILURE 180 +# define AMS_R_VERIFICATION_FAILURE 158 +# define AMS_R_WRAP_ERROR 159 + +# endif +#endif diff --git a/server/external/openssl/win_32/include/openssl/ams.h b/server/external/openssl/win_32/include/openssl/ams.h new file mode 100644 index 0000000..35b6bd0 --- /dev/null +++ b/server/external/openssl/win_32/include/openssl/ams.h @@ -0,0 +1,501 @@ +/* crypto/ams/ams.h */ +/* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL + * project. + */ +/* ==================================================================== + * Copyright (c) 2008 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * licensing@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + */ + + +#ifndef HEADER_AMS_H +#define HEADER_AMS_H + +#include + +#ifdef OPENSSL_NO_AMS +#error AMS is disabled. +#endif + +#ifdef __cplusplus +extern "C" { +#endif + + +typedef struct AMS_ContentInfo_st AMS_ContentInfo; +typedef struct AMS_SignerInfo_st AMS_SignerInfo; +typedef struct AMS_CertificateChoices AMS_CertificateChoices; +typedef struct AMS_RevocationInfoChoice_st AMS_RevocationInfoChoice; +typedef struct AMS_RecipientInfo_st AMS_RecipientInfo; +typedef struct AMS_ReceiptRequest_st AMS_ReceiptRequest; +typedef struct AMS_Receipt_st AMS_Receipt; + +DECLARE_STACK_OF(AMS_SignerInfo) +DECLARE_STACK_OF(GENERAL_NAMES) +DECLARE_ASN1_FUNCTIONS(AMS_ContentInfo) +DECLARE_ASN1_FUNCTIONS(AMS_ReceiptRequest) +DECLARE_ASN1_PRINT_FUNCTION(AMS_ContentInfo) + +#define AMS_SIGNERINFO_ISSUER_SERIAL 0 +#define AMS_SIGNERINFO_KEYIDENTIFIER 1 + +#define AMS_RECIPINFO_TRANS 0 +#define AMS_RECIPINFO_AGREE 1 +#define AMS_RECIPINFO_KEK 2 +#define AMS_RECIPINFO_PASS 3 +#define AMS_RECIPINFO_OTHER 4 + +/* S/MIME related flags */ + +#define AMS_TEXT 0x1 +#define AMS_NOCERTS 0x2 +#define AMS_NO_CONTENT_VERIFY 0x4 +#define AMS_NO_ATTR_VERIFY 0x8 +#define AMS_NOSIGS \ + (AMS_NO_CONTENT_VERIFY|AMS_NO_ATTR_VERIFY) +#define AMS_NOINTERN 0x10 +#define AMS_NO_SIGNER_CERT_VERIFY 0x20 +#define AMS_NOVERIFY 0x20 +#define AMS_DETACHED 0x40 +#define AMS_BINARY 0x80 +#define AMS_NOATTR 0x100 +#define AMS_NOSMIMECAP 0x200 +#define AMS_NOOLDMIMETYPE 0x400 +#define AMS_CRLFEOL 0x800 +#define AMS_STREAM 0x1000 +#define AMS_NOCRL 0x2000 +#define AMS_PARTIAL 0x4000 +#define AMS_REUSE_DIGEST 0x8000 +#define AMS_USE_KEYID 0x10000 +#define AMS_DEBUG_DECRYPT 0x20000 + +const ASN1_OBJECT *AMS_get0_type(AMS_ContentInfo *ams); + +BIO *AMS_dataInit(AMS_ContentInfo *ams, BIO *icont); +int AMS_dataFinal(AMS_ContentInfo *ams, BIO *bio); + +ASN1_OCTET_STRING **AMS_get0_content(AMS_ContentInfo *ams); +int AMS_is_detached(AMS_ContentInfo *ams); +int AMS_set_detached(AMS_ContentInfo *ams, int detached); + +#ifdef HEADER_PEM_H +DECLARE_PEM_rw_const(AMS, AMS_ContentInfo) +#endif + +int AMS_stream(unsigned char ***boundary, AMS_ContentInfo *ams); +AMS_ContentInfo *d2i_AMS_bio(BIO *bp, AMS_ContentInfo **ams); +int i2d_AMS_bio(BIO *bp, AMS_ContentInfo *ams); + +BIO *BIO_new_AMS(BIO *out, AMS_ContentInfo *ams); +int i2d_AMS_bio_stream(BIO *out, AMS_ContentInfo *ams, BIO *in, int flags); +int PEM_write_bio_AMS_stream(BIO *out, AMS_ContentInfo *ams, BIO *in, int flags); +AMS_ContentInfo *SMIME_read_AMS(BIO *bio, BIO **bcont); +int SMIME_write_AMS(BIO *bio, AMS_ContentInfo *ams, BIO *data, int flags); + +int AMS_final(AMS_ContentInfo *ams, BIO *data, BIO *dcont, unsigned int flags); + +AMS_ContentInfo *AMS_sign(X509 *signcert, EVP_PKEY *pkey, STACK_OF(X509) *certs, + BIO *data, unsigned int flags); + +AMS_ContentInfo *AMS_sign_receipt(AMS_SignerInfo *si, + X509 *signcert, EVP_PKEY *pkey, + STACK_OF(X509) *certs, + unsigned int flags); + +int AMS_data(AMS_ContentInfo *ams, BIO *out, unsigned int flags); +AMS_ContentInfo *AMS_data_create(BIO *in, unsigned int flags); + +int AMS_digest_verify(AMS_ContentInfo *ams, BIO *dcont, BIO *out, + unsigned int flags); +AMS_ContentInfo *AMS_digest_create(BIO *in, const EVP_MD *md, + unsigned int flags); + +int AMS_EncryptedData_decrypt(AMS_ContentInfo *ams, + const unsigned char *key, size_t keylen, + BIO *dcont, BIO *out, unsigned int flags); + +AMS_ContentInfo *AMS_EncryptedData_encrypt(BIO *in, const EVP_CIPHER *cipher, + const unsigned char *key, size_t keylen, + unsigned int flags); + +int AMS_EncryptedData_set1_key(AMS_ContentInfo *ams, const EVP_CIPHER *ciph, + const unsigned char *key, size_t keylen); + +int AMS_verify(AMS_ContentInfo *ams, STACK_OF(X509) *certs, + X509_STORE *store, BIO *dcont, BIO *out, unsigned int flags); + +int AMS_verify_receipt(AMS_ContentInfo *rams, AMS_ContentInfo *oams, + STACK_OF(X509) *certs, + X509_STORE *store, unsigned int flags); + +STACK_OF(X509) *AMS_get0_signers(AMS_ContentInfo *ams); + +AMS_ContentInfo *AMS_encrypt(STACK_OF(X509) *certs, BIO *in, + const EVP_CIPHER *cipher, unsigned int flags); + +int AMS_decrypt(AMS_ContentInfo *ams, EVP_PKEY *pkey, X509 *cert, + BIO *dcont, BIO *out, + unsigned int flags); + +int AMS_decrypt_set1_pkey(AMS_ContentInfo *ams, EVP_PKEY *pk, X509 *cert); +int AMS_decrypt_set1_key(AMS_ContentInfo *ams, + unsigned char *key, size_t keylen, + unsigned char *id, size_t idlen); +int AMS_decrypt_set1_password(AMS_ContentInfo *ams, + unsigned char *pass, ossl_ssize_t passlen); + +STACK_OF(AMS_RecipientInfo) *AMS_get0_RecipientInfos(AMS_ContentInfo *ams); +int AMS_RecipientInfo_type(AMS_RecipientInfo *ri); +AMS_ContentInfo *AMS_EnvelopedData_create(const EVP_CIPHER *cipher); +AMS_RecipientInfo *AMS_add1_recipient_cert(AMS_ContentInfo *ams, + X509 *recip, unsigned int flags); +int AMS_RecipientInfo_set0_pkey(AMS_RecipientInfo *ri, EVP_PKEY *pkey); +int AMS_RecipientInfo_ktri_cert_cmp(AMS_RecipientInfo *ri, X509 *cert); +int AMS_RecipientInfo_ktri_get0_algs(AMS_RecipientInfo *ri, + EVP_PKEY **pk, X509 **recip, + X509_ALGOR **palg); +int AMS_RecipientInfo_ktri_get0_signer_id(AMS_RecipientInfo *ri, + ASN1_OCTET_STRING **keyid, + X509_NAME **issuer, ASN1_INTEGER **sno); + +AMS_RecipientInfo *AMS_add0_recipient_key(AMS_ContentInfo *ams, int nid, + unsigned char *key, size_t keylen, + unsigned char *id, size_t idlen, + ASN1_GENERALIZEDTIME *date, + ASN1_OBJECT *otherTypeId, + ASN1_TYPE *otherType); + +int AMS_RecipientInfo_kekri_get0_id(AMS_RecipientInfo *ri, + X509_ALGOR **palg, + ASN1_OCTET_STRING **pid, + ASN1_GENERALIZEDTIME **pdate, + ASN1_OBJECT **potherid, + ASN1_TYPE **pothertype); + +int AMS_RecipientInfo_set0_key(AMS_RecipientInfo *ri, + unsigned char *key, size_t keylen); + +int AMS_RecipientInfo_kekri_id_cmp(AMS_RecipientInfo *ri, + const unsigned char *id, size_t idlen); + +int AMS_RecipientInfo_set0_password(AMS_RecipientInfo *ri, + unsigned char *pass, + ossl_ssize_t passlen); + +AMS_RecipientInfo *AMS_add0_recipient_password(AMS_ContentInfo *ams, + int iter, int wrap_nid, int pbe_nid, + unsigned char *pass, + ossl_ssize_t passlen, + const EVP_CIPHER *kekciph); + +int AMS_RecipientInfo_decrypt(AMS_ContentInfo *ams, AMS_RecipientInfo *ri); + +int AMS_uncompress(AMS_ContentInfo *ams, BIO *dcont, BIO *out, + unsigned int flags); +AMS_ContentInfo *AMS_compress(BIO *in, int comp_nid, unsigned int flags); + +int AMS_set1_eContentType(AMS_ContentInfo *ams, const ASN1_OBJECT *oid); +const ASN1_OBJECT *AMS_get0_eContentType(AMS_ContentInfo *ams); + +AMS_CertificateChoices *AMS_add0_CertificateChoices(AMS_ContentInfo *ams); +int AMS_add0_cert(AMS_ContentInfo *ams, X509 *cert); +int AMS_add1_cert(AMS_ContentInfo *ams, X509 *cert); +STACK_OF(X509) *AMS_get1_certs(AMS_ContentInfo *ams); + +AMS_RevocationInfoChoice *AMS_add0_RevocationInfoChoice(AMS_ContentInfo *ams); +int AMS_add0_crl(AMS_ContentInfo *ams, X509_CRL *crl); +int AMS_add1_crl(AMS_ContentInfo *ams, X509_CRL *crl); +STACK_OF(X509_CRL) *AMS_get1_crls(AMS_ContentInfo *ams); + +int AMS_SignedData_init(AMS_ContentInfo *ams); +AMS_SignerInfo *AMS_add1_signer(AMS_ContentInfo *ams, + X509 *signer, EVP_PKEY *pk, const EVP_MD *md, + unsigned int flags); +STACK_OF(AMS_SignerInfo) *AMS_get0_SignerInfos(AMS_ContentInfo *ams); + +void AMS_SignerInfo_set1_signer_cert(AMS_SignerInfo *si, X509 *signer); +int AMS_SignerInfo_get0_signer_id(AMS_SignerInfo *si, + ASN1_OCTET_STRING **keyid, + X509_NAME **issuer, ASN1_INTEGER **sno); +int AMS_SignerInfo_cert_cmp(AMS_SignerInfo *si, X509 *cert); +int AMS_set1_signers_certs(AMS_ContentInfo *ams, STACK_OF(X509) *certs, + unsigned int flags); +void AMS_SignerInfo_get0_algs(AMS_SignerInfo *si, EVP_PKEY **pk, X509 **signer, + X509_ALGOR **pdig, X509_ALGOR **psig); +int AMS_SignerInfo_sign(AMS_SignerInfo *si); +int AMS_SignerInfo_verify(AMS_SignerInfo *si); +int AMS_SignerInfo_verify_content(AMS_SignerInfo *si, BIO *chain); + +int AMS_add_smimecap(AMS_SignerInfo *si, STACK_OF(X509_ALGOR) *algs); +int AMS_add_simple_smimecap(STACK_OF(X509_ALGOR) **algs, + int algnid, int keysize); +int AMS_add_standard_smimecap(STACK_OF(X509_ALGOR) **smcap); + +int AMS_signed_get_attr_count(const AMS_SignerInfo *si); +int AMS_signed_get_attr_by_NID(const AMS_SignerInfo *si, int nid, + int lastpos); +int AMS_signed_get_attr_by_OBJ(const AMS_SignerInfo *si, ASN1_OBJECT *obj, + int lastpos); +X509_ATTRIBUTE *AMS_signed_get_attr(const AMS_SignerInfo *si, int loc); +X509_ATTRIBUTE *AMS_signed_delete_attr(AMS_SignerInfo *si, int loc); +int AMS_signed_add1_attr(AMS_SignerInfo *si, X509_ATTRIBUTE *attr); +int AMS_signed_add1_attr_by_OBJ(AMS_SignerInfo *si, + const ASN1_OBJECT *obj, int type, + const void *bytes, int len); +int AMS_signed_add1_attr_by_NID(AMS_SignerInfo *si, + int nid, int type, + const void *bytes, int len); +int AMS_signed_add1_attr_by_txt(AMS_SignerInfo *si, + const char *attrname, int type, + const void *bytes, int len); +void *AMS_signed_get0_data_by_OBJ(AMS_SignerInfo *si, ASN1_OBJECT *oid, + int lastpos, int type); + +int AMS_unsigned_get_attr_count(const AMS_SignerInfo *si); +int AMS_unsigned_get_attr_by_NID(const AMS_SignerInfo *si, int nid, + int lastpos); +int AMS_unsigned_get_attr_by_OBJ(const AMS_SignerInfo *si, ASN1_OBJECT *obj, + int lastpos); +X509_ATTRIBUTE *AMS_unsigned_get_attr(const AMS_SignerInfo *si, int loc); +X509_ATTRIBUTE *AMS_unsigned_delete_attr(AMS_SignerInfo *si, int loc); +int AMS_unsigned_add1_attr(AMS_SignerInfo *si, X509_ATTRIBUTE *attr); +int AMS_unsigned_add1_attr_by_OBJ(AMS_SignerInfo *si, + const ASN1_OBJECT *obj, int type, + const void *bytes, int len); +int AMS_unsigned_add1_attr_by_NID(AMS_SignerInfo *si, + int nid, int type, + const void *bytes, int len); +int AMS_unsigned_add1_attr_by_txt(AMS_SignerInfo *si, + const char *attrname, int type, + const void *bytes, int len); +void *AMS_unsigned_get0_data_by_OBJ(AMS_SignerInfo *si, ASN1_OBJECT *oid, + int lastpos, int type); + +#ifdef HEADER_X509V3_H + +int AMS_get1_ReceiptRequest(AMS_SignerInfo *si, AMS_ReceiptRequest **prr); +AMS_ReceiptRequest *AMS_ReceiptRequest_create0(unsigned char *id, int idlen, + int allorfirst, + STACK_OF(GENERAL_NAMES) *receiptList, + STACK_OF(GENERAL_NAMES) *receiptsTo); +int AMS_add1_ReceiptRequest(AMS_SignerInfo *si, AMS_ReceiptRequest *rr); +void AMS_ReceiptRequest_get0_values(AMS_ReceiptRequest *rr, + ASN1_STRING **pcid, + int *pallorfirst, + STACK_OF(GENERAL_NAMES) **plist, + STACK_OF(GENERAL_NAMES) **prto); + +#endif + +/* BEGIN ERROR CODES */ +/* The following lines are auto generated by the script mkerr.pl. Any changes + * made after this point may be overwritten when the script is next run. + */ +void ERR_load_AMS_strings(void); + +/* Error codes for the AMS functions. */ + +/* Function codes. */ +#define AMS_F_CHECK_CONTENT 99 +#define AMS_F_AMS_ADD0_CERT 164 +#define AMS_F_AMS_ADD0_RECIPIENT_KEY 100 +#define AMS_F_AMS_ADD0_RECIPIENT_PASSWORD 165 +#define AMS_F_AMS_ADD1_RECEIPTREQUEST 158 +#define AMS_F_AMS_ADD1_RECIPIENT_CERT 101 +#define AMS_F_AMS_ADD1_SIGNER 102 +#define AMS_F_AMS_ADD1_SIGNINGTIME 103 +#define AMS_F_AMS_COMPRESS 104 +#define AMS_F_AMS_COMPRESSEDDATA_CREATE 105 +#define AMS_F_AMS_COMPRESSEDDATA_INIT_BIO 106 +#define AMS_F_AMS_COPY_CONTENT 107 +#define AMS_F_AMS_COPY_MESSAGEDIGEST 108 +#define AMS_F_AMS_DATA 109 +#define AMS_F_AMS_DATAFINAL 110 +#define AMS_F_AMS_DATAINIT 111 +#define AMS_F_AMS_DECRYPT 112 +#define AMS_F_AMS_DECRYPT_SET1_KEY 113 +#define AMS_F_AMS_DECRYPT_SET1_PASSWORD 166 +#define AMS_F_AMS_DECRYPT_SET1_PKEY 114 +#define AMS_F_AMS_DIGESTALGORITHM_FIND_CTX 115 +#define AMS_F_AMS_DIGESTALGORITHM_INIT_BIO 116 +#define AMS_F_AMS_DIGESTEDDATA_DO_FINAL 117 +#define AMS_F_AMS_DIGEST_VERIFY 118 +#define AMS_F_AMS_ENCODE_RECEIPT 161 +#define AMS_F_AMS_ENCRYPT 119 +#define AMS_F_AMS_ENCRYPTEDCONTENT_INIT_BIO 120 +#define AMS_F_AMS_ENCRYPTEDDATA_DECRYPT 121 +#define AMS_F_AMS_ENCRYPTEDDATA_ENCRYPT 122 +#define AMS_F_AMS_ENCRYPTEDDATA_SET1_KEY 123 +#define AMS_F_AMS_ENVELOPEDDATA_CREATE 124 +#define AMS_F_AMS_ENVELOPEDDATA_INIT_BIO 125 +#define AMS_F_AMS_ENVELOPED_DATA_INIT 126 +#define AMS_F_AMS_FINAL 127 +#define AMS_F_AMS_GET0_CERTIFICATE_CHOICES 128 +#define AMS_F_AMS_GET0_CONTENT 129 +#define AMS_F_AMS_GET0_ECONTENT_TYPE 130 +#define AMS_F_AMS_GET0_ENVELOPED 131 +#define AMS_F_AMS_GET0_REVOCATION_CHOICES 132 +#define AMS_F_AMS_GET0_SIGNED 133 +#define AMS_F_AMS_MSGSIGDIGEST_ADD1 162 +#define AMS_F_AMS_RECEIPTREQUEST_CREATE0 159 +#define AMS_F_AMS_RECEIPT_VERIFY 160 +#define AMS_F_AMS_RECIPIENTINFO_DECRYPT 134 +#define AMS_F_AMS_RECIPIENTINFO_KEKRI_DECRYPT 135 +#define AMS_F_AMS_RECIPIENTINFO_KEKRI_ENCRYPT 136 +#define AMS_F_AMS_RECIPIENTINFO_KEKRI_GET0_ID 137 +#define AMS_F_AMS_RECIPIENTINFO_KEKRI_ID_CMP 138 +#define AMS_F_AMS_RECIPIENTINFO_KTRI_CERT_CMP 139 +#define AMS_F_AMS_RECIPIENTINFO_KTRI_DECRYPT 140 +#define AMS_F_AMS_RECIPIENTINFO_KTRI_ENCRYPT 141 +#define AMS_F_AMS_RECIPIENTINFO_KTRI_GET0_ALGS 142 +#define AMS_F_AMS_RECIPIENTINFO_KTRI_GET0_SIGNER_ID 143 +#define AMS_F_AMS_RECIPIENTINFO_PWRI_CRYPT 167 +#define AMS_F_AMS_RECIPIENTINFO_SET0_KEY 144 +#define AMS_F_AMS_RECIPIENTINFO_SET0_PASSWORD 168 +#define AMS_F_AMS_RECIPIENTINFO_SET0_PKEY 145 +#define AMS_F_AMS_SET1_SIGNERIDENTIFIER 146 +#define AMS_F_AMS_SET_DETACHED 147 +#define AMS_F_AMS_SIGN 148 +#define AMS_F_AMS_SIGNED_DATA_INIT 149 +#define AMS_F_AMS_SIGNERINFO_CONTENT_SIGN 150 +#define AMS_F_AMS_SIGNERINFO_SIGN 151 +#define AMS_F_AMS_SIGNERINFO_VERIFY 152 +#define AMS_F_AMS_SIGNERINFO_VERIFY_CERT 153 +#define AMS_F_AMS_SIGNERINFO_VERIFY_CONTENT 154 +#define AMS_F_AMS_SIGN_RECEIPT 163 +#define AMS_F_AMS_STREAM 155 +#define AMS_F_AMS_UNCOMPRESS 156 +#define AMS_F_AMS_VERIFY 157 + +/* Reason codes. */ +#define AMS_R_ADD_SIGNER_ERROR 99 +#define AMS_R_CERTIFICATE_ALREADY_PRESENT 175 +#define AMS_R_CERTIFICATE_HAS_NO_KEYID 160 +#define AMS_R_CERTIFICATE_VERIFY_ERROR 100 +#define AMS_R_CIPHER_INITIALISATION_ERROR 101 +#define AMS_R_CIPHER_PARAMETER_INITIALISATION_ERROR 102 +#define AMS_R_AMS_DATAFINAL_ERROR 103 +#define AMS_R_AMS_LIB 104 +#define AMS_R_CONTENTIDENTIFIER_MISMATCH 170 +#define AMS_R_CONTENT_NOT_FOUND 105 +#define AMS_R_CONTENT_TYPE_MISMATCH 171 +#define AMS_R_CONTENT_TYPE_NOT_COMPRESSED_DATA 106 +#define AMS_R_CONTENT_TYPE_NOT_ENVELOPED_DATA 107 +#define AMS_R_CONTENT_TYPE_NOT_SIGNED_DATA 108 +#define AMS_R_CONTENT_VERIFY_ERROR 109 +#define AMS_R_CTRL_ERROR 110 +#define AMS_R_CTRL_FAILURE 111 +#define AMS_R_DECRYPT_ERROR 112 +#define AMS_R_DIGEST_ERROR 161 +#define AMS_R_ERROR_GETTING_PUBLIC_KEY 113 +#define AMS_R_ERROR_READING_MESSAGEDIGEST_ATTRIBUTE 114 +#define AMS_R_ERROR_SETTING_KEY 115 +#define AMS_R_ERROR_SETTING_RECIPIENTINFO 116 +#define AMS_R_INVALID_ENCRYPTED_KEY_LENGTH 117 +#define AMS_R_INVALID_KEY_ENCRYPTION_PARAMETER 176 +#define AMS_R_INVALID_KEY_LENGTH 118 +#define AMS_R_MD_BIO_INIT_ERROR 119 +#define AMS_R_MESSAGEDIGEST_ATTRIBUTE_WRONG_LENGTH 120 +#define AMS_R_MESSAGEDIGEST_WRONG_LENGTH 121 +#define AMS_R_MSGSIGDIGEST_ERROR 172 +#define AMS_R_MSGSIGDIGEST_VERIFICATION_FAILURE 162 +#define AMS_R_MSGSIGDIGEST_WRONG_LENGTH 163 +#define AMS_R_NEED_ONE_SIGNER 164 +#define AMS_R_NOT_A_SIGNED_RECEIPT 165 +#define AMS_R_NOT_ENCRYPTED_DATA 122 +#define AMS_R_NOT_KEK 123 +#define AMS_R_NOT_KEY_TRANSPORT 124 +#define AMS_R_NOT_PWRI 177 +#define AMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE 125 +#define AMS_R_NO_CIPHER 126 +#define AMS_R_NO_CONTENT 127 +#define AMS_R_NO_CONTENT_TYPE 173 +#define AMS_R_NO_DEFAULT_DIGEST 128 +#define AMS_R_NO_DIGEST_SET 129 +#define AMS_R_NO_KEY 130 +#define AMS_R_NO_KEY_OR_CERT 174 +#define AMS_R_NO_MATCHING_DIGEST 131 +#define AMS_R_NO_MATCHING_RECIPIENT 132 +#define AMS_R_NO_MATCHING_SIGNATURE 166 +#define AMS_R_NO_MSGSIGDIGEST 167 +#define AMS_R_NO_PASSWORD 178 +#define AMS_R_NO_PRIVATE_KEY 133 +#define AMS_R_NO_PUBLIC_KEY 134 +#define AMS_R_NO_RECEIPT_REQUEST 168 +#define AMS_R_NO_SIGNERS 135 +#define AMS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE 136 +#define AMS_R_RECEIPT_DECODE_ERROR 169 +#define AMS_R_RECIPIENT_ERROR 137 +#define AMS_R_SIGNER_CERTIFICATE_NOT_FOUND 138 +#define AMS_R_SIGNFINAL_ERROR 139 +#define AMS_R_SMIME_TEXT_ERROR 140 +#define AMS_R_STORE_INIT_ERROR 141 +#define AMS_R_TYPE_NOT_COMPRESSED_DATA 142 +#define AMS_R_TYPE_NOT_DATA 143 +#define AMS_R_TYPE_NOT_DIGESTED_DATA 144 +#define AMS_R_TYPE_NOT_ENCRYPTED_DATA 145 +#define AMS_R_TYPE_NOT_ENVELOPED_DATA 146 +#define AMS_R_UNABLE_TO_FINALIZE_CONTEXT 147 +#define AMS_R_UNKNOWN_CIPHER 148 +#define AMS_R_UNKNOWN_DIGEST_ALGORIHM 149 +#define AMS_R_UNKNOWN_ID 150 +#define AMS_R_UNSUPPORTED_COMPRESSION_ALGORITHM 151 +#define AMS_R_UNSUPPORTED_CONTENT_TYPE 152 +#define AMS_R_UNSUPPORTED_KEK_ALGORITHM 153 +#define AMS_R_UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM 179 +#define AMS_R_UNSUPPORTED_RECIPIENT_TYPE 154 +#define AMS_R_UNSUPPORTED_RECPIENTINFO_TYPE 155 +#define AMS_R_UNSUPPORTED_TYPE 156 +#define AMS_R_UNWRAP_ERROR 157 +#define AMS_R_UNWRAP_FAILURE 180 +#define AMS_R_VERIFICATION_FAILURE 158 +#define AMS_R_WRAP_ERROR 159 + +#ifdef __cplusplus +} +#endif +#endif diff --git a/server/external/openssl/win_64/include/openssl/ams.h b/server/external/openssl/win_64/include/openssl/ams.h new file mode 100644 index 0000000..35b6bd0 --- /dev/null +++ b/server/external/openssl/win_64/include/openssl/ams.h @@ -0,0 +1,501 @@ +/* crypto/ams/ams.h */ +/* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL + * project. + */ +/* ==================================================================== + * Copyright (c) 2008 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * licensing@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + */ + + +#ifndef HEADER_AMS_H +#define HEADER_AMS_H + +#include + +#ifdef OPENSSL_NO_AMS +#error AMS is disabled. +#endif + +#ifdef __cplusplus +extern "C" { +#endif + + +typedef struct AMS_ContentInfo_st AMS_ContentInfo; +typedef struct AMS_SignerInfo_st AMS_SignerInfo; +typedef struct AMS_CertificateChoices AMS_CertificateChoices; +typedef struct AMS_RevocationInfoChoice_st AMS_RevocationInfoChoice; +typedef struct AMS_RecipientInfo_st AMS_RecipientInfo; +typedef struct AMS_ReceiptRequest_st AMS_ReceiptRequest; +typedef struct AMS_Receipt_st AMS_Receipt; + +DECLARE_STACK_OF(AMS_SignerInfo) +DECLARE_STACK_OF(GENERAL_NAMES) +DECLARE_ASN1_FUNCTIONS(AMS_ContentInfo) +DECLARE_ASN1_FUNCTIONS(AMS_ReceiptRequest) +DECLARE_ASN1_PRINT_FUNCTION(AMS_ContentInfo) + +#define AMS_SIGNERINFO_ISSUER_SERIAL 0 +#define AMS_SIGNERINFO_KEYIDENTIFIER 1 + +#define AMS_RECIPINFO_TRANS 0 +#define AMS_RECIPINFO_AGREE 1 +#define AMS_RECIPINFO_KEK 2 +#define AMS_RECIPINFO_PASS 3 +#define AMS_RECIPINFO_OTHER 4 + +/* S/MIME related flags */ + +#define AMS_TEXT 0x1 +#define AMS_NOCERTS 0x2 +#define AMS_NO_CONTENT_VERIFY 0x4 +#define AMS_NO_ATTR_VERIFY 0x8 +#define AMS_NOSIGS \ + (AMS_NO_CONTENT_VERIFY|AMS_NO_ATTR_VERIFY) +#define AMS_NOINTERN 0x10 +#define AMS_NO_SIGNER_CERT_VERIFY 0x20 +#define AMS_NOVERIFY 0x20 +#define AMS_DETACHED 0x40 +#define AMS_BINARY 0x80 +#define AMS_NOATTR 0x100 +#define AMS_NOSMIMECAP 0x200 +#define AMS_NOOLDMIMETYPE 0x400 +#define AMS_CRLFEOL 0x800 +#define AMS_STREAM 0x1000 +#define AMS_NOCRL 0x2000 +#define AMS_PARTIAL 0x4000 +#define AMS_REUSE_DIGEST 0x8000 +#define AMS_USE_KEYID 0x10000 +#define AMS_DEBUG_DECRYPT 0x20000 + +const ASN1_OBJECT *AMS_get0_type(AMS_ContentInfo *ams); + +BIO *AMS_dataInit(AMS_ContentInfo *ams, BIO *icont); +int AMS_dataFinal(AMS_ContentInfo *ams, BIO *bio); + +ASN1_OCTET_STRING **AMS_get0_content(AMS_ContentInfo *ams); +int AMS_is_detached(AMS_ContentInfo *ams); +int AMS_set_detached(AMS_ContentInfo *ams, int detached); + +#ifdef HEADER_PEM_H +DECLARE_PEM_rw_const(AMS, AMS_ContentInfo) +#endif + +int AMS_stream(unsigned char ***boundary, AMS_ContentInfo *ams); +AMS_ContentInfo *d2i_AMS_bio(BIO *bp, AMS_ContentInfo **ams); +int i2d_AMS_bio(BIO *bp, AMS_ContentInfo *ams); + +BIO *BIO_new_AMS(BIO *out, AMS_ContentInfo *ams); +int i2d_AMS_bio_stream(BIO *out, AMS_ContentInfo *ams, BIO *in, int flags); +int PEM_write_bio_AMS_stream(BIO *out, AMS_ContentInfo *ams, BIO *in, int flags); +AMS_ContentInfo *SMIME_read_AMS(BIO *bio, BIO **bcont); +int SMIME_write_AMS(BIO *bio, AMS_ContentInfo *ams, BIO *data, int flags); + +int AMS_final(AMS_ContentInfo *ams, BIO *data, BIO *dcont, unsigned int flags); + +AMS_ContentInfo *AMS_sign(X509 *signcert, EVP_PKEY *pkey, STACK_OF(X509) *certs, + BIO *data, unsigned int flags); + +AMS_ContentInfo *AMS_sign_receipt(AMS_SignerInfo *si, + X509 *signcert, EVP_PKEY *pkey, + STACK_OF(X509) *certs, + unsigned int flags); + +int AMS_data(AMS_ContentInfo *ams, BIO *out, unsigned int flags); +AMS_ContentInfo *AMS_data_create(BIO *in, unsigned int flags); + +int AMS_digest_verify(AMS_ContentInfo *ams, BIO *dcont, BIO *out, + unsigned int flags); +AMS_ContentInfo *AMS_digest_create(BIO *in, const EVP_MD *md, + unsigned int flags); + +int AMS_EncryptedData_decrypt(AMS_ContentInfo *ams, + const unsigned char *key, size_t keylen, + BIO *dcont, BIO *out, unsigned int flags); + +AMS_ContentInfo *AMS_EncryptedData_encrypt(BIO *in, const EVP_CIPHER *cipher, + const unsigned char *key, size_t keylen, + unsigned int flags); + +int AMS_EncryptedData_set1_key(AMS_ContentInfo *ams, const EVP_CIPHER *ciph, + const unsigned char *key, size_t keylen); + +int AMS_verify(AMS_ContentInfo *ams, STACK_OF(X509) *certs, + X509_STORE *store, BIO *dcont, BIO *out, unsigned int flags); + +int AMS_verify_receipt(AMS_ContentInfo *rams, AMS_ContentInfo *oams, + STACK_OF(X509) *certs, + X509_STORE *store, unsigned int flags); + +STACK_OF(X509) *AMS_get0_signers(AMS_ContentInfo *ams); + +AMS_ContentInfo *AMS_encrypt(STACK_OF(X509) *certs, BIO *in, + const EVP_CIPHER *cipher, unsigned int flags); + +int AMS_decrypt(AMS_ContentInfo *ams, EVP_PKEY *pkey, X509 *cert, + BIO *dcont, BIO *out, + unsigned int flags); + +int AMS_decrypt_set1_pkey(AMS_ContentInfo *ams, EVP_PKEY *pk, X509 *cert); +int AMS_decrypt_set1_key(AMS_ContentInfo *ams, + unsigned char *key, size_t keylen, + unsigned char *id, size_t idlen); +int AMS_decrypt_set1_password(AMS_ContentInfo *ams, + unsigned char *pass, ossl_ssize_t passlen); + +STACK_OF(AMS_RecipientInfo) *AMS_get0_RecipientInfos(AMS_ContentInfo *ams); +int AMS_RecipientInfo_type(AMS_RecipientInfo *ri); +AMS_ContentInfo *AMS_EnvelopedData_create(const EVP_CIPHER *cipher); +AMS_RecipientInfo *AMS_add1_recipient_cert(AMS_ContentInfo *ams, + X509 *recip, unsigned int flags); +int AMS_RecipientInfo_set0_pkey(AMS_RecipientInfo *ri, EVP_PKEY *pkey); +int AMS_RecipientInfo_ktri_cert_cmp(AMS_RecipientInfo *ri, X509 *cert); +int AMS_RecipientInfo_ktri_get0_algs(AMS_RecipientInfo *ri, + EVP_PKEY **pk, X509 **recip, + X509_ALGOR **palg); +int AMS_RecipientInfo_ktri_get0_signer_id(AMS_RecipientInfo *ri, + ASN1_OCTET_STRING **keyid, + X509_NAME **issuer, ASN1_INTEGER **sno); + +AMS_RecipientInfo *AMS_add0_recipient_key(AMS_ContentInfo *ams, int nid, + unsigned char *key, size_t keylen, + unsigned char *id, size_t idlen, + ASN1_GENERALIZEDTIME *date, + ASN1_OBJECT *otherTypeId, + ASN1_TYPE *otherType); + +int AMS_RecipientInfo_kekri_get0_id(AMS_RecipientInfo *ri, + X509_ALGOR **palg, + ASN1_OCTET_STRING **pid, + ASN1_GENERALIZEDTIME **pdate, + ASN1_OBJECT **potherid, + ASN1_TYPE **pothertype); + +int AMS_RecipientInfo_set0_key(AMS_RecipientInfo *ri, + unsigned char *key, size_t keylen); + +int AMS_RecipientInfo_kekri_id_cmp(AMS_RecipientInfo *ri, + const unsigned char *id, size_t idlen); + +int AMS_RecipientInfo_set0_password(AMS_RecipientInfo *ri, + unsigned char *pass, + ossl_ssize_t passlen); + +AMS_RecipientInfo *AMS_add0_recipient_password(AMS_ContentInfo *ams, + int iter, int wrap_nid, int pbe_nid, + unsigned char *pass, + ossl_ssize_t passlen, + const EVP_CIPHER *kekciph); + +int AMS_RecipientInfo_decrypt(AMS_ContentInfo *ams, AMS_RecipientInfo *ri); + +int AMS_uncompress(AMS_ContentInfo *ams, BIO *dcont, BIO *out, + unsigned int flags); +AMS_ContentInfo *AMS_compress(BIO *in, int comp_nid, unsigned int flags); + +int AMS_set1_eContentType(AMS_ContentInfo *ams, const ASN1_OBJECT *oid); +const ASN1_OBJECT *AMS_get0_eContentType(AMS_ContentInfo *ams); + +AMS_CertificateChoices *AMS_add0_CertificateChoices(AMS_ContentInfo *ams); +int AMS_add0_cert(AMS_ContentInfo *ams, X509 *cert); +int AMS_add1_cert(AMS_ContentInfo *ams, X509 *cert); +STACK_OF(X509) *AMS_get1_certs(AMS_ContentInfo *ams); + +AMS_RevocationInfoChoice *AMS_add0_RevocationInfoChoice(AMS_ContentInfo *ams); +int AMS_add0_crl(AMS_ContentInfo *ams, X509_CRL *crl); +int AMS_add1_crl(AMS_ContentInfo *ams, X509_CRL *crl); +STACK_OF(X509_CRL) *AMS_get1_crls(AMS_ContentInfo *ams); + +int AMS_SignedData_init(AMS_ContentInfo *ams); +AMS_SignerInfo *AMS_add1_signer(AMS_ContentInfo *ams, + X509 *signer, EVP_PKEY *pk, const EVP_MD *md, + unsigned int flags); +STACK_OF(AMS_SignerInfo) *AMS_get0_SignerInfos(AMS_ContentInfo *ams); + +void AMS_SignerInfo_set1_signer_cert(AMS_SignerInfo *si, X509 *signer); +int AMS_SignerInfo_get0_signer_id(AMS_SignerInfo *si, + ASN1_OCTET_STRING **keyid, + X509_NAME **issuer, ASN1_INTEGER **sno); +int AMS_SignerInfo_cert_cmp(AMS_SignerInfo *si, X509 *cert); +int AMS_set1_signers_certs(AMS_ContentInfo *ams, STACK_OF(X509) *certs, + unsigned int flags); +void AMS_SignerInfo_get0_algs(AMS_SignerInfo *si, EVP_PKEY **pk, X509 **signer, + X509_ALGOR **pdig, X509_ALGOR **psig); +int AMS_SignerInfo_sign(AMS_SignerInfo *si); +int AMS_SignerInfo_verify(AMS_SignerInfo *si); +int AMS_SignerInfo_verify_content(AMS_SignerInfo *si, BIO *chain); + +int AMS_add_smimecap(AMS_SignerInfo *si, STACK_OF(X509_ALGOR) *algs); +int AMS_add_simple_smimecap(STACK_OF(X509_ALGOR) **algs, + int algnid, int keysize); +int AMS_add_standard_smimecap(STACK_OF(X509_ALGOR) **smcap); + +int AMS_signed_get_attr_count(const AMS_SignerInfo *si); +int AMS_signed_get_attr_by_NID(const AMS_SignerInfo *si, int nid, + int lastpos); +int AMS_signed_get_attr_by_OBJ(const AMS_SignerInfo *si, ASN1_OBJECT *obj, + int lastpos); +X509_ATTRIBUTE *AMS_signed_get_attr(const AMS_SignerInfo *si, int loc); +X509_ATTRIBUTE *AMS_signed_delete_attr(AMS_SignerInfo *si, int loc); +int AMS_signed_add1_attr(AMS_SignerInfo *si, X509_ATTRIBUTE *attr); +int AMS_signed_add1_attr_by_OBJ(AMS_SignerInfo *si, + const ASN1_OBJECT *obj, int type, + const void *bytes, int len); +int AMS_signed_add1_attr_by_NID(AMS_SignerInfo *si, + int nid, int type, + const void *bytes, int len); +int AMS_signed_add1_attr_by_txt(AMS_SignerInfo *si, + const char *attrname, int type, + const void *bytes, int len); +void *AMS_signed_get0_data_by_OBJ(AMS_SignerInfo *si, ASN1_OBJECT *oid, + int lastpos, int type); + +int AMS_unsigned_get_attr_count(const AMS_SignerInfo *si); +int AMS_unsigned_get_attr_by_NID(const AMS_SignerInfo *si, int nid, + int lastpos); +int AMS_unsigned_get_attr_by_OBJ(const AMS_SignerInfo *si, ASN1_OBJECT *obj, + int lastpos); +X509_ATTRIBUTE *AMS_unsigned_get_attr(const AMS_SignerInfo *si, int loc); +X509_ATTRIBUTE *AMS_unsigned_delete_attr(AMS_SignerInfo *si, int loc); +int AMS_unsigned_add1_attr(AMS_SignerInfo *si, X509_ATTRIBUTE *attr); +int AMS_unsigned_add1_attr_by_OBJ(AMS_SignerInfo *si, + const ASN1_OBJECT *obj, int type, + const void *bytes, int len); +int AMS_unsigned_add1_attr_by_NID(AMS_SignerInfo *si, + int nid, int type, + const void *bytes, int len); +int AMS_unsigned_add1_attr_by_txt(AMS_SignerInfo *si, + const char *attrname, int type, + const void *bytes, int len); +void *AMS_unsigned_get0_data_by_OBJ(AMS_SignerInfo *si, ASN1_OBJECT *oid, + int lastpos, int type); + +#ifdef HEADER_X509V3_H + +int AMS_get1_ReceiptRequest(AMS_SignerInfo *si, AMS_ReceiptRequest **prr); +AMS_ReceiptRequest *AMS_ReceiptRequest_create0(unsigned char *id, int idlen, + int allorfirst, + STACK_OF(GENERAL_NAMES) *receiptList, + STACK_OF(GENERAL_NAMES) *receiptsTo); +int AMS_add1_ReceiptRequest(AMS_SignerInfo *si, AMS_ReceiptRequest *rr); +void AMS_ReceiptRequest_get0_values(AMS_ReceiptRequest *rr, + ASN1_STRING **pcid, + int *pallorfirst, + STACK_OF(GENERAL_NAMES) **plist, + STACK_OF(GENERAL_NAMES) **prto); + +#endif + +/* BEGIN ERROR CODES */ +/* The following lines are auto generated by the script mkerr.pl. Any changes + * made after this point may be overwritten when the script is next run. + */ +void ERR_load_AMS_strings(void); + +/* Error codes for the AMS functions. */ + +/* Function codes. */ +#define AMS_F_CHECK_CONTENT 99 +#define AMS_F_AMS_ADD0_CERT 164 +#define AMS_F_AMS_ADD0_RECIPIENT_KEY 100 +#define AMS_F_AMS_ADD0_RECIPIENT_PASSWORD 165 +#define AMS_F_AMS_ADD1_RECEIPTREQUEST 158 +#define AMS_F_AMS_ADD1_RECIPIENT_CERT 101 +#define AMS_F_AMS_ADD1_SIGNER 102 +#define AMS_F_AMS_ADD1_SIGNINGTIME 103 +#define AMS_F_AMS_COMPRESS 104 +#define AMS_F_AMS_COMPRESSEDDATA_CREATE 105 +#define AMS_F_AMS_COMPRESSEDDATA_INIT_BIO 106 +#define AMS_F_AMS_COPY_CONTENT 107 +#define AMS_F_AMS_COPY_MESSAGEDIGEST 108 +#define AMS_F_AMS_DATA 109 +#define AMS_F_AMS_DATAFINAL 110 +#define AMS_F_AMS_DATAINIT 111 +#define AMS_F_AMS_DECRYPT 112 +#define AMS_F_AMS_DECRYPT_SET1_KEY 113 +#define AMS_F_AMS_DECRYPT_SET1_PASSWORD 166 +#define AMS_F_AMS_DECRYPT_SET1_PKEY 114 +#define AMS_F_AMS_DIGESTALGORITHM_FIND_CTX 115 +#define AMS_F_AMS_DIGESTALGORITHM_INIT_BIO 116 +#define AMS_F_AMS_DIGESTEDDATA_DO_FINAL 117 +#define AMS_F_AMS_DIGEST_VERIFY 118 +#define AMS_F_AMS_ENCODE_RECEIPT 161 +#define AMS_F_AMS_ENCRYPT 119 +#define AMS_F_AMS_ENCRYPTEDCONTENT_INIT_BIO 120 +#define AMS_F_AMS_ENCRYPTEDDATA_DECRYPT 121 +#define AMS_F_AMS_ENCRYPTEDDATA_ENCRYPT 122 +#define AMS_F_AMS_ENCRYPTEDDATA_SET1_KEY 123 +#define AMS_F_AMS_ENVELOPEDDATA_CREATE 124 +#define AMS_F_AMS_ENVELOPEDDATA_INIT_BIO 125 +#define AMS_F_AMS_ENVELOPED_DATA_INIT 126 +#define AMS_F_AMS_FINAL 127 +#define AMS_F_AMS_GET0_CERTIFICATE_CHOICES 128 +#define AMS_F_AMS_GET0_CONTENT 129 +#define AMS_F_AMS_GET0_ECONTENT_TYPE 130 +#define AMS_F_AMS_GET0_ENVELOPED 131 +#define AMS_F_AMS_GET0_REVOCATION_CHOICES 132 +#define AMS_F_AMS_GET0_SIGNED 133 +#define AMS_F_AMS_MSGSIGDIGEST_ADD1 162 +#define AMS_F_AMS_RECEIPTREQUEST_CREATE0 159 +#define AMS_F_AMS_RECEIPT_VERIFY 160 +#define AMS_F_AMS_RECIPIENTINFO_DECRYPT 134 +#define AMS_F_AMS_RECIPIENTINFO_KEKRI_DECRYPT 135 +#define AMS_F_AMS_RECIPIENTINFO_KEKRI_ENCRYPT 136 +#define AMS_F_AMS_RECIPIENTINFO_KEKRI_GET0_ID 137 +#define AMS_F_AMS_RECIPIENTINFO_KEKRI_ID_CMP 138 +#define AMS_F_AMS_RECIPIENTINFO_KTRI_CERT_CMP 139 +#define AMS_F_AMS_RECIPIENTINFO_KTRI_DECRYPT 140 +#define AMS_F_AMS_RECIPIENTINFO_KTRI_ENCRYPT 141 +#define AMS_F_AMS_RECIPIENTINFO_KTRI_GET0_ALGS 142 +#define AMS_F_AMS_RECIPIENTINFO_KTRI_GET0_SIGNER_ID 143 +#define AMS_F_AMS_RECIPIENTINFO_PWRI_CRYPT 167 +#define AMS_F_AMS_RECIPIENTINFO_SET0_KEY 144 +#define AMS_F_AMS_RECIPIENTINFO_SET0_PASSWORD 168 +#define AMS_F_AMS_RECIPIENTINFO_SET0_PKEY 145 +#define AMS_F_AMS_SET1_SIGNERIDENTIFIER 146 +#define AMS_F_AMS_SET_DETACHED 147 +#define AMS_F_AMS_SIGN 148 +#define AMS_F_AMS_SIGNED_DATA_INIT 149 +#define AMS_F_AMS_SIGNERINFO_CONTENT_SIGN 150 +#define AMS_F_AMS_SIGNERINFO_SIGN 151 +#define AMS_F_AMS_SIGNERINFO_VERIFY 152 +#define AMS_F_AMS_SIGNERINFO_VERIFY_CERT 153 +#define AMS_F_AMS_SIGNERINFO_VERIFY_CONTENT 154 +#define AMS_F_AMS_SIGN_RECEIPT 163 +#define AMS_F_AMS_STREAM 155 +#define AMS_F_AMS_UNCOMPRESS 156 +#define AMS_F_AMS_VERIFY 157 + +/* Reason codes. */ +#define AMS_R_ADD_SIGNER_ERROR 99 +#define AMS_R_CERTIFICATE_ALREADY_PRESENT 175 +#define AMS_R_CERTIFICATE_HAS_NO_KEYID 160 +#define AMS_R_CERTIFICATE_VERIFY_ERROR 100 +#define AMS_R_CIPHER_INITIALISATION_ERROR 101 +#define AMS_R_CIPHER_PARAMETER_INITIALISATION_ERROR 102 +#define AMS_R_AMS_DATAFINAL_ERROR 103 +#define AMS_R_AMS_LIB 104 +#define AMS_R_CONTENTIDENTIFIER_MISMATCH 170 +#define AMS_R_CONTENT_NOT_FOUND 105 +#define AMS_R_CONTENT_TYPE_MISMATCH 171 +#define AMS_R_CONTENT_TYPE_NOT_COMPRESSED_DATA 106 +#define AMS_R_CONTENT_TYPE_NOT_ENVELOPED_DATA 107 +#define AMS_R_CONTENT_TYPE_NOT_SIGNED_DATA 108 +#define AMS_R_CONTENT_VERIFY_ERROR 109 +#define AMS_R_CTRL_ERROR 110 +#define AMS_R_CTRL_FAILURE 111 +#define AMS_R_DECRYPT_ERROR 112 +#define AMS_R_DIGEST_ERROR 161 +#define AMS_R_ERROR_GETTING_PUBLIC_KEY 113 +#define AMS_R_ERROR_READING_MESSAGEDIGEST_ATTRIBUTE 114 +#define AMS_R_ERROR_SETTING_KEY 115 +#define AMS_R_ERROR_SETTING_RECIPIENTINFO 116 +#define AMS_R_INVALID_ENCRYPTED_KEY_LENGTH 117 +#define AMS_R_INVALID_KEY_ENCRYPTION_PARAMETER 176 +#define AMS_R_INVALID_KEY_LENGTH 118 +#define AMS_R_MD_BIO_INIT_ERROR 119 +#define AMS_R_MESSAGEDIGEST_ATTRIBUTE_WRONG_LENGTH 120 +#define AMS_R_MESSAGEDIGEST_WRONG_LENGTH 121 +#define AMS_R_MSGSIGDIGEST_ERROR 172 +#define AMS_R_MSGSIGDIGEST_VERIFICATION_FAILURE 162 +#define AMS_R_MSGSIGDIGEST_WRONG_LENGTH 163 +#define AMS_R_NEED_ONE_SIGNER 164 +#define AMS_R_NOT_A_SIGNED_RECEIPT 165 +#define AMS_R_NOT_ENCRYPTED_DATA 122 +#define AMS_R_NOT_KEK 123 +#define AMS_R_NOT_KEY_TRANSPORT 124 +#define AMS_R_NOT_PWRI 177 +#define AMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE 125 +#define AMS_R_NO_CIPHER 126 +#define AMS_R_NO_CONTENT 127 +#define AMS_R_NO_CONTENT_TYPE 173 +#define AMS_R_NO_DEFAULT_DIGEST 128 +#define AMS_R_NO_DIGEST_SET 129 +#define AMS_R_NO_KEY 130 +#define AMS_R_NO_KEY_OR_CERT 174 +#define AMS_R_NO_MATCHING_DIGEST 131 +#define AMS_R_NO_MATCHING_RECIPIENT 132 +#define AMS_R_NO_MATCHING_SIGNATURE 166 +#define AMS_R_NO_MSGSIGDIGEST 167 +#define AMS_R_NO_PASSWORD 178 +#define AMS_R_NO_PRIVATE_KEY 133 +#define AMS_R_NO_PUBLIC_KEY 134 +#define AMS_R_NO_RECEIPT_REQUEST 168 +#define AMS_R_NO_SIGNERS 135 +#define AMS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE 136 +#define AMS_R_RECEIPT_DECODE_ERROR 169 +#define AMS_R_RECIPIENT_ERROR 137 +#define AMS_R_SIGNER_CERTIFICATE_NOT_FOUND 138 +#define AMS_R_SIGNFINAL_ERROR 139 +#define AMS_R_SMIME_TEXT_ERROR 140 +#define AMS_R_STORE_INIT_ERROR 141 +#define AMS_R_TYPE_NOT_COMPRESSED_DATA 142 +#define AMS_R_TYPE_NOT_DATA 143 +#define AMS_R_TYPE_NOT_DIGESTED_DATA 144 +#define AMS_R_TYPE_NOT_ENCRYPTED_DATA 145 +#define AMS_R_TYPE_NOT_ENVELOPED_DATA 146 +#define AMS_R_UNABLE_TO_FINALIZE_CONTEXT 147 +#define AMS_R_UNKNOWN_CIPHER 148 +#define AMS_R_UNKNOWN_DIGEST_ALGORIHM 149 +#define AMS_R_UNKNOWN_ID 150 +#define AMS_R_UNSUPPORTED_COMPRESSION_ALGORITHM 151 +#define AMS_R_UNSUPPORTED_CONTENT_TYPE 152 +#define AMS_R_UNSUPPORTED_KEK_ALGORITHM 153 +#define AMS_R_UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM 179 +#define AMS_R_UNSUPPORTED_RECIPIENT_TYPE 154 +#define AMS_R_UNSUPPORTED_RECPIENTINFO_TYPE 155 +#define AMS_R_UNSUPPORTED_TYPE 156 +#define AMS_R_UNWRAP_ERROR 157 +#define AMS_R_UNWRAP_FAILURE 180 +#define AMS_R_VERIFICATION_FAILURE 158 +#define AMS_R_WRAP_ERROR 159 + +#ifdef __cplusplus +} +#endif +#endif diff --git a/server/src/am_auto_task.cpp b/server/src/am_auto_task.cpp new file mode 100644 index 0000000..3b679c7 --- /dev/null +++ b/server/src/am_auto_task.cpp @@ -0,0 +1,218 @@ +/* + * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. + * + * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + + +/* + * cm_auto_task.cpp - + */ + +#include +#include + +#include "cm_auto_task.h" +#include "cm_porting.h" +#include "cm_dep.h" +#include "cm_server_util.h" +#include "cm_config.h" +#include "cm_user.h" +#include "cm_text_encryption.h" +#include "string.h" +#include "stdlib.h" + +#if defined(WINDOWS) +#include +#else +#include +#endif + +#ifdef _DEBUG_ +#include "deb.h" +#endif + +int +ts_validate_user (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char *id, *passwd; + char strbuf[1024]; + int retval, i; + T_DBMT_USER dbmt_user; + + id = nv_get_val (req, "id"); + passwd = nv_get_val (req, "password"); + + nv_update_val (res, "task", "authenticate"); + /* id, passwd checking */ + if (id == NULL) + { + sprintf (_dbmt_error, "%s", "parameter(id) is missing in request."); + ut_error_log (req, "ID not specified in the request"); + return ERR_PARAM_MISSING; + } + + if (passwd == NULL) + { + sprintf (_dbmt_error, "%s", + "parameter(password) is missing in request."); + ut_error_log (req, "password not specified in the request."); + return ERR_PARAM_MISSING; + } + + if (dbmt_user_read (&dbmt_user, strbuf) != ERR_NO_ERROR) + { + sprintf (_dbmt_error, "%s", "password file open error"); + ut_error_log (req, "Failed to read user info"); + return ERR_WITH_MSG; + } + + retval = -1; + for (i = 0; i < dbmt_user.num_dbmt_user; i++) + { + if (strcmp (dbmt_user.user_info[i].user_name, id) == 0) + { + char decrypted[PASSWD_LENGTH + 1]; + + uDecrypt (PASSWD_LENGTH, dbmt_user.user_info[i].user_passwd, + decrypted); + if (uStringEqual (passwd, decrypted)) + { + nv_update_val (res, "status", "success"); + retval = ERR_NO_ERROR; + } + else + { + ut_error_log (req, "Incorrect password"); + sprintf (_dbmt_error, "Incorrect password"); + retval = ERR_WITH_MSG; + } + break; + } + } + dbmt_user_free (&dbmt_user); + + if (retval < 0) + { + sprintf (_dbmt_error, "%s", "user not found."); + ut_error_log (req, "User not found."); + return ERR_WITH_MSG; + } + + return retval; +} + +int +ts_check_client_version (nvplist *req, nvplist *res) +{ + char *p; + int major_ver, minor_ver; + T_EMGR_VERSION clt_ver; + + major_ver = minor_ver = 0; + p = nv_get_val (req, "clientver"); + if (p != NULL) + { + major_ver = atoi (p); + p = strchr (p, '.'); + if (p != NULL) + { + minor_ver = atoi (p + 1); + } + } + clt_ver = EMGR_MAKE_VER (major_ver, minor_ver); + + if (clt_ver < EMGR_MAKE_VER (1, 0)) + { + nv_update_val (res, "status", "failure"); + nv_update_val (res, "note", + "Can not connect to the server due to version mismatch."); + return 0; + } + + return 1; +} + +int +ts_check_already_connected (nvplist *cli_response, int max_index, + int current_index, T_CLIENT_INFO *client_info) +{ + int index = 0; + for (index = 0; index <= max_index; index++) + { + if (IS_INVALID_SOCKET (client_info[index].sock_fd) + || (index == current_index)) + { + continue; + } + + if (!strcmp (client_info[current_index].user_id, client_info[index].user_id)) + { + char message[1024]; + sprintf (message, + "User %s was already connected from another client(%s)", + client_info[index].user_id, client_info[index].ip_address); + + nv_update_val (cli_response, "status", "failure"); + nv_update_val (cli_response, "note", message); + return index; + } + } + + return -1; +} + +int +ts_get_server_version (nvplist *req, nvplist *res) +{ + char tmpfile[PATH_MAX]; + char strbuf[1024]; + FILE *infile; + char cmd_name[ARNIADB_CMD_NAME_LEN]; + const char *argv[5]; + + nv_update_val (res, "task", "getversion"); + snprintf (tmpfile, PATH_MAX - 1, "%s/DBMT_task_015", sco.dbmt_tmp_dir); + + cmd_name[0] = '\0'; + snprintf (cmd_name, sizeof (cmd_name) - 1, "%s/%s%s", sco.szArniadb, + ARNIADB_DIR_BIN, UTIL_ARNIADB_REL_NAME); + + argv[0] = cmd_name; + argv[1] = NULL; + + run_child (argv, 1, NULL, tmpfile, NULL, NULL); /* arniadb_rel */ + + if ((infile = fopen (tmpfile, "r")) != NULL) + { + fgets (strbuf, sizeof (strbuf), infile); + fgets (strbuf, sizeof (strbuf), infile); + uRemoveCRLF (strbuf); + fclose (infile); + unlink (tmpfile); + nv_add_nvp (res, "ARNIADBVER", strbuf); + nv_update_val (res, "status", "success"); + } + else + { + nv_add_nvp (res, "ARNIADBVER", "none"); + nv_update_val (res, "status", "failure"); + nv_update_val (res, "note", "version information not available"); + return 0; + } + + return 1; +} diff --git a/server/src/am_auto_task.h b/server/src/am_auto_task.h new file mode 100644 index 0000000..c4b232c --- /dev/null +++ b/server/src/am_auto_task.h @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. + * + * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + + +/* + * cm_auto_task.h - + */ + +#ifndef _CM_AUTO_TASK_H_ +#define _CM_AUTO_TASK_H_ + +#include "cm_porting.h" +#include "cm_dep.h" + +typedef struct +{ + SOCKET sock_fd; + int state; + char *user_id; + char *ip_address; + short port; +} T_CLIENT_INFO; + +int ts_validate_user (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_get_server_version (nvplist *req, nvplist *res); +int ts_check_client_version (nvplist *req, nvplist *res); +int ts_check_already_connected (nvplist *cli_response, int max_index, + int current_index, + T_CLIENT_INFO *client_info); + +#endif /* _CM_AUTO_TASK_H_ */ diff --git a/server/src/am_autojob.cpp b/server/src/am_autojob.cpp new file mode 100644 index 0000000..b855884 --- /dev/null +++ b/server/src/am_autojob.cpp @@ -0,0 +1,1701 @@ +/* + * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. + * + * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + + +/* + * cm_autojob.cpp - + */ + +#include +#include +#include +#include +#include +#include + +#if defined(WINDOWS) +#include +#include +#include +#else +#include +#include +#include +#include +#endif + +#include "cm_porting.h" +#include "cm_server_util.h" +#include "cm_autojob.h" +#include "cm_dep.h" +#include "cm_server_stat.h" +#include "cm_config.h" +#include "cm_cmd_exec.h" +#include "cm_text_encryption.h" +#include "cm_stat.h" + +#ifdef _DEBUG_ +#include "deb.h" +#include +#endif + +#define MIN_AUTOBACKUPDB_DELAY 600 +#define MAX_AUTOADD_FREE_SPACE_RATE 0.5 + + +typedef struct backup_period_details_t +{ + int date; + struct backup_period_details_t *next; +} backup_period_details; + +typedef struct autobackupdb_node_t +{ + char *dbname; + char *backup_id; + char *path; + int period_type; + //int period_date; + backup_period_details *period_date; + int time; + int level; + int archivedel; + int updatestatus; + int storeold; + int onoff; + int zip; + int check; + int mt; + int bk_num; + time_t lbt; + struct autobackupdb_node_t *next; + int is_interval; // 0 for specific time, 1 for interval +} autobackupdb_node; + +typedef struct unicasm_node_t +{ + char *bname; + short cpumonitor; + short busymonitor; + short logcpu; + short logbusy; + short cpurestart; + short busyrestart; + short cpulimit; + int busylimit; + time_t lrt; + struct unicasm_node_t *next; +} unicasm_node; + +/* This struct is for auto addvolume */ + +typedef enum +{ + AEQT_ONE, + AEQT_DAY, + AEQT_WEEK, + AEQT_MONTH +} T_EXECQUERY_PERIOD_TYPE; + +#define DETAIL_LEN 32 + +typedef struct query_period_details_t +{ + char detail[DETAIL_LEN]; + struct query_period_details_t *next; + +} query_period_details; + +typedef struct autoexecquery_t +{ + char dbname[64]; + char dbmt_uid[64]; + char query_id[64]; + char db_uid[64]; + char db_passwd[PASSWD_ENC_LENGTH]; + T_EXECQUERY_PERIOD_TYPE period; + query_period_details *detail1; + char detail2[16]; + char query_string[MAX_AUTOQUERY_SCRIPT_SIZE]; + int db_mode; + struct autoexecquery_t *next; +} autoexecquery_node; + +#ifdef HOST_MONITOR_PROC +/* This struct is for auto history logging */ +typedef struct autohistory_t +{ + time_t start_time; + time_t end_time; + float memory_limit; + float cpu_limit; + char **dbname; + int dbcount; + FILE *hfile; + void *mondata; +} autohistory_node; +#endif + +typedef enum +{ + ABPT_MONTHLY, + ABPT_WEEKLY, + ABPT_DAILY, + ABPT_HOURLY, + ABPT_SPECIAL +} T_AUTOBACKUP_PERIOD_TYPE; + +static void aj_load_execquery_conf (ajob *p_aj); +static void aj_execquery_handler (void *hd, time_t prev_check_time, + time_t cur_time); +static void aj_execquery_get_exec_time (autoexecquery_node *c, + query_period_details *d, + struct tm *exec_tm, + time_t prev_check_time); + +static void aj_execquery (autoexecquery_node *c); +static void _aj_autoexecquery_error_log (autoexecquery_node *node, + int err_code, const char *errmsg); +static void aj_load_autobackupdb_conf (ajob *ajp); +static void aj_load_autoaddvoldb_config (ajob *ajp); +static void aj_load_autohistory_conf (ajob *ajp); + +static void aj_autobackupdb_handler (void *ajp, time_t prev_check_time, + time_t cur_time); +static void aj_autoaddvoldb_handler (void *hd, time_t prev_check_time, + time_t cur_time); +static void aj_autohistory_handler (void *ajp, time_t prev_check_time, + time_t cur_time); + +static void aj_backupdb (autobackupdb_node *n); +static void _aj_autobackupdb_error_log (autobackupdb_node *n, char *errmsg); + +void +aj_initialize (ajob *ajlist, void *ud) +{ + struct stat statbuf; + + sprintf (ajlist[0].name, "autoaddvoldb"); + conf_get_dbmt_file (FID_AUTO_ADDVOLDB_CONF, ajlist[0].config_file); + stat (ajlist[0].config_file, &statbuf); + ajlist[0].last_modi = statbuf.st_mtime; + ajlist[0].is_on = 0; /* initially off */ + ajlist[0].ajob_handler = aj_autoaddvoldb_handler; + ajlist[0].ajob_loader = aj_load_autoaddvoldb_config; + ajlist[0].hd = NULL; + ajlist[0].mondata = ud; + + sprintf (ajlist[1].name, "autohistory"); + conf_get_dbmt_file (FID_AUTO_HISTORY_CONF, ajlist[1].config_file); + stat (ajlist[1].config_file, &statbuf); + ajlist[1].last_modi = statbuf.st_mtime; + ajlist[1].is_on = 0; + ajlist[1].ajob_handler = aj_autohistory_handler; + ajlist[1].ajob_loader = aj_load_autohistory_conf; + ajlist[1].hd = NULL; + ajlist[1].mondata = ud; + + sprintf (ajlist[2].name, "autobackupdb"); + conf_get_dbmt_file (FID_AUTO_BACKUPDB_CONF, ajlist[2].config_file); + stat (ajlist[2].config_file, &statbuf); + ajlist[2].last_modi = statbuf.st_mtime; + ajlist[2].is_on = 0; + ajlist[2].ajob_handler = aj_autobackupdb_handler; + ajlist[2].ajob_loader = aj_load_autobackupdb_conf; + ajlist[2].hd = NULL; + ajlist[2].mondata = ud; + + sprintf (ajlist[3].name, "autoexecquery"); + conf_get_dbmt_file (FID_AUTO_EXECQUERY_CONF, ajlist[3].config_file); + stat (ajlist[3].config_file, &statbuf); + ajlist[3].last_modi = statbuf.st_mtime; + ajlist[3].is_on = 0; + ajlist[3].ajob_handler = aj_execquery_handler; + ajlist[3].ajob_loader = aj_load_execquery_conf; + ajlist[3].hd = NULL; + ajlist[3].mondata = ud; +} + +/* This function calculates the free space fraction of given type */ +double +ajFreeSpace (GeneralSpacedbResult *cmd_res, const char *type) +{ + double total_page, free_page; + + total_page = free_page = 0.0; + cmd_res->get_total_and_free_page (type, free_page, total_page); + if (total_page > 0.0) + { + return (free_page / total_page); + } + + return 1.0; +} + +/* This function adds volume and write to file for fserver */ +void +aj_add_volume (char *dbname, const char *type, int increase, + int pagesize) +{ + char dbloca[512]; + char strbuf[1024]; + char volname[512] = { '\0' }; + FILE *outfile; + time_t mytime; + int retval; + char log_file_name[512]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; + char inc_str[128]; + const char *argv[16]; + int argc = 0; + GeneralSpacedbResult *all_volumes; + char *pos = NULL; + char tmp_dbname[DB_NAME_LEN + MAXHOSTNAMELEN]; + + tmp_dbname[0] = '\0'; + pos = strchr (dbname, '@'); + if (pos != NULL) + { + strncpy (tmp_dbname, dbname, pos - dbname); + tmp_dbname[pos - dbname] = '\0'; + } + else + { + strncpy (tmp_dbname, dbname, strlen (dbname) + 1); + } + + if (uRetrieveDBDirectory (tmp_dbname, dbloca) != ERR_NO_ERROR) + { + return; + } + + if (access (dbloca, W_OK | X_OK | R_OK) < 0) + { + return; + } + +#if defined(WINDOWS) + nt_style_path (dbloca, dbloca); +#endif + + arniadb_cmd_name (cmd_name); + argv[argc++] = cmd_name; + argv[argc++] = UTIL_OPTION_ADDVOLDB; + argv[argc++] = "--" ADDVOL_FILE_PATH_L; + argv[argc++] = dbloca; + argv[argc++] = "--" ADDVOL_PURPOSE_L; + argv[argc++] = type; + argv[argc++] = "--" ADDVOL_DB_VOLUMN_SIZE_L; + sprintf (inc_str, "%lldB", (long long) pagesize * increase); + argv[argc++] = inc_str; + argv[argc++] = dbname; + argv[argc++] = NULL; + retval = run_child (argv, 1, NULL, NULL, NULL, NULL); /* addvoldb */ + + mytime = time (NULL); + conf_get_dbmt_file (FID_AUTO_ADDVOLDB_LOG, log_file_name); + if ((outfile = fopen (log_file_name, "a")) != NULL) + { + fprintf (outfile, "%s ", dbname); + fprintf (outfile, "%s ", type); + fprintf (outfile, "%d ", increase); + time_to_str (mytime, "%d-%d-%d,%d:%d:%d", strbuf, + TIME_STR_FMT_DATE_TIME); + fprintf (outfile, "%s ", strbuf); + fprintf (outfile, "start\n"); + fclose (outfile); + } + + mytime = 0; + + all_volumes = cmd_spacedb (dbname, ARNIADB_MODE_CS); + if (all_volumes == NULL) + { + return; + } + + mytime = all_volumes->get_my_time (dbloca); + mytime = time (&mytime); + if ((outfile = fopen (log_file_name, "a")) != NULL) + { + fprintf (outfile, "%s ", dbname); + if (retval == 0) + { + fprintf (outfile, "%s ", volname); + } + else + { + fprintf (outfile, "none "); + } + fprintf (outfile, "%s ", type); + fprintf (outfile, "%d ", increase); + time_to_str (mytime, "%d-%d-%d,%d:%d:%d", strbuf, + TIME_STR_FMT_DATE_TIME); + fprintf (outfile, "%s ", strbuf); + if (retval == 0) + { + fprintf (outfile, "success\n"); + } + else + { + fprintf (outfile, "failure\n"); + } + fclose (outfile); + } +} + +static void +aj_autohistory_handler (void *ajp, time_t prev_check_time, time_t cur_time) +{ +#ifdef HOST_MONITOR_PROC + time_t mytime, current_time; + float current_cpu, current_mem; + char strbuf[1024]; + autohistory_node *hsp; + userdata *mondata; + char timestr[64]; + + hsp = (autohistory_node *) ajp; + mondata = (userdata *) (hsp->mondata); + + current_time = time (¤t_time); + if ((current_time < hsp->start_time) || (current_time > hsp->end_time)) + { + if (hsp->hfile != NULL) + { + fclose (hsp->hfile); + } + hsp->hfile = NULL; + return; + } + + /* auto histoy feature */ + current_cpu = (float) (1000 - mondata->ssbuf.cpu_states[0]); + current_mem = + (float) (mondata->ssbuf.memory_stats[1]) / + (float) (mondata->ssbuf.memory_stats[0]) * 100.0; + + if ((current_cpu > hsp->cpu_limit) || (current_mem > hsp->memory_limit)) + { + mytime = time (&mytime); + + if (hsp->hfile == NULL) + { + time_to_str (mytime, "%04d%02d%02d.%02d%02d%02d", timestr, + TIME_STR_FMT_DATE_TIME); +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (strbuf, "%s/logs/_dbmt_history.%s", sco.szArniadb, timestr); +#else + sprintf (strbuf, "%s/_dbmt_history.%s", ARNIADB_LOGDIR, timestr); +#endif + hsp->hfile = fopen (strbuf, "w"); + } + /* record system information */ + if (hsp->hfile != NULL) + { + time_to_str (mytime, "[%04d/%02d/%02d-%02d:%02d:%02d]", timestr, + TIME_STR_FMT_DATE_TIME); + fprintf (hsp->hfile, "%s", timestr); + fprintf (hsp->hfile, "load average 1min:%d 5min:%d 15min:%d\n", + mondata->ssbuf.load_avg[0], + mondata->ssbuf.load_avg[1], mondata->ssbuf.load_avg[2]); + fprintf (hsp->hfile, + "cpu time idle:%d user:%d kernel%d iowait:%d swap:%d\n", + mondata->ssbuf.cpu_states[0], + mondata->ssbuf.cpu_states[1], + mondata->ssbuf.cpu_states[2], + mondata->ssbuf.cpu_states[3], + mondata->ssbuf.cpu_states[4]); + fprintf (hsp->hfile, + "memory real:%dK active:%dK free:%dK swap:%dK swapfree:%dK\n", + mondata->ssbuf.memory_stats[0], + mondata->ssbuf.memory_stats[1], + mondata->ssbuf.memory_stats[2], + mondata->ssbuf.memory_stats[3], + mondata->ssbuf.memory_stats[4]); + fflush (hsp->hfile); + } + /* record db information */ + + if (hsp->hfile != NULL) + { + FILE *infile; + int i; + infile = + fopen (conf_get_dbmt_file (FID_AUTO_HISTORY_CONF, strbuf), "r"); + if (infile != NULL) + { + while (fgets (strbuf, sizeof (strbuf), infile)) + { + ut_trim (strbuf); + for (i = 0; i < MAX_INSTALLED_DB; ++i) + { + if ((mondata->dbvect[i] == 1) && + (uStringEqual (strbuf, mondata->dbbuf[i].db_name))) + { + fprintf (hsp->hfile, "database name:%s ", + mondata->dbbuf[i].db_name); + fprintf (hsp->hfile, "pid:%d ", + mondata->dbbuf[i].db_pid); + fprintf (hsp->hfile, "size:%ld ", + mondata->dbbuf[i].db_size); + fprintf (hsp->hfile, "status:%c ", + mondata->dbbuf[i].proc_stat[0]); + mytime = mondata->dbbuf[i].db_start_time; + time_to_str (mytime, + "%04d/%02d/%02d-%02d:%02d:%02d", + timestr, TIME_STR_FMT_DATE_TIME); + fprintf (hsp->hfile, "start_time:%s ", timestr); + fprintf (hsp->hfile, "cpu_usage:%f%% ", + mondata->dbbuf[i].db_cpu_usage); + fprintf (hsp->hfile, "mem_usage:%f%%\n\n", + mondata->dbbuf[i].db_mem_usage); + fflush (hsp->hfile); + } + } + } + fclose (infile); + } + fclose (hsp->hfile); + } + } +#endif +} + +static void +aj_autoaddvoldb_handler (void *hd, time_t prev_check_time, time_t cur_time) +{ + char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; + autoaddvoldb_node *curr; + GeneralSpacedbResult *spacedb_res; + T_SERVER_STATUS_RESULT *server_status_res; + int db_mode = 0; + + server_status_res = cmd_server_status (); + if (server_status_res == NULL) + { + return; + } + + for (curr = (autoaddvoldb_node *) hd; curr != NULL; curr = curr->next) + { + if (curr->dbname == NULL) + { + continue; + } + + if ((db_mode = + uIsDatabaseActive2 (server_status_res, curr->dbname)) == 0) + { + continue; + } + + /* if the HA mode is on, the db_mode equals 2. */ + if (db_mode == HA_MODE) + { + append_host_to_dbname (dbname_at_hostname, curr->dbname, + sizeof (dbname_at_hostname)); + spacedb_res = cmd_spacedb (dbname_at_hostname, ARNIADB_MODE_CS); + } + else + { + spacedb_res = cmd_spacedb (curr->dbname, ARNIADB_MODE_CS); + } + + if (spacedb_res == NULL) + { + continue; + } + + spacedb_res->auto_add_volume (curr, db_mode, dbname_at_hostname); + delete spacedb_res; + } + cmd_servstat_result_free (server_status_res); +} + +static void +aj_load_autoaddvoldb_config (ajob *ajp) +{ + FILE *infile = NULL; + char strbuf[1024]; + char *conf_item[AUTOADDVOL_CONF_ENTRY_NUM]; + autoaddvoldb_node *next, *curr; + + /* turn off autoaddvoldb feature */ + ajp->is_on = 0; + + /* free existing structure */ + curr = (autoaddvoldb_node *) (ajp->hd); + while (curr) + { + /* clear the linked list */ + next = curr->next; + FREE_MEM (curr); + curr = next; + } + ajp->hd = curr = NULL; + + infile = fopen (ajp->config_file, "r"); + if (infile == NULL) + { + return; + } + + while (fgets (strbuf, sizeof (strbuf), infile)) + { + ut_trim (strbuf); + if (strbuf[0] == '#' || strbuf[0] == '\0') + { + continue; + } + + if (string_tokenize (strbuf, conf_item, AUTOADDVOL_CONF_ENTRY_NUM) < 0) + { + continue; + } + + if (curr == NULL) + { + curr = (autoaddvoldb_node *) malloc (sizeof (autoaddvoldb_node)); + ajp->hd = curr; + } + else + { + curr->next = + (autoaddvoldb_node *) malloc (sizeof (autoaddvoldb_node)); + curr = curr->next; + } + if (curr == NULL) + { + break; + } + + memset (curr, 0, sizeof (autoaddvoldb_node)); + strcpy (curr->dbname, conf_item[0]); + + if (strcmp (conf_item[1], "ON") == 0) + { + curr->data_vol = 1; + ajp->is_on = 1; + } + + curr->data_warn_outofspace = atof (conf_item[2]); + if (curr->data_warn_outofspace > MAX_AUTOADD_FREE_SPACE_RATE) + { + curr->data_warn_outofspace = MAX_AUTOADD_FREE_SPACE_RATE; + } + + curr->data_ext_page = atoi (conf_item[3]); + + if (strcmp (conf_item[4], "ON") == 0) + { + curr->index_vol = 1; + ajp->is_on = 1; + } + + curr->index_warn_outofspace = atof (conf_item[5]); + if (curr->index_warn_outofspace > MAX_AUTOADD_FREE_SPACE_RATE) + { + curr->index_warn_outofspace = MAX_AUTOADD_FREE_SPACE_RATE; + } + + curr->index_ext_page = atoi (conf_item[6]); + curr->next = NULL; + } + fclose (infile); +} + +/* parameter ud : autojob structure for autohistory */ +/* parameter ud2 : data from collect_start() */ +static void +aj_load_autohistory_conf (ajob *ajp) +{ +#ifdef HOST_MONITOR_PROC + int i; + FILE *infile; + struct tm timeptr; + autohistory_node *ahist; + char strbuf[1024]; + char *conf_item[AUTOHISTORY_CONF_ENTRY_NUM]; + + ajp->is_on = 0; + + ahist = (autohistory_node *) (ajp->hd); + /* free existing structure */ + if (ahist) + { + for (i = 0; i < ahist->dbcount; ++i) + { + FREE_MEM (ahist->dbname[i]); + } + FREE_MEM (ahist->dbname); + FREE_MEM (ahist); + } + + /* create new struct and initialize */ + ajp->hd = (void *) malloc (sizeof (autohistory_node)); + ahist = (autohistory_node *) (ajp->hd); + ahist->memory_limit = 100.0; + ahist->cpu_limit = 100.0; + ahist->dbname = NULL; + ahist->dbcount = 0; + ahist->hfile = NULL; + ahist->mondata = ajp->mondata; + + if ((infile = fopen (ajp->config_file, "r")) == NULL) + { + return; + } + + memset (strbuf, 0, sizeof (strbuf)); + while (fgets (strbuf, sizeof (strbuf), infile)) + { + ut_trim (strbuf); + if (strbuf[0] == '#' || strbuf[0] == '\0') + { + memset (strbuf, 0, sizeof (strbuf)); + continue; + } + break; + } + if (string_tokenize (strbuf, conf_item, AUTOHISTORY_CONF_ENTRY_NUM) < 0) + { + fclose (infile); + return; + } + + if (strcmp (conf_item[0], "ON") == 0) + { + ajp->is_on = 1; + } + else + { + ajp->is_on = 0; + } + + timeptr.tm_year = atoi (conf_item[1]) - 1900; + timeptr.tm_mon = atoi (conf_item[2]) - 1; + timeptr.tm_mday = atoi (conf_item[3]); + timeptr.tm_hour = atoi (conf_item[4]); + timeptr.tm_min = atoi (conf_item[5]); + timeptr.tm_sec = atoi (conf_item[6]); + ahist->start_time = mktime (&timeptr); + + timeptr.tm_year = atoi (conf_item[7]) - 1900; + timeptr.tm_mon = atoi (conf_item[8]) - 1; + timeptr.tm_mday = atoi (conf_item[9]); + timeptr.tm_hour = atoi (conf_item[10]); + timeptr.tm_min = atoi (conf_item[11]); + timeptr.tm_sec = atoi (conf_item[12]); + ahist->end_time = mktime (&timeptr); + + ahist->memory_limit = atof (conf_item[13]); + ahist->cpu_limit = atof (conf_item[14]); + + while (fgets (strbuf, sizeof (strbuf), infile)) + { + ut_trim (strbuf); + ahist->dbcount++; + ahist->dbname = + REALLOC (ahist->dbname, sizeof (char *) * (ahist->dbcount)); + if (ahist->dbname == NULL) + { + break; + } + ahist->dbname[ahist->dbcount - 1] = strdup (strbuf); + } + + fclose (infile); +#endif +} + +static void +set_query_period_details (query_period_details **details, char *conf_item) +{ + char delim[] = " ,"; + char *token = NULL; + query_period_details *head = NULL; + + token = strtok (conf_item, delim); + while (token != NULL) + { + *details = (query_period_details *) malloc (sizeof (query_period_details)); + strncpy ((*details)->detail, token, DETAIL_LEN); + (*details)->next = head; + head = *details; + token = strtok (NULL, delim); + } +} + +static void +set_backup_period_details (backup_period_details **details, + int period_type, char *conf_item) +{ + char delim[] = " ,"; + char *token; + backup_period_details *head = NULL; + + token = strtok (conf_item, delim); + while (token != NULL) + { + *details = + (backup_period_details *) malloc (sizeof (backup_period_details)); + + switch (period_type) + { + case ABPT_MONTHLY: + case ABPT_HOURLY: + (*details)->date = atoi (token); + break; + + case ABPT_WEEKLY: + if (!strcmp (token, WEEK_SUNDAY_L)) + { + (*details)->date = 0; + } + else if (!strcmp (token, WEEK_MONDAY_L)) + { + (*details)->date = 1; + } + else if (!strcmp (token, WEEK_TUESDAY_L)) + { + (*details)->date = 2; + } + else if (!strcmp (token, WEEK_WEDNESDAY_L)) + { + (*details)->date = 3; + } + else if (!strcmp (token, WEEK_THURSDAY_L)) + { + (*details)->date = 4; + } + else if (!strcmp (token, WEEK_FRIDAY_L)) + { + (*details)->date = 5; + } + else if (!strcmp (token, WEEK_SATURDAY_L)) + { + (*details)->date = 6; + } + break; + + case ABPT_DAILY: + (*details)->date = -1; + break; + + case ABPT_SPECIAL: + (*details)->date = atoi (token) * 10000; + (*details)->date += atoi (token + 5) * 100; + (*details)->date += atoi (token + 8); + break; + + default: + break; + } + + (*details)->next = head; + head = *details; + token = strtok (NULL, delim); + } +} + +static void +aj_load_autobackupdb_conf (ajob *p_aj) +{ + char buf[1024]; + FILE *infile = NULL; + autobackupdb_node *c; + char *conf_item[AUTOBACKUP_CONF_ENTRY_NUM]; + int is_old_version_entry; + + p_aj->is_on = 0; + + c = (autobackupdb_node *) (p_aj->hd); + while (c != NULL) + { + autobackupdb_node *t; + backup_period_details *p; + + while (c->period_date != NULL) + { + p = c->period_date; + c->period_date = c->period_date->next; + FREE_MEM (p); + } + + t = c; + FREE_MEM (t->dbname); + FREE_MEM (t->backup_id); + FREE_MEM (t->path); + c = c->next; + FREE_MEM (t); + } + p_aj->hd = c = NULL; + + if ((infile = fopen (p_aj->config_file, "r")) == NULL) + { + return; + } + + while (fgets (buf, sizeof (buf), infile)) + { + is_old_version_entry = 0; + ut_trim (buf); + if (buf[0] == '#' || buf[0] == '\0') + { + continue; + } + + if (string_tokenize (buf, conf_item, AUTOBACKUP_CONF_ENTRY_NUM) < 0) + { + if (string_tokenize (buf, conf_item, AUTOBACKUP_CONF_ENTRY_NUM - 3) < 0) + { + continue; + } + else + { + is_old_version_entry = 1; + } + } + + if (c == NULL) + { + c = (autobackupdb_node *) malloc (sizeof (autobackupdb_node)); + p_aj->hd = c; + } + else + { + c->next = (autobackupdb_node *) malloc (sizeof (autobackupdb_node)); + c = c->next; + } + if (c == NULL) + { + break; + } + + c->lbt = -1; + c->dbname = strdup (conf_item[0]); + c->backup_id = strdup (conf_item[1]); + c->path = strdup (conf_item[2]); + + if (!strcmp (conf_item[3], "Monthly")) + { + c->period_type = ABPT_MONTHLY; + } + else if (!strcmp (conf_item[3], "Weekly")) + { + c->period_type = ABPT_WEEKLY; + } + else if (!strcmp (conf_item[3], "Daily")) + { + c->period_type = ABPT_DAILY; + } + else if (!strcmp (conf_item[3], "Hourly")) + { + c->period_type = ABPT_HOURLY; + } + else if (!strcmp (conf_item[3], "Special")) + { + c->period_type = ABPT_SPECIAL; + } + else + { + if (c != NULL) + { + FREE_MEM (c->dbname); + FREE_MEM (c->backup_id); + FREE_MEM (c->path); + FREE_MEM (c); + } + continue; + } + + set_backup_period_details (& (c->period_date), c->period_type, conf_item[4]); + + if ('i' == conf_item[5][0]) // interval time is set + { + c->is_interval = 1; + c->time = atoi (conf_item[5] + 1); + } + else // sepcific time is set + { + c->time = atoi (conf_item[5]); + c->is_interval = 0; + } + c->level = atoi (conf_item[6]); + c->archivedel = !strcmp (conf_item[7], "ON") ? 1 : 0; + c->updatestatus = !strcmp (conf_item[8], "ON") ? 1 : 0; + c->storeold = !strcmp (conf_item[9], "ON") ? 1 : 0; + c->onoff = !strcmp (conf_item[10], "ON") ? 1 : 0; + + if (is_old_version_entry) + { + c->zip = 0; + c->check = 0; + c->mt = 0; + c->bk_num = 1; + } + else + { + c->zip = !strcmp (conf_item[11], "y") ? 1 : 0; + c->check = !strcmp (conf_item[12], "y") ? 1 : 0; + c->mt = atoi (conf_item[13]); + c->bk_num = conf_item[14] ? atoi (conf_item[14]) : 1; + } + c->next = NULL; + } /* end of while */ + fclose (infile); + p_aj->is_on = 1; +} + +static void +aj_load_execquery_conf (ajob *p_aj) +{ + FILE *infile = NULL; + char *conf_item[AUTOEXECQUERY_CONF_ENTRY_NUM]; + char buf[MAX_JOB_CONFIG_FILE_LINE_LENGTH]; + autoexecquery_node *c; + + p_aj->is_on = 0; + + /* NODE reset */ + c = (autoexecquery_node *) (p_aj->hd); + while (c != NULL) + { + autoexecquery_node *t; + query_period_details *p; + + while (c->detail1 != NULL) + { + p = c->detail1; + c->detail1 = c->detail1->next; + FREE_MEM (p); + } + + t = c; + c = c->next; + FREE_MEM (t); + } + + p_aj->hd = c = NULL; + + /* read NODE information from file */ + if ((infile = fopen (p_aj->config_file, "r")) == NULL) + { + return; + } + + while (fgets (buf, sizeof (buf), infile)) + { + ut_trim (buf); + if (buf[0] == '#' || buf[0] == '\0') + { + continue; + } + + if (string_tokenize_accept_laststring_space + (buf, conf_item, AUTOEXECQUERY_CONF_ENTRY_NUM) < 0) + { + continue; + } + + if (c == NULL) + { + c = (autoexecquery_node *) malloc (sizeof (autoexecquery_node)); + p_aj->hd = c; + } + else + { + c->next = + (autoexecquery_node *) malloc (sizeof (autoexecquery_node)); + c = c->next; + } + if (c == NULL) + { + break; + } + + snprintf (c->dbname, sizeof (c->dbname) - 1, "%s", conf_item[0]); + snprintf (c->query_id, sizeof (c->query_id) - 1, "%s", conf_item[1]); + snprintf (c->db_uid, sizeof (c->db_uid) - 1, "%s", conf_item[2]); + snprintf (c->db_passwd, sizeof (c->db_passwd) - 1, "%s", conf_item[3]); + c->db_passwd[sizeof (c->db_passwd) - 1] = '\0'; + snprintf (c->dbmt_uid, sizeof (c->dbmt_uid) - 1, "%s", conf_item[4]); + + if (strcmp (conf_item[5], "ONE") == 0) + { + c->period = AEQT_ONE; + } + else if (strcmp (conf_item[5], "DAY") == 0) + { + c->period = AEQT_DAY; + } + else if (strcmp (conf_item[5], "WEEK") == 0) + { + c->period = AEQT_WEEK; + } + else if (strcmp (conf_item[5], "MONTH") == 0) + { + c->period = AEQT_MONTH; + } + + // snprintf (c->detail1, sizeof (c->detail1) - 1, "%s", conf_item[6]); + + //Tools-822, use a link list to store period_details. + set_query_period_details (& (c->detail1), conf_item[6]); + + snprintf (c->detail2, sizeof (c->detail2) - 1, "%s", conf_item[7]); + snprintf (c->query_string, sizeof (c->query_string) - 1, "%s", + conf_item[8]); + c->db_mode = 2; + c->next = NULL; + } /* end of while */ + fclose (infile); + p_aj->is_on = 1; + +} + +static void +aj_execquery_handler (void *hd, time_t prev_check_time, time_t cur_time) +{ + time_t execquery_time; + struct tm exec_tm, cur_tm, *tm_p; + autoexecquery_node *c; + query_period_details *detail1 = NULL; + int tm_wday = 0; + + tm_p = localtime (&cur_time); + if (tm_p == NULL) + { + return; + } + cur_tm = *tm_p; + + for (c = (autoexecquery_node *) (hd); c != NULL; c = c->next) + { + exec_tm = cur_tm; + detail1 = c->detail1; + + while (detail1 != NULL) + { + aj_execquery_get_exec_time (c, detail1, &exec_tm, prev_check_time); + + // backup tm_wday, since mktime can change tm_wday field. + tm_wday = exec_tm.tm_wday; + execquery_time = mktime (&exec_tm); + + if (execquery_time <= prev_check_time || execquery_time > cur_time) + { + detail1 = detail1->next; + continue; + } + + if ((c->period == AEQT_ONE) + || (c->period == AEQT_DAY) + || ((c->period == AEQT_WEEK) && cur_tm.tm_wday == tm_wday) + || ((c->period == AEQT_MONTH) + && cur_tm.tm_mday == exec_tm.tm_mday)) + { + aj_execquery (c); + } + detail1 = detail1->next; + } + } + + return; +} + +static void +aj_execquery_get_exec_time (autoexecquery_node *c, + query_period_details *d, + struct tm *exec_tm, time_t prev_check_time) +{ + switch (c->period) + { + case AEQT_ONE: + sscanf (d->detail, "%d/%d/%d", & (exec_tm->tm_year), & (exec_tm->tm_mon), + & (exec_tm->tm_mday)); + exec_tm->tm_year -= 1900; /* year : since 1900 */ + exec_tm->tm_mon -= 1; /* month : zero based month */ + break; + + case AEQT_DAY: + /* sscanf(c->detail2, "%d:%d", &(exec_tm->tm_hour), &(exec_tm->tm_min)); */ + break; + + case AEQT_WEEK: + if (strcmp (d->detail, WEEK_CAPITAL_SUNDAY_S) == 0) + { + exec_tm->tm_wday = 0; + } + else if (strcmp (d->detail, WEEK_CAPITAL_MONDAY_S) == 0) + { + exec_tm->tm_wday = 1; + } + else if (strcmp (d->detail, WEEK_CAPITAL_TUESDAY_S) == 0) + { + exec_tm->tm_wday = 2; + } + else if (strcmp (d->detail, WEEK_CAPITAL_WEDNESDAY_S) == 0) + { + exec_tm->tm_wday = 3; + } + else if (strcmp (d->detail, WEEK_CAPITAL_THURSDAY_S) == 0) + { + exec_tm->tm_wday = 4; + } + else if (strcmp (d->detail, WEEK_CAPITAL_FRIDAY_S) == 0) + { + exec_tm->tm_wday = 5; + } + else if (strcmp (d->detail, WEEK_CAPITAL_SATURDAY_S) == 0) + { + exec_tm->tm_wday = 6; + } + break; + + case AEQT_MONTH: + sscanf (d->detail, "%d", & (exec_tm->tm_mday)); + break; + } + + if ('i' == c->detail2[0]) // time interval for auto execute query + { + int interval; + time_t prev_day_sec = 0; + struct tm prev_tm, *tm_p; + + tm_p = localtime (&prev_check_time); + if (tm_p == NULL) + { + return; + } + prev_tm = *tm_p; + + sscanf (c->detail2, "i%d", &interval); + + prev_day_sec = + prev_tm.tm_hour * 3600 + prev_tm.tm_min * 60 + prev_tm.tm_sec; + if ((prev_day_sec + interval * 60) >= (24 * 3600)) // if across a day, start at 00:00 + { + exec_tm->tm_hour = 0; + exec_tm->tm_min = 0; + } + else // not across a day + { + time_t exec_sec = + (prev_day_sec / (interval * 60) + 1) * interval * 60; + exec_tm->tm_hour = (int) (exec_sec / 3600); + exec_tm->tm_min = (exec_sec % 3600) / 60; + } + } + else // specific time for auto execute query + { + sscanf (c->detail2, "%d:%d", & (exec_tm->tm_hour), & (exec_tm->tm_min)); + } + exec_tm->tm_sec = 0; +} + +static void +aj_execquery (autoexecquery_node *c) +{ + int retval; + int argc = 0; + const char *argv[11]; + char cmd_name[ARNIADB_CMD_NAME_LEN + 1]; + int ha_mode; + T_DB_SERVICE_MODE db_mode; + char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; + char dbpasswd[PASSWD_LENGTH + 1]; + int error_code; + char error_buffer[1024]; + char arniadb_err_file[PATH_MAX]; + char input_filename[256]; + FILE *input_file; + + arniadb_err_file[0] = '\0'; + + _aj_autoexecquery_error_log (c, 0, PRINT_CMD_START); + + memset (error_buffer, '\0', sizeof (error_buffer)); + + cmd_name[0] = '\0'; +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ASQL_NAME); +#else + sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_ASQL_NAME); +#endif + argv[argc++] = cmd_name; + + db_mode = uDatabaseMode (c->dbname, &ha_mode); + if (ha_mode != 0) + { + append_host_to_dbname (dbname_at_hostname, c->dbname, + sizeof (dbname_at_hostname)); + argv[argc++] = dbname_at_hostname; + } + else + { + argv[argc++] = c->dbname; + } + + switch (db_mode) + { + case DB_SERVICE_MODE_SA: + sprintf (error_buffer, "Database(%s) is running in stand alone mode", + c->dbname); + _aj_autoexecquery_error_log (c, ERR_GENERAL_ERROR, error_buffer); + return; + case DB_SERVICE_MODE_CS: + argv[argc++] = "--" ASQL_CS_MODE_L; + break; + case DB_SERVICE_MODE_NONE: + argv[argc++] = "--" ASQL_SA_MODE_L; + break; + } + + sprintf (input_filename, "%s/dbmt_auto_execquery_%d", sco.dbmt_tmp_dir, + (int) getpid ()); + argv[argc++] = "--" ASQL_INPUT_FILE_L; + argv[argc++] = input_filename; + + argv[argc++] = "--" ASQL_USER_L; + argv[argc++] = c->db_uid; + + uDecrypt (PASSWD_LENGTH, c->db_passwd, dbpasswd); + argv[argc++] = "--" ASQL_PASSWORD_L; + argv[argc++] = dbpasswd; + + argv[argc++] = "--" ASQL_NO_AUTO_COMMIT_L; + + for (; argc < 11; argc++) + { + argv[argc] = NULL; + } + + input_file = fopen (input_filename, "w+"); + if (input_file != NULL) + { + fprintf (input_file, "%s\n", c->query_string); + fprintf (input_file, ";commit"); + fclose (input_file); + } + else + { + sprintf (error_buffer, "Can't create temp file"); + _aj_autoexecquery_error_log (c, ERR_FILE_CREATE_FAIL, error_buffer); + return; + } + + snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", + sco.dbmt_tmp_dir, "aj_execquery", getpid ()); + retval = run_child (argv, 1, NULL, NULL, arniadb_err_file, NULL); /* asql auto-execute */ + unlink (input_filename); + if (retval != 0) + { + sprintf (error_buffer, "Failed to execute Query with"); + _aj_autoexecquery_error_log (c, ERR_SYSTEM_CALL, error_buffer); + if (access (arniadb_err_file, F_OK) == 0) + { + unlink (arniadb_err_file); + } + return; + } + else + { + if (read_error_file2 (arniadb_err_file, error_buffer, DBMT_ERROR_MSG_SIZE, &error_code) < 0) + { + if (error_code == 0) + { + error_code = ERR_GENERAL_ERROR; + } + _aj_autoexecquery_error_log (c, error_code, error_buffer); + if (access (arniadb_err_file, F_OK) == 0) + { + unlink (arniadb_err_file); + } + return; + } + else + { + _aj_autoexecquery_error_log (c, 0, "success"); + if (access (arniadb_err_file, F_OK) == 0) + { + unlink (arniadb_err_file); + } + } + } +} + +static void +_aj_autoexecquery_error_log (autoexecquery_node *node, int error_code, + const char *errmsg) +{ + /* open error file and write errmsg */ + time_t tt; + FILE *outfile; + char logfile[256]; + char strbuf[128]; + + tt = time (&tt); +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (logfile, "%s/log/manager/auto_execquery.log", sco.szArniadb); +#else + sprintf (logfile, "%s/manager/auto_execquery.log", ARNIADB_LOGDIR); +#endif + + outfile = fopen (logfile, "a"); + if (outfile == NULL) + { + return; + } + + time_to_str (tt, "DATE:%04d/%02d/%02d TIME:%02d:%02d:%02d", strbuf, + TIME_STR_FMT_DATE_TIME); + fprintf (outfile, "%s\n", strbuf); + fprintf (outfile, "DBNAME:%s EMGR-USERNAME:%s QUERY-ID:%s ERROR-CODE:%d\n", + node->dbname, node->dbmt_uid, node->query_id, error_code); + fprintf (outfile, "=> %s\n", errmsg); + fflush (outfile); + fclose (outfile); +} + +static void +aj_autobackupdb_handler (void *hd, time_t prev_check_time, time_t cur_time) +{ + time_t backup_time; + struct tm backup_tm, cur_tm, prev_tm, *tm_p; + autobackupdb_node *c; + + backup_period_details *period_date = NULL; + + tm_p = localtime (&cur_time); + if (tm_p == NULL) + { + return; + } + cur_tm = *tm_p; + + for (c = (autobackupdb_node *) (hd); c != NULL; c = c->next) + { + backup_tm = cur_tm; + period_date = c->period_date; + + while (period_date != NULL) + { + if (c->period_type == ABPT_SPECIAL) + { + backup_tm.tm_year = period_date->date / 10000 - 1900; + backup_tm.tm_mon = (period_date->date % 10000) / 100 - 1; + backup_tm.tm_mday = period_date->date % 100; + } + if (1 == c->is_interval) // interval time for auto backup + { + time_t prev_day_sec; + tm_p = localtime (&prev_check_time); + if (tm_p == NULL) + { + return; + } + prev_tm = *tm_p; + + prev_day_sec = + prev_tm.tm_hour * 3600 + prev_tm.tm_min * 60 + prev_tm.tm_sec; + if ((prev_day_sec + c->time * 60) >= 24 * 3600) // if across a day, start at 00:00 + { + backup_tm.tm_hour = 0; + backup_tm.tm_min = 0; + } + else // not across a day + { + time_t exec_sec = + (prev_day_sec / (c->time * 60) + 1) * c->time * 60; + backup_tm.tm_hour = (int) (exec_sec / 3600); + backup_tm.tm_min = (exec_sec % 3600) / 60; + } + } + else // specific time for auto backup + { + if (c->period_type != ABPT_HOURLY) + { + backup_tm.tm_hour = c->time / 100; + } + backup_tm.tm_min = c->time % 100; + } + backup_tm.tm_sec = 0; + + backup_time = mktime (&backup_tm); + if (backup_time <= prev_check_time || backup_time > cur_time) + { + period_date = period_date->next; + continue; + } + + if ((c->period_type == ABPT_MONTHLY + && cur_tm.tm_mday == period_date->date) + || (c->period_type == ABPT_WEEKLY + && cur_tm.tm_wday == period_date->date) + || (c->period_type == ABPT_DAILY) + || (c->period_type == ABPT_HOURLY) + || (c->period_type == ABPT_SPECIAL)) + { + aj_backupdb (c); + } + period_date = period_date->next; + } // while + } // for +} + +static void +_aj_autobackupdb_error_log (autobackupdb_node *n, char *errmsg) +{ + time_t tt; + FILE *outfile; + char logfile[256]; + char strbuf[128]; + + tt = time (&tt); +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (logfile, "%s/log/manager/auto_backupdb.log", sco.szArniadb); +#else + sprintf (logfile, "%s/manager/auto_backupdb.log", ARNIADB_LOGDIR); +#endif + + outfile = fopen (logfile, "a"); + if (outfile == NULL) + { + return; + } + time_to_str (tt, "DATE:%04d/%02d/%02d TIME:%02d:%02d:%02d", strbuf, + TIME_STR_FMT_DATE_TIME); + fprintf (outfile, "%s\n", strbuf); + fprintf (outfile, "DBNAME:%s BACKUPID:%s\n", n->dbname, n->backup_id); + fprintf (outfile, "=> %s\n", errmsg); + fflush (outfile); + fclose (outfile); +} + +static void +aj_backupdb (autobackupdb_node *n) +{ + char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; + int ha_mode; + char bkpath[512]; + char inputfilepath[512]; + char buf[2048], dbdir[512]; + char backup_vol_name[128]; + const char *opt_mode; + char db_start_flag = 0; + char arniadb_err_file[PATH_MAX]; + int retval; + char cmd_name[ARNIADB_CMD_NAME_LEN]; + char level_str[32]; + char strtime[32]; + char thread_num_str[16]; + const char *argv[16]; + int argc = 0; + FILE *inputfile; + T_DB_SERVICE_MODE db_mode; + + arniadb_err_file[0] = '\0'; + + sprintf (buf, "backupdb(%s): auto job start", n->dbname); + _aj_autobackupdb_error_log (n, buf); + + n->lbt = time (NULL); + if (uRetrieveDBDirectory (n->dbname, dbdir) != ERR_NO_ERROR) + { + sprintf (buf, "DB directory not found"); + _aj_autobackupdb_error_log (n, buf); + return; + } + time_to_str (n->lbt, "%04d%02d%02d_%02d%02d%02d", strtime, + TIME_STR_FMT_DATE_TIME); + sprintf (backup_vol_name, "%s_auto_backup_lv%d", n->dbname, n->level); + sprintf (bkpath, "%s/%s_%s", n->path, strtime, backup_vol_name); + + db_mode = uDatabaseMode (n->dbname, &ha_mode); + if (db_mode == DB_SERVICE_MODE_SA) + { + sprintf (buf, "Failed to execute backupdb: %s is in standalone mode", n->dbname); + _aj_autobackupdb_error_log (n, buf); + return; + } + if (n->onoff == 1 && db_mode == DB_SERVICE_MODE_NONE) + { + sprintf (buf, "Failed to execute backupdb: %s is offline", n->dbname); + _aj_autobackupdb_error_log (n, buf); + return; + } + + if (access (n->path, F_OK) < 0) + { + if (uCreateDir (n->path) != ERR_NO_ERROR) + { + sprintf (buf, "Directory creation failed: %s", n->path); + _aj_autobackupdb_error_log (n, buf); + return; + } + } + + remove_extra_subdir (n->path, backup_vol_name, n->bk_num); + + if (access (bkpath, F_OK) < 0) + { + if (uCreateDir (bkpath) != ERR_NO_ERROR) + { + sprintf (buf, "Directory creation failed: %s", bkpath); + _aj_autobackupdb_error_log (n, buf); + return; + } + } + + /* if DB status is on then turn off */ + if (n->onoff == 0 && db_mode == DB_SERVICE_MODE_CS) + { + if (cmd_stop_server (n->dbname, NULL, 0) < 0) + { + sprintf (buf, "Failed to turn off DB"); + _aj_autobackupdb_error_log (n, buf); + return; + } + db_start_flag = 1; + } + + opt_mode = (n->onoff == 0) ? "--" ASQL_SA_MODE_L : "--" ASQL_CS_MODE_L; + + arniadb_cmd_name (cmd_name); + sprintf (thread_num_str, "%d", n->mt); + sprintf (level_str, "%d", n->level); + argc = 0; + argv[argc++] = cmd_name; + argv[argc++] = UTIL_OPTION_BACKUPDB; + argv[argc++] = opt_mode; + argv[argc++] = "--" BACKUP_LEVEL_L; + argv[argc++] = level_str; + argv[argc++] = "--" BACKUP_DESTINATION_PATH_L; + argv[argc++] = bkpath; + if (n->archivedel) + { + argv[argc++] = "--" BACKUP_REMOVE_ARCHIVE_L; + } + + if (n->mt > 0) + { + argv[argc++] = "--" BACKUP_THREAD_COUNT_L; + argv[argc++] = thread_num_str; + } + + if (n->zip) + { + argv[argc++] = "--" BACKUP_COMPRESS_L; + } + + if (!n->check) + { + argv[argc++] = "--" BACKUP_NO_CHECK_L; + } + + if (ha_mode != 0) + { + append_host_to_dbname (dbname_at_hostname, n->dbname, + sizeof (dbname_at_hostname)); + argv[argc++] = dbname_at_hostname; + } + else + { + argv[argc++] = n->dbname; + } + argv[argc++] = NULL; + + snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", + sco.dbmt_tmp_dir, "aj_backupdb", getpid ()); + + sprintf (inputfilepath, "%s/DBMT_task_%d.%d", sco.dbmt_tmp_dir, TS_BACKUPDB, + (int) getpid ()); + inputfile = fopen (inputfilepath, "w"); + if (inputfile) + { + fprintf (inputfile, "y"); + fclose (inputfile); + } + else + { + sprintf (buf, "Failed to write file: %s", inputfilepath); + _aj_autobackupdb_error_log (n, buf); + return; + } + + retval = run_child (argv, 1, inputfilepath, NULL, arniadb_err_file, NULL); /* backupdb */ + unlink (inputfilepath); + + if (read_error_file (arniadb_err_file, buf, sizeof (buf)) < 0) + { + _aj_autobackupdb_error_log (n, buf); + if (access (arniadb_err_file, F_OK) == 0) + { + unlink (arniadb_err_file); + } + return; + } + if (access (arniadb_err_file, F_OK) == 0) + { + unlink (arniadb_err_file); + } + if (retval < 0) + { + /* backupdb */ + sprintf (buf, "Failed to execute backupdb: %s", argv[0]); + _aj_autobackupdb_error_log (n, buf); + return; + } + + sprintf (buf, "backupdb(%s): success", n->dbname); + _aj_autobackupdb_error_log (n, buf); /* log success info to notify arniadb manager user */ + + /* update statistics */ + if (n->onoff == 0 && n->updatestatus) + { + arniadb_cmd_name (cmd_name); + argv[0] = cmd_name; + argv[1] = UTIL_OPTION_OPTIMIZEDB; + argv[2] = n->dbname; + argv[3] = NULL; + if (run_child (argv, 1, NULL, NULL, NULL, NULL) < 0) + { + /* optimizedb */ + sprintf (buf, "Failed to update statistics"); + _aj_autobackupdb_error_log (n, buf); + return; + } + } + + if (db_start_flag) + { + char err_buf[ERR_MSG_SIZE]; + if (cmd_start_server (n->dbname, err_buf, sizeof (err_buf)) < 0) + { + int buf_len; + memset (buf, 0, sizeof (buf)); + buf_len = sprintf (buf, "Failed to turn on DB : "); + snprintf (buf + buf_len, sizeof (buf) - buf_len - 1, "%s", err_buf); + _aj_autobackupdb_error_log (n, buf); + } + } +} diff --git a/server/src/am_autojob.h b/server/src/am_autojob.h new file mode 100644 index 0000000..24a178b --- /dev/null +++ b/server/src/am_autojob.h @@ -0,0 +1,82 @@ +/* + * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. + * + * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + + +/* + * cm_autojob.h - + */ + +#ifndef _CM_AUTOJOB_H_ +#define _CM_AUTOJOB_H_ + +#include +#include "cm_cmd_exec.h" + +#define AUTOJOB_SIZE 4 +#define MIN_AUTO_ADDVOL_PAGE_SIZE 1000 +#define DBNAME_MAX_LEN 64 + +/* autobackupdb.conf */ +#define AJ_BACKUP_CONF_DBNAME "dbname" +#define AJ_BACKUP_CONF_BACKUPID "backupid" +#define AJ_BACKUP_CONF_PATH "path" +#define AJ_BACKUP_CONF_PERIOD_TYPE "period_type" +#define AJ_BACKUP_CONF_PERIOD_DATE "period_date" +#define AJ_BACKUP_CONF_TIME "time" +#define AJ_BACKUP_CONF_LEVEL "level" +#define AJ_BACKUP_CONF_ARCHIVEDEL "archivedel" +#define AJ_BACKUP_CONF_UPDATESTATUS "updatestatus" +#define AJ_BACKUP_CONF_STOREOLD "storeold" +#define AJ_BACKUP_CONF_ONOFF "onoff" + +class GeneralSpacedbResult; + +/* automatic job */ +typedef struct _ajob +{ + char name[64]; + char config_file[512]; /* config file name */ + time_t last_modi; /* last modified time of config file */ + int is_on; + void (*ajob_handler) (void *, time_t, time_t); + void (*ajob_loader) (struct _ajob *); + void *hd; /* handler specific data strudture */ + /* this pointer will be handed to ajob_handler as parameter */ + void *mondata; +} ajob; + +typedef struct autoaddvoldb_t +{ + char dbname[DBNAME_MAX_LEN]; + int data_vol; + double data_warn_outofspace; + int data_ext_page; + int index_vol; + double index_warn_outofspace; + int index_ext_page; + struct autoaddvoldb_t *next; +} autoaddvoldb_node; + +void aj_initialize (ajob *ajlist, void *ud); +void aj_add_volume (char *dbname, const char *type, + int increase, int pagesize); +double +ajFreeSpace (GeneralSpacedbResult *cmd_res, const char *type); + +#endif /* _CM_AUTOJOB_H_ */ diff --git a/server/src/am_cci_interface.cpp b/server/src/am_cci_interface.cpp new file mode 100644 index 0000000..ef33cef --- /dev/null +++ b/server/src/am_cci_interface.cpp @@ -0,0 +1,1655 @@ +/* + * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. + * + * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +/* +* cm_cci_interface.cpp +*/ + +#include +#include +#include +#include + +#if defined(WINDOWS) +#include +#else +#include +#endif + +#include +#include + +#include "cm_log.h" +#include "cm_cci_interface.h" +#include "cm_server_util.h" +#include "cm_cmd_exec.h" +#include "cm_config.h" + +#define SQL_FILE_SUFFIX ".sql" +#define CSV_FILE_SUFFIX ".csv" + +using namespace std; + +static T_HTTP_TASK_INFO http_task_info[] = +{ + {"exportdb", 0, http_arniadb_exportdb}, + {"importdb", 0, http_arniadb_importdb}, + {"sql", 0, http_arniadb_sql}, + {NULL, 0, NULL} +}; + +int +get_cci_task_info (const char *task, T_HTTP_TASK_FUNC *task_func) +{ + int i; + + for (i = 0; http_task_info[i].task_str != NULL; i++) + { + if (!strcmp (task, http_task_info[i].task_str)) + { + if (task_func) + { + *task_func = http_task_info[i].task_func; + } + return http_task_info[i].task_code; + } + } + + *task_func = NULL; + + return -1; +} + +int +build_common_header (Json::Value &response, int status, const char *note) +{ + response["status"] = status; + response["note"] = string (note); + + return status; +} + +int +_get_col_info (int req, T_CCI_SQLX_CMD &cmd_type, Json::Value &response) +{ + int i, col_count; + char *temp; + T_CCI_COL_INFO *res_col_info; + Json::Value attribute, col; + + res_col_info = cci_get_result_info (req, &cmd_type, &col_count); + if (cmd_type == ARNIADB_STMT_SELECT && !res_col_info) + { + return -1; + } + response["stmt_type"] = cmd_type; + + for (i = 1; i <= col_count; i++) + { + temp = CCI_GET_RESULT_INFO_NAME (res_col_info, i); + col["name"] = (temp == NULL) ? "" : temp; + temp = CCI_GET_RESULT_INFO_ATTR_NAME (res_col_info, i); + col["attr_name"] = (temp == NULL) ? "" : temp; + temp = CCI_GET_RESULT_INFO_CLASS_NAME (res_col_info, i); + col["class_name"] = (temp == NULL) ? "" : temp; + temp = CCI_GET_RESULT_INFO_DEFAULT_VALUE (res_col_info, i); + col["default"] = (temp == NULL) ? "" : temp; + + col["type"] = CCI_GET_RESULT_INFO_TYPE (res_col_info, i); + col["precision"] = CCI_GET_RESULT_INFO_PRECISION (res_col_info, i); + col["scale"] = CCI_GET_RESULT_INFO_SCALE (res_col_info, i); + col["is_not_null"] = CCI_GET_RESULT_INFO_IS_NON_NULL (res_col_info, i); + col["is_auto_inc"] = + CCI_GET_RESULT_INFO_IS_AUTO_INCREMENT (res_col_info, i); + col["is_unique_key"] = + CCI_GET_RESULT_INFO_IS_UNIQUE_KEY (res_col_info, i); + col["is_primary_key"] = + CCI_GET_RESULT_INFO_IS_PRIMARY_KEY (res_col_info, i); + col["is_foreign_key"] = + CCI_GET_RESULT_INFO_IS_FOREIGN_KEY (res_col_info, i); + col["is_reverse_index"] = + CCI_GET_RESULT_INFO_IS_REVERSE_INDEX (res_col_info, i); + col["is_reverse_unique"] = + CCI_GET_RESULT_INFO_IS_REVERSE_UNIQUE (res_col_info, i); + col["is_shared"] = CCI_GET_RESULT_INFO_IS_SHARED (res_col_info, i); + attribute.append (col); + } + response["attribute"] = attribute; + return col_count; +} + +typedef struct +{ + int con_id; + int fetch_size; + int fetch_offset; + int dump_plan; + const char *stmt; + Json::Value *response; +#ifndef WINDOWS + pthread_mutex_t *mutex; + pthread_cond_t *cond; +#endif +} async_stmt_st; + +int +_execute_async_stmt (int con_id, const char *stmt, int fetch_size, + int fetch_offset, int dump_plan, Json::Value &response) +{ + int req = 0, col_count = 0, res, ind, i, flag = 0; + char *buffer, oidbuf[1024], *plan = NULL; + Json::Value values, col, oid; + T_CCI_ERROR error; + int elapsed_msec = 0; + T_CCI_SQLX_CMD cmd_type; + struct timeval task_begin, task_end; + + response["stmt"] = stmt; + /* record the start time of running stmt */ + gettimeofday (&task_begin, NULL); + + if ((req = cci_prepare (con_id, (char *) stmt, CCI_PREPARE_INCLUDE_OID, &error)) < 0) + { + response["status"] = error.err_code; + response["note"] = error.err_msg; + res = req; + goto handle_error; + } + + if ((col_count = _get_col_info (req, cmd_type, response)) < 0) + { + response["status"] = -1; + response["note"] = "get col info error"; + res = col_count; + goto handle_error; + } + + if (dump_plan) + { + flag |= CCI_EXEC_QUERY_INFO; + } + if ((res = cci_execute (req, flag, 0, &error)) < 0) + { + response["status"] = error.err_code; + response["note"] = error.err_msg; + goto handle_error; + } + response["exec_retval"] = res; + + if (dump_plan && cmd_type == ARNIADB_STMT_SELECT) + { + if (cci_get_query_plan (req, &plan) >= 0) + { + response["query_plan"] = plan ? plan : ""; + cci_query_info_free (plan); + } + } + + if (fetch_size == 0) + { + fetch_size = res; + } + + while (fetch_size--) + { + res = cci_cursor (req, fetch_offset, CCI_CURSOR_CURRENT, &error); + if (res < 0) + { + break; + } + + fetch_offset = 1; + if ((res = cci_fetch (req, &error)) < 0) + { + break; + } + + col.clear (); + for (i = 1; i <= col_count; i++) + { + buffer = NULL; + if ((res = + cci_get_data (req, i, CCI_A_TYPE_STR, &buffer, &ind)) < 0) + { + break; + } + if (buffer == NULL) + { + col.append (Json::Value::null); + } + else + { + col.append (buffer); + } + } + values.append (col); + + if (!cci_get_cur_oid (req, oidbuf)) + { + oid.append (oidbuf); + } + else + { + oid.append (""); + } + } + response["values"] = values; + response["oid"] = oid; + + response["status"] = CCI_ER_NO_ERROR; + response["note"] = "note"; + res = CCI_ER_NO_ERROR; +handle_error: + if (req > 0) + { + cci_close_req_handle (req); + } + + gettimeofday (&task_end, NULL); + _ut_timeval_diff (&task_begin, &task_end, &elapsed_msec); + response["__EXEC_TIME"] = elapsed_msec; + return res; +} + +#ifdef WINDOWS +DWORD WINAPI +_async_stmt (LPVOID lpArg) +#else +void * +_async_stmt (void *lpArg) +#endif +{ + async_stmt_st *pstmt = (async_stmt_st *) lpArg; + _execute_async_stmt (pstmt->con_id, pstmt->stmt, pstmt->fetch_size, + pstmt->fetch_offset, pstmt->dump_plan, + * (pstmt->response)); + +#ifndef WINDOWS + pthread_mutex_lock (pstmt->mutex); + pthread_cond_broadcast (pstmt->cond); + pthread_mutex_unlock (pstmt->mutex); +#endif + return NULL; +} + +#ifdef WINDOWS +int +_execute_stmt (int con_id, const char *stmt, int fetch_size, int fetch_offset, + int dump_plan, Json::Value &response, unsigned long time_out = 120) +{ + HANDLE hHandles; + DWORD ThreadID; + DWORD dwCount = 0, dwWaitResult; + async_stmt_st *pstmt = (async_stmt_st *) malloc (sizeof (async_stmt_st)); + if (pstmt == NULL) + { + return CCI_ER_NO_MORE_MEMORY; + } + + pstmt->con_id = con_id; + pstmt->stmt = stmt; + pstmt->fetch_size = fetch_size; + pstmt->fetch_offset = fetch_offset; + pstmt->dump_plan = dump_plan; + pstmt->response = &response; + + hHandles = CreateThread (NULL, 0, _async_stmt, pstmt, 0, &ThreadID); + if (hHandles == NULL) + { + free (pstmt); + return build_common_header (response, CCI_ER_DBMS, + "failed to execute stmt"); + } + + dwWaitResult = WaitForSingleObject (hHandles, // handle to mutex + time_out * 1000); // no time-out interval + + if (dwWaitResult == WAIT_TIMEOUT) + { + TerminateThread (hHandles, 1); + CloseHandle (hHandles); + free (pstmt); + return build_common_header (response, CCI_ER_DBMS, + "execute stmt timeout"); + } + + CloseHandle (hHandles); + free (pstmt); + return CCI_ER_NO_ERROR; +} +#else +int +_execute_stmt (int con_id, const char *stmt, int fetch_size, int fetch_offset, + int dump_plan, Json::Value &response, unsigned long time_out = 120) +{ + int err = 0; + pthread_t async_thrd; +#if defined(AIX) + pthread_attr_t thread_attr; +#endif + pthread_cond_t cond; + pthread_mutex_t mutex; + timespec to; + async_stmt_st *pstmt = (async_stmt_st *) malloc (sizeof (async_stmt_st)); + if (pstmt == NULL) + { + return CCI_ER_NO_MORE_MEMORY; + } + + err = pthread_mutex_init (&mutex, NULL); + if (err != 0) + { + LOG_ERROR ("_execute_stmt : fail to set thread mutex."); + return build_common_header (response, CCI_ER_DBMS, + "failed to execute stmt"); + } + + err = pthread_cond_init (&cond, NULL); + if (err != 0) + { + LOG_ERROR ("_execute_stmt : fail to set thread condition."); + return build_common_header (response, CCI_ER_DBMS, + "failed to execute stmt"); + } + + pstmt->con_id = con_id; + pstmt->stmt = stmt; + pstmt->fetch_size = fetch_size; + pstmt->fetch_offset = fetch_offset; + pstmt->dump_plan = dump_plan; + pstmt->response = &response; + + pstmt->mutex = &mutex; + pstmt->cond = &cond; + +#if defined(AIX) + err = pthread_attr_init (&thread_attr); + if (err != 0) + { + LOG_ERROR ("_execute_stmt : fail to set thread attribute."); + return build_common_header (response, CCI_ER_DBMS, + "failed to execute stmt"); + } + + err = pthread_attr_setdetachstate (&thread_attr, PTHREAD_CREATE_DETACHED); + if (err != 0) + { + LOG_ERROR ("_execute_stmt : fail to set thread detach state."); + return build_common_header (response, CCI_ER_DBMS, + "failed to execute stmt"); + } + + /* AIX's pthread is slightly different from other systems. + Its performance highly depends on the pthread's scope and it's related + kernel parameters. */ + err = pthread_attr_setscope (&thread_attr, PTHREAD_SCOPE_PROCESS); + if (err != 0) + { + LOG_ERROR ("cm_execute_request_async : fail to set thread scope."); + return build_common_header (response, CCI_ER_DBMS, + "failed to execute stmt"); + } + + err = pthread_attr_setstacksize (&thread_attr, AIX_STACKSIZE_PER_THREAD); + if (err != 0) + { + LOG_ERROR ("cm_execute_request_async : fail to set thread stack size."); + return build_common_header (response, CCI_ER_DBMS, + "failed to execute stmt"); + } + + err = pthread_create (&async_thrd, &thread_attr, _async_stmt, pstmt); +#else /* except AIX */ + err = pthread_create (&async_thrd, NULL, _async_stmt, pstmt); +#endif + + if (err != 0) + { + free (pstmt); + pthread_mutex_destroy (&mutex); + pthread_cond_destroy (&cond); + return build_common_header (response, CCI_ER_DBMS, + "failed to execute stmt"); + } + pthread_mutex_lock (&mutex); + to.tv_sec = time (NULL) + time_out; + to.tv_nsec = 0; + err = pthread_cond_timedwait (&cond, &mutex, &to); + pthread_mutex_unlock (&mutex); + if (err == ETIMEDOUT) + { + pthread_cancel (async_thrd); + } + else + { + pthread_join (async_thrd, NULL); + } + + pthread_mutex_destroy (&mutex); + pthread_cond_destroy (&cond); + + free (pstmt); + + if (err == ETIMEDOUT) + return build_common_header (response, CCI_ER_QUERY_TIMEOUT, + "execute stmt timeout"); + + return CCI_ER_NO_ERROR; +} +#endif + +int +_saveto (string file_name, string info, string flag) +{ + FILE *fp = fopen (file_name.c_str (), flag.c_str ()); + if (fp == NULL) + { + return -1; + } + + fwrite (info.c_str (), 1, info.size (), fp); + fclose (fp); + return 0; +} + +string +_get_auto_increment () +{ + //" AUTO_INCREMENT(1,1)" + return ""; +} + +string +str_replace (const string &orign, const string &oldstr, + const string &newstr) +{ + size_t pos = 0; + string tempstr = orign; + string::size_type newlen = newstr.length (); + string::size_type oldlen = oldstr.length (); + while (true) + { + pos = tempstr.find (oldstr, pos); + if (pos == string::npos) + { + break; + } + + tempstr.replace (pos, oldlen, newstr); + pos += newlen; + } + + return tempstr; +} + + +string +_fix_cci_get_attr_type_str (const char *buf) +{ + int flag = 0; + const char *p = buf; + string fix_str = buf; + if (!strstr (buf, "float") && strstr (buf, "floa")) + { + fix_str = str_replace (fix_str, "floa", "float"); + } + if (!strstr (buf, "blob") && strstr (buf, "blo")) + { + fix_str = str_replace (fix_str, "blo", "blob"); + } + if (!strstr (buf, "clob") && strstr (buf, "clo")) + { + fix_str = str_replace (fix_str, "clo", "clob"); + } + if (!strstr (buf, "datetime") && strstr (buf, "datetim")) + { + fix_str = str_replace (fix_str, "datetim", "datetime"); + } + else if (!strstr (buf, "date") && strstr (buf, "dat")) + { + fix_str = str_replace (fix_str, "dat", "date"); + } + else if (!strstr (buf, "timestamp") && strstr (buf, "timestam")) + { + fix_str = str_replace (fix_str, "timestam", "timestamp"); + } + else if (!strstr (buf, "time") && strstr (buf, "tim")) + { + fix_str = str_replace (fix_str, "tim", "time"); + } + if (!strstr (buf, "monetary") && strstr (buf, "monetar")) + { + fix_str = str_replace (fix_str, "monetar", "monetary"); + } + if (!strstr (buf, "integer") && strstr (buf, "intege")) + { + fix_str = str_replace (fix_str, "intege", "integer"); + } + if (!strstr (buf, "double") && strstr (buf, "doubl")) + { + fix_str = str_replace (fix_str, "doubl", "double"); + } + if (!strstr (buf, "smallint") && strstr (buf, "smallin")) + { + fix_str = str_replace (fix_str, "smallin", "smallint"); + } + if (!strstr (buf, "string") && strstr (buf, "strin")) + { + fix_str = str_replace (fix_str, "strin", "string"); + } + if (!strstr (buf, "bigint") && strstr (buf, "bigin")) + { + fix_str = str_replace (fix_str, "bigin", "bigint"); + } + + while (*p != 0) + { + if (*p == '(') + { + flag++; + } + if (*p == ')') + { + flag--; + } + p++; + } + if (flag > 0) + { + fix_str.append (")"); + } + return fix_str; +} + +int +_get_attribute_type (int con_id, string db_name, string class_name, + Json::Value &attribute, list < string > &result_list) +{ + string schema; + char buf[256]; + T_CCI_ERROR err_buf; + string st_default = + attribute["default"].asString () == + "" ? "" : " DEFAULT '" + attribute["default"].asString () + "'"; + + schema += "\"" + attribute["name"].asString () + "\" "; + + /*cci_get_attr_type_str has bug, so before fix ,we use _fix_cci_get_attr_type_str */ + cci_get_attr_type_str (con_id, (char *) class_name.c_str (), + (char *) attribute["name"].asString ().c_str (), buf, + 256, &err_buf); + /* schema += buf; */ + schema += _fix_cci_get_attr_type_str (buf); + schema += st_default; + if (attribute["is_auto_inc"].asInt ()) + { + schema += _get_auto_increment (); + } + + if (attribute["is_not_null"].asInt ()) + { + schema += " NOT NULL"; + } + + if (!attribute["is_primary_key"].asInt ()) + { + if (attribute["is_unique_key"].asInt ()) + { + schema += " UNIQUE"; + } + } + attribute["type_str"] = buf; + + result_list.push_back (schema); + + return 0; +} + +int +_get_class_primary_key (string &pk, int has_pk, Json::Value &attribute) +{ + if (!attribute["is_primary_key"].asInt ()) + { + return 0; + } + + if (has_pk) + { + pk += ","; + } + pk += "\"" + attribute["name"].asString () + "\""; + return 1; +} + +int +_get_class_constraint (int con_id, string class_name, Json::Value &result) +{ + int cci_request = 0, cci_retval, cci_ind; + T_CCI_ERROR cci_error; + UNI_CCI_A_TYPE cci_value; + Json::Value constraint; + string index_name; + + if ((cci_request = cci_schema_info (con_id, CCI_SCH_CONSTRAINT, + (char *) class_name.c_str (), NULL, 0, + &cci_error)) < 0) + { + return -1; + } + + while (1) + { + cci_retval = cci_cursor (cci_request, 1, CCI_CURSOR_CURRENT, &cci_error); + if (cci_retval < 0) + { + break; + } + + if ((cci_retval = cci_fetch (cci_request, &cci_error)) < 0) + { + break; + } + + constraint.clear (); + /* type */ + if ((cci_retval = cci_get_data (cci_request, 1, CCI_A_TYPE_INT, &cci_value, &cci_ind)) < 0) + { + break; + } + constraint["type"] = cci_value.i; + + /* asc_or_desc */ + if ((cci_retval = cci_get_data (cci_request, 8, CCI_A_TYPE_STR, &cci_value, &cci_ind)) < 0) + { + break; + } + constraint["asc_or_desc"] = cci_value.str; + + /* index name */ + if ((cci_retval = cci_get_data (cci_request, 2, CCI_A_TYPE_STR, &cci_value, &cci_ind)) < 0) + { + break; + } + index_name = cci_value.str; + constraint["index_name"] = cci_value.str; + + /* column name */ + if ((cci_retval = cci_get_data (cci_request, 3, CCI_A_TYPE_STR, &cci_value, &cci_ind)) < 0) + { + break; + } + constraint["attr_name"] = cci_value.str; + + /* num pages */ + if ((cci_retval = cci_get_data (cci_request, 4, CCI_A_TYPE_INT, &cci_value, &cci_ind)) < 0) + { + break; + } + constraint["num_pages"] = cci_value.i; + + /* num keys */ + if ((cci_retval = cci_get_data (cci_request, 5, CCI_A_TYPE_INT, &cci_value, &cci_ind)) < 0) + { + break; + } + constraint["num_keys"] = cci_value.i; + + /* primary key */ + if ((cci_retval = cci_get_data (cci_request, 6, CCI_A_TYPE_INT, &cci_value, &cci_ind)) < 0) + { + break; + } + constraint["primary_key"] = cci_value.i; + + /* key order */ + if ((cci_retval = cci_get_data (cci_request, 7, CCI_A_TYPE_INT, &cci_value, &cci_ind)) < 0) + { + break; + } + constraint["key_order"] = cci_value.i; + + result[index_name].append (constraint); + } + cci_close_req_handle (cci_request); + return 0; +} + +int +_get_class_foreign_key (int con_id, string class_name, Json::Value &result) +{ + int cci_request = 0, cci_retval, cci_ind; + T_CCI_ERROR cci_error; + UNI_CCI_A_TYPE cci_value; + Json::Value constraint; + string fk_name; + if ((cci_request = + cci_schema_info (con_id, CCI_SCH_IMPORTED_KEYS, (char *) class_name.c_str (), NULL, 0, &cci_error)) < 0) + { + return -1; + } + + while (1) + { + cci_retval = cci_cursor (cci_request, 1, CCI_CURSOR_CURRENT, &cci_error); + if (cci_retval < 0) + { + break; + } + + if ((cci_retval = cci_fetch (cci_request, &cci_error)) < 0) + { + break; + } + + constraint.clear (); + + /* pk class name */ + if ((cci_retval = cci_get_data (cci_request, 1, CCI_A_TYPE_STR, &cci_value, &cci_ind)) < 0) + { + break; + } + constraint["pk_table_name"] = cci_value.str; + + /* pk column name */ + if ((cci_retval = cci_get_data (cci_request, 2, CCI_A_TYPE_STR, &cci_value, &cci_ind)) < 0) + { + break; + } + constraint["pk_column_name"] = cci_value.str; + + /* fk class name */ + if ((cci_retval = cci_get_data (cci_request, 3, CCI_A_TYPE_STR, &cci_value, &cci_ind)) < 0) + { + break; + } + constraint["fk_table_name"] = cci_value.str; + + /* fk column name */ + if ((cci_retval = cci_get_data (cci_request, 4, CCI_A_TYPE_STR, &cci_value, &cci_ind)) < 0) + { + break; + } + constraint["fk_column_name"] = cci_value.str; + + /* key sequence number */ + if ((cci_retval = cci_get_data (cci_request, 5, CCI_A_TYPE_INT, &cci_value, &cci_ind)) < 0) + { + break; + } + constraint["key_seq"] = cci_value.i; + + /* update rule */ + if ((cci_retval = cci_get_data (cci_request, 6, CCI_A_TYPE_INT, &cci_value, &cci_ind)) < 0) + { + break; + } + constraint["update_action"] = cci_value.i; + + /* delete rule */ + if ((cci_retval = cci_get_data (cci_request, 7, CCI_A_TYPE_INT, &cci_value, &cci_ind)) < 0) + { + break; + } + constraint["delete_action"] = cci_value.i; + + /* foreign key name */ + if ((cci_retval = cci_get_data (cci_request, 8, CCI_A_TYPE_STR, &cci_value, &cci_ind)) < 0) + { + break; + } + fk_name = cci_value.str; + constraint["fk_name"] = cci_value.str; + + /* primary key name */ + if ((cci_retval = cci_get_data (cci_request, 9, CCI_A_TYPE_STR, &cci_value, &cci_ind)) < 0) + { + break; + } + constraint["fk_name"] = cci_value.str; + + result[fk_name].append (constraint); + } + cci_close_req_handle (cci_request); + return 0; +} + +string +_get_action_type_str (int action) +{ + switch (action) + { + case 0: + return "CASCADE"; + case 1: + return "RESTRICT"; + case 2: + return "NO ACTION"; + case 3: + return "SET NULL"; + default: + break; + } + return ""; +} + +string +_get_index_type_str (int type) +{ + switch (type) + { + case 0: + return "UNIQUE INDEX"; + case 1: + return "INDEX"; + case 2: + return "REVERSE UNIQUE INDEX"; + case 3: + return "REVERSE INDEX"; + default: + break; + } + return ""; +} + +int +_build_foreign_key_str (Json::Value &f_key, list < string > &schema) +{ + int i = 0, size, on_delete = -1, on_update = -1; + string f_key_str = ""; + string fk_col_name, pk_col_name, pk_tab_name; + Json::Value::Members members (f_key.getMemberNames ()); + + for (Json::Value::Members::iterator it = members.begin (); + it != members.end (); ++it) + { + size = f_key[*it].size (); + fk_col_name = ""; + pk_col_name = ""; + for (i = 0; i < size; i++) + { + fk_col_name += + "\"" + f_key[*it][i]["fk_column_name"].asString () + "\""; + pk_col_name += + "\"" + f_key[*it][i]["pk_column_name"].asString () + "\""; + pk_tab_name = + "\"" + f_key[*it][i]["pk_table_name"].asString () + "\""; + on_delete = f_key[*it][i]["delete_action"].asInt (); + on_update = f_key[*it][i]["update_action"].asInt (); + if (i != (size - 1)) + { + fk_col_name += ","; + pk_col_name += ","; + } + } + f_key_str = "FOREIGN KEY (" + fk_col_name + ") REFERENCES " + + pk_tab_name + "(" + pk_col_name + ") ON DELETE " + + _get_action_type_str (on_delete) + " ON UPDATE " + + _get_action_type_str (on_update); + + schema.push_back (f_key_str); + } + return 0; +} + + +int +_build_index_str (Json::Value &index, string class_name, + list < string > &schema) +{ + int i = 0, size, type = 0; + string index_str = "", asc = ""; + string attr_name, pk_col_name, pk_tab_name; + Json::Value::Members members (index.getMemberNames ()); + + for (Json::Value::Members::iterator it = members.begin (); + it != members.end (); ++it) + { + size = index[*it].size (); + attr_name = ""; + for (i = 0; i < size; i++) + { + attr_name += "\"" + index[*it][i]["attr_name"].asString () + "\""; + asc = index[*it][i]["asc_or_desc"].asString (); + type = index[*it][i]["type"].asInt (); + + if (asc == "D") + { + attr_name += " DESC"; + } + + if (i != (size - 1)) + { + attr_name += ","; + } + } + + /* exclude ASC UNIQUE */ + if (type == 0 && asc == "A") + { + continue; + } + + index_str = + "CREATE " + _get_index_type_str (type) + " ON \"" + class_name + + "\"(" + attr_name + ");"; + + schema.push_back (index_str); + } + return 0; +} + +string +_dump_constraint_list (list < string > &schema_list, const string quote = ",") +{ + list < string >::iterator itor; + string schema = ""; + int flag = 0; + for (itor = schema_list.begin (); itor != schema_list.end (); + itor++, flag++) + { + if (flag) + { + schema += quote + "\n"; + } + schema += *itor; + } + schema += "\n"; + return schema; +} + +int +_export_class_schema (int con_id, string db_name, string class_name, + Json::Value &result, string export_path) +{ + int i, has_primary_key = 0; + int attr_size = result["attribute"].size (); + Json::Value fkey, index; + string schema = "CREATE TABLE \"" + class_name + "\" (\n"; + string pk = "CONSTRAINT PRIMARY KEY("; + list < string > schema_list, index_list; + + for (i = 0; i < attr_size; i++) + { + _get_attribute_type (con_id, db_name, class_name, result["attribute"][i], schema_list); + } + + for (i = 0; i < attr_size; i++) + { + has_primary_key += _get_class_primary_key (pk, has_primary_key, result["attribute"][i]); + } + + if (has_primary_key) + { + schema_list.push_back (pk + ")"); + } + + if (_get_class_foreign_key (con_id, class_name, fkey) == 0) + { + _build_foreign_key_str (fkey, schema_list); + } + + schema += _dump_constraint_list (schema_list) + ");\n"; + + if (_get_class_constraint (con_id, class_name, index) == 0) + { + _build_index_str (index, class_name, index_list); + } + + schema += _dump_constraint_list (index_list, "") + "\n"; + + return _saveto (export_path, schema, "a+"); +} + +string +_quota_mark (string &col) +{ + size_t it, size = col.size (); + string result; + for (it = 0; it != size; it++) + { + if (col[it] == '\'') + { + result.append (1, '\''); + } + + result.append (1, col[it]); + } + + return result; +} + +int +_export_class_object_sql (string class_name, Json::Value &result, + string export_path) +{ + unsigned int i, j; + string header = "insert into \"" + class_name + "\" "; + string values, col, type_str, prefix; + header = header + " values "; + for (i = 0; i < result["values"].size (); i++) + { + values = "("; + for (j = 0; j < result["values"][i].size (); j++) + { + type_str = result["attribute"][j]["type_str"].asString (); + if (type_str == "date") + { + prefix = "DATE"; + } + else + { + prefix = ""; + } + + col = result["values"][i][j].asString (); + + values += prefix + "'" + _quota_mark (col) + "'"; + if (j != (result["values"][i].size () - 1)) + { + values += ", "; + } + } + values += ");\n"; + _saveto (export_path, header + values, "a+"); + } + return 0; +} + +int +_export_class_object_csv (string class_name, Json::Value &result, + string export_path) +{ + unsigned int i, j; + string values, col; + + for (i = 0; i < result["values"].size (); i++) + { + values = ""; + for (j = 0; j < result["values"][i].size (); j++) + { + col = result["values"][i][j].asString (); + values += "\"" + _quota_mark (col) + "\""; + if (j != (result["values"][i].size () - 1)) + { + values += ","; + } + } + values += "\n"; + _saveto (export_path, values, "a+"); + } + return 0; +} + +typedef enum +{ + DUMP_TYPE_SQL = 0, + DUMP_TYPE_CSV +} E_DUMP_TYPE; + +typedef enum +{ + DUMP_FLAG_DATA = 1, + DUMP_FLAG_SCHEMA = 2, + DUMP_FLAG_DATA_SCHEMA = 3 +} E_DUMP_FLAG; + +void +_export_class (int con_id, string db_name, string class_name, + string export_path, int export_type, int export_flag, + Json::Value &result) +{ + switch (export_type) + { + case DUMP_TYPE_SQL: + if (export_flag & DUMP_FLAG_SCHEMA) + { + _export_class_schema (con_id, db_name, class_name, result, export_path); + } + if (export_flag & DUMP_FLAG_DATA) + { + _export_class_object_sql (class_name, result, export_path); + } + break; + case DUMP_TYPE_CSV: + _export_class_object_csv (class_name, result, export_path); + break; + default: + break; + } +} + +static bool +_get_export_path (string &export_path, string &export_filename, + int export_type, const string &db_name) +{ + time_t time_now; + struct tm *tm_now = NULL; + char file_name_dt[PATH_MAX]; + + file_name_dt[0] = '\0'; + + export_filename = ""; + export_path = string (sco.szCWMPath) + "/files/"; + if (access ((char *) export_path.c_str (), F_OK | R_OK | W_OK | X_OK) < 0) + { + return false; + } + + time_now = time (NULL); + if (time_now == -1) + { + return false; + } + +#ifndef WINDOWS + tm_now = new struct tm (); + if (localtime_r (&time_now, tm_now) == NULL) + { + delete tm_now; + tm_now = NULL; + return false; + } +#else + tm_now = localtime (&time_now); + if (tm_now == NULL) + { + return false; + } +#endif + + if (strftime (file_name_dt, PATH_MAX, "_%Y%m%d_%H%M%S", tm_now) == 0) + { +#ifndef WINDOWS + delete tm_now; +#endif + tm_now = NULL; + return false; + } + + bool success = true; + switch (export_type) + { + case DUMP_TYPE_SQL: + export_filename = db_name + file_name_dt + SQL_FILE_SUFFIX; + break; + + case DUMP_TYPE_CSV: + export_filename = db_name + file_name_dt + CSV_FILE_SUFFIX; + break; + + default: + export_filename = ""; + export_path = ""; + success = false; + break; + } + +#ifndef WINDOWS + delete tm_now; +#endif + tm_now = NULL; + + if (success) + { + export_path += export_filename; + } + return success; +} + +int +http_arniadb_exportdb (Json::Value &request, Json::Value &response) +{ + int con_handle, port, export_size, export_type, export_flag, res; + unsigned int i; + int time_out; + string ip, db_name, db_user, dbpasswd; + string export_path, export_filename, stmt, classname; + Json::Value result; + T_CCI_ERROR error; + + ip = request.get ("bip", "localhost").asString (); + port = request.get ("bport", sco.iAMS_port).asInt (); + export_size = request.get ("export_size", 0).asInt (); + export_type = request.get ("export_type", DUMP_TYPE_SQL).asInt (); + export_flag = request.get ("export_flag", DUMP_FLAG_DATA_SCHEMA).asInt (); + time_out = request.get ("time_out", 120).asInt (); + + JSON_FIND_V (request, "dbname", + build_common_header (response, ERR_PARAM_MISSING, "dbname")); + db_name = request["dbname"].asString (); + + JSON_FIND_V (request, "dbid", + build_common_header (response, ERR_PARAM_MISSING, "dbid")); + db_user = request["dbid"].asString (); + + JSON_FIND_V (request, "dbpasswd", + build_common_header (response, ERR_PARAM_MISSING, "dbpasswd")); + dbpasswd = request["dbpasswd"].asString (); + + if (!_get_export_path (export_path, export_filename, export_type, db_name)) + { + return build_common_header (response, ERR_WITH_MSG, "Can not generate the export file name."); + } + + con_handle = + cci_connect ((char *) ip.c_str (), port, (char *) db_name.c_str (), + (char *) db_user.c_str (), (char *) dbpasswd.c_str ()); + if (con_handle < 0) + { + cci_get_err_msg (con_handle, error.err_msg, 1024); + return build_common_header (response, con_handle, error.err_msg); + } + + if (Json::Value::null != request["charset"]) + { + cci_set_charset (con_handle, (char *) request["charset"].asString ().c_str ()); + } + + _saveto (export_path, "", "w"); + JSON_FIND_V (request, "class", + build_common_header (response, ERR_PARAM_MISSING, "stmt")); + for (i = 0; i < request["class"].size (); i++) + { + result.clear (); + classname = request["class"][i].asString (); + stmt = "select * from \"" + classname + "\""; + res = _execute_stmt (con_handle, stmt.c_str (), export_size, 1, 0, result, time_out); + if (res < 0) + { + result["class"] = classname; + response["result"].append (result); + continue; + } + _export_class (con_handle, db_name, request["class"][i].asString (), + export_path, export_type, export_flag, result); + } + + cci_disconnect (con_handle, &error); + build_common_header (response, ERR_NO_ERROR, "none"); + response["export_filename"] = export_filename; + + return ERR_NO_ERROR; +} + +int +_import_class_sql (Json::Value &request, Json::Value &response) +{ + string ip, db_name, db_user, dbpasswd; + string import_filename; + string import_path; + string error_continue_option = "y"; + T_ASQL_RESULT *asql_result; + T_ARNIADB_MODE mode; + + JSON_FIND_V (request, "dbname", + build_common_header (response, ERR_PARAM_MISSING, "dbname")); + db_name = request["dbname"].asString (); + + JSON_FIND_V (request, "dbid", + build_common_header (response, ERR_PARAM_MISSING, "dbid")); + db_user = request["dbid"].asString (); + + JSON_FIND_V (request, "dbpasswd", + build_common_header (response, ERR_PARAM_MISSING, "dbpasswd")); + dbpasswd = request["dbpasswd"].asString (); + + JSON_FIND_V (request, "import_filename", + build_common_header (response, ERR_PARAM_MISSING, + "Parameter(import_filename) missing in the request.")); + + import_filename = request["import_filename"].asString (); + import_path = string (sco.dbmt_tmp_dir) + "/" + import_filename; + + mode = (uDatabaseMode ((char *) db_name.c_str (), NULL) == + DB_SERVICE_MODE_NONE ? ARNIADB_MODE_SA : ARNIADB_MODE_CS); + asql_result = + cmd_asql ((char *) db_name.c_str (), (char *) db_user.c_str (), + (char *) dbpasswd.c_str (), mode, (char *) import_path.c_str (), + NULL, (char *) error_continue_option.c_str ()); + if (asql_result == NULL) + { + return build_common_header (response, ERR_WITH_MSG, + "Error occur when execurating asql."); + } + else if (strlen (asql_result->err_msg) != 0) + { + build_common_header (response, ERR_WITH_MSG, asql_result->err_msg); + free (asql_result); + return ERR_WITH_MSG; + } + free (asql_result); + return build_common_header (response, ERR_NO_ERROR, "none"); +} + +char * +_char_replace (char *str, char src, char dst) +{ + char *p = str; + while (*p != 0) + { + if (*p == src) + { + *p = dst; + } + p++; + } + + return str; +} + +string +_build_with_double_quotes (char *str, const char delimiter) +{ + char *pos = str; + char *begin = NULL, *end = NULL; + int quotes = 0; + string value; + while (*pos != 0) + { + if (*pos == '"') + { + if (quotes++) + { + end = pos; + } + else + { + begin = pos; + } + } + if (*pos == delimiter && 0 == (quotes % 2)) + { + if (begin) + { + *begin = '\''; + } + if (end) + { + *end = '\''; + } + *pos = 0; + value += begin; + value += ","; + quotes = 0; + } + pos++; + } + if (begin) + { + *begin = '\''; + } + if (end) + { + *end = '\''; + } + value += begin; + return value; +} + +string +_build_without_quotes (char *str, const char delimiter) +{ + char *pos = str; + char *begin = str; + string value; + while ((pos = strchr (begin, delimiter)) != NULL) + { + *pos = 0; + value += "'"; + value += begin; + value += "',"; + begin = pos + 1; + } + value += "'"; + value += begin; + value += "'"; + return value; +} + +string +_build_quotes (char *str, const char delimiter) +{ + if (str == NULL) + { + return ""; + } + if (*str == '"') + { + return _build_with_double_quotes (str, delimiter); + } + return _build_without_quotes (str, delimiter); +} + +int +_import_class_csv (Json::Value &request, Json::Value &response) +{ + string ip, db_name, db_user, dbpasswd, stmt, classname; + string import_path; + string import_filename; + FILE *fp; + char buf[1024]; + int con_handle, port, time_out, success = 0, fail = 0; + Json::Value result; + T_CCI_ERROR error; + + ip = request.get ("bip", "localhost").asString (); + port = request.get ("bport", sco.iAMS_port).asInt (); + time_out = request.get ("time_out", 120).asInt (); + + JSON_FIND_V (request, "dbname", + build_common_header (response, ERR_PARAM_MISSING, "dbname")); + db_name = request["dbname"].asString (); + + JSON_FIND_V (request, "dbid", + build_common_header (response, ERR_PARAM_MISSING, "dbid")); + db_user = request["dbid"].asString (); + + JSON_FIND_V (request, "dbpasswd", + build_common_header (response, ERR_PARAM_MISSING, "dbpasswd")); + dbpasswd = request["dbpasswd"].asString (); + + JSON_FIND_V (request, "classname", + build_common_header (response, ERR_PARAM_MISSING, "classname")); + classname = request["classname"].asString (); + + JSON_FIND_V (request, "import_filename", + build_common_header (response, ERR_PARAM_MISSING, + "Parameter(import_filename) missing in the request")); + import_filename = request["import_filename"].asString (); + import_path = string (sco.dbmt_tmp_dir) + "/" + import_filename; + + fp = fopen (import_path.c_str (), "r"); + if (NULL == fp) + { + return build_common_header (response, ERR_GENERAL_ERROR, "failed to open import file!"); + } + + con_handle = + cci_connect ((char *) ip.c_str (), port, (char *) db_name.c_str (), + (char *) db_user.c_str (), (char *) dbpasswd.c_str ()); + if (con_handle < 0) + { + cci_get_err_msg (con_handle, error.err_msg, 1024); + fclose (fp); + return build_common_header (response, con_handle, error.err_msg); + } + + while (fgets (buf, 1024, fp)) + { + ut_trim (buf); + stmt = + "insert into \"" + classname + "\" values (" + _build_quotes (buf, ',') + string (")"); + _execute_stmt (con_handle, stmt.c_str (), 0, 1, 0, result, time_out); + if (result["status"].asInt () != CCI_ER_NO_ERROR) + { + response["result"].append (stmt + " error"); + fail++; + } + else + { + success++; + } + + } + + fclose (fp); + response["fail_cnt"] = fail; + response["success_cnt"] = success; + cci_end_tran (con_handle, CCI_TRAN_COMMIT, &error); + cci_disconnect (con_handle, &error); + build_common_header (response, ERR_NO_ERROR, "none"); + return ERR_NO_ERROR; +} + +int +http_arniadb_importdb (Json::Value &request, Json::Value &response) +{ + int import_type, result = ERR_NO_ERROR; + string ip, db_name, db_user, dbpasswd; + string import_path, stmt; + + import_type = request.get ("import_type", DUMP_TYPE_SQL).asInt (); + switch (import_type) + { + case DUMP_TYPE_SQL: + result = _import_class_sql (request, response); + break; + case DUMP_TYPE_CSV: + result = _import_class_csv (request, response); + break; + default: + break; + } + return result; +} + +int +http_arniadb_sql (Json::Value &request, Json::Value &response) +{ + int con_handle, port, fetch_size, fetch_offset, dump_plan, time_out; + unsigned int i; + int return_err = 0, err_continue = 0; + int autocommit = 1; + string ip, db_name, db_user, dbpasswd; + Json::Value result; + T_CCI_ERROR error; + + ip = request.get ("bip", "localhost").asString (); + port = request.get ("bport", sco.iAMS_port).asInt (); + err_continue = request.get ("error_continue", 0).asInt (); + fetch_size = request.get ("fetch_size", 5000).asInt (); + fetch_offset = request.get ("fetch_offset", 1).asInt (); + dump_plan = request.get ("dump_plan", 0).asInt (); + time_out = request.get ("time_out", 120).asInt (); + autocommit = request.get ("autocommit", 1).asInt (); + + JSON_FIND_V (request, "dbname", + build_common_header (response, ERR_PARAM_MISSING, "dbname")); + db_name = request["dbname"].asString (); + + JSON_FIND_V (request, "dbid", + build_common_header (response, ERR_PARAM_MISSING, "dbid")); + db_user = request["dbid"].asString (); + + JSON_FIND_V (request, "dbpasswd", + build_common_header (response, ERR_PARAM_MISSING, "dbpasswd")); + dbpasswd = request["dbpasswd"].asString (); + + con_handle = + cci_connect ((char *) ip.c_str (), port, (char *) db_name.c_str (), + (char *) db_user.c_str (), (char *) dbpasswd.c_str ()); + if (con_handle < 0) + { + cci_get_err_msg (con_handle, error.err_msg, 1024); + return build_common_header (response, con_handle, error.err_msg); + } + + cci_set_autocommit (con_handle, (CCI_AUTOCOMMIT_MODE) autocommit); + + if (Json::Value::null != request["charset"]) + { + cci_set_charset (con_handle, (char *) request["charset"].asString ().c_str ()); + } + + JSON_FIND_V (request, "stmt", + build_common_header (response, ERR_PARAM_MISSING, "stmt")); + for (i = 0; i < request["stmt"].size (); i++) + { + result.clear (); + + if (_execute_stmt (con_handle, request["stmt"][i].asString ().c_str (), fetch_size, + fetch_offset, dump_plan, result, time_out) < 0 + && 0 == err_continue) + { + return_err = 1; + response["result"].append (result); + break; + } + + response["result"].append (result); + } + + cci_end_tran (con_handle, CCI_TRAN_COMMIT, &error); + cci_disconnect (con_handle, &error); + build_common_header (response, ERR_NO_ERROR, "none"); + return ERR_NO_ERROR; +} + +int +arn_cci_request_handler (Json::Value &request, Json::Value &response) +{ + int res; + int elapsed_msec = 0; + struct timeval task_begin, task_end; + string task_name; + T_HTTP_TASK_FUNC task_func = NULL; + + JSON_FIND_V (request, "task", + build_common_header (response, ERR_PARAM_MISSING, "task")); + task_name = request["task"].asString (); + + /* record the start time of running arn_manager task. */ + gettimeofday (&task_begin, NULL); + + get_cci_task_info (task_name.c_str (), &task_func); + if (task_func) + { + try + { + res = (*task_func) (request, response); + } + catch (exception &e) + { + res = build_common_header (response, ERR_REQUEST_FORMAT, e.what ()); + } + } + else + { + res = build_common_header (response, ERR_UNDEFINED_TASK, task_name.c_str ()); + } + + /* record the end time of running arn_manager task. */ + gettimeofday (&task_end, NULL); + + /* caculate the running time of arn_manager task. */ + _ut_timeval_diff (&task_begin, &task_end, &elapsed_msec); + response["__EXEC_TIME"] = elapsed_msec; + + return res; +} diff --git a/server/src/am_cci_interface.h b/server/src/am_cci_interface.h new file mode 100644 index 0000000..5bb3a6d --- /dev/null +++ b/server/src/am_cci_interface.h @@ -0,0 +1,53 @@ +/* + * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. + * + * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifndef __CM_CCI_H__ +#define __CM_CII_H__ +#include + +typedef int (*T_HTTP_TASK_FUNC) (Json::Value &request, + Json::Value &response); + +typedef struct +{ + const char *task_str; + int task_code; + T_HTTP_TASK_FUNC task_func; +} T_HTTP_TASK_INFO; + +typedef union tagUNI_CCI_A_TYPE +{ + char *str; + int i; + short s; + float f; + double d; +} UNI_CCI_A_TYPE; + +#define JSON_FIND_V(root, key, err) \ + if (Json::Value::null == root[key]) \ + return err; + +int http_arniadb_exportdb (Json::Value &request, Json::Value &response); +int http_arniadb_importdb (Json::Value &request, Json::Value &response); +int http_arniadb_sql (Json::Value &request, Json::Value &response); +int get_cci_task_info (const char *task, T_HTTP_TASK_FUNC *task_func); +int arn_cci_request_handler (Json::Value &request, Json::Value &response); + +#endif diff --git a/server/src/am_cmd.cpp b/server/src/am_cmd.cpp new file mode 100644 index 0000000..1c3cfb5 --- /dev/null +++ b/server/src/am_cmd.cpp @@ -0,0 +1,83 @@ +/* + * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. + * + * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + + +/* + * cm_cmd.cpp - + */ + +#include + +#if defined(WINDOWS) +#include +#include +#include +#else +#include +#include +#endif + +#include "cm_config.h" +#include "cm_cmd_task.h" +#include "cm_cmd_util.h" + +static void _print_help (void); + +int +main (int argc, char *argv[]) +{ + int retval = 0; + + if (argc < 2) + { + retval = 0; + goto print_help_msg; + } + + sys_config_init (); + if (uReadEnvVariables (argv[0]) < 0) + { + return -1; + } + + retval = run_task (argv[1], (argc - 1), (const char **) (&argv[1])); + + if (retval == E_CMD_NOT_EXIST) + { + retval = -1; + goto print_help_msg; + } + + return 0; + +print_help_msg: + _print_help (); + return retval; +} + +static void +_print_help (void) +{ + const char *title_pattern = + "amserver utility, version R%s\nusage: %s [args]\n"; + printf (title_pattern, CM_ADMIN_VERSION, CM_ADMIN_NAME); + print_cmd (); + + return; +} diff --git a/server/src/am_cmd_exec.cpp b/server/src/am_cmd_exec.cpp new file mode 100644 index 0000000..eceaa7f --- /dev/null +++ b/server/src/am_cmd_exec.cpp @@ -0,0 +1,1406 @@ +/* + * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. + * + * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + + +/* + * cm_cmd_exec.cpp - + */ + +#include +#include +#include +#include +#include + +#if defined(WINDOWS) +#include +#else +#include +#include +#endif + +#include "cm_config.h" +#include "cm_cmd_exec.h" +#include "cm_server_util.h" +#include "cm_stat.h" +#include "cm_autojob.h" +#include "cm_log.h" + +#ifdef _DEBUG_ +#include "deb.h" +#endif + +#define new_servstat_result() (T_SERVER_STATUS_RESULT*) new_cmd_result() +#define new_asql_result() (T_ASQL_RESULT*) new_cmd_result() + +static T_CMD_RESULT *new_cmd_result (void); +static const char *get_arniadb_mode_opt (T_ARNIADB_MODE mode); +static void read_server_status_output (T_SERVER_STATUS_RESULT *res, + char *out_file); +static void read_spacedb_output (GeneralSpacedbResult *res, char *out_file); + +static int read_start_server_output (char *stdout_log_file, + char *stderr_log_file, + char *_dbmt_error); + +static int _size_to_byte_by_unit (double orgin_num, char unit); + +char * +arniadb_cmd_name (char *buf) +{ + buf[0] = '\0'; +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (buf, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ARNIADB); +#else + sprintf (buf, "%s/%s", ARNIADB_BINDIR, UTIL_ARNIADB); +#endif + return buf; +} + +T_ASQL_RESULT * +cmd_asql (char *dbname, char *uid, char *passwd, T_ARNIADB_MODE mode, + char *infile, char *command, char *error_continue) +{ + char arniadb_err_file[PATH_MAX]; + char out_file[512]; + T_ASQL_RESULT *res; + char cmd_name[ARNIADB_CMD_NAME_LEN]; + const char *argv[15]; + int argc = 0; + + cmd_name[0] = '\0'; + arniadb_err_file[0] = '\0'; +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ASQL_NAME); +#else + sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_ASQL_NAME); +#endif + argv[argc++] = cmd_name; + argv[argc++] = get_arniadb_mode_opt (mode); + if (uid) + { + argv[argc++] = "--" ASQL_USER_L; + argv[argc++] = uid; + + if (passwd) + { + argv[argc++] = "--" ASQL_PASSWORD_L; + argv[argc++] = passwd; + } + } + if (infile) + { + argv[argc++] = "--" ASQL_INPUT_FILE_L; + argv[argc++] = infile; + } + else if (command) + { + argv[argc++] = "--" ASQL_COMMAND_L; + argv[argc++] = command; + } + else + { + return NULL; + } + + if (uStringEqualIgnoreCase (error_continue, "y")) + { + argv[argc++] = "--" ASQL_ERROR_CONTINUE_L; + } + + argv[argc++] = dbname; + argv[argc++] = NULL; + +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (out_file, "%s/tmp/DBMT_util_003.%d", sco.szArniadb, + (int) getpid ()); +#else + sprintf (out_file, "%s/DBMT_util_003.%d", ARNIADB_TMPDIR, (int) getpid ()); +#endif + snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", + sco.dbmt_tmp_dir, "cmd_asql", getpid ()); + SET_TRANSACTION_NO_WAIT_MODE_ENV (); + + run_child (argv, 1, NULL, NULL, out_file, NULL); /* asql */ + + res = new_asql_result (); + if (res == NULL) + { + return NULL; + } + + read_error_file (out_file, res->err_msg, ERR_MSG_SIZE); + + unlink (out_file); + return res; +} + +void find_and_parse_arn_admin_version (int &major_version, int &minor_version) +{ + const char *argv[3]; + char tmpfile[PATH_MAX], strbuf[BUFFER_MAX_LEN]; + FILE *infile; + char cmd_name[ARNIADB_CMD_NAME_LEN]; + + arniadb_cmd_name (cmd_name); + snprintf (tmpfile, PATH_MAX - 1, "%s/arn_admin_version", sco.dbmt_tmp_dir); + argv[0] = cmd_name; + argv[1] = "--version"; + argv[2] = NULL; + + run_child (argv, 1, NULL, tmpfile, NULL, NULL); + if ((infile = fopen (tmpfile, "r")) != NULL) + { + if (!fgets (strbuf, sizeof (strbuf), infile) || ! fgets (strbuf, sizeof (strbuf), infile)) + { + LOG_ERROR ("Spacedb is skipped due to temporarily insufficient resources"); + major_version = minor_version = -1; + return; + } + char version[10]; + sscanf (strbuf, "%*s %s", version); + + char *p = strtok (version, "."); + major_version = atoi (p); + p = strtok (NULL, "."); + minor_version = atoi (p); + + fclose (infile); + unlink (tmpfile); + } + else + { + major_version = minor_version = -1; + } +} + +GeneralSpacedbResult * +cmd_spacedb (const char *dbname, T_ARNIADB_MODE mode) +{ + GeneralSpacedbResult *res = NULL; + int minor_version, major_version; + char out_file[PATH_MAX]; + char arniadb_err_file[PATH_MAX]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; + char err_message[ERR_MSG_SIZE]; + const char *argv[10]; + int argc = 0; + arniadb_err_file[0] = '\0'; + + if (IS_INVALID_ARNIADB_VERS_MAJOR (arniadb_version_major)) + { + LOG_ERROR ("Invalid ARNIADB Engine Version: %d.%d", arniadb_version_major, arniadb_version_minor); + find_and_parse_arn_admin_version (major_version, minor_version); + arniadb_version_major = major_version; + arniadb_version_minor = minor_version; + } + + if (arniadb_version_major < 10 || (arniadb_version_minor == 10 && arniadb_version_minor == 0)) + { + res = new SpaceDbResultOldFormat(); + } + else + { + res = new SpaceDbResultNewFormat(); + } + + sprintf (out_file, "%s/DBMT_util_002.%d", sco.dbmt_tmp_dir, + (int) getpid ()); + arniadb_cmd_name (cmd_name); + argv[argc++] = cmd_name; + argv[argc++] = UTIL_OPTION_SPACEDB; + argv[argc++] = get_arniadb_mode_opt (mode); + argv[argc++] = "--" SPACE_SIZE_UNIT_L; + argv[argc++] = "PAGE"; + argv[argc++] = "--" SPACE_OUTPUT_FILE_L; + argv[argc++] = out_file; + argv[argc++] = dbname; + argv[argc++] = "-p"; + argv[argc++] = NULL; + + snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", + sco.dbmt_tmp_dir, "cmd_spacedb", getpid ()); + run_child (argv, 1, NULL, NULL, arniadb_err_file, NULL); /* spacedb */ + read_error_file (arniadb_err_file, err_message, ERR_MSG_SIZE); + res->set_err_msg (err_message); + read_spacedb_output (res, out_file); + if (access (arniadb_err_file, F_OK) == 0) + { + unlink (arniadb_err_file); + } + unlink (out_file); + return res; +} + + +int +cmd_start_server (char *dbname, char *err_buf, int err_buf_size) +{ + char stdout_log_file[512]; + char stderr_log_file[512]; + int pid; + int ret_val; + char cmd_name[ARNIADB_CMD_NAME_LEN]; + const char *argv[5]; + +#ifdef HPUX + char jvm_env_string[32]; +#endif + + cmd_start_master (); + sprintf (stdout_log_file, "%s/amserverstart.%d.err", sco.dbmt_tmp_dir, + (int) getpid ()); + sprintf (stderr_log_file, "%s/amserverstart2.%d.err", sco.dbmt_tmp_dir, + (int) getpid ()); + + + /* unset ARNIADB_ERROR_LOG environment variable, using default value */ +#if defined(WINDOWS) + _putenv ("ARNIADB_ERROR_LOG="); +#else + unsetenv ("ARNIADB_ERROR_LOG"); +#endif + + cmd_name[0] = '\0'; +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ARNIADB); +#else + sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_ARNIADB); +#endif + + argv[0] = cmd_name; + argv[1] = PRINT_CMD_SERVER; + argv[2] = PRINT_CMD_START; + argv[3] = dbname; + argv[4] = NULL; + +#ifdef HPUX +#ifdef HPUX_IA64 + strcpy (jvm_env_string, "LD_PRELOAD=libjvm.so"); +#else /* pa-risc */ + strcpy (jvm_env_string, "LD_PRELOAD=libjvm.sl"); +#endif + putenv (jvm_env_string); +#endif + + pid = run_child (argv, 1, NULL, stdout_log_file, stderr_log_file, NULL); /* start server */ + +#ifdef HPUX + putenv ("LD_PRELOAD="); +#endif + + if (pid < 0) + { + if (err_buf) + { + sprintf (err_buf, "system error : %s %s %s %s", cmd_name, PRINT_CMD_SERVER, PRINT_CMD_START, dbname); + } + unlink (stdout_log_file); + unlink (stderr_log_file); + return -1; + } + + ret_val = + read_start_server_output (stdout_log_file, stderr_log_file, err_buf); + unlink (stdout_log_file); + unlink (stderr_log_file); + + return ret_val; +} + +int +cmd_stop_server (char *dbname, char *err_buf, int err_buf_size) +{ + char strbuf[1024]; + int t, timeout = 30, interval = 3; /* sec */ + char cmd_name[ARNIADB_CMD_NAME_LEN]; + const char *argv[5]; + + if (err_buf) + { + memset (err_buf, 0, err_buf_size); + } + + cmd_name[0] = '\0'; +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ARNIADB); +#else + sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_ARNIADB); +#endif + + argv[0] = cmd_name; + argv[1] = PRINT_CMD_SERVER; + argv[2] = PRINT_CMD_STOP; + argv[3] = dbname; + argv[4] = NULL; + if (run_child (argv, 1, NULL, NULL, NULL, NULL) < 0) + { + /* stop_server */ + if (err_buf) + { + sprintf (strbuf, "Command returned error : %s %s %s %s", cmd_name, + PRINT_CMD_SERVER, PRINT_CMD_STOP, dbname); + strncpy (err_buf, strbuf, err_buf_size - 1); + } + return -1; + } + + for (t = timeout; t > 0; t -= interval) + { + SLEEP_MILISEC (interval, 0); + if (!uIsDatabaseActive (dbname)) + { + return 0; + } + } + if (err_buf) + { + sprintf (strbuf, "%s server hasn't shut down after %d seconds", dbname, timeout); + strncpy (err_buf, strbuf, err_buf_size - 1); + } + return -1; +} + +void +cmd_start_master (void) +{ + int pid; + char cmd_name[ARNIADB_CMD_NAME_LEN]; + const char *argv[2]; + + cmd_name[0] = '\0'; +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (cmd_name, "%s/%s%s", sco.szArniadb, + ARNIADB_DIR_BIN, UTIL_MASTER_NAME); +#else + sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_MASTER_NAME); +#endif + argv[0] = cmd_name; + argv[1] = NULL; + + pid = run_child (argv, 0, NULL, NULL, NULL, NULL); /* arn_master */ + SLEEP_MILISEC (0, 500); +} + + +int +read_asql_error_file (char *err_file, char *err_buf, int err_buf_size) +{ + FILE *fp; + char buf[1024]; + int msg_size = 0; + + if (err_buf) + { + memset (err_buf, 0, err_buf_size); + } + + if (err_file == NULL || err_file[0] == '\0') + { + return 0; + } + + fp = fopen (err_file, "r"); + if (fp == NULL) + { + return 0; + } + + while (1) + { + memset (buf, 0, sizeof (buf)); + if (fgets (buf, sizeof (buf) - 1, fp) == NULL) + { + break; + } + + ut_trim (buf); + + if ((strncasecmp (buf, "ERROR", 5) == 0)) + { + if (err_buf != NULL) + { + snprintf (err_buf, err_buf_size - 1, "%s", buf + 6); + } + msg_size = (int) strlen (buf + 6); + break; + } + else if (strstr (buf, "*** ERROR") != NULL) + { + memset (buf, 0, sizeof (buf)); + if (fgets (buf, sizeof (buf) - 1, fp) == NULL) + { + break; + } + if (err_buf != NULL) + { + snprintf (err_buf, err_buf_size - 1, "%s", buf); + } + msg_size = (int) strlen (buf); + break; + } + } + + fclose (fp); + + return (msg_size > 0 ? -1 : 0); +} + +int +read_error_file (const char *err_file, char *err_buf, int err_buf_size) +{ + FILE *fp; + char buf[1024]; + int msg_size = 0; + char rm_prev_flag = 0; + char is_debug = 0; + size_t i; + + if (err_buf == NULL || err_file == NULL || err_file[0] == '\0' + || err_buf_size == 0) + { + return 0; + } + + memset (err_buf, 0, err_buf_size); + + fp = fopen (err_file, "r"); + if (fp == NULL) + { + return 0; + } + + while (1) + { + memset (buf, 0, sizeof (buf)); + if (fgets (buf, sizeof (buf) - 1, fp) == NULL) + { + break; + } + for (i = 0; i < sizeof (buf) - 2; i++) + { + if (buf[i] == '\0') + { + if (buf[i + 1] == '\0') + { + break; + } + + buf[i] = ' '; + } + } + ut_trim (buf); + if (buf[0] == '\0') + { + continue; + } + if (strncmp (buf, "---", 3) == 0 || + strncmp (buf, "***", 3) == 0 || + strncmp (buf, "<<<", 3) == 0 || strncmp (buf, "Time:", 5) == 0) + { + if (strstr (buf, "- DEBUG") != NULL) + { + is_debug = 1; + } + else + { + is_debug = 0; + rm_prev_flag = 1; + } + continue; + } + /* ignore all the debug information, until find new line start with "---"|"***"|"<<<"|"Time:". */ + if (is_debug != 0) + { + continue; + } + + if (rm_prev_flag != 0) + { + msg_size = 0; + } + strcat (buf, ""); + if ((err_buf_size - msg_size - 1) > 0) + { + strncpy (err_buf + msg_size, buf, err_buf_size - msg_size - 1); + } + else + { + break; + } + msg_size += (int) strlen (buf); + rm_prev_flag = 0; + } + err_buf[err_buf_size - 1] = '\0'; + fclose (fp); + return (msg_size > 0 ? -1 : 0); +} + +int +read_error_file2 (char *err_file, char *err_buf, int err_buf_size, + int *err_code) +{ + FILE *fp; + char buf[1024]; + int found = 0; + int success = 1; + + if (err_buf == NULL || err_file == NULL) + { + return 0; + } + + err_buf[0] = 0; + + fp = fopen (err_file, "r"); + if (fp == NULL) + { + *err_code = 0; + return 0; /* not found error file */ + } + + while (1) + { + char *p = NULL; + size_t len; + if (fgets (buf, sizeof (buf), fp) == NULL) + { + break; + } + + /* start with "ERROR: " */ + len = strlen (buf); + if (len > 7 && memcmp (buf, "ERROR: ", 7) == 0) + { + /* ignore a newline character if it exists */ + if (buf[len - 1] == '\n') + { + len--; + } + len -= 7; + + if (len >= (size_t) err_buf_size) + { + len = (size_t) err_buf_size - 1; + } + + memcpy (err_buf, buf + 7, len); + err_buf[len] = 0; + + success = 0; + continue; + } + + /* find "CODE = " */ + p = strstr (buf, "CODE = "); + if (p != NULL) + { + if (sscanf (p, "CODE = %d", err_code) != 1) + { + continue; + } + + success = 0; + found = 1; + + /* read error description */ + if (fgets (buf, sizeof (buf), fp) == NULL) + { + break; + } + + len = strlen (buf); + if (len > 0 && buf[len - 1] == '\n') + { + len--; + } + + if (len >= (size_t) err_buf_size) + { + len = (size_t) err_buf_size - 1; + } + + memcpy (err_buf, buf, len); + err_buf[len] = 0; + } + } + + fclose (fp); + + if (success != 0) + { + *err_code = 0; + return 0; + } + else if (found == 0) + { + *err_code = -1; + } + + return -1; +} + +static T_CMD_RESULT * +new_cmd_result (void) +{ + T_CMD_RESULT *res; + + res = (T_CMD_RESULT *) malloc (sizeof (T_CMD_RESULT)); + if (res == NULL) + { + return NULL; + } + memset (res, 0, sizeof (T_CMD_RESULT)); + return res; +} + +static const char * +get_arniadb_mode_opt (T_ARNIADB_MODE mode) +{ + if (mode == ARNIADB_MODE_SA) + { + return ("--" ASQL_SA_MODE_L); + } + + return ("--" ASQL_CS_MODE_L); +} + +static bool is_valid_database_description (char *str) +{ + if (strncmp (str, "PERMANENT", 9) != 0 && strncmp (str, "TEMPORARY", 9) != 0) + { + return false; + } + + return true; +} + +static bool is_valid_volume_description (char *str) +{ + if (strstr (str, "PERMANENT") == NULL && strstr (str, "TEMPORARY") == NULL) + { + return false; + } + + return true; +} + +static bool is_valid_file_description (char *str) +{ + if (strncmp (str, "INDEX", 5) != 0 && strncmp (str, "HEAP", 4) != 0 && + strncmp (str, "SYSTEM", 6) != 0 && strncmp (str, "TEMP", 4) != 0) + { + return false; + } + + return true; +} + +static void +read_spacedb_output (GeneralSpacedbResult *res, char *out_file) +{ + FILE *fp; + + fp = fopen (out_file, "r"); + if (fp == NULL) + { + return; + } + + res->read_spacedb_output (fp); +} + +static int +read_start_server_output (char *stdout_file, char *stderr_file, + char *_dbmt_error) +{ + FILE *fp, *fp2; + char buf[1024]; + char *strp; + int retval = 0; + + if (access (stdout_file, F_OK) == 0) + { + fp = fopen (stdout_file, "r"); + if (fp != NULL) + { + while (fgets (buf, sizeof (buf), fp) != NULL) + { + if (strncmp (buf, "++", 2) == 0) + { + if ((strp = strchr (buf, ':')) && strstr (strp, "fail")) + { + retval = -1; + break; + } + } + } + fclose (fp); + } + } + + if (access (stderr_file, F_OK) == 0) + { + fp2 = fopen (stderr_file, "r"); + if (fp2 != NULL) + { + int len = 0; + while (fgets (buf, sizeof (buf), fp2) != NULL) + { + ut_trim (buf); + len += (int) strlen (buf); + if (len < (DBMT_ERROR_MSG_SIZE - 1)) + { + strcpy (_dbmt_error, buf); + _dbmt_error += len; + } + else + { + strcpy_limit (_dbmt_error, buf, DBMT_ERROR_MSG_SIZE); + strcpy_limit (_dbmt_error + DBMT_ERROR_MSG_SIZE - 4, "...", 4); + break; + } + } + + if (len != 0 && retval != -1) + { + retval = 1; + } + fclose (fp2); + } + } + + return retval; +} + +static int +_size_to_byte_by_unit (double orgin_num, char unit) +{ + switch (unit) + { + case 'B': + case 'b': + break; + case 'K': + case 'k': + orgin_num *= BYTES_IN_K; + break; + case 'M': + case 'm': + orgin_num *= BYTES_IN_M; + break; + case 'G': + case 'g': + orgin_num *= BYTES_IN_G; + break; + default: + /* if none of the above occur, return -1 to indicate error. */ + orgin_num = -1; + break; + } + + return (int) (orgin_num); +} + +void SpaceDbResultNewFormat::add_volume (char *str_buf) +{ + char purpose[128], volume_name[PATH_MAX], type[32]; + struct stat statbuf; + + SpaceDbVolumeInfoNewFormat volume; + sscanf (str_buf, "%d %s %s DATA %d %d %d %s", &volume.volid, type, purpose, + &volume.used_size, + &volume.free_size, + &volume.total_size, + volume_name); + strcpy (volume.purpose, purpose); + strcpy (volume.type, type); + strcpy (volume.volume_name, volume_name); + + stat (volume_name, &statbuf); + volume.date = statbuf.st_mtime; + + volumes.push_back (volume); +} + +int SpaceDbResultOldFormat::get_volume_info (char *str_buf, SpaceDbVolumeInfoOldFormat &volume) +{ + int volid, total_page, free_page; + char purpose[COLUMN_VALUE_MAX_SIZE], vol_name[PATH_MAX]; + char *token = NULL, *p; + struct stat statbuf; + + volid = total_page = free_page = 0; + purpose[0] = vol_name[0] = '\0'; + + token = strtok (str_buf, " "); + if (token == NULL) + { + return FALSE; + } + volid = atoi (token); + + token = strtok (NULL, " "); + if (token == NULL) + { + return FALSE; + } + strcpy (purpose, token); + + if (strcmp (purpose, "GENERIC") != 0 && strcmp (purpose, "DATA") != 0 + && strcmp (purpose, "INDEX") != 0 && strcmp (purpose, "TEMP") != 0) + { + return FALSE; + } + + token = strtok (NULL, " "); + if (token == NULL) + { + return FALSE; + } + + if (strcmp (token, "TEMP") == 0) + { + if (strcmp (purpose, "TEMP") != 0) + { + return FALSE; + } + else + { + strcat (purpose, " "); + strcat (purpose, token); + } + + token = strtok (NULL, " "); + if (token == NULL) + { + return FALSE; + } + } + total_page = atoi (token); + + token = strtok (NULL, " "); + if (token == NULL) + { + return FALSE; + } + free_page = atoi (token); + + token = strtok (NULL, "\n"); + if (token == NULL) + { + return FALSE; + } + strcpy (vol_name, token + 1); + + volume.volid = volid; + volume.total_size = total_page; + volume.free_size = free_page; + strcpy (volume.purpose, purpose); + + stat (vol_name, &statbuf); + volume.date = statbuf.st_mtime; + +#if defined(WINDOWS) + unix_style_path (vol_name); +#endif + + p = strrchr (vol_name, '/'); + if (p == NULL) + { + volume.location[0] = '\0'; + volume.vol_name[0] = '\0'; + } + else + { + *p = '\0'; + snprintf (volume.location, sizeof (volume.location) - 1, "%s", vol_name); + snprintf (volume.vol_name, sizeof (volume.vol_name) - 1, "%s", p + 1); + *p = '/'; + } + + return TRUE; + +} + +void SpaceDbResultOldFormat::create_result (nvplist *res) +{ + nv_update_val_int (res, "pagesize", page_size); + nv_update_val_int (res, "logpagesize", log_page_size); + + for (int i = 0; i < volumes.size(); i++) + { + nv_add_nvp (res, "open", "spaceinfo"); + nv_add_nvp (res, "spacename", volumes[i].vol_name); + nv_add_nvp (res, "type", volumes[i].purpose); + nv_add_nvp (res, "location", volumes[i].location); + nv_add_nvp_int (res, "totalpage", volumes[i].total_size); + nv_add_nvp_int (res, "freepage", volumes[i].free_size); + ts_add_nvp_time (res, "date", volumes[i].date, "%04d%02d%02d", + NV_ADD_DATE); + nv_add_nvp (res, "close", "spaceinfo"); + } + + for (int i = 0; i < temporary_volumes.size(); i++) + { + nv_add_nvp (res, "open", "spaceinfo"); + nv_add_nvp (res, "spacename", temporary_volumes[i].vol_name); + nv_add_nvp (res, "type", temporary_volumes[i].purpose); + nv_add_nvp (res, "location", temporary_volumes[i].location); + nv_add_nvp_int (res, "totalpage", temporary_volumes[i].total_size); + nv_add_nvp_int (res, "freepage", temporary_volumes[i].free_size); + ts_add_nvp_time (res, "date", temporary_volumes[i].date, "%04d%02d%02d", + NV_ADD_DATE); + nv_add_nvp (res, "close", "spaceinfo"); + } +} + +void SpaceDbResultNewFormat::create_result (nvplist *res) +{ + nv_update_val_int (res, "pagesize", page_size); + nv_update_val_int (res, "logpagesize", log_page_size); + + for (int i = 0; i < DATABASE_DESCRIPTION_NUM_LINES; i++) + { + nv_add_nvp (res, "open", "dbinfo"); + nv_add_nvp (res, "type", databaseSpaceDescriptions[i].type); + nv_add_nvp (res, "purpose", databaseSpaceDescriptions[i].purpose); + nv_add_nvp_int (res, "volume_count", databaseSpaceDescriptions[i].volume_count); + nv_add_nvp_int (res, "used_size", databaseSpaceDescriptions[i].used_size); + nv_add_nvp_int (res, "free_size", databaseSpaceDescriptions[i].free_size); + nv_add_nvp_int (res, "total_size", databaseSpaceDescriptions[i].total_size); + nv_add_nvp (res, "close", "dbinfo"); + } + + for (int i = 0; i < volumes.size(); i++) + { + nv_add_nvp (res, "open", "spaceinfo"); + nv_add_nvp (res, "type", volumes[i].type); + nv_add_nvp (res, "purpose", volumes[i].purpose); + nv_add_nvp (res, "location", volumes[i].volume_name); + nv_add_nvp (res, "spacename", volumes[i].volume_name); + nv_add_nvp_int (res, "volid", volumes[i].volid); + nv_add_nvp_int (res, "usedpage", volumes[i].used_size); + nv_add_nvp_int (res, "freepage", volumes[i].free_size); + nv_add_nvp_int (res, "totalpage", volumes[i].total_size); + ts_add_nvp_time (res, "date", volumes[i].date, "%04d%02d%02d", + NV_ADD_DATE); + nv_add_nvp (res, "close", "spaceinfo"); + } + + for (int i = 0; i < FILES_DESCRIPTION_NUM_LINES; i++) + { + nv_add_nvp (res, "open", "fileinfo"); + nv_add_nvp (res, "data_type", fileSpaceDescriptions[i].data_type); + nv_add_nvp_int (res, "file_count", fileSpaceDescriptions[i].file_count); + nv_add_nvp_int (res, "used_size", fileSpaceDescriptions[i].used_size); + nv_add_nvp_int (res, "file_table_size", fileSpaceDescriptions[i].file_table_size); + nv_add_nvp_int (res, "reserved_size", fileSpaceDescriptions[i].reserved_size); + nv_add_nvp_int (res, "total_size", fileSpaceDescriptions[i].total_size); + nv_add_nvp (res, "close", "fileinfo"); + } +} + +int SpaceDbResultOldFormat::get_cnt_tpage() +{ + int cnt_tpage = 0, i; + + for (i = 0; i < volumes.size(); i++) + { + cnt_tpage += volumes[i].total_size; + } + for (i = 0; i < temporary_volumes.size(); i++) + { + cnt_tpage += temporary_volumes[i].total_size; + } + + return cnt_tpage; +} + +int SpaceDbResultNewFormat::get_cnt_tpage() +{ + int cnt_tpage = 0; + + for (int i = 0; i < volumes.size(); i++) + { + cnt_tpage += volumes[i].total_size; + } + + return cnt_tpage; +} + +time_t SpaceDbResultOldFormat::get_my_time (char *dbloca) +{ + char strbuf[BUFFER_MAX_LEN]; + char volname[PATH_MAX] = { '\0' }; + time_t mytime = time (NULL);; + struct stat statbuf; + + for (int i = 0; i < volumes.size(); i++) + { + if (uStringEqual (volumes[i].purpose, "DATA") + || uStringEqual (volumes[i].purpose, "INDEX")) + { + strcpy (volname, volumes[i].vol_name); + snprintf (strbuf, BUFFER_MAX_LEN, "%s/%s", dbloca, volname); + if (!stat (strbuf, &statbuf)) + { + mytime = statbuf.st_mtime; + } + } + } + + return mytime; +} + +time_t SpaceDbResultNewFormat::get_my_time (char *dbloca) +{ + char strbuf[BUFFER_MAX_LEN]; + char volname[PATH_MAX] = { '\0' }; + time_t mytime = time (NULL);; + struct stat statbuf; + + for (int i = 0; i < volumes.size(); i++) + { + if (uStringEqual (volumes[i].purpose, "PERMANENT")) + { + strcpy (volname, volumes[i].volume_name); + snprintf (strbuf, BUFFER_MAX_LEN, "%s/%s", dbloca, volname); + if (!stat (strbuf, &statbuf)) + { + mytime = statbuf.st_mtime; + } + } + } + + return mytime; +} + +void SpaceDbResultOldFormat::auto_add_volume (autoaddvoldb_node *curr, int db_mode, char *dbname_at_hostname) +{ + double frate; + int page_add = curr->data_ext_page; + if ((curr->data_vol) && (page_add > 0)) + { + frate = ajFreeSpace (this, "DATA"); + if (page_add < MIN_AUTO_ADDVOL_PAGE_SIZE) + { + page_add = MIN_AUTO_ADDVOL_PAGE_SIZE; + } + if (curr->data_warn_outofspace >= frate) + { + if (db_mode == HA_MODE) + { + append_host_to_dbname (dbname_at_hostname, curr->dbname, + sizeof (dbname_at_hostname)); + aj_add_volume (dbname_at_hostname, "data", page_add, page_size); + } + else + { + aj_add_volume (curr->dbname, "data", page_add, page_size); + } + } + } + + page_add = curr->index_ext_page; + if ((curr->index_vol) && (page_add > 0)) + { + frate = ajFreeSpace (this, "INDEX"); + if (page_add < MIN_AUTO_ADDVOL_PAGE_SIZE) + { + page_add = MIN_AUTO_ADDVOL_PAGE_SIZE; + } + if (curr->index_warn_outofspace >= frate) + { + if (db_mode == HA_MODE) + { + append_host_to_dbname (dbname_at_hostname, curr->dbname, + sizeof (dbname_at_hostname)); + aj_add_volume (dbname_at_hostname, "index", page_add, page_size); + } + else + { + aj_add_volume (curr->dbname, "index", page_add, page_size); + } + } + } +} + +void SpaceDbResultNewFormat::auto_add_volume (autoaddvoldb_node *curr, int db_mode, char *dbname_at_hostname) +{ + double frate; + int page_add = curr->data_ext_page; + if ((curr->data_vol) && (page_add > 0)) + { + frate = ajFreeSpace (this, "PERMANENT"); + if (page_add < MIN_AUTO_ADDVOL_PAGE_SIZE) + { + page_add = MIN_AUTO_ADDVOL_PAGE_SIZE; + } + if (curr->data_warn_outofspace >= frate) + { + if (db_mode == 2) + { + append_host_to_dbname (dbname_at_hostname, curr->dbname, + sizeof (dbname_at_hostname)); + aj_add_volume (dbname_at_hostname, "data", page_add, page_size); + } + else + { + aj_add_volume (curr->dbname, "data", page_add, page_size); + } + } + } +} + +void SpaceDbResultOldFormat::read_spacedb_output (FILE *fp) +{ + char str_buf[1024]; + int db_page_size = 0, log_page_size = 0; + + while (fgets (str_buf, sizeof (str_buf), fp)) + { + char *tmp_p; + + ut_trim (str_buf); + + if (strncmp (str_buf, "Space", 5) == 0) + { + int matchs = 0; + double page_size = 0.0; + char page_unit = 'H'; + + /* + * The log format looks like the following: + * Space description for database 'demodb' with pagesize 16.0K. (log pagesize: 16.0K) + */ + tmp_p = strstr (str_buf, "pagesize"); + if (tmp_p == NULL) + { + goto spacedb_error; + } + + if ((matchs = + sscanf (tmp_p, "pagesize %lf%c", &page_size, &page_unit)) != 2) + { + goto spacedb_error; + } + + if ((db_page_size = + _size_to_byte_by_unit (page_size, page_unit)) < 0) + { + goto spacedb_error; + } + + tmp_p = strstr (str_buf, "log pagesize:"); + if (tmp_p != NULL) + { + if ((matchs = + sscanf (tmp_p, "log pagesize: %lf%c", &page_size, + &page_unit)) != 2) + { + goto spacedb_error; + } + + if ((log_page_size = + _size_to_byte_by_unit (page_size, page_unit)) < 0) + { + goto spacedb_error; + } + } + else + { + /* log pagesize default value */ + log_page_size = 4096; + } + } + + else if (strncmp (str_buf, "Volid", 5) == 0) + { + break; + } + } + + while (fgets (str_buf, sizeof (str_buf), fp)) + { + ut_trim (str_buf); + if (str_buf[0] == '\0' || str_buf[0] == '-') + { + continue; + } + if (strncmp (str_buf, "Volid", 5) == 0) + { + break; + } + + if (strncmp (str_buf, "Space", 5) == 0) + { + continue; + } + + if (add_volume (str_buf)) + { + continue; + } + } + + while (fgets (str_buf, sizeof (str_buf), fp)) + { + ut_trim (str_buf); + if (str_buf[0] == '\0' || str_buf[0] == '-') + { + continue; + } + if (strncmp (str_buf, "Volid", 5) == 0) + { + break; + } + + if (add_temporary_volume (str_buf)) + { + continue; + } + } + set_page_size (db_page_size); + set_log_page_size (log_page_size); + + fclose (fp); + return; + +spacedb_error: + fclose (fp); +} + +void SpaceDbResultNewFormat::read_spacedb_output (FILE *fp) +{ + char page_unit, log_page_unit, *p; + double page_size, log_page_size_double; + char str_buf[1024]; + int db_page_size = 0, log_page_size = 0; + int index = 0; + + while (fgets (str_buf, sizeof (str_buf), fp)) + { + ut_trim (str_buf); + + if (strncmp (str_buf, "Space", 5) == 0) + { + p = strstr (str_buf, "pagesize"); + if (p) + { + sscanf (p, "pagesize %lf%c", &page_size, &page_unit); + if ((db_page_size = + _size_to_byte_by_unit (page_size, page_unit)) < 0) + { + goto spacedb_error; + } + set_page_size (db_page_size); + } + p = strstr (str_buf, "log pagesize:"); + if (p) + { + sscanf (p, "log pagesize: %lf%c", &log_page_size_double, &log_page_unit); + if ((log_page_size = + _size_to_byte_by_unit (log_page_size_double, log_page_unit)) < 0) + { + goto spacedb_error; + } + set_log_page_size (log_page_size); + } + } + if (strncmp (str_buf, "type", 4) == 0) + { + break; + } + } + + while (fgets (str_buf, sizeof (str_buf), fp)) + { + ut_trim (str_buf); + + if (strncmp (str_buf, "Space", 5) == 0) + { + break; + } + if (!is_valid_database_description (str_buf)) + { + break; + } + sscanf (str_buf, "%s %s DATA %d %d %d %d", databaseSpaceDescriptions[index].type, + databaseSpaceDescriptions[index].purpose, &databaseSpaceDescriptions[index].volume_count, + &databaseSpaceDescriptions[index].used_size, + &databaseSpaceDescriptions[index].free_size, + &databaseSpaceDescriptions[index].total_size); + index++; + } + + while (fgets (str_buf, sizeof (str_buf), fp)) + { + ut_trim (str_buf); + + if (strncmp (str_buf, "Detailed", 8) == 0) + { + break; + } + + if (!is_valid_volume_description (str_buf)) + { + continue; + } + + add_volume (str_buf); + } + + while (fgets (str_buf, sizeof (str_buf), fp)) + { + ut_trim (str_buf); + + if (strncmp (str_buf, "data_type", 9) == 0) + { + break; + } + } + + index = 0; + + while (fgets (str_buf, sizeof (str_buf), fp)) + { + ut_trim (str_buf); + + if (!is_valid_file_description (str_buf)) + { + continue; + } + + sscanf (str_buf, "%s %d %d %d %d %d\n", fileSpaceDescriptions[index].data_type, + &fileSpaceDescriptions[index].file_count, + &fileSpaceDescriptions[index].used_size, + &fileSpaceDescriptions[index].file_table_size, + &fileSpaceDescriptions[index].reserved_size, + &fileSpaceDescriptions[index].total_size); + index++; + } + + fclose (fp); + return; + +spacedb_error: + fclose (fp); +} + diff --git a/server/src/am_cmd_exec.h b/server/src/am_cmd_exec.h new file mode 100644 index 0000000..54ed878 --- /dev/null +++ b/server/src/am_cmd_exec.h @@ -0,0 +1,279 @@ +/* + * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. + * + * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + + +/* + * cm_cmd_exec.h - + */ + +#ifndef _CM_COMMAND_EXECUTE_H_ +#define _CM_COMMAND_EXECUTE_H_ + +#include + +#include "cm_dep.h" + +#if defined(WINDOWS) +#define DBMT_EXE_EXT ".exe" +#else +#define DBMT_EXE_EXT "" +#endif + +#define cmd_servstat_result_free(RESULT) cmd_result_free(RESULT) +#define cmd_asql_result_free(RESULT) cmd_result_free(RESULT) + +#define ERR_MSG_SIZE 1024 +#define COLUMN_VALUE_MAX_SIZE 32 +#define DATABASE_DESCRIPTION_NUM_LINES 3 +#define FILES_DESCRIPTION_NUM_LINES 4 +#define BUFFER_MAX_LEN 128 + +#if !defined (DO_NOT_USE_ARNIADBENV) +#define ARNIADB_ERROR_LOG_DIR "log/server" +#define ARNIADB_BROKER_LOG_DIR "log/broker" +#else +#define ARNIADB_ERROR_LOG_DIR ARNIADB_LOGDIR "/server" +#define ARNIADB_BROKER_LOG_DIR ARNIADB_LOGDIR"/broker" +#endif + +#define ARNIADB_DATABASE_TXT "databases.txt" +#define ARNIADB_ARNIADB_CONF "arniadb.conf" +#define ARNIADB_DBMT_CONF "cm.conf" +#define ARNIADB_BROKER_CONF "arniadb_broker.conf" +#define ARNIADB_HA_CONF "arniadb_ha.conf" +#define ARNIADB_UNLOAD_EXT_INDEX "_indexes" +#define ARNIADB_UNLOAD_EXT_TRIGGER "_trigger" +#define ARNIADB_UNLOAD_EXT_OBJ "_objects" +#define ARNIADB_UNLOAD_EXT_SCHEMA "_schema" +#define ARNIADB_SERVER_LOCK_EXT "_lgat__lock" +#define ARNIADB_ACT_LOG_EXT "_lgat" +#define ARNIADB_ARC_LOG_EXT "_lgar" +#define ARNIADB_BACKUP_INFO_EXT "_bkvinf" +#define ARNIADB_ARC_LOG_EXT_LEN strlen(ARNIADB_ARC_LOG_EXT) + +#define ARNIADB_CMD_NAME_LEN 128 + +#if !defined (DO_NOT_USE_ARNIADBENV) +#if defined(WINDOWS) +#define ARNIADB_DIR_BIN "bin\\" +#else +#define ARNIADB_DIR_BIN "bin/" +#endif +#endif + +#include +#include "cm_autojob.h" + +typedef enum +{ + ARNIADB_MODE_CS = 0, + ARNIADB_MODE_SA = 1 +} T_ARNIADB_MODE; + +struct SpaceDbVolumeInfoOldFormat +{ + int volid; + int total_size; + int free_size; + int data_size; + int index_size; + char purpose[COLUMN_VALUE_MAX_SIZE]; + char location[PATH_MAX]; + char vol_name[PATH_MAX]; + time_t date; +}; + +struct SpaceDbVolumeInfoNewFormat +{ + int volid; + int used_size; + int free_size; + int total_size; + char type[COLUMN_VALUE_MAX_SIZE]; + char purpose[COLUMN_VALUE_MAX_SIZE]; + char volume_name[PATH_MAX]; + time_t date; +}; + +struct DatabaseSpaceDescription +{ + char type[COLUMN_VALUE_MAX_SIZE]; + char purpose[COLUMN_VALUE_MAX_SIZE]; + int volume_count; + int used_size; + int free_size; + int total_size; +}; + +struct FileSpaceDescription +{ + char data_type[COLUMN_VALUE_MAX_SIZE]; + int file_count; + int used_size; + int file_table_size; + int reserved_size; + int total_size; +}; + +class GeneralSpacedbResult +{ + protected: + int page_size; + int log_page_size; + char err_msg[ERR_MSG_SIZE]; + public: + GeneralSpacedbResult() + { + page_size = 0; + log_page_size = 0; + err_msg[0] = '\0'; + } + GeneralSpacedbResult (int page_size, int log_page_size) + { + this->page_size = page_size; + this->log_page_size = log_page_size; + err_msg[0] = '\0'; + } + int get_page_size() + { + return page_size; + } + int get_log_page_size() + { + return log_page_size; + } + void set_page_size (int page_size) + { + this->page_size = page_size; + } + void set_log_page_size (int log_page_size) + { + this->log_page_size = log_page_size; + } + const char *get_err_msg() + { + return err_msg; + } + void set_err_msg (char *str) + { + strncpy (err_msg, str, ERR_MSG_SIZE); + } + bool has_error() + { + return err_msg[0] != '\0'; + } + virtual void create_result (nvplist *res) = 0; + virtual int get_cnt_tpage() = 0; + virtual void get_total_and_free_page (const char *type, double &free_page, double &total_page) = 0; + virtual time_t get_my_time (char *dbloca) = 0; + virtual void auto_add_volume (autoaddvoldb_node *current, int db_mode, char *dbname) = 0; + virtual void read_spacedb_output (FILE *fp) = 0; + virtual ~GeneralSpacedbResult() {} +}; + +class SpaceDbResultNewFormat : public GeneralSpacedbResult +{ + public: + SpaceDbResultNewFormat() {} + void add_volume (char *); + int get_cnt_tpage(); + void get_total_and_free_page (const char *type, double &free_page, double &total_page) + { + for (unsigned int i = 0; i < volumes.size(); i++) + { + if (strcmp (volumes[i].purpose, type) == 0) + { + total_page += volumes[i].total_size; + free_page += volumes[i].free_size; + } + } + } + time_t get_my_time (char *dbloca); + void auto_add_volume (autoaddvoldb_node *current, int db_mode, char *dbname); + void read_spacedb_output (FILE *fp); + void create_result (nvplist *res); + + DatabaseSpaceDescription databaseSpaceDescriptions[DATABASE_DESCRIPTION_NUM_LINES]; + FileSpaceDescription fileSpaceDescriptions[FILES_DESCRIPTION_NUM_LINES]; + private: + std::vector volumes; +}; + +class SpaceDbResultOldFormat : public GeneralSpacedbResult +{ + public: + SpaceDbResultOldFormat() {} + int get_volume_info (char *, SpaceDbVolumeInfoOldFormat &); + int add_volume (char *str_buf) + { + SpaceDbVolumeInfoOldFormat volume; + int rc = get_volume_info (str_buf, volume); + if (rc == TRUE) + { + volumes.push_back (volume); + } + return rc; + } + + int add_temporary_volume (char *str_buf) + { + SpaceDbVolumeInfoOldFormat volume; + int rc = get_volume_info (str_buf, volume); + if (rc == TRUE) + { + temporary_volumes.push_back (volume); + } + return rc; + } + + void create_result (nvplist *); + void get_total_and_free_page (const char *type, double &free_page, double &total_page) + { + for (unsigned int i = 0; i < volumes.size(); i++) + { + if (strcmp (volumes[i].purpose, type) == 0) + { + total_page += volumes[i].total_size; + free_page += volumes[i].free_size; + } + } + } + int get_cnt_tpage(); + time_t get_my_time (char *dbloca); + void auto_add_volume (autoaddvoldb_node *current, int db_mode, char *dbname); + void read_spacedb_output (FILE *); + private: + std::vector volumes; + std::vector temporary_volumes; +}; + +typedef T_CMD_RESULT T_ASQL_RESULT; + +GeneralSpacedbResult *cmd_spacedb (const char *dbname, T_ARNIADB_MODE mode); +T_ASQL_RESULT *cmd_asql (char *dbname, char *uid, char *passwd, + T_ARNIADB_MODE mode, char *infile, char *command, char *error_continue); +int cmd_start_server (char *dbname, char *err_buf, int err_buf_size); +int cmd_stop_server (char *dbname, char *err_buf, int err_buf_size); +void cmd_start_master (void); +char *arniadb_cmd_name (char *buf); +int read_error_file (const char *err_file, char *err_buf, int err_buf_size); +int read_error_file2 (char *err_file, char *err_buf, int err_buf_size, int *err_code); +int read_asql_error_file (char *err_file, char *err_buf, int err_buf_size); + +#endif /* _CM_COMMAND_EXECUTE_H_ */ diff --git a/server/src/am_cmd_task.cpp b/server/src/am_cmd_task.cpp new file mode 100644 index 0000000..1508a81 --- /dev/null +++ b/server/src/am_cmd_task.cpp @@ -0,0 +1,1490 @@ +/* + * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. + * + * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + + +/* + * cm_cmd_task.cpp - + */ + +#include +#include +#include +#include + +#if defined(WINDOWS) +#include +#include +#include +#include +#include "cm_win_wsa.h" +#else +#include +#include +#include +#include +#include +#include +#include +#endif + +#include "cm_dep.h" +#include "cm_text_encryption.h" +#include "cm_server_util.h" +#include "cm_user.h" +#include "cm_cmd_task.h" +#include "cm_cmd_util.h" +#include "cm_config.h" + +static struct option adddbinfo_opt[] = +{ + {ARG_AUTH, 1, 0, 'a'}, + {ARG_UID, 1, 0, 'u'}, + {ARG_HOST, 1, 0, 'h'}, + {ARG_PORT, 1, 0, 'p'}, + {0, 0, 0, 0} +}; + +static struct option adduser_opt[] = +{ + {ARG_UNICAS, 1, 0, 'b'}, + {ARG_DBCREATE, 1, 0, 'c'}, + {ARG_MONITOR, 1, 0, 'm'}, + {ARG_DB_INFO, 1, 0, 'd'}, + {0, 0, 0, 0} +}; + +static struct option chguserpwd_opt[] = +{ + {ARG_NEW_PASS, 1, 0, 'n'}, + {ARG_OLD_PASS, 1, 0, 'o'}, + {ARG_ADMIN_PASS, 1, 0, ADMIN_FLAG}, + {0, 0, 0, 0} +}; + +static struct option chguserauth_opt[] = +{ + {ARG_UNICAS, 1, 0, 'b'}, + {ARG_DBCREATE, 1, 0, 'c'}, + {ARG_MONITOR, 1, 0, 'm'}, + {0, 0, 0, 0} +}; + +static struct option chgdbinfo_opt[] = +{ + {ARG_AUTH, 1, 0, 'a'}, + {ARG_UID, 1, 0, 'u'}, + {ARG_HOST, 1, 0, 'h'}, + {ARG_PORT, 1, 0, 'p'}, + {0, 0, 0, 0} +}; + +static const char *auth_list[] = +{ + "none", + "admin", + "monitor", + NULL +}; + +static const char *createdb_auth_list[] = +{ + "none", + "admin", + NULL +}; + +static int _get_dbmt_user_index (T_DBMT_USER *dbmt_user, const char *username); +static T_DBMT_USER *_dbmt_user_get (char *error_msg); +static void _dbmt_user_free (T_DBMT_USER *dbmt_user); +static void _errmsg_output (int cmd_id, const char *error_msg); +static void _print_dbmtuser_info (T_DBMT_USER_INFO *dbmtuser_info); +static int _add_dbinfo_to_dbinfo_array (const char *dbinfo_str, + T_DBMT_USER_DBINFO **dbmt_dbinfo, + int *num_db, char *error_msg); +static int _check_str_in_list (const char *str, const char *str_list[]); +static int _check_dbmt_user_passwd (T_DBMT_USER *dbmt_user, + const char *username, const char *passwd, + char *error_msg); + +static int +_get_cmd_nvplist (nvplist *arg_list, const char *argv[], int argc, + struct option opt[], const char *need_arg_list[], + char *error_msg); + +static int +_get_longname_by_shortname (struct option opt[], int shortname, + char *longname, int buflen); + +static int +_set_nvplist_by_arglist (nvplist *arg_list, const char *argnamearray[], + const char *argvalarray[]); + +static int +_dbmtuser_auth_arg_check (const char *unicas_auth, const char *dbcreate_auth, + const char *monitor_auth, char *error_msg); +static int _get_localhost_ip (char *ipaddr, int ipaddr_len); + + +/* *************************************** + * + * Command Task Interface + * + * ***************************************/ + +int +cmd_listdb (int argc, const char *in_argv[]) +{ + int i = 0; + int cmd_id = CMD_LISTDB; + char *tok[2]; + char buf[LINE_MAX]; + char db_txt_path[PATH_MAX]; + + FILE *fp = NULL; + + snprintf (db_txt_path, sizeof (db_txt_path) - 1, "%s/%s", + sco.szArniadb_databases, ARNIADB_DATABASE_TXT); + + if ((fp = fopen (db_txt_path, "r")) == NULL) + { + _errmsg_output (cmd_id, "The databases.txt file does not exist.\n"); + return E_FAILURE; + } + + while (fgets (buf, sizeof (buf), fp)) + { + ut_trim (buf); + + if (buf[0] == '#') + { + continue; + } + + if (string_tokenize (buf, tok, 2) < 0) + { + continue; + } + + printf (" %d. %s\n", ++i, ut_trim (tok[0])); + } + + fclose (fp); + + return E_SUCCESS; +} + +int +cmd_deluser (int argc, const char *in_argv[]) +{ + int retval = E_SUCCESS; + int cmd_id = CMD_DELUSER; + int dbmt_user_index = -1; + char error_msg[DBMT_ERROR_MSG_SIZE]; + char dbmt_user_name[DBMT_USER_NAME_LEN]; + T_DBMT_USER *dbmt_user = NULL; + + if (argc == 1) + { + print_help_msg (cmd_id); + return E_SUCCESS; + } + + if (argc != 2) + { + strcpy_limit (error_msg, get_msg_by_id (PTN_ARG_NUM_ERR), + DBMT_ERROR_MSG_SIZE); + retval = E_ARG_ERR; + goto error_clean_return; + } + + if ((dbmt_user = _dbmt_user_get (error_msg)) == NULL) + { + retval = E_FAILURE; + goto error_clean_return; + } + + strcpy_limit (dbmt_user_name, in_argv[1], sizeof (dbmt_user_name)); + + if (uStringEqual (DBMT_USER_ADMIN_NAME, dbmt_user_name)) + { + snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, + get_msg_by_id (PTN_DBMT_USER_NOT_DEL), DBMT_USER_ADMIN_NAME); + retval = E_FAILURE; + goto error_clean_return; + } + + dbmt_user_index = _get_dbmt_user_index (dbmt_user, dbmt_user_name); + + if (dbmt_user_index < 0) + { + snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, + get_msg_by_id (PTN_DBMT_USER_NOT_EXIST), dbmt_user_name); + retval = E_FAILURE; + goto error_clean_return; + } + + dbmt_user->user_info[dbmt_user_index].user_name[0] = '\0'; + + if (dbmt_user_write_auth (dbmt_user, error_msg) != ERR_NO_ERROR) + { + retval = E_FAILURE; + goto error_clean_return; + } + + retval = E_SUCCESS; + goto clean_return; + +error_clean_return: + _errmsg_output (cmd_id, error_msg); + if (retval == E_ARG_ERR) + { + print_help_msg (cmd_id); + } + +clean_return: + _dbmt_user_free (dbmt_user); + return retval; +} + +int +cmd_adduser (int argc, const char *in_argv[]) +{ + int i; + int num_dbmt_user; + int num_db = 0; + int retval = E_SUCCESS; + int cmd_id = CMD_ADDUSER; + char dbmt_pass[PASSWD_ENC_LENGTH]; + char error_msg[DBMT_ERROR_MSG_SIZE] = { '\0' }; + T_DBMT_USER *dbmt_user; + T_DBMT_USER_AUTHINFO *auth_info = NULL; + T_DBMT_USER_DBINFO *db_info = NULL; + + const char *username, *userpass, *unicas, *dbcreate, *monitor, *tmp; + const char *need_arg_list[] = + { + ARG_DBMT_USER_NAME, + ARG_DBMT_USER_PWD, + NULL + }; + + nvplist *arg_list; + + if (argc == 1) + { + print_help_msg (cmd_id); + return E_SUCCESS; + } + + arg_list = nv_create (5, NULL, "\n", ":", "\n"); + if ((retval = + _get_cmd_nvplist (arg_list, in_argv, argc, adduser_opt, + need_arg_list, error_msg)) != E_SUCCESS) + { + goto error_return; + } + + tmp = nv_get_val (arg_list, ARG_UNICAS); + unicas = (tmp == NULL ? "none" : tmp); + + tmp = nv_get_val (arg_list, ARG_DBCREATE); + dbcreate = (tmp == NULL ? "none" : tmp); + + tmp = nv_get_val (arg_list, ARG_MONITOR); + monitor = (tmp == NULL ? "none" : tmp); + + username = nv_get_val (arg_list, ARG_DBMT_USER_NAME); + userpass = nv_get_val (arg_list, ARG_DBMT_USER_PWD); + + if ((retval = + _dbmtuser_auth_arg_check (unicas, dbcreate, monitor, error_msg)) != E_SUCCESS) + { + goto error_return; + } + + for (i = 0; i < arg_list->nvplist_leng; i++) + { + char *n, *v; + nv_lookup (arg_list, i, &n, &v); + if (n != NULL && (uStringEqual (n, ARG_DB_INFO))) + { + if ((_add_dbinfo_to_dbinfo_array (v, &db_info, + &num_db, error_msg)) != E_SUCCESS) + { + retval = E_ARG_ERR; + goto error_return; + } + } + } + + if ((dbmt_user = _dbmt_user_get (error_msg)) == NULL) + { + retval = E_FAILURE; + goto error_return; + } + + if (_get_dbmt_user_index (dbmt_user, username) >= 0) + { + snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, + get_msg_by_id (PTN_DBMT_USER_EXIST), username); + retval = E_FAILURE; + goto error_clean_return; + } + + /* set dbmt user auth info. */ + if ((auth_info = + (T_DBMT_USER_AUTHINFO *) malloc (AUTH_NUM_TOTAL * sizeof (T_DBMT_USER_AUTHINFO))) == NULL) + { + goto error_mem_alloc_return; + } + + dbmt_user_set_authinfo (&auth_info[0], "unicas", unicas); + dbmt_user_set_authinfo (&auth_info[1], "dbcreate", dbcreate); + dbmt_user_set_authinfo (&auth_info[2], "statusmonitorauth", monitor); + + /* encrypt the password. */ + uEncrypt (PASSWD_LENGTH, userpass, dbmt_pass); + + num_dbmt_user = dbmt_user->num_dbmt_user; + + /* set dbmt user info struct. */ + dbmt_user->user_info = + (T_DBMT_USER_INFO *) increase_capacity (dbmt_user->user_info, sizeof (T_DBMT_USER_INFO), + num_dbmt_user, num_dbmt_user + 1); + + if (dbmt_user->user_info == NULL) + { + goto error_mem_alloc_return; + } + + dbmt_user_set_userinfo (& (dbmt_user->user_info[num_dbmt_user]), + (char *) username, (char *) dbmt_pass, + AUTH_NUM_TOTAL, auth_info, num_db, db_info); + dbmt_user->num_dbmt_user++; + + /* update the cmdbpass & cm.pass conf file. */ + if (dbmt_user_write_pass (dbmt_user, error_msg) != ERR_NO_ERROR) + { + retval = E_FAILURE; + goto error_clean_return; + } + + if (dbmt_user_write_auth (dbmt_user, error_msg) != ERR_NO_ERROR) + { + retval = E_FAILURE; + goto error_clean_return; + } + + _dbmt_user_free (dbmt_user); + nv_destroy (arg_list); + + return E_SUCCESS; + +error_mem_alloc_return: + retval = E_FAILURE; + strcpy_limit (error_msg, get_msg_by_id (PTN_MEM_ALLOC_ERR), DBMT_ERROR_MSG_SIZE); + +error_clean_return: + _dbmt_user_free (dbmt_user); + +error_return: + nv_destroy (arg_list); + _errmsg_output (cmd_id, error_msg); + if (db_info) + { + free (db_info); + } + if (auth_info) + { + free (auth_info); + } + if (retval == E_ARG_ERR) + { + print_help_msg (cmd_id); + } + + return retval; +} + +int +cmd_viewuser (int argc, const char *in_argv[]) +{ + int i; + int retval = E_SUCCESS; + int cmd_id = CMD_VIEWUSER; + char error_msg[DBMT_ERROR_MSG_SIZE] = { '\0' }; + T_DBMT_USER *dbmt_user = NULL; + + if ((dbmt_user = _dbmt_user_get (error_msg)) == NULL) + { + retval = E_FAILURE; + goto error_return; + } + + if (argc == 1) + { + /* show all the dbmtuser info. */ + for (i = 0; i < dbmt_user->num_dbmt_user; i++) + { + _print_dbmtuser_info (&dbmt_user->user_info[i]); + } + } + else if (argc == 2) + { + int index = -1; + /* user specified a dbmtuser name. */ + index = _get_dbmt_user_index (dbmt_user, (char *) in_argv[1]); + + if (index < 0) + { + snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, + get_msg_by_id (PTN_DBMT_USER_NOT_EXIST), in_argv[1]); + retval = E_FAILURE; + goto error_return; + } + + _print_dbmtuser_info (&dbmt_user->user_info[index]); + } + else + { + snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, + get_msg_by_id (PTN_ARG_NUM_ERR)); + retval = E_ARG_ERR; + goto error_return; + } + + goto clean_return; + +error_return: + _errmsg_output (cmd_id, error_msg); + if (retval == E_ARG_ERR) + { + print_help_msg (cmd_id); + } + +clean_return: + _dbmt_user_free (dbmt_user); + return retval; +} + +int +cmd_chguser_pwd (int argc, const char *in_argv[]) +{ + int retval = E_SUCCESS; + int dbmt_user_index = -1; + int cmd_id = CMD_CHGUSER_PWD; + char pwd_tmp[PASSWD_ENC_LENGTH]; + char error_msg[DBMT_ERROR_MSG_SIZE]; + const char *dbmtusername, *oldpass, *newpass, *adminpass; + T_DBMT_USER *dbmt_user = NULL; + + nvplist *arg_list = NULL; + const char *need_arg_list[] = + { + ARG_DBMT_USER_NAME, + NULL + }; + + arg_list = nv_create (5, NULL, "\n", ":", "\n"); + + if (argc == 1) + { + print_help_msg (cmd_id); + return E_SUCCESS; + } + + if ((retval = + _get_cmd_nvplist (arg_list, in_argv, argc, chguserpwd_opt, need_arg_list, error_msg)) != E_SUCCESS) + { + goto error_clean_return; + } + + dbmtusername = nv_get_val (arg_list, ARG_DBMT_USER_NAME); + oldpass = nv_get_val (arg_list, ARG_OLD_PASS); + newpass = nv_get_val (arg_list, ARG_NEW_PASS); + adminpass = nv_get_val (arg_list, ARG_ADMIN_PASS); + + /* get dbmt user. */ + if ((dbmt_user = _dbmt_user_get (error_msg)) == NULL) + { + retval = E_FAILURE; + goto error_clean_return; + } + + if ((dbmt_user_index = _get_dbmt_user_index (dbmt_user, dbmtusername)) < 0) + { + snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, + get_msg_by_id (PTN_DBMT_USER_NOT_EXIST), dbmtusername); + retval = E_FAILURE; + goto error_clean_return; + } + + if (oldpass != NULL) + { + /* check old password. */ + if (_check_dbmt_user_passwd + (dbmt_user, dbmtusername, oldpass, error_msg) < 0) + { + retval = E_FAILURE; + goto error_clean_return; + } + } + else if (adminpass != NULL) + { + /* check admin password. */ + if (_check_dbmt_user_passwd + (dbmt_user, DBMT_USER_ADMIN_NAME, adminpass, error_msg) < 0) + { + retval = E_FAILURE; + goto error_clean_return; + } + } + else + { + snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, + get_msg_by_id (PTN_ARG_MUST_APPEAR_ERR), + ARG_OLD_PASS ", " ARG_ADMIN_PASS); + retval = E_FAILURE; + goto error_clean_return; + } + + /* reset the new password. */ + uEncrypt (PASSWD_LENGTH, newpass, pwd_tmp); + strcpy_limit (dbmt_user->user_info[dbmt_user_index].user_passwd, pwd_tmp, + PASSWD_ENC_LENGTH); + + if (dbmt_user_write_pass (dbmt_user, error_msg) != ERR_NO_ERROR) + { + retval = E_FAILURE; + goto error_clean_return; + } + + nv_destroy (arg_list); + _dbmt_user_free (dbmt_user); + return E_SUCCESS; + +error_clean_return: + nv_destroy (arg_list); + _dbmt_user_free (dbmt_user); + _errmsg_output (cmd_id, error_msg); + + if (retval == E_ARG_ERR) + { + print_help_msg (cmd_id); + } + + return retval; +} + +int +cmd_chguser_auth (int argc, const char *in_argv[]) +{ + int i = 0; + int retval = E_SUCCESS; + int dbmt_user_index = -1; + int cmd_id = CMD_CHGUSER_AUTH; + char error_msg[DBMT_ERROR_MSG_SIZE]; + const char *unicas, *dbcreate, *monitor, *username; + T_DBMT_USER *dbmt_user = NULL; + T_DBMT_USER_INFO *dbmt_user_info_t = NULL; + + nvplist *arg_list = NULL; + const char *need_arg_list[] = + { + ARG_DBMT_USER_NAME, + NULL + }; + + arg_list = nv_create (5, NULL, "\n", ":", "\n"); + + if (argc == 1) + { + print_help_msg (cmd_id); + return E_SUCCESS; + } + + if ((retval = + _get_cmd_nvplist (arg_list, in_argv, argc, chguserauth_opt, need_arg_list, error_msg)) != E_SUCCESS) + { + goto error_clean_return; + } + + unicas = nv_get_val (arg_list, ARG_UNICAS); + dbcreate = nv_get_val (arg_list, ARG_DBCREATE); + monitor = nv_get_val (arg_list, ARG_MONITOR); + username = nv_get_val (arg_list, ARG_DBMT_USER_NAME); + + if ((retval = + _dbmtuser_auth_arg_check (unicas, dbcreate, monitor, error_msg)) != E_SUCCESS) + { + goto error_clean_return; + } + + if (unicas == NULL && dbcreate == NULL && monitor == NULL) + { + snprintf (error_msg, sizeof (error_msg) - 1, + get_msg_by_id (PTN_ARG_MUST_APPEAR_ERR), + ARG_UNICAS ", " ARG_DBCREATE ", " ARG_MONITOR); + retval = E_ARG_ERR; + goto error_clean_return; + } + + /* get dbmt user. */ + if ((dbmt_user = _dbmt_user_get (error_msg)) == NULL) + { + _errmsg_output (cmd_id, error_msg); + return E_FAILURE; + } + + if ((dbmt_user_index = _get_dbmt_user_index (dbmt_user, username)) < 0) + { + snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, + get_msg_by_id (PTN_DBMT_USER_NOT_EXIST), username); + retval = E_FAILURE; + goto error_clean_return; + } + + dbmt_user_info_t = & (dbmt_user->user_info[dbmt_user_index]); + + for (i = 0; i < dbmt_user_info_t->num_authinfo; i++) + { + T_DBMT_USER_AUTHINFO *auth_t; + + auth_t = & (dbmt_user_info_t->authinfo[i]); + + if (uStringEqual (auth_t->domain, "unicas") && unicas != NULL) + { + strcpy_limit (auth_t->auth, unicas, sizeof (auth_t->auth)); + } + else if (uStringEqual (auth_t->domain, "dbcreate") && dbcreate != NULL) + { + strcpy_limit (auth_t->auth, dbcreate, sizeof (auth_t->auth)); + } + else if (uStringEqual (auth_t->domain, "statusmonitorauth") + && monitor != NULL) + { + strcpy_limit (auth_t->auth, monitor, sizeof (auth_t->auth)); + } + } + + if (dbmt_user_write_auth (dbmt_user, error_msg) != ERR_NO_ERROR) + { + retval = E_FAILURE; + goto error_clean_return; + } + + nv_destroy (arg_list); + _dbmt_user_free (dbmt_user); + return E_SUCCESS; + +error_clean_return: + nv_destroy (arg_list); + _dbmt_user_free (dbmt_user); + _errmsg_output (cmd_id, error_msg); + + if (retval == E_ARG_ERR) + { + print_help_msg (cmd_id); + } + + return retval; +} + +int +cmd_adddbinfo (int argc, const char *in_argv[]) +{ + int i; + int num_db; + int dbmt_user_index; + int retval = E_SUCCESS; + int cmd_id = CMD_ADDDBINFO; + char error_msg[DBMT_ERROR_MSG_SIZE]; + char local_ip[64]; + char broker_addr[BROKER_ADDR_LEN]; + const char *username, *dbname, *auth, *uid, *host, *port, *tmp; + int flag = 0; + char *n, *v; + int dbexist = 0; + + T_DBMT_USER *dbmt_user = NULL; + T_DBMT_USER_INFO *t_info = NULL; + + nvplist *arg_list = NULL; + nvplist *db_list = NULL; + const char *need_arg_list[] = + { + ARG_DBMT_USER_NAME, + ARG_DB_NAME, + NULL + }; + + local_ip[0] = '\0'; + + if (argc == 1) + { + print_help_msg (cmd_id); + return E_SUCCESS; + } + + if (_get_localhost_ip (local_ip, sizeof (local_ip)) != 0) + { + snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, + "failed to get localhost ip"); + retval = E_FAILURE; + goto error_clean_return; + } + + arg_list = nv_create (5, NULL, "\n", ":", "\n"); + db_list = nv_create (5, NULL, "\n", ":", "\n"); + + if ((retval = + _get_cmd_nvplist (arg_list, in_argv, argc, adddbinfo_opt, need_arg_list, error_msg)) != E_SUCCESS) + { + goto error_clean_return; + } + + /* set default value of auth, uid, host & port. */ + tmp = nv_get_val (arg_list, ARG_AUTH); + auth = ((tmp == NULL) ? "admin" : tmp); + + tmp = nv_get_val (arg_list, ARG_UID); + uid = ((tmp == NULL) ? "dba" : tmp); + + tmp = nv_get_val (arg_list, ARG_HOST); + host = ((tmp == NULL) ? local_ip : tmp); + + tmp = nv_get_val (arg_list, ARG_PORT); + port = ((tmp == NULL) ? "30000" : tmp); + + username = nv_get_val (arg_list, ARG_DBMT_USER_NAME); + dbname = nv_get_val (arg_list, ARG_DB_NAME); + + /* does this database exist in database.txt? */ + + if (ut_get_dblist (db_list, 0) != ERR_NO_ERROR) + { + snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, + "failed to get database lists."); + retval = E_FAILURE; + goto error_clean_return; + } + for (i = 0; i < db_list->nvplist_leng; i++) + { + nv_lookup (db_list, i, &n, &v); + if (n == NULL || v == NULL) + { + snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, "malformed database lists."); + retval = E_FAILURE; + goto error_clean_return; + } + + if (!strcmp (n, "open") && !strcmp (v, "dblist")) + { + flag = 1; + } + else if (!strcmp (n, "close") && !strcmp (v, "dblist")) + { + flag = 0; + break; + } + else if (flag == 1) + { + if (!strcmp (n, "dbname") && !strcmp (v, dbname)) + { + dbexist = 1; + } + } /* close "else if (flag == 1)" */ + } + if (!dbexist) + { + snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, + get_msg_by_id (PTN_DB_NOT_EXIST), dbname); + retval = E_FAILURE; + goto error_clean_return; + } + + if ((dbmt_user = _dbmt_user_get (error_msg)) == NULL) + { + _errmsg_output (cmd_id, error_msg); + return E_FAILURE; + } + + if ((dbmt_user_index = _get_dbmt_user_index (dbmt_user, username)) < 0) + { + snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, + get_msg_by_id (PTN_DBMT_USER_NOT_EXIST), username); + retval = E_FAILURE; + goto error_clean_return; + } + + snprintf (broker_addr, sizeof (broker_addr), "%s,%s", host, port); + + t_info = & (dbmt_user->user_info[dbmt_user_index]); + + /* check whether this user has been authorized to this DB. */ + if (dbmt_user_search (t_info, dbname) >= 0) + { + snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, + get_msg_by_id (PTN_DB_ALREADY_AUTH), dbname, username); + retval = E_FAILURE; + goto error_clean_return; + } + + num_db = t_info->num_dbinfo; + t_info->dbinfo = (T_DBMT_USER_DBINFO *) increase_capacity (t_info->dbinfo, + sizeof (T_DBMT_USER_DBINFO), + num_db, num_db + 1); + if (t_info->dbinfo == NULL) + { + strcpy_limit (error_msg, get_msg_by_id (PTN_MEM_ALLOC_ERR), DBMT_ERROR_MSG_SIZE); + retval = E_FAILURE; + goto error_clean_return; + } + + /* add dbinfo to dbmt user. */ + dbmt_user_set_dbinfo (& (t_info->dbinfo[num_db]), dbname, auth, uid, broker_addr); + + t_info->num_dbinfo++; + + if (dbmt_user_write_auth (dbmt_user, error_msg) != ERR_NO_ERROR) + { + retval = E_FAILURE; + goto error_clean_return; + } + + retval = E_SUCCESS; + goto memory_clean_return; + +error_clean_return: + _errmsg_output (cmd_id, error_msg); + + if (retval == E_ARG_ERR) + { + print_help_msg (cmd_id); + } + +memory_clean_return: + if (db_list) + { + nv_destroy (db_list); + } + if (arg_list) + { + nv_destroy (arg_list); + } + if (dbmt_user) + { + _dbmt_user_free (dbmt_user); + } + return retval; +} + +int +cmd_deldbinfo (int argc, const char *in_argv[]) +{ + int db_index; + int dbmt_user_index; + int retval = E_SUCCESS; + int cmd_id = CMD_DELDBINFO; + char dbname[DBNAME_LEN]; + char error_msg[DBMT_ERROR_MSG_SIZE]; + char dbmt_user_name[DBMT_USER_NAME_LEN]; + + T_DBMT_USER *dbmt_user = NULL; + + if (argc == 1) + { + print_help_msg (cmd_id); + return E_SUCCESS; + } + + if (argc != 3) + { + snprintf (error_msg, DBMT_USER_NAME_LEN - 1, get_msg_by_id (PTN_ARG_NUM_ERR)); + retval = E_ARG_ERR; + goto error_clean_return; + } + + if ((dbmt_user = _dbmt_user_get (error_msg)) == NULL) + { + retval = E_FAILURE; + goto error_clean_return; + } + + strcpy_limit (dbmt_user_name, in_argv[1], sizeof (dbmt_user_name)); + strcpy_limit (dbname, in_argv[2], sizeof (dbname)); + + dbmt_user_index = _get_dbmt_user_index (dbmt_user, dbmt_user_name); + if (dbmt_user_index < 0) + { + snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, + get_msg_by_id (PTN_DBMT_USER_NOT_EXIST), dbmt_user_name); + + retval = E_FAILURE; + goto error_clean_return; + } + + if ((db_index = + dbmt_user_search (&dbmt_user->user_info[dbmt_user_index], dbname)) < 0) + { + snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, + get_msg_by_id (PTN_DB_NOT_AUTH), dbname, dbmt_user_name); + retval = E_FAILURE; + goto error_clean_return; + } + + dbmt_user->user_info[dbmt_user_index].dbinfo[db_index].dbname[0] = '\0'; + + if (dbmt_user_write_auth (dbmt_user, error_msg) != ERR_NO_ERROR) + { + retval = E_FAILURE; + goto error_clean_return; + } + + retval = E_SUCCESS; + goto clean_return; + +error_clean_return: + _errmsg_output (cmd_id, error_msg); + + if (retval == E_ARG_ERR) + { + print_help_msg (cmd_id); + } + +clean_return: + _dbmt_user_free (dbmt_user); + return retval; +} + +int +cmd_chgdbinfo (int argc, const char *in_argv[]) +{ + int dbinfo_index; + int dbmt_user_index; + int retval = E_SUCCESS; + int cmd_id = CMD_CHGDBINFO; + char *broker_tok[2]; + char broker_addr[BROKER_ADDR_LEN]; + char broker_addr_t[BROKER_ADDR_LEN]; + char error_msg[DBMT_ERROR_MSG_SIZE]; + char *auth, *uid, *host, *port, *username, *dbname; + const char *need_arg_list[] = + { + ARG_DBMT_USER_NAME, + ARG_DB_NAME, + NULL + }; + + T_DBMT_USER *dbmt_user = NULL; + T_DBMT_USER_INFO *userinfo_t = NULL; + T_DBMT_USER_DBINFO *dbinfo_t = NULL; + + nvplist *arg_list = NULL; + + arg_list = nv_create (5, NULL, "\n", ":", "\n"); + + if (argc == 1) + { + print_help_msg (cmd_id); + return E_SUCCESS; + } + + if ((retval = + _get_cmd_nvplist (arg_list, in_argv, argc, chgdbinfo_opt,need_arg_list, error_msg)) != E_SUCCESS) + { + goto error_clean_return; + } + + auth = nv_get_val (arg_list, ARG_AUTH); + uid = nv_get_val (arg_list, ARG_UID); + host = nv_get_val (arg_list, ARG_HOST); + port = nv_get_val (arg_list, ARG_PORT); + username = nv_get_val (arg_list, ARG_DBMT_USER_NAME); + dbname = nv_get_val (arg_list, ARG_DB_NAME); + + if ((dbmt_user = _dbmt_user_get (error_msg)) == NULL) + { + _errmsg_output (cmd_id, error_msg); + return E_FAILURE; + } + + if ((dbmt_user_index = _get_dbmt_user_index (dbmt_user, username)) < 0) + { + snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, + get_msg_by_id (PTN_DBMT_USER_NOT_EXIST), username); + retval = E_FAILURE; + goto error_clean_return; + } + + userinfo_t = & (dbmt_user->user_info[dbmt_user_index]); + + if ((dbinfo_index = dbmt_user_search (userinfo_t, dbname)) < 0) + { + snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, + get_msg_by_id (PTN_DB_NOT_EXIST), dbname, username); + retval = E_FAILURE; + goto error_clean_return; + } + + dbinfo_t = & (userinfo_t->dbinfo[dbinfo_index]); + + strcpy_limit (broker_addr_t, dbinfo_t->broker_address, + sizeof (broker_addr_t)); + if (string_tokenize2 (broker_addr_t, broker_tok, 2, ',') < 0) + { + snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, + get_msg_by_id (PTN_BROKER_ADDR_ERR), dbinfo_t->broker_address); + retval = E_FAILURE; + goto error_clean_return; + } + + snprintf (broker_addr, sizeof (broker_addr) - 1, "%s,%s", + ((host == NULL) ? broker_tok[0] : host), + ((port == NULL) ? broker_tok[1] : port)); + + strcpy_limit (dbinfo_t->broker_address, broker_addr, + sizeof (dbinfo_t->broker_address)); + + if (auth != NULL) + { + strcpy_limit (dbinfo_t->auth, auth, sizeof (dbinfo_t->auth)); + } + + if (uid != NULL) + { + strcpy_limit (dbinfo_t->uid, uid, sizeof (dbinfo_t->uid)); + } + + if (dbmt_user_write_auth (dbmt_user, error_msg) != ERR_NO_ERROR) + { + retval = E_FAILURE; + goto error_clean_return; + } + + retval = E_SUCCESS; + goto memory_clean_return; + +error_clean_return: + _errmsg_output (cmd_id, error_msg); + + if (retval == E_ARG_ERR) + { + print_help_msg (cmd_id); + } + +memory_clean_return: + nv_destroy (arg_list); + _dbmt_user_free (dbmt_user); + return retval; +} + +/* *************************************** + * + * Command Task Tools + * + * ***************************************/ + +static int +_check_dbmt_user_passwd (T_DBMT_USER *dbmt_user, const char *username, + const char *passwd, char *error_msg) +{ + int dbmt_user_index = -1; + char pwd_tmp[PASSWD_ENC_LENGTH]; + T_DBMT_USER_INFO *dbmt_user_info_t = NULL; + + /* check admin password. */ + if ((dbmt_user_index = _get_dbmt_user_index (dbmt_user, username)) < 0) + { + snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, + get_msg_by_id (PTN_DBMT_USER_NOT_EXIST), username); + return -1; + } + + dbmt_user_info_t = & (dbmt_user->user_info[dbmt_user_index]); + uDecrypt (PASSWD_LENGTH, dbmt_user_info_t->user_passwd, pwd_tmp); + + if (!uStringEqual (pwd_tmp, passwd)) + { + snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, + get_msg_by_id (PTN_DBMT_USER_PWD_ERR), passwd); + return -1; + } + + return 0; +} + +static T_DBMT_USER * +_dbmt_user_get (char *error_msg) +{ + T_DBMT_USER *dbmt_user = NULL; + + if ((dbmt_user = (T_DBMT_USER *) malloc (sizeof (T_DBMT_USER))) == NULL) + { + return NULL; + } + + if (dbmt_user_read (dbmt_user, error_msg) < 0) + { + return NULL; + } + + return dbmt_user; +} + +static void +_dbmt_user_free (T_DBMT_USER *dbmt_user) +{ + if (dbmt_user != NULL) + { + dbmt_user_free (dbmt_user); + } + + free (dbmt_user); + return; +} + +static int +_get_dbmt_user_index (T_DBMT_USER *dbmt_user, const char *username) +{ + int i; + + for (i = 0; i < dbmt_user->num_dbmt_user; i++) + { + if (uStringEqual (username, dbmt_user->user_info[i].user_name)) + { + return i; + } + } + + return -1; +} + +static void +_errmsg_output (int cmd_id, const char *error_msg) +{ + char cmd_name[OPT_STR_LEN]; + + if (get_cmdname_by_id (cmd_id, cmd_name, sizeof (cmd_name)) < 0) + { + fprintf (stderr, "ERROR: Command id (%d) is not exist.\n", cmd_id); + return; + } + + fprintf (stderr, "ERROR: %s: %s\n", cmd_name, error_msg); + return; +} + +static int +_get_cmd_nvplist (nvplist *arg_list, const char *argv[], int argc, + struct option opt[], const char *need_arg_list[], + char *error_msg) +{ + int retval = E_SUCCESS; + int i, need_arg_num; + char opt_str[OPT_STR_LEN]; + char *l_opt_arg; + + for (i = 0; need_arg_list[i] != NULL; i++) + ; + need_arg_num = i; + if (0 == need_arg_num) + { + return E_ARG_ERR; + } + utility_make_getopt_optstring (opt, opt_str); + + while (1) + { + int opt_key = 0; + int opt_index = 0; + char longname[OPT_STR_LEN]; + + opt_key = + getopt_long (argc, (char **const) argv, opt_str, opt, &opt_index); + + /* end of args */ + if (opt_key == -1) + { + break; + } + if (_get_longname_by_shortname + (opt, opt_key, longname, sizeof (longname)) < 0) + { + return E_ARG_ERR; + } + l_opt_arg = optarg; + + nv_add_nvp (arg_list, longname, l_opt_arg); + } + + if (argc - optind == need_arg_num) + { + _set_nvplist_by_arglist (arg_list, need_arg_list, & (argv[optind])); + } + else if (argc - optind < need_arg_num) + { + snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, + get_msg_by_id (PTN_ARG_MISS), need_arg_list[need_arg_num - 1]); + retval = E_ARG_ERR; + } + else + { + snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, + get_msg_by_id (PTN_ARG_MORE), argv[optind + 1]); + retval = E_ARG_ERR; + } + + return retval; +} + +static int +_get_longname_by_shortname (struct option opt[], int shortname, + char *longname, int buflen) +{ + int i; + + for (i = 0; opt[i].val != 0; i++) + { + if (shortname == opt[i].val) + { + strcpy_limit (longname, opt[i].name, buflen); + return 0; + } + } + + return -1; +} + +static int +_set_nvplist_by_arglist (nvplist *arg_list, const char *argnamelist[], + const char *argvalarray[]) +{ + int i; + + for (i = 0; argnamelist[i] != NULL; i++) + { + nv_add_nvp (arg_list, argnamelist[i], argvalarray[i]); + } + + return 0; +} + +/* the str_list should be end with NULL. */ +static int +_check_str_in_list (const char *str, const char *str_list[]) +{ + int i; + + if (str == NULL) + { + return -1; + } + + for (i = 0; str_list[i] != NULL; i++) + { + if (uStringEqual (str, str_list[i])) + { + return i; + } + } + + return -1; +} + +static int +_add_dbinfo_to_dbinfo_array (const char *dbinfo_str, + T_DBMT_USER_DBINFO **dbmt_dbinfo, int *num_db, + char *error_msg) +{ + char *tok[3]; + char str_t[1024]; + char *broker_tok[3]; + char broker_str[BROKER_ADDR_LEN]; + int i; + + strcpy_limit (str_t, dbinfo_str, sizeof (str_t)); + + if (string_tokenize2 (str_t, tok, 3, ';') < 0) + { + snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, get_msg_by_id (PTN_ARG_FORMAT_ERR), str_t); + return E_FAILURE; + } + + /* check broker ip & broker port. */ + if (string_tokenize2 (tok[2], broker_tok, 2, ',') < 0) + { + snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, get_msg_by_id (PTN_BROKER_ADDR_ERR), tok[2]); + return E_FAILURE; + } + + if ((*num_db) > 0) + { + for (i = 0; i < (*num_db); i++) + { + if (uStringEqual (tok[0], (*dbmt_dbinfo)[i].dbname)) + { + snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, get_msg_by_id (PTN_DB_ADD_TWICE), tok[0]); + return E_FAILURE; + } + } + } + + snprintf (broker_str, sizeof (broker_str) - 1, "%s,%s", ut_trim (broker_tok[0]), ut_trim (broker_tok[1])); + + *dbmt_dbinfo = (T_DBMT_USER_DBINFO *) increase_capacity (*dbmt_dbinfo, + sizeof (T_DBMT_USER_DBINFO), + (*num_db), (*num_db) + 1); + + if (*dbmt_dbinfo == NULL) + { + snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, get_msg_by_id (PTN_MEM_ALLOC_ERR)); + return E_FAILURE; + } + + dbmt_user_set_dbinfo (& (*dbmt_dbinfo)[ (*num_db)], ut_trim (tok[0]), + DBMT_USER_ADMIN_NAME, ut_trim (tok[1]), broker_str); + (*num_db)++; + + return E_SUCCESS; +} + +static void +_print_dbmtuser_info (T_DBMT_USER_INFO *dbmtuser_info) +{ + int i; + const char *dbinfo_pattern = " %-48s %-17s %-23s \n"; + char split[17 + 23 + 48 + 3]; + int len = 17 + 23 + 48 + 3; + + memset (split, '=', len - 1); + split[len - 1] = '\0'; + + printf ("DBMT USER: %s\n", dbmtuser_info->user_name); + printf (" Auth info: \n"); + + for (i = 0; i < dbmtuser_info->num_authinfo; i++) + { + T_DBMT_USER_AUTHINFO *t_authinfo = &dbmtuser_info->authinfo[i]; + if (strcmp (t_authinfo->domain, "unicas") == 0) + { + printf (" broker: %s\n", t_authinfo->auth); + } + else + { + printf (" %s: %s\n", t_authinfo->domain, t_authinfo->auth); + } + } + + printf (" DB info: \n"); + printf (" %s\n", split); + printf (dbinfo_pattern, "DBNAME", "UID", "BROKER INFO"); + printf (" %s\n", split); + + for (i = 0; i < dbmtuser_info->num_dbinfo; i++) + { + T_DBMT_USER_DBINFO *t_dbinfo = &dbmtuser_info->dbinfo[i]; + printf (dbinfo_pattern, + t_dbinfo->dbname, t_dbinfo->uid, t_dbinfo->broker_address); + } + printf ("\n"); + + return; +} + +static int +_dbmtuser_auth_arg_check (const char *unicas_auth, const char *dbcreate_auth, + const char *monitor_auth, char *error_msg) +{ + if (unicas_auth != NULL && _check_str_in_list (unicas_auth, auth_list) < 0) + { + snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, + get_msg_by_id (PTN_ARG_FORMAT_ERR), ARG_UNICAS); + return E_ARG_ERR; + } + if (dbcreate_auth != NULL + && _check_str_in_list (dbcreate_auth, createdb_auth_list) < 0) + { + snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, + get_msg_by_id (PTN_ARG_FORMAT_ERR), ARG_DBCREATE); + return E_ARG_ERR; + } + if (monitor_auth != NULL && _check_str_in_list (monitor_auth, auth_list) < 0) + { + snprintf (error_msg, DBMT_ERROR_MSG_SIZE - 1, + get_msg_by_id (PTN_ARG_FORMAT_ERR), ARG_MONITOR); + return E_ARG_ERR; + } + + return E_SUCCESS; +} + +static int +_get_localhost_ip (char *ipaddr, int ipaddr_len) +{ + char hostname[64]; + char *ip = NULL; + int i = 0; + struct hostent *hostent_p = NULL; + +#if defined(WINDOWS) + WSADATA wsaData; + WSAStartup (MAKEWORD (2, 2), &wsaData); +#endif + + hostname[0] = '\0'; + + if (gethostname (hostname, sizeof (hostname)) < 0) + { + goto exit_err; + } + + hostent_p = gethostbyname (hostname); + + if (hostent_p == NULL) + { + ipaddr = NULL; + goto exit_err; + } + else + { + for (i = 0; hostent_p->h_addr_list[i] != NULL; i++) + { + ip = inet_ntoa (* ((struct in_addr *) hostent_p->h_addr_list[i])); + /* ignore the 127.0.0.1 */ + if (strcmp (ip, "127.0.0.1") == 0) + { + continue; + } + break; + } + if (ip) + { + strcpy_limit (ipaddr, ip, ipaddr_len); + return 0; + } + + goto exit_err; + } +exit_err: +#if defined(WINDOWS) + WSACleanup (); +#endif + return -1; +} diff --git a/server/src/am_cmd_task.h b/server/src/am_cmd_task.h new file mode 100644 index 0000000..907153c --- /dev/null +++ b/server/src/am_cmd_task.h @@ -0,0 +1,61 @@ +/* + * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. + * + * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + + +/* + * cm_cmd_task.h - + */ + +#ifndef _CM_CMD_TASK_H_ +#define _CM_CMD_TASK_H_ + +#include +#ifdef HAVE_GETOPT_H +#include +#else +#include "getopt.h" +#endif + +typedef enum +{ + CMD_CHANGEDBPWD, + CMD_LISTDB, + CMD_ADDUSER, + CMD_DELUSER, + CMD_VIEWUSER, + CMD_CHGUSER_AUTH, + CMD_CHGUSER_PWD, + CMD_ADDDBINFO, + CMD_DELDBINFO, + CMD_CHGDBINFO, + CMD_UNDEFINED, +} CMD_ID; + + +int cmd_listdb (int argc, const char *in_argv[]); +int cmd_adduser (int argc, const char *in_argv[]); +int cmd_deluser (int argc, const char *in_argv[]); +int cmd_viewuser (int argc, const char *in_argv[]); +int cmd_chguser_pwd (int argc, const char *in_argv[]); +int cmd_chguser_auth (int argc, const char *in_argv[]); +int cmd_adddbinfo (int argc, const char *in_argv[]); +int cmd_deldbinfo (int argc, const char *in_argv[]); +int cmd_chgdbinfo (int argc, const char *in_argv[]); + +#endif /* ! _CM_CMD_TASK_H_ */ diff --git a/server/src/am_cmd_util.cpp b/server/src/am_cmd_util.cpp new file mode 100644 index 0000000..1fa54ca --- /dev/null +++ b/server/src/am_cmd_util.cpp @@ -0,0 +1,282 @@ +/* + * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. + * + * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + + +/* + * cm_cmd_util.cpp - + */ + +#include +#include +#include +#include + +#include "cm_porting.h" +#include "cm_dep.h" +#include "cm_cmd_util.h" +#include "cm_cmd_task.h" + +typedef int (*CMD_FUNC) (int argc, const char *argv[]); + +#define DEF_CMD_FUNC(CMD_FUNC) CMD_FUNC; + +typedef struct +{ + const char *cmd_name; + CMD_FUNC cmd_func; + CMD_ID cmd_id; +} CMD_INFO; + +static CMD_INFO cmd_info[] = +{ + {"adduser", cmd_adduser, CMD_ADDUSER}, + {"deluser", cmd_deluser, CMD_DELUSER}, + {"viewuser", cmd_viewuser, CMD_VIEWUSER}, + {"changeuserauth", cmd_chguser_auth, CMD_CHGUSER_AUTH}, + {"changeuserpwd", cmd_chguser_pwd, CMD_CHGUSER_PWD}, + {"adddbinfo", cmd_adddbinfo, CMD_ADDDBINFO}, + {"deldbinfo", cmd_deldbinfo, CMD_DELDBINFO}, + {"changedbinfo", cmd_chgdbinfo, CMD_CHGDBINFO}, + {"listdb", cmd_listdb, CMD_LISTDB}, + {NULL, NULL, CMD_UNDEFINED}, +}; + +typedef struct +{ + PTN_ID ptn_id; + const char *ptn_msg; +} PTN_INFO; + +static PTN_INFO msg_str_ptn[] = +{ + {PTN_ARG_MISS, "Argument (%s) is missing."}, + {PTN_ARG_MORE, "Argument (%s) is not needed."}, + {PTN_ARG_NUM_ERR, "Argument number is not correct."}, + {PTN_ARG_FORMAT_ERR, "Argument (%s) not correct!"}, + {PTN_ARG_MUST_APPEAR_ERR, "Arg %s should appear at least one."}, + {PTN_DBMT_USER_NOT_EXIST, "DBMT user (%s) not exist."}, + {PTN_DBMT_USER_EXIST, "DBMT user (%s) already exist."}, + {PTN_DBMT_USER_NOT_DEL, "DBMT user (%s) is not allowed to be deleted."}, + {PTN_DBMT_USER_PWD_ERR, "Password (%s) is not correct."}, + {PTN_DB_NOT_AUTH, "Database (%s) is not authorized to DBMT user (%s)."}, + { + PTN_DB_ALREADY_AUTH, + "Database (%s) is already authorized to DBMT user (%s)." + }, + {PTN_DB_NOT_EXIST, "Database (%s) does not exist."}, + {PTN_DB_ADD_TWICE, "Database (%s) has been add twice."}, + {PTN_BROKER_ADDR_ERR, "Broker address (%s) format is wrong."}, + {PTN_MEM_ALLOC_ERR, "Memory Allocate Error!"}, + {PTN_UNDEFINE, NULL} +}; + +const char * +get_msg_by_id (int ptn_id) +{ + int i; + + for (i = 0; msg_str_ptn[i].ptn_id != PTN_UNDEFINE; i++) + { + if ((int) msg_str_ptn[i].ptn_id == ptn_id) + { + return msg_str_ptn[i].ptn_msg; + } + } + + return NULL; +} + +int +run_task (const char *task_name, int argc, const char *argv[]) +{ + int i; + int retval = E_FAILURE; + + for (i = 0; cmd_info[i].cmd_name != NULL; i++) + { + if (task_name != NULL && strcmp (task_name, cmd_info[i].cmd_name) == 0) + { + retval = (*cmd_info[i].cmd_func) (argc, argv); + return retval; + } + } + + return E_CMD_NOT_EXIST; +} + +char * +utility_make_getopt_optstring (struct option *opt_array, char *buf) +{ + int i; + char *p = buf; + + for (i = 0; opt_array[i].name; i++) + { + if (opt_array[i].val < 255) + { + *p++ = (char) opt_array[i].val; + if (opt_array[i].has_arg) + { + *p++ = ':'; + } + } + } + *p = '\0'; + return buf; +} + +void +print_cmd (void) +{ + int i; + + printf ("Available Utilities:\n"); + + for (i = 0; cmd_info[i].cmd_name != NULL; i++) + { + printf (" %s\n", cmd_info[i].cmd_name); + } + + printf ("\n"); + + return; +} + +int +get_cmdname_by_id (int cmd_id, char *cmd_name, int buf_size) +{ + int i; + + for (i = 0; cmd_info[i].cmd_name != NULL; i++) + { + if (cmd_id == (int) cmd_info[i].cmd_id) + { + snprintf (cmd_name, buf_size - 1, cmd_info[i].cmd_name); + return 0; + } + } + + return -1; +} + +void +print_help_msg (int cmd_id) +{ + const char *pattern = " %s, %-30s%s\n"; + const char *pattern2 = "%-36s%s\n"; + const char *pattern_long_only = " %-30s%s\n"; + const char *pattern_usage = "usage: " CM_ADMIN_NAME " %s\n\n"; + + switch (cmd_id) + { + case CMD_ADDUSER: + printf ("adduser: Add a DBMT user to the amserver.\n"); + printf (pattern_usage, + "adduser [OPTIONS] <" ARG_DBMT_USER_NAME "> <" ARG_DBMT_USER_PWD + ">"); + printf ("valid options:\n"); + printf (pattern, "-b", "--broker", + "Authority of broker, default: none; allowed:"); + printf (pattern2, " ", "none, admin, monitor"); + printf (pattern, "-c", "--dbcreate", + "Authority of creating a database, only admin user has the auth to create a database;"); + printf (pattern2, " ", "default: none; allowed: none, admin"); + printf (pattern, "-m", "--monitor", + "Authority of monitoring host & database, default: none; allowed:"); + printf (pattern2, " ", "none, admin, monitor"); + printf (pattern, "-d", "--dbinfo", + "DBINFO should be formatted as follows:"); + printf (pattern2, " ", "\";;,\""); + break; + + case CMD_DELUSER: + printf ("deluser: Delete a DBMT user from the amserver.\n"); + printf (pattern_usage, "deluser <" ARG_DBMT_USER_NAME ">"); + break; + + case CMD_VIEWUSER: + printf ("viewuser: View DBMT user info.\n"); + printf (pattern_usage, "viewuser [" ARG_DBMT_USER_NAME "]"); + break; + + case CMD_DELDBINFO: + printf ("deldbinfo: Delete a dbinfo of the specified DBMT user.\n"); + printf (pattern_usage, + "deldbinfo <" ARG_DBMT_USER_NAME "> <" ARG_DB_NAME ">"); + break; + + case CMD_ADDDBINFO: + printf ("adddbinfo: Add a dbinfo to a DBMT user.\n"); + printf (pattern_usage, + "adddbinfo [OPTIONS] <" ARG_DBMT_USER_NAME "> <" ARG_DB_NAME + ">"); + printf ("valid options:\n"); + printf (pattern, "-u", "--uid", + "Uid is the dbuser of the database; default: dba"); + printf (pattern, "-h", "--host", + "Host is the ipaddr of the broker; default: localhost"); + printf (pattern, "-p", "--port", + "Port is the port of broker; default: 30000"); + break; + + case CMD_CHGDBINFO: + printf ("changedbinfo: Add a dbinfo to a DBMT user.\n"); + printf (pattern_usage, + "changedbinfo [OPTIONS] <" ARG_DBMT_USER_NAME "> <" ARG_DB_NAME + ">"); + printf ("valid options:\n"); + printf (pattern, "-u", "--uid ", "Uid is the dbuser of the database"); + printf (pattern, "-h", "--host", "Host is the ipaddr of the broker"); + printf (pattern, "-p", "--port", "Port is the port of broker"); + break; + + case CMD_CHGUSER_PWD: + printf + ("changeuserpwd: Change the password of the specified DBMT user.\n"); + printf (pattern_usage, + "changeuserpwd [OPTIONS] <" ARG_DBMT_USER_NAME ">"); + printf ("valid options:\n"); + printf (pattern, "-o", "--oldpass", "Old password of the DBMT user."); + printf (pattern, "-n", "--newpass", "New password of the DBMT user."); + printf (pattern_long_only, "--adminpass", + "Admin password should be set when old password is not offered."); + break; + + case CMD_CHGUSER_AUTH: + printf + ("changeuserauth: Change the authority info of the DBMT user.\n"); + printf (pattern_usage, + "changeuserauth [OPTIONS] <" ARG_DBMT_USER_NAME ">"); + printf ("valid options:\n"); + printf (pattern, "-b", "--broker", "Authority of broker; allowed:"); + printf (pattern2, " ", "none, admin, monitor"); + printf (pattern, "-c", "--dbcreate", + "Authority of creating a database, only admin user has the authority to create database;"); + printf (pattern2, " ", "allowed: none, admin"); + printf (pattern, "-m", "--monitor", + "Authority of monitoring host and database; allowed:"); + printf (pattern2, " ", "none, admin, monitor"); + break; + + default: + break; + } + + return; +} diff --git a/server/src/am_cmd_util.h b/server/src/am_cmd_util.h new file mode 100644 index 0000000..6160452 --- /dev/null +++ b/server/src/am_cmd_util.h @@ -0,0 +1,123 @@ +/* + * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. + * + * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + + +/* + * cm_cmd_util.h - + */ + +#ifndef _CM_CMD_UTIL_H_ +#define _CM_CMD_UTIL_H_ + +#ifdef HAVE_GETOPT_H +#include +#else +#include "getopt.h" +#endif + + +/* typedef struct option GETOPT_LONG; */ + +/* + * CM_ADMIN COMMON MACRO. + */ +#define CM_ADMIN_NAME "cm_admin" +#define CM_ADMIN_VERSION "0.1" + +#define OPT_STR_LEN 128 +#define DBNAME_LEN 128 +#define UID_LEN 18 +#define PORT_LEN 8 +#define BROKER_ADDR_LEN MAXHOSTNAMELEN + PORT_LEN + 1 + +#define ADMIN_FLAG 1 + +#ifndef PATH_MAX +#define PATH_MAX 1024 +#endif + +#ifndef LINE_MAX +#define LINE_MAX 1024 +#endif + +#define SQL_STAT_LEN 1024 +#define DBMT_USER_ADMIN_NAME "admin" +#define AUTH_NUM_TOTAL 3 + + +/* + * CM_ADMIN ARG NAME DEFINITION. + */ + +#define ARG_DBMT_USER_NAME "dbmtuser-name" +#define ARG_DBMT_USER_PWD "dbmtuser-password" +#define ARG_DB_NAME "dbname" + +#define ARG_UNICAS "broker" +#define ARG_DBCREATE "dbcreate" +#define ARG_MONITOR "monitor" + +#define ARG_AUTH "auth" +#define ARG_UID "uid" +#define ARG_HOST "host" +#define ARG_PORT "port" + +#define ARG_OLD_PASS "old" +#define ARG_NEW_PASS "new" +#define ARG_ADMIN_PASS "adminpass" + +#define ARG_DB_INFO "dbinfo" + + +/* + * CM_ADMIN ERROR ID DEFINITION. + */ +#define E_SUCCESS 2000 +#define E_FAILURE 2001 +#define E_CMD_NOT_EXIST 2002 +#define E_ARG_ERR 2003 + +typedef enum +{ + PTN_ARG_MISS, + PTN_ARG_MORE, + PTN_ARG_NUM_ERR, + PTN_ARG_FORMAT_ERR, + PTN_ARG_MUST_APPEAR_ERR, + PTN_DBMT_USER_NOT_EXIST, + PTN_DBMT_USER_EXIST, + PTN_DBMT_USER_NOT_DEL, + PTN_DBMT_USER_PWD_ERR, + PTN_DB_NOT_AUTH, + PTN_DB_ALREADY_AUTH, + PTN_DB_NOT_EXIST, + PTN_DB_ADD_TWICE, + PTN_BROKER_ADDR_ERR, + PTN_MEM_ALLOC_ERR, + PTN_UNDEFINE, +} PTN_ID; + +void print_cmd (void); +void print_help_msg (int cmd_id); + +int run_task (const char *task_name, int argc, const char *argv[]); +int get_cmdname_by_id (int cmd_id, char *cmd_name, int buf_size); +const char *get_msg_by_id (int ptn_id); +char *utility_make_getopt_optstring (struct option *opt_array, char *buf); +#endif /* !_CM_CMD_UTIL_H_ */ diff --git a/server/src/am_compress.h b/server/src/am_compress.h new file mode 100644 index 0000000..cf58c48 --- /dev/null +++ b/server/src/am_compress.h @@ -0,0 +1,6747 @@ +/* miniz.c v1.12 - public domain deflate/inflate, zlib-subset, ZIP reading/writing/appending, PNG writing + See "unlicense" statement at the end of this file. + Rich Geldreich , last updated April 12, 2012 + Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt + + Most API's defined in miniz.c are optional. For example, to disable the archive related functions just define + MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO (see the list below for more macros). + + * Change History + 4/12/12 v1.12 - More comments, added low-level example5.c, fixed a couple minor level_and_flags issues in the archive API's. + level_and_flags can now be set to MZ_DEFAULT_COMPRESSION. Thanks to Bruce Dawson for the feedback/bug report. + 5/28/11 v1.11 - Added statement from unlicense.org + 5/27/11 v1.10 - Substantial compressor optimizations: + Level 1 is now ~4x faster than before. The L1 compressor's throughput now varies between 70-110MB/sec. on a + Core i7 (actual throughput varies depending on the type of data, and x64 vs. x86). + Improved baseline L2-L9 compression perf. Also, greatly improved compression perf. issues on some file types. + Refactored the compression code for better readability and maintainability. + Added level 10 compression level (L10 has slightly better ratio than level 9, but could have a potentially large + drop in throughput on some files). + 5/15/11 v1.09 - Initial stable release. + + * Low-level Deflate/Inflate implementation notes: + + Compression: Use the "tdefl" API's. The compressor supports raw, static, and dynamic blocks, lazy or + greedy parsing, match length filtering, RLE-only, and Huffman-only streams. It performs and compresses + approximately as well as zlib. + + Decompression: Use the "tinfl" API's. The entire decompressor is implemented as a single function + coroutine: see tinfl_decompress(). It supports decompression into a 32KB (or larger power of 2) wrapping buffer, or into a memory + block large enough to hold the entire file. + + The low-level tdefl/tinfl API's do not make any use of dynamic memory allocation. + + * zlib-style API notes: + + miniz.c implements a fairly large subset of zlib. There's enough functionality present for it to be a drop-in + zlib replacement in many apps: + The z_stream struct, optional memory allocation callbacks + deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound + inflateInit/inflateInit2/inflate/inflateEnd + compress, compress2, compressBound, uncompress + CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly routines. + Supports raw deflate streams or standard zlib streams with adler-32 checking. + + Limitations: + The callback API's are not implemented yet. No support for gzip headers or zlib static dictionaries. + I've tried to closely emulate zlib's various flavors of stream flushing and return status codes, but + there are no guarantees that miniz.c pulls this off perfectly. + + * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function, originally written by + Alex Evans. Supports 1-4 bytes/pixel images. + + * ZIP archive API notes: + + The ZIP archive API's where designed with simplicity and efficiency in mind, with just enough abstraction to + get the job done with minimal fuss. There are simple API's to retrieve file information, read files from + existing archives, create new archives, append new files to existing archives, or clone archive data from + one archive to another. It supports archives located in memory or the heap, on disk (using stdio.h), + or you can specify custom file read/write callbacks. + + - Archive reading: Just call this function to read a single file from a disk archive: + + void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, + size_t *pSize, mz_uint zip_flags); + + For more complex cases, use the "mz_zip_reader" functions. Upon opening an archive, the entire central + directory is located and read as-is into memory, and subsequent file access only occurs when reading individual files. + + - Archives file scanning: The simple way is to use this function to scan a loaded archive for a specific file: + + int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); + + The locate operation can optionally check file comments too, which (as one example) can be used to identify + multiple versions of the same file in an archive. This function uses a simple linear search through the central + directory, so it's not very fast. + + Alternately, you can iterate through all the files in an archive (using mz_zip_reader_get_num_files()) and + retrieve detailed info on each file by calling mz_zip_reader_file_stat(). + + - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer immediately writes compressed file data + to disk and builds an exact image of the central directory in memory. The central directory image is written + all at once at the end of the archive file when the archive is finalized. + + The archive writer can optionally align each file's local header and file data to any power of 2 alignment, + which can be useful when the archive will be read from optical media. Also, the writer supports placing + arbitrary data blobs at the very beginning of ZIP archives. Archives written using either feature are still + readable by any ZIP tool. + + - Archive appending: The simple way to add a single file to an archive is to call this function: + + mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, + const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); + + The archive will be created if it doesn't already exist, otherwise it'll be appended to. + Note the appending is done in-place and is not an atomic operation, so if something goes wrong + during the operation it's possible the archive could be left without a central directory (although the local + file headers and file data will be fine, so the archive will be recoverable). + + For more complex archive modification scenarios: + 1. The safest way is to use a mz_zip_reader to read the existing archive, cloning only those bits you want to + preserve into a new archive using using the mz_zip_writer_add_from_zip_reader() function (which compiles the + compressed file data as-is). When you're done, delete the old archive and rename the newly written archive, and + you're done. This is safe but requires a bunch of temporary disk space or heap memory. + + 2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using mz_zip_writer_init_from_reader(), + append new files as needed, then finalize the archive which will write an updated central directory to the + original archive. (This is basically what mz_zip_add_mem_to_archive_file_in_place() does.) There's a + possibility that the archive's central directory could be lost with this method if anything goes wrong, though. + + - ZIP archive support limitations: + No zip64 or spanning support. Extraction functions can only handle unencrypted, stored or deflated files. + Requires streams capable of seeking. + + * This is a header file library, like stb_image.c. To get only a header file, either cut and paste the + below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then include miniz.c from it. + + * Important: For best perf. be sure to customize the below macros for your target platform: + #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 + #define MINIZ_LITTLE_ENDIAN 1 + #define MINIZ_HAS_64BIT_REGISTERS 1 +*/ + +#ifndef MINIZ_HEADER_INCLUDED +#define MINIZ_HEADER_INCLUDED + +#include + +// Defines to completely disable specific portions of miniz.c: +// If all macros here are defined the only functionality remaining will be CRC-32, adler-32, tinfl, and tdefl. + +// Define MINIZ_NO_STDIO to disable all usage and any functions which rely on stdio for file I/O. +//#define MINIZ_NO_STDIO + +// If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able to get the current time, or +// get/set file times. +//#define MINIZ_NO_TIME + +// Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's. +//#define MINIZ_NO_ARCHIVE_APIS + +// Define MINIZ_NO_ARCHIVE_APIS to disable all writing related ZIP archive API's. +//#define MINIZ_NO_ARCHIVE_WRITING_APIS + +// Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression API's. +//#define MINIZ_NO_ZLIB_APIS + +// Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent conflicts against stock zlib. +//#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES + +// Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc. +// Note if MINIZ_NO_MALLOC is defined then the user must always provide custom user alloc/free/realloc +// callbacks to the zlib and archive API's, and a few stand-alone helper API's which don't provide custom user +// functions (such as tdefl_compress_mem_to_heap() and tinfl_decompress_mem_to_heap()) won't work. +//#define MINIZ_NO_MALLOC + +#if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || defined(__i386) || defined(__i486__) || defined(__i486) || defined(i386) || defined(__ia64__) || defined(__x86_64__) +// MINIZ_X86_OR_X64_CPU is only used to help set the below macros. +#define MINIZ_X86_OR_X64_CPU 1 +#endif + +#if (__BYTE_ORDER__==__ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU +// Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. +#define MINIZ_LITTLE_ENDIAN 1 +#endif + +#if MINIZ_X86_OR_X64_CPU +// Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient integer loads and stores from unaligned addresses. +#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 +#endif + +#if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || defined(__LP64__) || defined(__ia64__) || defined(__x86_64__) +// Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are reasonably fast (and don't involve compiler generated calls to helper functions). +#define MINIZ_HAS_64BIT_REGISTERS 1 +#endif + +#ifdef __cplusplus +extern "C" +{ +#endif + +// ------------------- zlib-style API Definitions. + +// For more compatibility with zlib, miniz.c uses unsigned long for some parameters/struct members. + typedef unsigned long mz_ulong; + +// Heap allocation callbacks. +// Note that mz_alloc_func parameter types purpsosely differ from zlib's: items/size is size_t, not unsigned long. + typedef void *(*mz_alloc_func) (void *opaque, size_t items, size_t size); + typedef void (*mz_free_func) (void *opaque, void *address); + typedef void *(*mz_realloc_func) (void *opaque, void *address, size_t items, + size_t size); + +#define MZ_ADLER32_INIT (1) +// mz_adler32() returns the initial adler-32 value to use when called with ptr==NULL. + mz_ulong mz_adler32 (mz_ulong adler, const unsigned char *ptr, + size_t buf_len); + +#define MZ_CRC32_INIT (0) +// mz_crc32() returns the initial CRC-32 value to use when called with ptr==NULL. + mz_ulong mz_crc32 (mz_ulong crc, const unsigned char *ptr, size_t buf_len); + +// Compression strategies. + enum + { MZ_DEFAULT_STRATEGY = 0, MZ_FILTERED = 1, MZ_HUFFMAN_ONLY = 2, MZ_RLE = + 3, MZ_FIXED = 4 + }; + +// Method +#define MZ_DEFLATED 8 + +#ifndef MINIZ_NO_ZLIB_APIS + +#define MZ_VERSION "9.1.12" +#define MZ_VERNUM 0x91C0 +#define MZ_VER_MAJOR 9 +#define MZ_VER_MINOR 1 +#define MZ_VER_REVISION 12 +#define MZ_VER_SUBREVISION 0 + +// Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The other values are for advanced use (refer to the zlib docs). + enum + { MZ_NO_FLUSH = 0, MZ_PARTIAL_FLUSH = 1, MZ_SYNC_FLUSH = 2, MZ_FULL_FLUSH = + 3, MZ_FINISH = 4, MZ_BLOCK = 5 + }; + +// Return status codes. MZ_PARAM_ERROR is non-standard. + enum + { MZ_OK = 0, MZ_STREAM_END = 1, MZ_NEED_DICT = 2, MZ_ERRNO = + -1, MZ_STREAM_ERROR = -2, MZ_DATA_ERROR = -3, MZ_MEM_ERROR = + -4, MZ_BUF_ERROR = -5, MZ_VERSION_ERROR = -6, MZ_PARAM_ERROR = -10000 + }; + +// Compression levels: 0-9 are the standard zlib-style levels, 10 is best possible compression (not zlib compatible, and may be very slow), MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL. + enum + { MZ_NO_COMPRESSION = 0, MZ_BEST_SPEED = 1, MZ_BEST_COMPRESSION = + 9, MZ_UBER_COMPRESSION = 10, MZ_DEFAULT_LEVEL = + 6, MZ_DEFAULT_COMPRESSION = -1 + }; + +// Window bits +#define MZ_DEFAULT_WINDOW_BITS 15 + + struct mz_internal_state; + +// Compression/decompression stream struct. + typedef struct mz_stream_s + { + const unsigned char *next_in; // pointer to next byte to read + unsigned int avail_in; // number of bytes available at next_in + mz_ulong total_in; // total number of bytes consumed so far + + unsigned char *next_out; // pointer to next byte to write + unsigned int avail_out; // number of bytes that can be written to next_out + mz_ulong total_out; // total number of bytes produced so far + + char *msg; // error msg (unused) + struct mz_internal_state *state; // internal state, allocated by zalloc/zfree + + mz_alloc_func zalloc; // optional heap allocation function (defaults to malloc) + mz_free_func zfree; // optional heap free function (defaults to free) + void *opaque; // heap alloc function user pointer + + int data_type; // data_type (unused) + mz_ulong adler; // adler32 of the source or uncompressed data + mz_ulong reserved; // not used + } mz_stream; + + typedef mz_stream *mz_streamp; + +// Returns the version string of miniz.c. + const char *mz_version (void); + +// mz_deflateInit() initializes a compressor with default options: +// Parameters: +// pStream must point to an initialized mz_stream struct. +// level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION]. +// level 1 enables a specially optimized compression function that's been optimized purely for performance, not ratio. +// (This special func. is currently only enabled when MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.) +// Return values: +// MZ_OK on success. +// MZ_STREAM_ERROR if the stream is bogus. +// MZ_PARAM_ERROR if the input parameters are bogus. +// MZ_MEM_ERROR on out of memory. + int mz_deflateInit (mz_streamp pStream, int level); + +// mz_deflateInit2() is like mz_deflate(), except with more control: +// Additional parameters: +// method must be MZ_DEFLATED +// window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no header or footer) +// mem_level must be between [1, 9] (it's checked but ignored by miniz.c) + int mz_deflateInit2 (mz_streamp pStream, int level, int method, + int window_bits, int mem_level, int strategy); + +// Quickly resets a compressor without having to reallocate anything. Same as calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2(). + int mz_deflateReset (mz_streamp pStream); + +// mz_deflate() compresses the input to output, consuming as much of the input and producing as much output as possible. +// Parameters: +// pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. +// flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or MZ_FINISH. +// Return values: +// MZ_OK on success (when flushing, or if more input is needed but not available, and/or there's more output to be written but the output buffer is full). +// MZ_STREAM_END if all input has been consumed and all output bytes have been written. Don't call mz_deflate() on the stream anymore. +// MZ_STREAM_ERROR if the stream is bogus. +// MZ_PARAM_ERROR if one of the parameters is invalid. +// MZ_BUF_ERROR if no forward progress is possible because the input and/or output buffers are empty. (Fill up the input buffer or free up some output space and try again.) + int mz_deflate (mz_streamp pStream, int flush); + +// mz_deflateEnd() deinitializes a compressor: +// Return values: +// MZ_OK on success. +// MZ_STREAM_ERROR if the stream is bogus. + int mz_deflateEnd (mz_streamp pStream); + +// mz_deflateBound() returns a (very) conservative upper bound on the amount of data that could be generated by deflate(), assuming flush is set to only MZ_NO_FLUSH or MZ_FINISH. + mz_ulong mz_deflateBound (mz_streamp pStream, mz_ulong source_len); + +// Single-call compression functions mz_compress() and mz_compress2(): +// Returns MZ_OK on success, or one of the error codes from mz_deflate() on failure. + int mz_compress (unsigned char *pDest, mz_ulong * pDest_len, + const unsigned char *pSource, mz_ulong source_len); + int mz_compress2 (unsigned char *pDest, mz_ulong * pDest_len, + const unsigned char *pSource, mz_ulong source_len, + int level); + +// mz_compressBound() returns a (very) conservative upper bound on the amount of data that could be generated by calling mz_compress(). + mz_ulong mz_compressBound (mz_ulong source_len); + +// Initializes a decompressor. + int mz_inflateInit (mz_streamp pStream); + +// mz_inflateInit2() is like mz_inflateInit() with an additional option that controls the window size and whether or not the stream has been wrapped with a zlib header/footer: +// window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate). + int mz_inflateInit2 (mz_streamp pStream, int window_bits); + +// Decompresses the input stream to the output, consuming only as much of the input as needed, and writing as much to the output as possible. +// Parameters: +// pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. +// flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH. +// On the first call, if flush is MZ_FINISH it's assumed the input and output buffers are both sized large enough to decompress the entire stream in a single call (this is slightly faster). +// MZ_FINISH implies that there are no more source bytes available beside what's already in the input buffer, and that the output buffer is large enough to hold the rest of the decompressed data. +// Return values: +// MZ_OK on success. Either more input is needed but not available, and/or there's more output to be written but the output buffer is full. +// MZ_STREAM_END if all needed input has been consumed and all output bytes have been written. For zlib streams, the adler-32 of the decompressed data has also been verified. +// MZ_STREAM_ERROR if the stream is bogus. +// MZ_DATA_ERROR if the deflate stream is invalid. +// MZ_PARAM_ERROR if one of the parameters is invalid. +// MZ_BUF_ERROR if no forward progress is possible because the input buffer is empty but the inflater needs more input to continue, or if the output buffer is not large enough. Call mz_inflate() again +// with more input data, or with more room in the output buffer (except when using single call decompression, described above). + int mz_inflate (mz_streamp pStream, int flush); + +// Deinitializes a decompressor. + int mz_inflateEnd (mz_streamp pStream); + +// Single-call decompression. +// Returns MZ_OK on success, or one of the error codes from mz_inflate() on failure. + int mz_uncompress (unsigned char *pDest, mz_ulong * pDest_len, + const unsigned char *pSource, mz_ulong source_len); + +// Returns a string description of the specified error code, or NULL if the error code is invalid. + const char *mz_error (int err); + +// Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used as a drop-in replacement for the subset of zlib that miniz.c supports. +// Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you use zlib in the same project. +#ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES + typedef unsigned char Byte; + typedef unsigned int uInt; + typedef mz_ulong uLong; + typedef Byte Bytef; + typedef uInt uIntf; + typedef char charf; + typedef int intf; + typedef void *voidpf; + typedef uLong uLongf; + typedef void *voidp; + typedef void *const voidpc; +#define Z_NULL 0 +#define Z_NO_FLUSH MZ_NO_FLUSH +#define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH +#define Z_SYNC_FLUSH MZ_SYNC_FLUSH +#define Z_FULL_FLUSH MZ_FULL_FLUSH +#define Z_FINISH MZ_FINISH +#define Z_BLOCK MZ_BLOCK +#define Z_OK MZ_OK +#define Z_STREAM_END MZ_STREAM_END +#define Z_NEED_DICT MZ_NEED_DICT +#define Z_ERRNO MZ_ERRNO +#define Z_STREAM_ERROR MZ_STREAM_ERROR +#define Z_DATA_ERROR MZ_DATA_ERROR +#define Z_MEM_ERROR MZ_MEM_ERROR +#define Z_BUF_ERROR MZ_BUF_ERROR +#define Z_VERSION_ERROR MZ_VERSION_ERROR +#define Z_PARAM_ERROR MZ_PARAM_ERROR +#define Z_NO_COMPRESSION MZ_NO_COMPRESSION +#define Z_BEST_SPEED MZ_BEST_SPEED +#define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION +#define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION +#define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY +#define Z_FILTERED MZ_FILTERED +#define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY +#define Z_RLE MZ_RLE +#define Z_FIXED MZ_FIXED +#define Z_DEFLATED MZ_DEFLATED +#define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS +#define alloc_func mz_alloc_func +#define free_func mz_free_func +#define internal_state mz_internal_state +#define z_stream mz_stream +#define deflateInit mz_deflateInit +#define deflateInit2 mz_deflateInit2 +#define deflateReset mz_deflateReset +#define deflate mz_deflate +#define deflateEnd mz_deflateEnd +#define deflateBound mz_deflateBound +#define compress mz_compress +#define compress2 mz_compress2 +#define compressBound mz_compressBound +#define inflateInit mz_inflateInit +#define inflateInit2 mz_inflateInit2 +#define inflate mz_inflate +#define inflateEnd mz_inflateEnd +#define uncompress mz_uncompress +#define crc32 mz_crc32 +#define adler32 mz_adler32 +#define MAX_WBITS 15 +#define MAX_MEM_LEVEL 9 +#define zError mz_error +#define ZLIB_VERSION MZ_VERSION +#define ZLIB_VERNUM MZ_VERNUM +#define ZLIB_VER_MAJOR MZ_VER_MAJOR +#define ZLIB_VER_MINOR MZ_VER_MINOR +#define ZLIB_VER_REVISION MZ_VER_REVISION +#define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION +#define zlibVersion mz_version +#define zlib_version mz_version() +#endif // #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES + +#endif // MINIZ_NO_ZLIB_APIS + +// ------------------- Types and macros + + typedef unsigned char mz_uint8; + typedef signed short mz_int16; + typedef unsigned short mz_uint16; + typedef unsigned int mz_uint32; + typedef unsigned int mz_uint; + typedef long long mz_int64; + typedef unsigned long long mz_uint64; + typedef int mz_bool; + +#define MZ_FALSE (0) +#define MZ_TRUE (1) + +// Works around MSVC's spammy "warning C4127: conditional expression is constant" message. +#define MZ_MACRO_END while (0, 0) + +// ------------------- ZIP archive reading/writing + +#ifndef MINIZ_NO_ARCHIVE_APIS + + enum + { + MZ_ZIP_MAX_IO_BUF_SIZE = 64 * 1024, + MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 260, + MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 256 + }; + + typedef struct + { + mz_uint32 m_file_index; + mz_uint32 m_central_dir_ofs; + mz_uint16 m_version_made_by; + mz_uint16 m_version_needed; + mz_uint16 m_bit_flag; + mz_uint16 m_method; +#ifndef MINIZ_NO_TIME + time_t m_time; +#endif + mz_uint32 m_crc32; + mz_uint64 m_comp_size; + mz_uint64 m_uncomp_size; + mz_uint16 m_internal_attr; + mz_uint32 m_external_attr; + mz_uint64 m_local_header_ofs; + mz_uint32 m_comment_size; + char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE]; + char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE]; + } mz_zip_archive_file_stat; + + typedef size_t (*mz_file_read_func) (void *pOpaque, mz_uint64 file_ofs, + void *pBuf, size_t n); + typedef size_t (*mz_file_write_func) (void *pOpaque, mz_uint64 file_ofs, + const void *pBuf, size_t n); + + struct mz_zip_internal_state_tag; + typedef struct mz_zip_internal_state_tag mz_zip_internal_state; + + typedef enum + { + MZ_ZIP_MODE_INVALID = 0, + MZ_ZIP_MODE_READING = 1, + MZ_ZIP_MODE_WRITING = 2, + MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3 + } mz_zip_mode; + + typedef struct + { + mz_uint64 m_archive_size; + mz_uint64 m_central_directory_file_ofs; + mz_uint m_total_files; + mz_zip_mode m_zip_mode; + + mz_uint m_file_offset_alignment; + + mz_alloc_func m_pAlloc; + mz_free_func m_pFree; + mz_realloc_func m_pRealloc; + void *m_pAlloc_opaque; + + mz_file_read_func m_pRead; + mz_file_write_func m_pWrite; + void *m_pIO_opaque; + + mz_zip_internal_state *m_pState; + + } mz_zip_archive; + + typedef enum + { + MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100, + MZ_ZIP_FLAG_IGNORE_PATH = 0x0200, + MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400, + MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800 + } mz_zip_flags; + +// ZIP archive reading + +// Inits a ZIP archive reader. +// These functions read and validate the archive's central directory. + mz_bool mz_zip_reader_init (mz_zip_archive * pZip, mz_uint64 size, + mz_uint32 flags); + mz_bool mz_zip_reader_init_mem (mz_zip_archive * pZip, const void *pMem, + size_t size, mz_uint32 flags); + +#ifndef MINIZ_NO_STDIO + mz_bool mz_zip_reader_init_file (mz_zip_archive * pZip, + const char *pFilename, mz_uint32 flags); +#endif + +// Returns the total number of files in the archive. + mz_uint mz_zip_reader_get_num_files (mz_zip_archive * pZip); + +// Returns detailed information about an archive file entry. + mz_bool mz_zip_reader_file_stat (mz_zip_archive * pZip, mz_uint file_index, + mz_zip_archive_file_stat * pStat); + +// Determines if an archive file entry is a directory entry. + mz_bool mz_zip_reader_is_file_a_directory (mz_zip_archive * pZip, + mz_uint file_index); + mz_bool mz_zip_reader_is_file_encrypted (mz_zip_archive * pZip, + mz_uint file_index); + +// Retrieves the filename of an archive file entry. +// Returns the number of bytes written to pFilename, or if filename_buf_size is 0 this function returns the number of bytes needed to fully store the filename. + mz_uint mz_zip_reader_get_filename (mz_zip_archive * pZip, + mz_uint file_index, char *pFilename, + mz_uint filename_buf_size); + +// Attempts to locates a file in the archive's central directory. +// Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH +// Returns -1 if the file cannot be found. + int mz_zip_reader_locate_file (mz_zip_archive * pZip, const char *pName, + const char *pComment, mz_uint flags); + +// Extracts a archive file to a memory buffer using no memory allocation. + mz_bool mz_zip_reader_extract_to_mem_no_alloc (mz_zip_archive * pZip, + mz_uint file_index, + void *pBuf, size_t buf_size, + mz_uint flags, + void *pUser_read_buf, + size_t user_read_buf_size); + mz_bool mz_zip_reader_extract_file_to_mem_no_alloc (mz_zip_archive * pZip, + const char *pFilename, + void *pBuf, + size_t buf_size, + mz_uint flags, + void *pUser_read_buf, + size_t + user_read_buf_size); + +// Extracts a archive file to a memory buffer. + mz_bool mz_zip_reader_extract_to_mem (mz_zip_archive * pZip, + mz_uint file_index, void *pBuf, + size_t buf_size, mz_uint flags); + mz_bool mz_zip_reader_extract_file_to_mem (mz_zip_archive * pZip, + const char *pFilename, + void *pBuf, size_t buf_size, + mz_uint flags); + +// Extracts a archive file to a dynamically allocated heap buffer. + void *mz_zip_reader_extract_to_heap (mz_zip_archive * pZip, + mz_uint file_index, size_t * pSize, + mz_uint flags); + void *mz_zip_reader_extract_file_to_heap (mz_zip_archive * pZip, + const char *pFilename, + size_t * pSize, mz_uint flags); + +// Extracts a archive file using a callback function to output the file's data. + mz_bool mz_zip_reader_extract_to_callback (mz_zip_archive * pZip, + mz_uint file_index, + mz_file_write_func pCallback, + void *pOpaque, mz_uint flags); + mz_bool mz_zip_reader_extract_file_to_callback (mz_zip_archive * pZip, + const char *pFilename, + mz_file_write_func + pCallback, void *pOpaque, + mz_uint flags); + +#ifndef MINIZ_NO_STDIO +// Extracts a archive file to a disk file and sets its last accessed and modified times. +// This function only extracts files, not archive directory records. + mz_bool mz_zip_reader_extract_to_file (mz_zip_archive * pZip, + mz_uint file_index, + const char *pDst_filename, + mz_uint flags); + mz_bool mz_zip_reader_extract_file_to_file (mz_zip_archive * pZip, + const char *pArchive_filename, + const char *pDst_filename, + mz_uint flags); +#endif + +// Ends archive reading, freeing all allocations, and closing the input archive file if mz_zip_reader_init_file() was used. + mz_bool mz_zip_reader_end (mz_zip_archive * pZip); + +// ZIP archive writing + +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + +// Inits a ZIP archive writer. + mz_bool mz_zip_writer_init (mz_zip_archive * pZip, mz_uint64 existing_size); + mz_bool mz_zip_writer_init_heap (mz_zip_archive * pZip, + size_t size_to_reserve_at_beginning, + size_t initial_allocation_size); + +#ifndef MINIZ_NO_STDIO + mz_bool mz_zip_writer_init_file (mz_zip_archive * pZip, + const char *pFilename, + mz_uint64 size_to_reserve_at_beginning); +#endif + +// Converts a ZIP archive reader object into a writer object, to allow efficient in-place file appends to occur on an existing archive. +// For archives opened using mz_zip_reader_init_file, pFilename must be the archive's filename so it can be reopened for writing. If the file can't be reopened, mz_zip_reader_end() will be called. +// For archives opened using mz_zip_reader_init_mem, the memory block must be growable using the realloc callback (which defaults to realloc unless you've overridden it). +// Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's user provided m_pWrite function cannot be NULL. +// Note: In-place archive modification is not recommended unless you know what you're doing, because if execution stops or something goes wrong before +// the archive is finalized the file's central directory will be hosed. + mz_bool mz_zip_writer_init_from_reader (mz_zip_archive * pZip, + const char *pFilename); + +// Adds the contents of a memory buffer to an archive. These functions record the current local time into the archive. +// To add a directory entry, call this method with an archive name ending in a forwardslash with empty buffer. +// level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. + mz_bool mz_zip_writer_add_mem (mz_zip_archive * pZip, + const char *pArchive_name, const void *pBuf, + size_t buf_size, mz_uint level_and_flags); + mz_bool mz_zip_writer_add_mem_ex (mz_zip_archive * pZip, + const char *pArchive_name, + const void *pBuf, size_t buf_size, + const void *pComment, + mz_uint16 comment_size, + mz_uint level_and_flags, + mz_uint64 uncomp_size, + mz_uint32 uncomp_crc32); + +#ifndef MINIZ_NO_STDIO +// Adds the contents of a disk file to an archive. This function also records the disk file's modified time into the archive. +// level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. + mz_bool mz_zip_writer_add_file (mz_zip_archive * pZip, + const char *pArchive_name, + const char *pSrc_filename, + const void *pComment, + mz_uint16 comment_size, + mz_uint level_and_flags); +#endif + +// Adds a file to an archive by fully cloning the data from another archive. +// This function fully clones the source file's compressed data (no recompression), along with its full filename, extra data, and comment fields. + mz_bool mz_zip_writer_add_from_zip_reader (mz_zip_archive * pZip, + mz_zip_archive * pSource_zip, + mz_uint file_index); + +// Finalizes the archive by writing the central directory records followed by the end of central directory record. +// After an archive is finalized, the only valid call on the mz_zip_archive struct is mz_zip_writer_end(). +// An archive must be manually finalized by calling this function for it to be valid. + mz_bool mz_zip_writer_finalize_archive (mz_zip_archive * pZip); + mz_bool mz_zip_writer_finalize_heap_archive (mz_zip_archive * pZip, + void **pBuf, size_t * pSize); + +// Ends archive writing, freeing all allocations, and closing the output file if mz_zip_writer_init_file() was used. +// Note for the archive to be valid, it must have been finalized before ending. + mz_bool mz_zip_writer_end (mz_zip_archive * pZip); + +// Misc. high-level helper functions: + +// mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) appends a memory blob to a ZIP archive. +// level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. + mz_bool mz_zip_add_mem_to_archive_file_in_place (const char *pZip_filename, + const char *pArchive_name, + const void *pBuf, + size_t buf_size, + const void *pComment, + mz_uint16 comment_size, + mz_uint level_and_flags); + +// Reads a single file from an archive into a heap block. +// Returns NULL on failure. + void *mz_zip_extract_archive_file_to_heap (const char *pZip_filename, + const char *pArchive_name, + size_t * pSize, + mz_uint zip_flags); + +#endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + +#endif // #ifndef MINIZ_NO_ARCHIVE_APIS + +// ------------------- Low-level Decompression API Definitions + +// Decompression flags used by tinfl_decompress(). +// TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the input is a raw deflate stream. +// TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available beyond the end of the supplied input buffer. If clear, the input buffer contains all remaining input. +// TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large enough to hold the entire decompressed stream. If clear, the output buffer is at least the size of the dictionary (typically 32KB). +// TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes. + enum + { + TINFL_FLAG_PARSE_ZLIB_HEADER = 1, + TINFL_FLAG_HAS_MORE_INPUT = 2, + TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4, + TINFL_FLAG_COMPUTE_ADLER32 = 8 + }; + +// High level decompression functions: +// tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block allocated via malloc(). +// On entry: +// pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress. +// On return: +// Function returns a pointer to the decompressed data, or NULL on failure. +// *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on uncompressible data. +// The caller must free() the returned block when it's no longer needed. + void *tinfl_decompress_mem_to_heap (const void *pSrc_buf, + size_t src_buf_len, size_t * pOut_len, + int flags); + +// tinfl_decompress_mem_to_mem() decompresses a block in memory to another block in memory. +// Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success. +#define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1)) + size_t tinfl_decompress_mem_to_mem (void *pOut_buf, size_t out_buf_len, + const void *pSrc_buf, + size_t src_buf_len, int flags); + +// tinfl_decompress_mem_to_callback() decompresses a block in memory to an internal 32KB buffer, and a user provided callback function will be called to flush the buffer. +// Returns 1 on success or 0 on failure. + typedef int (*tinfl_put_buf_func_ptr) (const void *pBuf, int len, + void *pUser); + int tinfl_decompress_mem_to_callback (const void *pIn_buf, + size_t * pIn_buf_size, + tinfl_put_buf_func_ptr pPut_buf_func, + void *pPut_buf_user, int flags); + + struct tinfl_decompressor_tag; + typedef struct tinfl_decompressor_tag tinfl_decompressor; + +// Max size of LZ dictionary. +#define TINFL_LZ_DICT_SIZE 32768 + +// Return status. + typedef enum + { + TINFL_STATUS_BAD_PARAM = -3, + TINFL_STATUS_ADLER32_MISMATCH = -2, + TINFL_STATUS_FAILED = -1, + TINFL_STATUS_DONE = 0, + TINFL_STATUS_NEEDS_MORE_INPUT = 1, + TINFL_STATUS_HAS_MORE_OUTPUT = 2 + } tinfl_status; + +// Initializes the decompressor to its initial state. +#define tinfl_init(r) do { (r)->m_state = 0; } MZ_MACRO_END +#define tinfl_get_adler32(r) (r)->m_check_adler32 + +// Main low-level decompressor coroutine function. This is the only function actually needed for decompression. All the other functions are just high-level helpers for improved usability. +// This is a universal API, i.e. it can be used as a building block to build any desired higher level decompression API. In the limit case, it can be called once per every byte input or output. + tinfl_status tinfl_decompress (tinfl_decompressor * r, + const mz_uint8 * pIn_buf_next, + size_t * pIn_buf_size, + mz_uint8 * pOut_buf_start, + mz_uint8 * pOut_buf_next, + size_t * pOut_buf_size, + const mz_uint32 decomp_flags); + +// Internal/private bits follow. + enum + { + TINFL_MAX_HUFF_TABLES = 3, TINFL_MAX_HUFF_SYMBOLS_0 = + 288, TINFL_MAX_HUFF_SYMBOLS_1 = 32, TINFL_MAX_HUFF_SYMBOLS_2 = 19, + TINFL_FAST_LOOKUP_BITS = 10, TINFL_FAST_LOOKUP_SIZE = + 1 << TINFL_FAST_LOOKUP_BITS + }; + + typedef struct + { + mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0]; + mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], + m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2]; + } tinfl_huff_table; + +#if MINIZ_HAS_64BIT_REGISTERS +#define TINFL_USE_64BIT_BITBUF 1 +#endif + +#if TINFL_USE_64BIT_BITBUF + typedef mz_uint64 tinfl_bit_buf_t; +#define TINFL_BITBUF_SIZE (64) +#else + typedef mz_uint32 tinfl_bit_buf_t; +#define TINFL_BITBUF_SIZE (32) +#endif + + struct tinfl_decompressor_tag + { + mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, + m_type, m_check_adler32, m_dist, m_counter, m_num_extra, + m_table_sizes[TINFL_MAX_HUFF_TABLES]; + tinfl_bit_buf_t m_bit_buf; + size_t m_dist_from_out_buf_start; + tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES]; + mz_uint8 m_raw_header[4], + m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137]; + }; + +// ------------------- Low-level Compression API Definitions + +// Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly slower, and raw/dynamic blocks will be output more frequently). +#define TDEFL_LESS_MEMORY 0 + +// tdefl_init() compression flags logically OR'd together (low 12 bits contain the max. number of probes per dictionary search): +// TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap compression), 4095=Huffman+LZ (slowest/best compression). + enum + { + TDEFL_HUFFMAN_ONLY = 0, TDEFL_DEFAULT_MAX_PROBES = + 128, TDEFL_MAX_PROBES_MASK = 0xFFF + }; + +// TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before the deflate data, and the Adler-32 of the source data at the end. Otherwise, you'll get raw deflate data. +// TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even when not writing zlib headers). +// TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more efficient lazy parsing. +// TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's initialization time to the minimum, but the output may vary from run to run given the same input (depending on the contents of memory). +// TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1) +// TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled. +// TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables. +// TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks. + enum + { + TDEFL_WRITE_ZLIB_HEADER = 0x01000, + TDEFL_COMPUTE_ADLER32 = 0x02000, + TDEFL_GREEDY_PARSING_FLAG = 0x04000, + TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000, + TDEFL_RLE_MATCHES = 0x10000, + TDEFL_FILTER_MATCHES = 0x20000, + TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000, + TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000 + }; + +// High level compression functions: +// tdefl_compress_mem_to_heap() compresses a block in memory to a heap block allocated via malloc(). +// On entry: +// pSrc_buf, src_buf_len: Pointer and size of source block to compress. +// flags: The max match finder probes (default is 128) logically OR'd against the above flags. Higher probes are slower but improve compression. +// On return: +// Function returns a pointer to the compressed data, or NULL on failure. +// *pOut_len will be set to the compressed data's size, which could be larger than src_buf_len on uncompressible data. +// The caller must free() the returned block when it's no longer needed. + void *tdefl_compress_mem_to_heap (const void *pSrc_buf, size_t src_buf_len, + size_t * pOut_len, int flags); + +// tdefl_compress_mem_to_mem() compresses a block in memory to another block in memory. +// Returns 0 on failure. + size_t tdefl_compress_mem_to_mem (void *pOut_buf, size_t out_buf_len, + const void *pSrc_buf, size_t src_buf_len, + int flags); + +// Compresses an image to a compressed PNG file in memory. +// On entry: +// pImage, w, h, and num_chans describe the image to compress. num_chans may be 1, 2, 3, or 4. +// On return: +// Function returns a pointer to the compressed data, or NULL on failure. +// *pLen_out will be set to the size of the PNG image file. +// The caller must free() the returned heap block (which will typically be larger than *pLen_out) when it's no longer needed. + void *tdefl_write_image_to_png_file_in_memory (const void *pImage, int w, + int h, int num_chans, + size_t * pLen_out); + +// Output stream interface. The compressor uses this interface to write compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time. + typedef mz_bool (*tdefl_put_buf_func_ptr) (const void *pBuf, int len, + void *pUser); + +// tdefl_compress_mem_to_output() compresses a block to an output stream. The above helpers use this function internally. + mz_bool tdefl_compress_mem_to_output (const void *pBuf, size_t buf_len, + tdefl_put_buf_func_ptr pPut_buf_func, + void *pPut_buf_user, int flags); + + enum + { TDEFL_MAX_HUFF_TABLES = 3, TDEFL_MAX_HUFF_SYMBOLS_0 = + 288, TDEFL_MAX_HUFF_SYMBOLS_1 = 32, TDEFL_MAX_HUFF_SYMBOLS_2 = + 19, TDEFL_LZ_DICT_SIZE = 32768, TDEFL_LZ_DICT_SIZE_MASK = + TDEFL_LZ_DICT_SIZE - 1, TDEFL_MIN_MATCH_LEN = 3, TDEFL_MAX_MATCH_LEN = + 258 + }; + +// TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed output block (using static/fixed Huffman codes). +#if TDEFL_LESS_MEMORY + enum + { TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024, TDEFL_OUT_BUF_SIZE = + (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, TDEFL_MAX_HUFF_SYMBOLS = + 288, TDEFL_LZ_HASH_BITS = 12, TDEFL_LEVEL1_HASH_SIZE_MASK = + 4095, TDEFL_LZ_HASH_SHIFT = + (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = + 1 << TDEFL_LZ_HASH_BITS + }; +#else + enum + { TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, TDEFL_OUT_BUF_SIZE = + (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, TDEFL_MAX_HUFF_SYMBOLS = + 288, TDEFL_LZ_HASH_BITS = 15, TDEFL_LEVEL1_HASH_SIZE_MASK = + 4095, TDEFL_LZ_HASH_SHIFT = + (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = + 1 << TDEFL_LZ_HASH_BITS + }; +#endif + +// The low-level tdefl functions below may be used directly if the above helper functions aren't flexible enough. The low-level functions don't make any heap allocations, unlike the above helper functions. + typedef enum + { + TDEFL_STATUS_BAD_PARAM = -2, + TDEFL_STATUS_PUT_BUF_FAILED = -1, + TDEFL_STATUS_OKAY = 0, + TDEFL_STATUS_DONE = 1, + } tdefl_status; + +// Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums + typedef enum + { + TDEFL_NO_FLUSH = 0, + TDEFL_SYNC_FLUSH = 2, + TDEFL_FULL_FLUSH = 3, + TDEFL_FINISH = 4 + } tdefl_flush; + +// tdefl's compression state structure. + typedef struct + { + tdefl_put_buf_func_ptr m_pPut_buf_func; + void *m_pPut_buf_user; + mz_uint m_flags, m_max_probes[2]; + int m_greedy_parsing; + mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size; + mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, + *m_pOutput_buf_end; + mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, + m_bits_in, m_bit_buffer; + mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, + m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, + m_wants_to_finish; + tdefl_status m_prev_return_status; + const void *m_pIn_buf; + void *m_pOut_buf; + size_t *m_pIn_buf_size, *m_pOut_buf_size; + tdefl_flush m_flush; + const mz_uint8 *m_pSrc; + size_t m_src_buf_left, m_out_buf_ofs; + mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1]; + mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE]; + mz_uint16 m_next[TDEFL_LZ_DICT_SIZE]; + mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE]; + mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE]; + } tdefl_compressor; + +// Initializes the compressor. +// There is no corresponding deinit() function because the tdefl API's do not dynamically allocate memory. +// pBut_buf_func: If NULL, output data will be supplied to the specified callback. In this case, the user should call the tdefl_compress_buffer() API for compression. +// If pBut_buf_func is NULL the user should always call the tdefl_compress() API. +// flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, etc.) + tdefl_status tdefl_init (tdefl_compressor * d, + tdefl_put_buf_func_ptr pPut_buf_func, + void *pPut_buf_user, int flags); + +// Compresses a block of data, consuming as much of the specified input buffer as possible, and writing as much compressed data to the specified output buffer as possible. + tdefl_status tdefl_compress (tdefl_compressor * d, const void *pIn_buf, + size_t * pIn_buf_size, void *pOut_buf, + size_t * pOut_buf_size, tdefl_flush flush); + +// tdefl_compress_buffer() is only usable when the tdefl_init() is called with a non-NULL tdefl_put_buf_func_ptr. +// tdefl_compress_buffer() always consumes the entire input buffer. + tdefl_status tdefl_compress_buffer (tdefl_compressor * d, + const void *pIn_buf, size_t in_buf_size, + tdefl_flush flush); + + tdefl_status tdefl_get_prev_return_status (tdefl_compressor * d); + mz_uint32 tdefl_get_adler32 (tdefl_compressor * d); + +// Create tdefl_compress() flags given zlib-style compression parameters. +// level may range from [0,10] (where 10 is absolute max compression, but may be much slower on some files) +// window_bits may be -15 (raw deflate) or 15 (zlib) +// strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, MZ_RLE, or MZ_FIXED + mz_uint tdefl_create_comp_flags_from_zip_params (int level, int window_bits, + int strategy); + +#ifdef __cplusplus +} +#endif + +#endif // MINIZ_HEADER_INCLUDED + +// ------------------- End of Header: Implementation follows. (If you only want the header, define MINIZ_HEADER_FILE_ONLY.) + +#ifndef MINIZ_HEADER_FILE_ONLY + +typedef unsigned char mz_validate_uint16[sizeof (mz_uint16) == 2 ? 1 : -1]; +typedef unsigned char mz_validate_uint32[sizeof (mz_uint32) == 4 ? 1 : -1]; +typedef unsigned char mz_validate_uint64[sizeof (mz_uint64) == 8 ? 1 : -1]; + +#include +#include + +#define MZ_ASSERT(x) assert(x) + +#ifdef MINIZ_NO_MALLOC +#define MZ_MALLOC(x) NULL +#define MZ_FREE(x) x, ((void)0) +#define MZ_REALLOC(p, x) NULL +#else +#define MZ_MALLOC(x) malloc(x) +#define MZ_FREE(x) free(x) +#define MZ_REALLOC(p, x) realloc(p, x) +#endif + +#define MZ_MAX(a,b) (((a)>(b))?(a):(b)) +#define MZ_MIN(a,b) (((a)<(b))?(a):(b)) +#define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj)) + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN +#define MZ_READ_LE16(p) *((const mz_uint16 *)(p)) +#define MZ_READ_LE32(p) *((const mz_uint32 *)(p)) +#else +#define MZ_READ_LE16(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U)) +#define MZ_READ_LE32(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U)) +#endif + +#if !defined(_MSC_VER) && !defined(__MINGW32__) && !defined(__MINGW64__) && !defined(__forceinline) +#ifdef __cplusplus +#define __forceinline inline +#else +#define __forceinline +#endif +#endif + +#ifdef __cplusplus +extern "C" +{ +#endif + +// ------------------- zlib-style API's + + static void *def_alloc_func (void *opaque, size_t items, size_t size) + { + (void) opaque; + return MZ_MALLOC (items * size); + } + static void def_free_func (void *opaque, void *address) + { + (void) opaque, MZ_FREE (address); + } + static void *def_realloc_func (void *opaque, void *address, size_t items, + size_t size) + { + (void) opaque; + return MZ_REALLOC (address, items * size); + } + + mz_ulong mz_adler32 (mz_ulong adler, const unsigned char *ptr, + size_t buf_len) + { + mz_uint32 i, s1 = (mz_uint32) (adler & 0xffff), s2 = + (mz_uint32) (adler >> 16); + size_t block_len = buf_len % 5552; + if (!ptr) + return MZ_ADLER32_INIT; + while (buf_len) + { + for (i = 0; i + 7 < block_len; i += 8, ptr += 8) + { + s1 += ptr[0], s2 += s1; + s1 += ptr[1], s2 += s1; + s1 += ptr[2], s2 += s1; + s1 += ptr[3], s2 += s1; + s1 += ptr[4], s2 += s1; + s1 += ptr[5], s2 += s1; + s1 += ptr[6], s2 += s1; + s1 += ptr[7], s2 += s1; + } + for (; i < block_len; ++i) + s1 += *ptr++, s2 += s1; + s1 %= 65521U, s2 %= 65521U; + buf_len -= block_len; + block_len = 5552; + } + return (s2 << 16) + s1; + } + +// Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C implementation that balances processor cache usage against speed": http://www.geocities.com/malbrain/ + mz_ulong mz_crc32 (mz_ulong crc, const mz_uint8 * ptr, size_t buf_len) + { + static const mz_uint32 s_crc32[16] = + { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, + 0x4db26158, 0x5005713c, + 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, + 0xa00ae278, 0xbdbdf21c + }; + if (!ptr) + return MZ_CRC32_INIT; + crc = ~crc; + while (buf_len--) + { + mz_uint8 b = *ptr++; + crc = (crc >> 4) ^ s_crc32[(crc & 0xF) ^ (b & 0xF)]; + crc = (crc >> 4) ^ s_crc32[(crc & 0xF) ^ (b >> 4)]; + } + return ~crc; + } + +#ifndef MINIZ_NO_ZLIB_APIS + + const char *mz_version (void) + { + return MZ_VERSION; + } + + int mz_deflateInit (mz_streamp pStream, int level) + { + return mz_deflateInit2 (pStream, level, MZ_DEFLATED, + MZ_DEFAULT_WINDOW_BITS, 9, MZ_DEFAULT_STRATEGY); + } + + int mz_deflateInit2 (mz_streamp pStream, int level, int method, + int window_bits, int mem_level, int strategy) + { + tdefl_compressor *pComp; + mz_uint comp_flags = + TDEFL_COMPUTE_ADLER32 | tdefl_create_comp_flags_from_zip_params (level, + window_bits, + strategy); + + if (!pStream) + return MZ_STREAM_ERROR; + if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) + || ((window_bits != MZ_DEFAULT_WINDOW_BITS) + && (-window_bits != MZ_DEFAULT_WINDOW_BITS))) + return MZ_PARAM_ERROR; + + pStream->data_type = 0; + pStream->adler = MZ_ADLER32_INIT; + pStream->msg = NULL; + pStream->reserved = 0; + pStream->total_in = 0; + pStream->total_out = 0; + if (!pStream->zalloc) + pStream->zalloc = def_alloc_func; + if (!pStream->zfree) + pStream->zfree = def_free_func; + + pComp = + (tdefl_compressor *) pStream->zalloc (pStream->opaque, 1, + sizeof (tdefl_compressor)); + if (!pComp) + return MZ_MEM_ERROR; + + pStream->state = (struct mz_internal_state *) pComp; + + if (tdefl_init (pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY) + { + mz_deflateEnd (pStream); + return MZ_PARAM_ERROR; + } + + return MZ_OK; + } + + int mz_deflateReset (mz_streamp pStream) + { + if ((!pStream) || (!pStream->state) || (!pStream->zalloc) + || (!pStream->zfree)) + return MZ_STREAM_ERROR; + pStream->total_in = pStream->total_out = 0; + tdefl_init ((tdefl_compressor *) pStream->state, NULL, NULL, + ((tdefl_compressor *) pStream->state)->m_flags); + return MZ_OK; + } + + int mz_deflate (mz_streamp pStream, int flush) + { + size_t in_bytes, out_bytes; + mz_ulong orig_total_in, orig_total_out; + int mz_status = MZ_OK; + + if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) + || (!pStream->next_out)) + return MZ_STREAM_ERROR; + if (!pStream->avail_out) + return MZ_BUF_ERROR; + + if (flush == MZ_PARTIAL_FLUSH) + flush = MZ_SYNC_FLUSH; + + if (((tdefl_compressor *) pStream->state)->m_prev_return_status == + TDEFL_STATUS_DONE) + return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR; + + orig_total_in = pStream->total_in; + orig_total_out = pStream->total_out; + for (;;) + { + tdefl_status defl_status; + in_bytes = pStream->avail_in; + out_bytes = pStream->avail_out; + + defl_status = + tdefl_compress ((tdefl_compressor *) pStream->state, + pStream->next_in, &in_bytes, pStream->next_out, + &out_bytes, (tdefl_flush) flush); + pStream->next_in += (mz_uint) in_bytes; + pStream->avail_in -= (mz_uint) in_bytes; + pStream->total_in += (mz_uint) in_bytes; + pStream->adler = + tdefl_get_adler32 ((tdefl_compressor *) pStream->state); + + pStream->next_out += (mz_uint) out_bytes; + pStream->avail_out -= (mz_uint) out_bytes; + pStream->total_out += (mz_uint) out_bytes; + + if (defl_status < 0) + { + mz_status = MZ_STREAM_ERROR; + break; + } + else if (defl_status == TDEFL_STATUS_DONE) + { + mz_status = MZ_STREAM_END; + break; + } + else if (!pStream->avail_out) + break; + else if ((!pStream->avail_in) && (flush != MZ_FINISH)) + { + if ((flush) || (pStream->total_in != orig_total_in) + || (pStream->total_out != orig_total_out)) + break; + return MZ_BUF_ERROR; // Can't make forward progress without some input. + } + } + return mz_status; + } + + int mz_deflateEnd (mz_streamp pStream) + { + if (!pStream) + return MZ_STREAM_ERROR; + if (pStream->state) + { + pStream->zfree (pStream->opaque, pStream->state); + pStream->state = NULL; + } + return MZ_OK; + } + + mz_ulong mz_deflateBound (mz_streamp pStream, mz_ulong source_len) + { + // This is really over conservative. (And lame, but it's actually pretty tricky to compute a true upper bound given the way tdefl's blocking works.) + return MZ_MAX (128 + (source_len * 110) / 100, + 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5); + } + + int mz_compress2 (unsigned char *pDest, mz_ulong * pDest_len, + const unsigned char *pSource, mz_ulong source_len, + int level) + { + int status; + mz_stream stream; + memset (&stream, 0, sizeof (stream)); + + // In case mz_ulong is 64-bits (argh I hate longs). + if ((source_len | *pDest_len) > 0xFFFFFFFFU) + return MZ_PARAM_ERROR; + + stream.next_in = pSource; + stream.avail_in = (mz_uint32) source_len; + stream.next_out = pDest; + stream.avail_out = (mz_uint32) * pDest_len; + + status = mz_deflateInit (&stream, level); + if (status != MZ_OK) + return status; + + status = mz_deflate (&stream, MZ_FINISH); + if (status != MZ_STREAM_END) + { + mz_deflateEnd (&stream); + return (status == MZ_OK) ? MZ_BUF_ERROR : status; + } + + *pDest_len = stream.total_out; + return mz_deflateEnd (&stream); + } + + int mz_compress (unsigned char *pDest, mz_ulong * pDest_len, + const unsigned char *pSource, mz_ulong source_len) + { + return mz_compress2 (pDest, pDest_len, pSource, source_len, + MZ_DEFAULT_COMPRESSION); + } + + mz_ulong mz_compressBound (mz_ulong source_len) + { + return mz_deflateBound (NULL, source_len); + } + + typedef struct + { + tinfl_decompressor m_decomp; + mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed; + int m_window_bits; + mz_uint8 m_dict[TINFL_LZ_DICT_SIZE]; + tinfl_status m_last_status; + } inflate_state; + + int mz_inflateInit2 (mz_streamp pStream, int window_bits) + { + inflate_state *pDecomp; + if (!pStream) + return MZ_STREAM_ERROR; + if ((window_bits != MZ_DEFAULT_WINDOW_BITS) + && (-window_bits != MZ_DEFAULT_WINDOW_BITS)) + return MZ_PARAM_ERROR; + + pStream->data_type = 0; + pStream->adler = 0; + pStream->msg = NULL; + pStream->total_in = 0; + pStream->total_out = 0; + pStream->reserved = 0; + if (!pStream->zalloc) + pStream->zalloc = def_alloc_func; + if (!pStream->zfree) + pStream->zfree = def_free_func; + + pDecomp = + (inflate_state *) pStream->zalloc (pStream->opaque, 1, + sizeof (inflate_state)); + if (!pDecomp) + return MZ_MEM_ERROR; + + pStream->state = (struct mz_internal_state *) pDecomp; + + tinfl_init (&pDecomp->m_decomp); + pDecomp->m_dict_ofs = 0; + pDecomp->m_dict_avail = 0; + pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT; + pDecomp->m_first_call = 1; + pDecomp->m_has_flushed = 0; + pDecomp->m_window_bits = window_bits; + + return MZ_OK; + } + + int mz_inflateInit (mz_streamp pStream) + { + return mz_inflateInit2 (pStream, MZ_DEFAULT_WINDOW_BITS); + } + + int mz_inflate (mz_streamp pStream, int flush) + { + inflate_state *pState; + mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32; + size_t in_bytes, out_bytes, orig_avail_in; + tinfl_status status; + + if ((!pStream) || (!pStream->state)) + return MZ_STREAM_ERROR; + if (flush == MZ_PARTIAL_FLUSH) + flush = MZ_SYNC_FLUSH; + if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH)) + return MZ_STREAM_ERROR; + + pState = (inflate_state *) pStream->state; + if (pState->m_window_bits > 0) + decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER; + orig_avail_in = pStream->avail_in; + + first_call = pState->m_first_call; + pState->m_first_call = 0; + if (pState->m_last_status < 0) + return MZ_DATA_ERROR; + + if (pState->m_has_flushed && (flush != MZ_FINISH)) + return MZ_STREAM_ERROR; + pState->m_has_flushed |= (flush == MZ_FINISH); + + if ((flush == MZ_FINISH) && (first_call)) + { + // MZ_FINISH on the first call implies that the input and output buffers are large enough to hold the entire compressed/decompressed file. + decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF; + in_bytes = pStream->avail_in; + out_bytes = pStream->avail_out; + status = + tinfl_decompress (&pState->m_decomp, pStream->next_in, &in_bytes, + pStream->next_out, pStream->next_out, &out_bytes, + decomp_flags); + pState->m_last_status = status; + pStream->next_in += (mz_uint) in_bytes; + pStream->avail_in -= (mz_uint) in_bytes; + pStream->total_in += (mz_uint) in_bytes; + pStream->adler = tinfl_get_adler32 (&pState->m_decomp); + pStream->next_out += (mz_uint) out_bytes; + pStream->avail_out -= (mz_uint) out_bytes; + pStream->total_out += (mz_uint) out_bytes; + + if (status < 0) + return MZ_DATA_ERROR; + else if (status != TINFL_STATUS_DONE) + { + pState->m_last_status = TINFL_STATUS_FAILED; + return MZ_BUF_ERROR; + } + return MZ_STREAM_END; + } + // flush != MZ_FINISH then we must assume there's more input. + if (flush != MZ_FINISH) + decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT; + + if (pState->m_dict_avail) + { + n = MZ_MIN (pState->m_dict_avail, pStream->avail_out); + memcpy (pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); + pStream->next_out += n; + pStream->avail_out -= n; + pStream->total_out += n; + pState->m_dict_avail -= n; + pState->m_dict_ofs = + (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); + return ((pState->m_last_status == TINFL_STATUS_DONE) + && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; + } + + for (;;) + { + in_bytes = pStream->avail_in; + out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs; + + status = + tinfl_decompress (&pState->m_decomp, pStream->next_in, &in_bytes, + pState->m_dict, + pState->m_dict + pState->m_dict_ofs, &out_bytes, + decomp_flags); + pState->m_last_status = status; + + pStream->next_in += (mz_uint) in_bytes; + pStream->avail_in -= (mz_uint) in_bytes; + pStream->total_in += (mz_uint) in_bytes; + pStream->adler = tinfl_get_adler32 (&pState->m_decomp); + + pState->m_dict_avail = (mz_uint) out_bytes; + + n = MZ_MIN (pState->m_dict_avail, pStream->avail_out); + memcpy (pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); + pStream->next_out += n; + pStream->avail_out -= n; + pStream->total_out += n; + pState->m_dict_avail -= n; + pState->m_dict_ofs = + (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); + + if (status < 0) + return MZ_DATA_ERROR; // Stream is corrupted (there could be some uncompressed data left in the output dictionary - oh well). + else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) + && (!orig_avail_in)) + return MZ_BUF_ERROR; // Signal caller that we can't make forward progress without supplying more input or by setting flush to MZ_FINISH. + else if (flush == MZ_FINISH) + { + // The output buffer MUST be large to hold the remaining uncompressed data when flush==MZ_FINISH. + if (status == TINFL_STATUS_DONE) + return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END; + // status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's at least 1 more byte on the way. If there's no more room left in the output buffer then something is wrong. + else if (!pStream->avail_out) + return MZ_BUF_ERROR; + } + else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) + || (!pStream->avail_out) || (pState->m_dict_avail)) + break; + } + + return ((status == TINFL_STATUS_DONE) + && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; + } + + int mz_inflateEnd (mz_streamp pStream) + { + if (!pStream) + return MZ_STREAM_ERROR; + if (pStream->state) + { + pStream->zfree (pStream->opaque, pStream->state); + pStream->state = NULL; + } + return MZ_OK; + } + + int mz_uncompress (unsigned char *pDest, mz_ulong * pDest_len, + const unsigned char *pSource, mz_ulong source_len) + { + mz_stream stream; + int status; + memset (&stream, 0, sizeof (stream)); + + // In case mz_ulong is 64-bits (argh I hate longs). + if ((source_len | *pDest_len) > 0xFFFFFFFFU) + return MZ_PARAM_ERROR; + + stream.next_in = pSource; + stream.avail_in = (mz_uint32) source_len; + stream.next_out = pDest; + stream.avail_out = (mz_uint32) * pDest_len; + + status = mz_inflateInit (&stream); + if (status != MZ_OK) + return status; + + status = mz_inflate (&stream, MZ_FINISH); + if (status != MZ_STREAM_END) + { + mz_inflateEnd (&stream); + return ((status == MZ_BUF_ERROR) + && (!stream.avail_in)) ? MZ_DATA_ERROR : status; + } + *pDest_len = stream.total_out; + + return mz_inflateEnd (&stream); + } + + const char *mz_error (int err) + { + static struct + { + int m_err; + const char *m_pDesc; + } s_error_descs[] = + { + { + MZ_OK, ""}, + { + MZ_STREAM_END, "stream end"}, + { + MZ_NEED_DICT, "need dictionary"}, + { + MZ_ERRNO, "file error"}, + { + MZ_STREAM_ERROR, "stream error"}, + { + MZ_DATA_ERROR, "data error"}, + { + MZ_MEM_ERROR, "out of memory"}, + { + MZ_BUF_ERROR, "buf error"}, + { + MZ_VERSION_ERROR, "version error"}, + { + MZ_PARAM_ERROR, "parameter error"} + }; + mz_uint i; + for (i = 0; i < sizeof (s_error_descs) / sizeof (s_error_descs[0]); ++i) + if (s_error_descs[i].m_err == err) + return s_error_descs[i].m_pDesc; + return NULL; + } + +#endif //MINIZ_NO_ZLIB_APIS + +// ------------------- Low-level Decompression (completely independent from all compression API's) + +#define TINFL_MEMCPY(d, s, l) memcpy(d, s, l) +#define TINFL_MEMSET(p, c, l) memset(p, c, l) + +#define TINFL_CR_BEGIN switch(r->m_state) { case 0: +#define TINFL_CR_RETURN(state_index, result) do { status = result; r->m_state = state_index; goto common_exit; case state_index:; } MZ_MACRO_END +#define TINFL_CR_RETURN_FOREVER(state_index, result) do { for ( ; ; ) { TINFL_CR_RETURN(state_index, result); } } MZ_MACRO_END +#define TINFL_CR_FINISH } + +// TODO: If the caller has indicated that there's no more input, and we attempt to read beyond the input buf, then something is wrong with the input because the inflator never +// reads ahead more than it needs to. Currently TINFL_GET_BYTE() pads the end of the stream with 0's in this scenario. +#define TINFL_GET_BYTE(state_index, c) do { \ + if (pIn_buf_cur >= pIn_buf_end) { \ + for ( ; ; ) { \ + if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { \ + TINFL_CR_RETURN(state_index, TINFL_STATUS_NEEDS_MORE_INPUT); \ + if (pIn_buf_cur < pIn_buf_end) { \ + c = *pIn_buf_cur++; \ + break; \ + } \ + } else { \ + c = 0; \ + break; \ + } \ + } \ + } else c = *pIn_buf_cur++; } MZ_MACRO_END + +#define TINFL_NEED_BITS(state_index, n) do { mz_uint c; TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; } while (num_bits < (mz_uint)(n)) +#define TINFL_SKIP_BITS(state_index, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END +#define TINFL_GET_BITS(state_index, b, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } b = bit_buf & ((1 << (n)) - 1); bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END + +// TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes remaining in the input buffer falls below 2. +// It reads just enough bytes from the input stream that are needed to decode the next Huffman code (and absolutely no more). It works by trying to fully decode a +// Huffman code by using whatever bits are currently present in the bit buffer. If this fails, it reads another byte, and tries again until it succeeds or until the +// bit buffer contains >=15 bits (deflate's max. Huffman code size). +#define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \ + do { \ + temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \ + if (temp >= 0) { \ + code_len = temp >> 9; \ + if ((code_len) && (num_bits >= code_len)) \ + break; \ + } else if (num_bits > TINFL_FAST_LOOKUP_BITS) { \ + code_len = TINFL_FAST_LOOKUP_BITS; \ + do { \ + temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ + } while ((temp < 0) && (num_bits >= (code_len + 1))); if (temp >= 0) break; \ + } TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; \ + } while (num_bits < 15); + +// TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex than you would initially expect because the zlib API expects the decompressor to never read +// beyond the final byte of the deflate stream. (In other words, when this macro wants to read another byte from the input, it REALLY needs another byte in order to fully +// decode the next Huffman code.) Handling this properly is particularly important on raw deflate (non-zlib) streams, which aren't followed by a byte aligned adler-32. +// The slow path is only executed at the very end of the input buffer. +#define TINFL_HUFF_DECODE(state_index, sym, pHuff) do { \ + int temp; mz_uint code_len, c; \ + if (num_bits < 15) { \ + if ((pIn_buf_end - pIn_buf_cur) < 2) { \ + TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \ + } else { \ + bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); pIn_buf_cur += 2; num_bits += 16; \ + } \ + } \ + if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) \ + code_len = temp >> 9, temp &= 511; \ + else { \ + code_len = TINFL_FAST_LOOKUP_BITS; do { temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; } while (temp < 0); \ + } sym = temp; bit_buf >>= code_len; num_bits -= code_len; } MZ_MACRO_END + + tinfl_status tinfl_decompress (tinfl_decompressor * r, + const mz_uint8 * pIn_buf_next, + size_t * pIn_buf_size, + mz_uint8 * pOut_buf_start, + mz_uint8 * pOut_buf_next, + size_t * pOut_buf_size, + const mz_uint32 decomp_flags) + { + static const int s_length_base[31] = + { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, + 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 + }; + static const int s_length_extra[31] = + { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, + 4, 5, 5, 5, 5, 0, 0, 0 + }; + static const int s_dist_base[32] = + { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, + 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, + 0, 0 + }; + static const int s_dist_extra[32] = + { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, + 10, 11, 11, 12, 12, 13, 13 + }; + static const mz_uint8 s_length_dezigzag[19] = + { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; + static const int s_min_table_sizes[3] = { 257, 1, 4 }; + + tinfl_status status = TINFL_STATUS_FAILED; + mz_uint32 num_bits, dist, counter, num_extra; + tinfl_bit_buf_t bit_buf; + const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = + pIn_buf_next + *pIn_buf_size; + mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = + pOut_buf_next + *pOut_buf_size; + size_t out_buf_size_mask = + (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF) ? (size_t) - + 1 : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, + dist_from_out_buf_start; + + // Ensure the output buffer's size is a power of 2, unless the output buffer is large enough to hold the entire output file (in which case it doesn't matter). + if (((out_buf_size_mask + 1) & out_buf_size_mask) + || (pOut_buf_next < pOut_buf_start)) + { + *pIn_buf_size = *pOut_buf_size = 0; + return TINFL_STATUS_BAD_PARAM; + } + + num_bits = r->m_num_bits; + bit_buf = r->m_bit_buf; + dist = r->m_dist; + counter = r->m_counter; + num_extra = r->m_num_extra; + dist_from_out_buf_start = r->m_dist_from_out_buf_start; + TINFL_CR_BEGIN + bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = + r->m_zhdr1 = 0; + r->m_z_adler32 = r->m_check_adler32 = 1; + if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) + { + TINFL_GET_BYTE (1, r->m_zhdr0); + TINFL_GET_BYTE (2, r->m_zhdr1); + counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) + || (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8)); + if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) + counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) + || ((out_buf_size_mask + 1) < + (size_t) (1U << (8U + (r->m_zhdr0 >> 4))))); + if (counter) + { + TINFL_CR_RETURN_FOREVER (36, TINFL_STATUS_FAILED); + } + } + + do + { + TINFL_GET_BITS (3, r->m_final, 3); + r->m_type = r->m_final >> 1; + if (r->m_type == 0) + { + TINFL_SKIP_BITS (5, num_bits & 7); + for (counter = 0; counter < 4; ++counter) + { + if (num_bits) + TINFL_GET_BITS (6, r->m_raw_header[counter], 8); + else + TINFL_GET_BYTE (7, r->m_raw_header[counter]); + } + if ((counter = + (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != + (mz_uint) (0xFFFF ^ + (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) + { + TINFL_CR_RETURN_FOREVER (39, TINFL_STATUS_FAILED); + } + while ((counter) && (num_bits)) + { + TINFL_GET_BITS (51, dist, 8); + while (pOut_buf_cur >= pOut_buf_end) + { + TINFL_CR_RETURN (52, TINFL_STATUS_HAS_MORE_OUTPUT); + } + *pOut_buf_cur++ = (mz_uint8) dist; + counter--; + } + while (counter) + { + size_t n; + while (pOut_buf_cur >= pOut_buf_end) + { + TINFL_CR_RETURN (9, TINFL_STATUS_HAS_MORE_OUTPUT); + } + while (pIn_buf_cur >= pIn_buf_end) + { + if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) + { + TINFL_CR_RETURN (38, TINFL_STATUS_NEEDS_MORE_INPUT); + } + else + { + TINFL_CR_RETURN_FOREVER (40, TINFL_STATUS_FAILED); + } + } + n = + MZ_MIN (MZ_MIN + ((size_t) (pOut_buf_end - pOut_buf_cur), + (size_t) (pIn_buf_end - pIn_buf_cur)), counter); + TINFL_MEMCPY (pOut_buf_cur, pIn_buf_cur, n); + pIn_buf_cur += n; + pOut_buf_cur += n; + counter -= (mz_uint) n; + } + } + else if (r->m_type == 3) + { + TINFL_CR_RETURN_FOREVER (10, TINFL_STATUS_FAILED); + } + else + { + if (r->m_type == 1) + { + mz_uint8 *p = r->m_tables[0].m_code_size; + mz_uint i; + r->m_table_sizes[0] = 288; + r->m_table_sizes[1] = 32; + TINFL_MEMSET (r->m_tables[1].m_code_size, 5, 32); + for (i = 0; i <= 143; ++i) + *p++ = 8; + for (; i <= 255; ++i) + *p++ = 9; + for (; i <= 279; ++i) + *p++ = 7; + for (; i <= 287; ++i) + *p++ = 8; + } + else + { + for (counter = 0; counter < 3; counter++) + { + TINFL_GET_BITS (11, r->m_table_sizes[counter], + "\05\05\04"[counter]); + r->m_table_sizes[counter] += s_min_table_sizes[counter]; + } + MZ_CLEAR_OBJ (r->m_tables[2].m_code_size); + for (counter = 0; counter < r->m_table_sizes[2]; counter++) + { + mz_uint s; + TINFL_GET_BITS (14, s, 3); + r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = + (mz_uint8) s; + } + r->m_table_sizes[2] = 19; + } + for (; (int) r->m_type >= 0; r->m_type--) + { + int tree_next, tree_cur; + tinfl_huff_table *pTable; + mz_uint i, j, used_syms, total, sym_index, next_code[17], + total_syms[16]; + pTable = &r->m_tables[r->m_type]; + MZ_CLEAR_OBJ (total_syms); + MZ_CLEAR_OBJ (pTable->m_look_up); + MZ_CLEAR_OBJ (pTable->m_tree); + for (i = 0; i < r->m_table_sizes[r->m_type]; ++i) + total_syms[pTable->m_code_size[i]]++; + used_syms = 0, total = 0; + next_code[0] = next_code[1] = 0; + for (i = 1; i <= 15; ++i) + { + used_syms += total_syms[i]; + next_code[i + 1] = (total = + ((total + total_syms[i]) << 1)); + } + if ((65536 != total) && (used_syms > 1)) + { + TINFL_CR_RETURN_FOREVER (35, TINFL_STATUS_FAILED); + } + for (tree_next = -1, sym_index = 0; + sym_index < r->m_table_sizes[r->m_type]; ++sym_index) + { + mz_uint rev_code = 0, l, cur_code, code_size = + pTable->m_code_size[sym_index]; + if (!code_size) + continue; + cur_code = next_code[code_size]++; + for (l = code_size; l > 0; l--, cur_code >>= 1) + rev_code = (rev_code << 1) | (cur_code & 1); + if (code_size <= TINFL_FAST_LOOKUP_BITS) + { + mz_int16 k = + (mz_int16) ((code_size << 9) | sym_index); + while (rev_code < TINFL_FAST_LOOKUP_SIZE) + { + pTable->m_look_up[rev_code] = k; + rev_code += (1 << code_size); + } + continue; + } + if (0 == + (tree_cur = + pTable-> + m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)])) + { + pTable-> + m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = + (mz_int16) tree_next; + tree_cur = tree_next; + tree_next -= 2; + } + rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1); + for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--) + { + tree_cur -= ((rev_code >>= 1) & 1); + if (!pTable->m_tree[-tree_cur - 1]) + { + pTable->m_tree[-tree_cur - 1] = + (mz_int16) tree_next; + tree_cur = tree_next; + tree_next -= 2; + } + else + tree_cur = pTable->m_tree[-tree_cur - 1]; + } + tree_cur -= ((rev_code >>= 1) & 1); + pTable->m_tree[-tree_cur - 1] = (mz_int16) sym_index; + } + if (r->m_type == 2) + { + for (counter = 0; + counter < + (r->m_table_sizes[0] + r->m_table_sizes[1]);) + { + mz_uint s; + TINFL_HUFF_DECODE (16, dist, &r->m_tables[2]); + if (dist < 16) + { + r->m_len_codes[counter++] = (mz_uint8) dist; + continue; + } + if ((dist == 16) && (!counter)) + { + TINFL_CR_RETURN_FOREVER (17, TINFL_STATUS_FAILED); + } + num_extra = "\02\03\07"[dist - 16]; + TINFL_GET_BITS (18, s, num_extra); + s += "\03\03\013"[dist - 16]; + TINFL_MEMSET (r->m_len_codes + counter, + (dist == + 16) ? r->m_len_codes[counter - 1] : 0, + s); + counter += s; + } + if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != + counter) + { + TINFL_CR_RETURN_FOREVER (21, TINFL_STATUS_FAILED); + } + TINFL_MEMCPY (r->m_tables[0].m_code_size, r->m_len_codes, + r->m_table_sizes[0]); + TINFL_MEMCPY (r->m_tables[1].m_code_size, + r->m_len_codes + r->m_table_sizes[0], + r->m_table_sizes[1]); + } + } + for (;;) + { + mz_uint8 *pSrc; + for (;;) + { + if (((pIn_buf_end - pIn_buf_cur) < 4) + || ((pOut_buf_end - pOut_buf_cur) < 2)) + { + TINFL_HUFF_DECODE (23, counter, &r->m_tables[0]); + if (counter >= 256) + break; + while (pOut_buf_cur >= pOut_buf_end) + { + TINFL_CR_RETURN (24, + TINFL_STATUS_HAS_MORE_OUTPUT); + } + *pOut_buf_cur++ = (mz_uint8) counter; + } + else + { + int sym2; + mz_uint code_len; +#if TINFL_USE_64BIT_BITBUF + if (num_bits < 30) + { + bit_buf |= + (((tinfl_bit_buf_t) MZ_READ_LE32 (pIn_buf_cur)) + << num_bits); + pIn_buf_cur += 4; + num_bits += 32; + } +#else + if (num_bits < 15) + { + bit_buf |= + (((tinfl_bit_buf_t) MZ_READ_LE16 (pIn_buf_cur)) + << num_bits); + pIn_buf_cur += 2; + num_bits += 16; + } +#endif + if ((sym2 = + r->m_tables[0]. + m_look_up[bit_buf & + (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) + code_len = sym2 >> 9; + else + { + code_len = TINFL_FAST_LOOKUP_BITS; + do + { + sym2 = + r->m_tables[0].m_tree[~sym2 + + ((bit_buf >> + code_len++) & 1)]; + } + while (sym2 < 0); + } + counter = sym2; + bit_buf >>= code_len; + num_bits -= code_len; + if (counter & 256) + break; + +#if !TINFL_USE_64BIT_BITBUF + if (num_bits < 15) + { + bit_buf |= + (((tinfl_bit_buf_t) MZ_READ_LE16 (pIn_buf_cur)) + << num_bits); + pIn_buf_cur += 2; + num_bits += 16; + } +#endif + if ((sym2 = + r->m_tables[0]. + m_look_up[bit_buf & + (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) + code_len = sym2 >> 9; + else + { + code_len = TINFL_FAST_LOOKUP_BITS; + do + { + sym2 = + r->m_tables[0].m_tree[~sym2 + + ((bit_buf >> + code_len++) & 1)]; + } + while (sym2 < 0); + } + bit_buf >>= code_len; + num_bits -= code_len; + + pOut_buf_cur[0] = (mz_uint8) counter; + if (sym2 & 256) + { + pOut_buf_cur++; + counter = sym2; + break; + } + pOut_buf_cur[1] = (mz_uint8) sym2; + pOut_buf_cur += 2; + } + } + if ((counter &= 511) == 256) + break; + + num_extra = s_length_extra[counter - 257]; + counter = s_length_base[counter - 257]; + if (num_extra) + { + mz_uint extra_bits; + TINFL_GET_BITS (25, extra_bits, num_extra); + counter += extra_bits; + } + + TINFL_HUFF_DECODE (26, dist, &r->m_tables[1]); + num_extra = s_dist_extra[dist]; + dist = s_dist_base[dist]; + if (num_extra) + { + mz_uint extra_bits; + TINFL_GET_BITS (27, extra_bits, num_extra); + dist += extra_bits; + } + + dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start; + if ((dist > dist_from_out_buf_start) + && (decomp_flags & + TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) + { + TINFL_CR_RETURN_FOREVER (37, TINFL_STATUS_FAILED); + } + + pSrc = + pOut_buf_start + + ((dist_from_out_buf_start - dist) & out_buf_size_mask); + + if ((MZ_MAX (pOut_buf_cur, pSrc) + counter) > pOut_buf_end) + { + while (counter--) + { + while (pOut_buf_cur >= pOut_buf_end) + { + TINFL_CR_RETURN (53, + TINFL_STATUS_HAS_MORE_OUTPUT); + } + *pOut_buf_cur++ = + pOut_buf_start[(dist_from_out_buf_start++ - + dist) & out_buf_size_mask]; + } + continue; + } +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES + else if ((counter >= 9) && (counter <= dist)) + { + const mz_uint8 *pSrc_end = pSrc + (counter & ~7); + do + { + ((mz_uint32 *) pOut_buf_cur)[0] = + ((const mz_uint32 *) pSrc)[0]; + ((mz_uint32 *) pOut_buf_cur)[1] = + ((const mz_uint32 *) pSrc)[1]; + pOut_buf_cur += 8; + } + while ((pSrc += 8) < pSrc_end); + if ((counter &= 7) < 3) + { + if (counter) + { + pOut_buf_cur[0] = pSrc[0]; + if (counter > 1) + pOut_buf_cur[1] = pSrc[1]; + pOut_buf_cur += counter; + } + continue; + } + } +#endif + do + { + pOut_buf_cur[0] = pSrc[0]; + pOut_buf_cur[1] = pSrc[1]; + pOut_buf_cur[2] = pSrc[2]; + pOut_buf_cur += 3; + pSrc += 3; + } + while ((int) (counter -= 3) > 2); + if ((int) counter > 0) + { + pOut_buf_cur[0] = pSrc[0]; + if ((int) counter > 1) + pOut_buf_cur[1] = pSrc[1]; + pOut_buf_cur += counter; + } + } + } + } + while (!(r->m_final & 1)); + if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) + { + TINFL_SKIP_BITS (32, num_bits & 7); + for (counter = 0; counter < 4; ++counter) + { + mz_uint s; + if (num_bits) + TINFL_GET_BITS (41, s, 8); + else + TINFL_GET_BYTE (42, s); + r->m_z_adler32 = (r->m_z_adler32 << 8) | s; + } + } + TINFL_CR_RETURN_FOREVER (34, TINFL_STATUS_DONE); + TINFL_CR_FINISH common_exit: + r->m_num_bits = num_bits; + r->m_bit_buf = bit_buf; + r->m_dist = dist; + r->m_counter = counter; + r->m_num_extra = num_extra; + r->m_dist_from_out_buf_start = dist_from_out_buf_start; + *pIn_buf_size = pIn_buf_cur - pIn_buf_next; + *pOut_buf_size = pOut_buf_cur - pOut_buf_next; + if ((decomp_flags & + (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) + && (status >= 0)) + { + const mz_uint8 *ptr = pOut_buf_next; + size_t buf_len = *pOut_buf_size; + mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = + r->m_check_adler32 >> 16; + size_t block_len = buf_len % 5552; + while (buf_len) + { + for (i = 0; i + 7 < block_len; i += 8, ptr += 8) + { + s1 += ptr[0], s2 += s1; + s1 += ptr[1], s2 += s1; + s1 += ptr[2], s2 += s1; + s1 += ptr[3], s2 += s1; + s1 += ptr[4], s2 += s1; + s1 += ptr[5], s2 += s1; + s1 += ptr[6], s2 += s1; + s1 += ptr[7], s2 += s1; + } + for (; i < block_len; ++i) + s1 += *ptr++, s2 += s1; + s1 %= 65521U, s2 %= 65521U; + buf_len -= block_len; + block_len = 5552; + } + r->m_check_adler32 = (s2 << 16) + s1; + if ((status == TINFL_STATUS_DONE) + && (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) + && (r->m_check_adler32 != r->m_z_adler32)) + status = TINFL_STATUS_ADLER32_MISMATCH; + } + return status; + } + +// Higher level helper functions. + void *tinfl_decompress_mem_to_heap (const void *pSrc_buf, + size_t src_buf_len, size_t * pOut_len, + int flags) + { + tinfl_decompressor decomp; + void *pBuf = NULL, *pNew_buf; + size_t src_buf_ofs = 0, out_buf_capacity = 0; + *pOut_len = 0; + tinfl_init (&decomp); + for (;;) + { + size_t src_buf_size = src_buf_len - src_buf_ofs, dst_buf_size = + out_buf_capacity - *pOut_len, new_out_buf_capacity; + tinfl_status status = + tinfl_decompress (&decomp, + (const mz_uint8 *) pSrc_buf + src_buf_ofs, + &src_buf_size, (mz_uint8 *) pBuf, + pBuf ? (mz_uint8 *) pBuf + *pOut_len : NULL, + &dst_buf_size, + (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | + TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); + if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT)) + { + MZ_FREE (pBuf); + *pOut_len = 0; + return NULL; + } + src_buf_ofs += src_buf_size; + *pOut_len += dst_buf_size; + if (status == TINFL_STATUS_DONE) + break; + new_out_buf_capacity = out_buf_capacity * 2; + if (new_out_buf_capacity < 128) + new_out_buf_capacity = 128; + pNew_buf = MZ_REALLOC (pBuf, new_out_buf_capacity); + if (!pNew_buf) + { + MZ_FREE (pBuf); + *pOut_len = 0; + return NULL; + } + pBuf = pNew_buf; + out_buf_capacity = new_out_buf_capacity; + } + return pBuf; + } + + size_t tinfl_decompress_mem_to_mem (void *pOut_buf, size_t out_buf_len, + const void *pSrc_buf, + size_t src_buf_len, int flags) + { + tinfl_decompressor decomp; + tinfl_status status; + tinfl_init (&decomp); + status = + tinfl_decompress (&decomp, (const mz_uint8 *) pSrc_buf, &src_buf_len, + (mz_uint8 *) pOut_buf, (mz_uint8 *) pOut_buf, + &out_buf_len, + (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | + TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); + return (status != + TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED : + out_buf_len; + } + + int tinfl_decompress_mem_to_callback (const void *pIn_buf, + size_t * pIn_buf_size, + tinfl_put_buf_func_ptr pPut_buf_func, + void *pPut_buf_user, int flags) + { + int result = 0; + tinfl_decompressor decomp; + mz_uint8 *pDict = (mz_uint8 *) MZ_MALLOC (TINFL_LZ_DICT_SIZE); + size_t in_buf_ofs = 0, dict_ofs = 0; + if (!pDict) + return TINFL_STATUS_FAILED; + tinfl_init (&decomp); + for (;;) + { + size_t in_buf_size = *pIn_buf_size - in_buf_ofs, dst_buf_size = + TINFL_LZ_DICT_SIZE - dict_ofs; + tinfl_status status = + tinfl_decompress (&decomp, (const mz_uint8 *) pIn_buf + in_buf_ofs, + &in_buf_size, pDict, pDict + dict_ofs, + &dst_buf_size, + (flags & + ~(TINFL_FLAG_HAS_MORE_INPUT | + TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))); + in_buf_ofs += in_buf_size; + if ((dst_buf_size) + && + (!(*pPut_buf_func) + (pDict + dict_ofs, (int) dst_buf_size, pPut_buf_user))) + break; + if (status != TINFL_STATUS_HAS_MORE_OUTPUT) + { + result = (status == TINFL_STATUS_DONE); + break; + } + dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1); + } + MZ_FREE (pDict); + *pIn_buf_size = in_buf_ofs; + return result; + } + +// ------------------- Low-level Compression (independent from all decompression API's) + +// Purposely making these tables static for faster init and thread safety. + static const mz_uint16 s_tdefl_len_sym[256] = { + 257, 258, 259, 260, 261, 262, 263, 264, 265, 265, 266, 266, 267, 267, 268, + 268, 269, 269, 269, 269, 270, 270, 270, 270, 271, 271, 271, 271, 272, + 272, 272, 272, + 273, 273, 273, 273, 273, 273, 273, 273, 274, 274, 274, 274, 274, 274, 274, + 274, 275, 275, 275, 275, 275, 275, 275, 275, 276, 276, 276, 276, 276, + 276, 276, 276, + 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, + 277, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, + 278, 278, 278, + 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, + 279, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, + 280, 280, 280, + 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, + 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, + 281, 281, 281, + 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, + 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, + 282, 282, 282, + 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, + 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, + 283, 283, 283, + 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, + 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, + 284, 284, 285 + }; + + static const mz_uint8 s_tdefl_len_extra[256] = { + 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0 + }; + + static const mz_uint8 s_tdefl_small_dist_sym[512] = { + 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, + 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, + 10, 10, 10, 11, 11, 11, 11, 11, 11, + 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, + 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, + 12, 12, 12, 12, 12, 12, 13, + 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, + 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, + 14, 14, 14, 14, 14, 14, 14, + 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, + 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, + 14, 14, 14, 14, 14, 14, 14, + 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, + 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, + 15, 15, 15, 15, 15, 15, 15, + 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, + 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, + 17, 17, 17, 17, 17, 17, 17, + 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, + 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, + 17, 17, 17, 17, 17, 17, 17, + 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, + 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, + 17, 17, 17, 17, 17, 17, 17, + 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, + 17, 17, 17, 17, 17, 17, 17, 17, 17, 17 + }; + + static const mz_uint8 s_tdefl_small_dist_extra[512] = { + 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7 + }; + + static const mz_uint8 s_tdefl_large_dist_sym[128] = { + 0, 0, 18, 19, 20, 20, 21, 21, 22, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24, + 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, + 26, 26, 26, 26, 26, 26, 26, + 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, + 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, + 28, 28, 28, 28, 28, 28, 28, 28, + 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, + 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, + 29, 29, 29, 29 + }; + + static const mz_uint8 s_tdefl_large_dist_extra[128] = { + 0, 0, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, + 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, + 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, + 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, + 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, + 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, + 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, + 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13 + }; + +// Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted values. + typedef struct + { + mz_uint16 m_key, m_sym_index; + } tdefl_sym_freq; + static tdefl_sym_freq *tdefl_radix_sort_syms (mz_uint num_syms, + tdefl_sym_freq * pSyms0, + tdefl_sym_freq * pSyms1) + { + mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2]; + tdefl_sym_freq *pCur_syms = pSyms0, *pNew_syms = pSyms1; + MZ_CLEAR_OBJ (hist); + for (i = 0; i < num_syms; i++) + { + mz_uint freq = pSyms0[i].m_key; + hist[freq & 0xFF]++; + hist[256 + ((freq >> 8) & 0xFF)]++; + } + while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256])) + total_passes--; + for (pass_shift = 0, pass = 0; pass < total_passes; + pass++, pass_shift += 8) + { + const mz_uint32 *pHist = &hist[pass << 8]; + mz_uint offsets[256], cur_ofs = 0; + for (i = 0; i < 256; i++) + { + offsets[i] = cur_ofs; + cur_ofs += pHist[i]; + } + for (i = 0; i < num_syms; i++) + pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = + pCur_syms[i]; + { + tdefl_sym_freq *t = pCur_syms; + pCur_syms = pNew_syms; + pNew_syms = t; + } + } + return pCur_syms; + } + +// tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat, alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996. + static void tdefl_calculate_minimum_redundancy (tdefl_sym_freq * A, int n) + { + int root, leaf, next, avbl, used, dpth; + if (n == 0) + return; + else if (n == 1) + { + A[0].m_key = 1; + return; + } + A[0].m_key += A[1].m_key; + root = 0; + leaf = 2; + for (next = 1; next < n - 1; next++) + { + if (leaf >= n || A[root].m_key < A[leaf].m_key) + { + A[next].m_key = A[root].m_key; + A[root++].m_key = (mz_uint16) next; + } + else + A[next].m_key = A[leaf++].m_key; + if (leaf >= n || (root < next && A[root].m_key < A[leaf].m_key)) + { + A[next].m_key = (mz_uint16) (A[next].m_key + A[root].m_key); + A[root++].m_key = (mz_uint16) next; + } + else + A[next].m_key = (mz_uint16) (A[next].m_key + A[leaf++].m_key); + } + A[n - 2].m_key = 0; + for (next = n - 3; next >= 0; next--) + A[next].m_key = A[A[next].m_key].m_key + 1; + avbl = 1; + used = dpth = 0; + root = n - 2; + next = n - 1; + while (avbl > 0) + { + while (root >= 0 && (int) A[root].m_key == dpth) + { + used++; + root--; + } + while (avbl > used) + { + A[next--].m_key = (mz_uint16) (dpth); + avbl--; + } + avbl = 2 * used; + dpth++; + used = 0; + } + } + +// Limits canonical Huffman code table's max code size. + enum + { TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 }; + static void tdefl_huffman_enforce_max_code_size (int *pNum_codes, + int code_list_len, + int max_code_size) + { + int i; + mz_uint32 total = 0; + if (code_list_len <= 1) + return; + for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++) + pNum_codes[max_code_size] += pNum_codes[i]; + for (i = max_code_size; i > 0; i--) + total += (((mz_uint32) pNum_codes[i]) << (max_code_size - i)); + while (total != (1UL << max_code_size)) + { + pNum_codes[max_code_size]--; + for (i = max_code_size - 1; i > 0; i--) + if (pNum_codes[i]) + { + pNum_codes[i]--; + pNum_codes[i + 1] += 2; + break; + } + total--; + } + } + + static void tdefl_optimize_huffman_table (tdefl_compressor * d, + int table_num, int table_len, + int code_size_limit, + int static_table) + { + int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE]; + mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1]; + MZ_CLEAR_OBJ (num_codes); + if (static_table) + { + for (i = 0; i < table_len; i++) + num_codes[d->m_huff_code_sizes[table_num][i]]++; + } + else + { + tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], + syms1[TDEFL_MAX_HUFF_SYMBOLS], *pSyms; + int num_used_syms = 0; + const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0]; + for (i = 0; i < table_len; i++) + if (pSym_count[i]) + { + syms0[num_used_syms].m_key = (mz_uint16) pSym_count[i]; + syms0[num_used_syms++].m_sym_index = (mz_uint16) i; + } + + pSyms = tdefl_radix_sort_syms (num_used_syms, syms0, syms1); + tdefl_calculate_minimum_redundancy (pSyms, num_used_syms); + + for (i = 0; i < num_used_syms; i++) + num_codes[pSyms[i].m_key]++; + + tdefl_huffman_enforce_max_code_size (num_codes, num_used_syms, + code_size_limit); + + MZ_CLEAR_OBJ (d->m_huff_code_sizes[table_num]); + MZ_CLEAR_OBJ (d->m_huff_codes[table_num]); + for (i = 1, j = num_used_syms; i <= code_size_limit; i++) + for (l = num_codes[i]; l > 0; l--) + d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = + (mz_uint8) (i); + } + + next_code[1] = 0; + for (j = 0, i = 2; i <= code_size_limit; i++) + next_code[i] = j = ((j + num_codes[i - 1]) << 1); + + for (i = 0; i < table_len; i++) + { + mz_uint rev_code = 0, code, code_size; + if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0) + continue; + code = next_code[code_size]++; + for (l = code_size; l > 0; l--, code >>= 1) + rev_code = (rev_code << 1) | (code & 1); + d->m_huff_codes[table_num][i] = (mz_uint16) rev_code; + } + } + +#define TDEFL_PUT_BITS(b, l) do { \ + mz_uint bits = b; mz_uint len = l; MZ_ASSERT(bits <= ((1U << len) - 1U)); \ + d->m_bit_buffer |= (bits << d->m_bits_in); d->m_bits_in += len; \ + while (d->m_bits_in >= 8) { \ + if (d->m_pOutput_buf < d->m_pOutput_buf_end) \ + *d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \ + d->m_bit_buffer >>= 8; \ + d->m_bits_in -= 8; \ + } \ +} MZ_MACRO_END + +#define TDEFL_RLE_PREV_CODE_SIZE() { if (rle_repeat_count) { \ + if (rle_repeat_count < 3) { \ + d->m_huff_count[2][prev_code_size] = (mz_uint16)(d->m_huff_count[2][prev_code_size] + rle_repeat_count); \ + while (rle_repeat_count--) packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \ + } else { \ + d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); packed_code_sizes[num_packed_code_sizes++] = 16; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_repeat_count - 3); \ +} rle_repeat_count = 0; } } + +#define TDEFL_RLE_ZERO_CODE_SIZE() { if (rle_z_count) { \ + if (rle_z_count < 3) { \ + d->m_huff_count[2][0] = (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); while (rle_z_count--) packed_code_sizes[num_packed_code_sizes++] = 0; \ + } else if (rle_z_count <= 10) { \ + d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); packed_code_sizes[num_packed_code_sizes++] = 17; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 3); \ + } else { \ + d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); packed_code_sizes[num_packed_code_sizes++] = 18; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 11); \ +} rle_z_count = 0; } } + + static mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = + { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; + + static void tdefl_start_dynamic_block (tdefl_compressor * d) + { + int num_lit_codes, num_dist_codes, num_bit_lengths; + mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count, + rle_repeat_count, packed_code_sizes_index; + mz_uint8 code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + + TDEFL_MAX_HUFF_SYMBOLS_1], + packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], + prev_code_size = 0xFF; + + d->m_huff_count[0][256] = 1; + + tdefl_optimize_huffman_table (d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, + MZ_FALSE); + tdefl_optimize_huffman_table (d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, + MZ_FALSE); + + for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--) + if (d->m_huff_code_sizes[0][num_lit_codes - 1]) + break; + for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--) + if (d->m_huff_code_sizes[1][num_dist_codes - 1]) + break; + + memcpy (code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes); + memcpy (code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0], + num_dist_codes); + total_code_sizes_to_pack = num_lit_codes + num_dist_codes; + num_packed_code_sizes = 0; + rle_z_count = 0; + rle_repeat_count = 0; + + memset (&d->m_huff_count[2][0], 0, + sizeof (d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2); + for (i = 0; i < total_code_sizes_to_pack; i++) + { + mz_uint8 code_size = code_sizes_to_pack[i]; + if (!code_size) + { + TDEFL_RLE_PREV_CODE_SIZE (); + if (++rle_z_count == 138) + { + TDEFL_RLE_ZERO_CODE_SIZE (); + } + } + else + { + TDEFL_RLE_ZERO_CODE_SIZE (); + if (code_size != prev_code_size) + { + TDEFL_RLE_PREV_CODE_SIZE (); + d->m_huff_count[2][code_size] = + (mz_uint16) (d->m_huff_count[2][code_size] + 1); + packed_code_sizes[num_packed_code_sizes++] = code_size; + } + else if (++rle_repeat_count == 6) + { + TDEFL_RLE_PREV_CODE_SIZE (); + } + } + prev_code_size = code_size; + } + if (rle_repeat_count) + { + TDEFL_RLE_PREV_CODE_SIZE (); + } + else + { + TDEFL_RLE_ZERO_CODE_SIZE (); + } + + tdefl_optimize_huffman_table (d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, + MZ_FALSE); + + TDEFL_PUT_BITS (2, 2); + + TDEFL_PUT_BITS (num_lit_codes - 257, 5); + TDEFL_PUT_BITS (num_dist_codes - 1, 5); + + for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--) + if (d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle + [num_bit_lengths]]) + break; + num_bit_lengths = MZ_MAX (4, (num_bit_lengths + 1)); + TDEFL_PUT_BITS (num_bit_lengths - 4, 4); + for (i = 0; (int) i < num_bit_lengths; i++) + TDEFL_PUT_BITS (d->m_huff_code_sizes[2] + [s_tdefl_packed_code_size_syms_swizzle[i]], 3); + + for (packed_code_sizes_index = 0; + packed_code_sizes_index < num_packed_code_sizes;) + { + mz_uint code = packed_code_sizes[packed_code_sizes_index++]; + MZ_ASSERT (code < TDEFL_MAX_HUFF_SYMBOLS_2); + TDEFL_PUT_BITS (d->m_huff_codes[2][code], + d->m_huff_code_sizes[2][code]); + if (code >= 16) + TDEFL_PUT_BITS (packed_code_sizes[packed_code_sizes_index++], + "\02\03\07"[code - 16]); + } + } + + static void tdefl_start_static_block (tdefl_compressor * d) + { + mz_uint i; + mz_uint8 *p = &d->m_huff_code_sizes[0][0]; + + for (i = 0; i <= 143; ++i) + *p++ = 8; + for (; i <= 255; ++i) + *p++ = 9; + for (; i <= 279; ++i) + *p++ = 7; + for (; i <= 287; ++i) + *p++ = 8; + + memset (d->m_huff_code_sizes[1], 5, 32); + + tdefl_optimize_huffman_table (d, 0, 288, 15, MZ_TRUE); + tdefl_optimize_huffman_table (d, 1, 32, 15, MZ_TRUE); + + TDEFL_PUT_BITS (1, 2); + } + + static const mz_uint mz_bitmasks[17] = + { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, + 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF + }; + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS + static mz_bool tdefl_compress_lz_codes (tdefl_compressor * d) + { + mz_uint flags; + mz_uint8 *pLZ_codes; + mz_uint8 *pOutput_buf = d->m_pOutput_buf; + mz_uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf; + mz_uint64 bit_buffer = d->m_bit_buffer; + mz_uint bits_in = d->m_bits_in; + +#define TDEFL_PUT_BITS_FAST(b, l) { bit_buffer |= (((mz_uint64)(b)) << bits_in); bits_in += (l); } + + flags = 1; + for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end; + flags >>= 1) + { + if (flags == 1) + flags = *pLZ_codes++ | 0x100; + + if (flags & 1) + { + mz_uint s0, s1, n0, n1, sym, num_extra_bits; + mz_uint match_len = pLZ_codes[0], match_dist = + *(const mz_uint16 *) (pLZ_codes + 1); + pLZ_codes += 3; + + MZ_ASSERT (d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS_FAST (d-> + m_huff_codes[0][s_tdefl_len_sym[match_len]], + d-> + m_huff_code_sizes[0][s_tdefl_len_sym + [match_len]]); + TDEFL_PUT_BITS_FAST (match_len & + mz_bitmasks[s_tdefl_len_extra[match_len]], + s_tdefl_len_extra[match_len]); + + // This sequence coaxes MSVC into using cmov's vs. jmp's. + s0 = s_tdefl_small_dist_sym[match_dist & 511]; + n0 = s_tdefl_small_dist_extra[match_dist & 511]; + s1 = s_tdefl_large_dist_sym[match_dist >> 8]; + n1 = s_tdefl_large_dist_extra[match_dist >> 8]; + sym = (match_dist < 512) ? s0 : s1; + num_extra_bits = (match_dist < 512) ? n0 : n1; + + MZ_ASSERT (d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS_FAST (d->m_huff_codes[1][sym], + d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS_FAST (match_dist & mz_bitmasks[num_extra_bits], + num_extra_bits); + } + else + { + mz_uint lit = *pLZ_codes++; + MZ_ASSERT (d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS_FAST (d->m_huff_codes[0][lit], + d->m_huff_code_sizes[0][lit]); + + if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) + { + flags >>= 1; + lit = *pLZ_codes++; + MZ_ASSERT (d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS_FAST (d->m_huff_codes[0][lit], + d->m_huff_code_sizes[0][lit]); + + if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) + { + flags >>= 1; + lit = *pLZ_codes++; + MZ_ASSERT (d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS_FAST (d->m_huff_codes[0][lit], + d->m_huff_code_sizes[0][lit]); + } + } + } + + if (pOutput_buf >= d->m_pOutput_buf_end) + return MZ_FALSE; + + *(mz_uint64 *) pOutput_buf = bit_buffer; + pOutput_buf += (bits_in >> 3); + bit_buffer >>= (bits_in & ~7); + bits_in &= 7; + } + +#undef TDEFL_PUT_BITS_FAST + + d->m_pOutput_buf = pOutput_buf; + d->m_bits_in = 0; + d->m_bit_buffer = 0; + + while (bits_in) + { + mz_uint32 n = MZ_MIN (bits_in, 16); + TDEFL_PUT_BITS ((mz_uint) bit_buffer & mz_bitmasks[n], n); + bit_buffer >>= n; + bits_in -= n; + } + + TDEFL_PUT_BITS (d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); + + return (d->m_pOutput_buf < d->m_pOutput_buf_end); + } +#else + static mz_bool tdefl_compress_lz_codes (tdefl_compressor * d) + { + mz_uint flags; + mz_uint8 *pLZ_codes; + + flags = 1; + for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf; + flags >>= 1) + { + if (flags == 1) + flags = *pLZ_codes++ | 0x100; + if (flags & 1) + { + mz_uint sym, num_extra_bits; + mz_uint match_len = pLZ_codes[0], match_dist = + (pLZ_codes[1] | (pLZ_codes[2] << 8)); + pLZ_codes += 3; + + MZ_ASSERT (d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS (d->m_huff_codes[0][s_tdefl_len_sym[match_len]], + d->m_huff_code_sizes[0][s_tdefl_len_sym + [match_len]]); + TDEFL_PUT_BITS (match_len & + mz_bitmasks[s_tdefl_len_extra[match_len]], + s_tdefl_len_extra[match_len]); + + if (match_dist < 512) + { + sym = s_tdefl_small_dist_sym[match_dist]; + num_extra_bits = s_tdefl_small_dist_extra[match_dist]; + } + else + { + sym = s_tdefl_large_dist_sym[match_dist >> 8]; + num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8]; + } + MZ_ASSERT (d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS (d->m_huff_codes[1][sym], + d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS (match_dist & mz_bitmasks[num_extra_bits], + num_extra_bits); + } + else + { + mz_uint lit = *pLZ_codes++; + MZ_ASSERT (d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS (d->m_huff_codes[0][lit], + d->m_huff_code_sizes[0][lit]); + } + } + + TDEFL_PUT_BITS (d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); + + return (d->m_pOutput_buf < d->m_pOutput_buf_end); + } +#endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS + + static mz_bool tdefl_compress_block (tdefl_compressor * d, + mz_bool static_block) + { + if (static_block) + tdefl_start_static_block (d); + else + tdefl_start_dynamic_block (d); + return tdefl_compress_lz_codes (d); + } + + static int tdefl_flush_block (tdefl_compressor * d, int flush) + { + mz_uint saved_bit_buf, saved_bits_in; + mz_uint8 *pSaved_output_buf; + mz_bool comp_block_succeeded = MZ_FALSE; + int n, use_raw_block = ((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) + && (d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size; + mz_uint8 *pOutput_buf_start = ((d->m_pPut_buf_func == NULL) + && + ((*d->m_pOut_buf_size - + d->m_out_buf_ofs) >= + TDEFL_OUT_BUF_SIZE)) ? ((mz_uint8 *) + d->m_pOut_buf + + d->m_out_buf_ofs) + : d->m_output_buf; + + d->m_pOutput_buf = pOutput_buf_start; + d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16; + + MZ_ASSERT (!d->m_output_flush_remaining); + d->m_output_flush_ofs = 0; + d->m_output_flush_remaining = 0; + + *d->m_pLZ_flags = (mz_uint8) (*d->m_pLZ_flags >> d->m_num_flags_left); + d->m_pLZ_code_buf -= (d->m_num_flags_left == 8); + + if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index)) + { + TDEFL_PUT_BITS (0x78, 8); + TDEFL_PUT_BITS (0x01, 8); + } + + TDEFL_PUT_BITS (flush == TDEFL_FINISH, 1); + + pSaved_output_buf = d->m_pOutput_buf; + saved_bit_buf = d->m_bit_buffer; + saved_bits_in = d->m_bits_in; + + if (!use_raw_block) + comp_block_succeeded = + tdefl_compress_block (d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) + || (d->m_total_lz_bytes < 48)); + + // If the block gets expanded, forget the current contents of the output buffer and send a raw block instead. + if (((use_raw_block) + || ((d->m_total_lz_bytes) + && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >= + d->m_total_lz_bytes))) + && ((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= + d->m_dict_size)) + { + mz_uint i; + d->m_pOutput_buf = pSaved_output_buf; + d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; + TDEFL_PUT_BITS (0, 2); + if (d->m_bits_in) + { + TDEFL_PUT_BITS (0, 8 - d->m_bits_in); + } + for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF) + { + TDEFL_PUT_BITS (d->m_total_lz_bytes & 0xFFFF, 16); + } + for (i = 0; i < d->m_total_lz_bytes; ++i) + { + TDEFL_PUT_BITS (d->m_dict[(d->m_lz_code_buf_dict_pos + + i) & TDEFL_LZ_DICT_SIZE_MASK], 8); + } + } + // Check for the extremely unlikely (if not impossible) case of the compressed block not fitting into the output buffer when using dynamic codes. + else if (!comp_block_succeeded) + { + d->m_pOutput_buf = pSaved_output_buf; + d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; + tdefl_compress_block (d, MZ_TRUE); + } + + if (flush) + { + if (flush == TDEFL_FINISH) + { + if (d->m_bits_in) + { + TDEFL_PUT_BITS (0, 8 - d->m_bits_in); + } + if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER) + { + mz_uint i, a = d->m_adler32; + for (i = 0; i < 4; i++) + { + TDEFL_PUT_BITS ((a >> 24) & 0xFF, 8); + a <<= 8; + } + } + } + else + { + mz_uint i, z = 0; + TDEFL_PUT_BITS (0, 3); + if (d->m_bits_in) + { + TDEFL_PUT_BITS (0, 8 - d->m_bits_in); + } + for (i = 2; i; --i, z ^= 0xFFFF) + { + TDEFL_PUT_BITS (z & 0xFFFF, 16); + } + } + } + + MZ_ASSERT (d->m_pOutput_buf < d->m_pOutput_buf_end); + + memset (&d->m_huff_count[0][0], 0, + sizeof (d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); + memset (&d->m_huff_count[1][0], 0, + sizeof (d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); + + d->m_pLZ_code_buf = d->m_lz_code_buf + 1; + d->m_pLZ_flags = d->m_lz_code_buf; + d->m_num_flags_left = 8; + d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes; + d->m_total_lz_bytes = 0; + d->m_block_index++; + + if ((n = (int) (d->m_pOutput_buf - pOutput_buf_start)) != 0) + { + if (d->m_pPut_buf_func) + { + *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *) d->m_pIn_buf; + if (!(*d->m_pPut_buf_func) + (d->m_output_buf, n, d->m_pPut_buf_user)) + return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED); + } + else if (pOutput_buf_start == d->m_output_buf) + { + int bytes_to_copy = (int) MZ_MIN ((size_t) n, + (size_t) (*d->m_pOut_buf_size - + d->m_out_buf_ofs)); + memcpy ((mz_uint8 *) d->m_pOut_buf + d->m_out_buf_ofs, + d->m_output_buf, bytes_to_copy); + d->m_out_buf_ofs += bytes_to_copy; + if ((n -= bytes_to_copy) != 0) + { + d->m_output_flush_ofs = bytes_to_copy; + d->m_output_flush_remaining = n; + } + } + else + { + d->m_out_buf_ofs += n; + } + } + + return d->m_output_flush_remaining; + } + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES +#define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16*)(p) + static __forceinline void tdefl_find_match (tdefl_compressor * d, + mz_uint lookahead_pos, + mz_uint max_dist, + mz_uint max_match_len, + mz_uint * pMatch_dist, + mz_uint * pMatch_len) + { + mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = + *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; + mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; + const mz_uint16 *s = (const mz_uint16 *) (d->m_dict + pos), *p, *q; + mz_uint16 c01 = + TDEFL_READ_UNALIGNED_WORD (&d->m_dict[pos + match_len - 1]), s01 = + TDEFL_READ_UNALIGNED_WORD (s); + MZ_ASSERT (max_match_len <= TDEFL_MAX_MATCH_LEN); + if (max_match_len <= match_len) + return; + for (;;) + { + for (;;) + { + if (--num_probes_left == 0) + return; +#define TDEFL_PROBE \ + next_probe_pos = d->m_next[probe_pos]; \ + if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) return; \ + probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ + if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) break; + TDEFL_PROBE; + TDEFL_PROBE; + TDEFL_PROBE; + } + if (!dist) + break; + q = (const mz_uint16 *) (d->m_dict + probe_pos); + if (TDEFL_READ_UNALIGNED_WORD (q) != s01) + continue; + p = s; + probe_len = 32; + do + { + } + while ((TDEFL_READ_UNALIGNED_WORD (++p) == + TDEFL_READ_UNALIGNED_WORD (++q)) + && (TDEFL_READ_UNALIGNED_WORD (++p) == + TDEFL_READ_UNALIGNED_WORD (++q)) + && (TDEFL_READ_UNALIGNED_WORD (++p) == + TDEFL_READ_UNALIGNED_WORD (++q)) + && (TDEFL_READ_UNALIGNED_WORD (++p) == + TDEFL_READ_UNALIGNED_WORD (++q)) && (--probe_len > 0)); + if (!probe_len) + { + *pMatch_dist = dist; + *pMatch_len = MZ_MIN (max_match_len, (mz_uint) TDEFL_MAX_MATCH_LEN); + break; + } + else + if ((probe_len = + ((mz_uint) (p - s) * 2) + (mz_uint) (*(const mz_uint8 *) p == + *(const mz_uint8 *) q)) > + match_len) + { + *pMatch_dist = dist; + if ((*pMatch_len = match_len = + MZ_MIN (max_match_len, probe_len)) == max_match_len) + break; + c01 = TDEFL_READ_UNALIGNED_WORD (&d->m_dict[pos + match_len - 1]); + } + } + } +#else + static __forceinline void tdefl_find_match (tdefl_compressor * d, + mz_uint lookahead_pos, + mz_uint max_dist, + mz_uint max_match_len, + mz_uint * pMatch_dist, + mz_uint * pMatch_len) + { + mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = + *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; + mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; + const mz_uint8 *s = d->m_dict + pos, *p, *q; + mz_uint8 c0 = d->m_dict[pos + match_len], c1 = + d->m_dict[pos + match_len - 1]; + MZ_ASSERT (max_match_len <= TDEFL_MAX_MATCH_LEN); + if (max_match_len <= match_len) + return; + for (;;) + { + for (;;) + { + if (--num_probes_left == 0) + return; +#define TDEFL_PROBE \ + next_probe_pos = d->m_next[probe_pos]; \ + if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) return; \ + probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ + if ((d->m_dict[probe_pos + match_len] == c0) && (d->m_dict[probe_pos + match_len - 1] == c1)) break; + TDEFL_PROBE; + TDEFL_PROBE; + TDEFL_PROBE; + } + if (!dist) + break; + p = s; + q = d->m_dict + probe_pos; + for (probe_len = 0; probe_len < max_match_len; probe_len++) + if (*p++ != *q++) + break; + if (probe_len > match_len) + { + *pMatch_dist = dist; + if ((*pMatch_len = match_len = probe_len) == max_match_len) + return; + c0 = d->m_dict[pos + match_len]; + c1 = d->m_dict[pos + match_len - 1]; + } + } + } +#endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN + static mz_bool tdefl_compress_fast (tdefl_compressor * d) + { + // Faster, minimally featured LZRW1-style match+parse loop with better register utilization. Intended for applications where raw throughput is valued more highly than ratio. + mz_uint lookahead_pos = d->m_lookahead_pos, lookahead_size = + d->m_lookahead_size, dict_size = d->m_dict_size, total_lz_bytes = + d->m_total_lz_bytes, num_flags_left = d->m_num_flags_left; + mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags; + mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; + + while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size))) + { + const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096; + mz_uint dst_pos = + (lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; + mz_uint num_bytes_to_process = (mz_uint) MZ_MIN (d->m_src_buf_left, + TDEFL_COMP_FAST_LOOKAHEAD_SIZE + - lookahead_size); + d->m_src_buf_left -= num_bytes_to_process; + lookahead_size += num_bytes_to_process; + + while (num_bytes_to_process) + { + mz_uint32 n = + MZ_MIN (TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process); + memcpy (d->m_dict + dst_pos, d->m_pSrc, n); + if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) + memcpy (d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc, + MZ_MIN (n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos)); + d->m_pSrc += n; + dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK; + num_bytes_to_process -= n; + } + + dict_size = MZ_MIN (TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size); + if ((!d->m_flush) + && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE)) + break; + + while (lookahead_size >= 4) + { + mz_uint cur_match_dist, cur_match_len = 1; + mz_uint8 *pCur_dict = d->m_dict + cur_pos; + mz_uint first_trigram = + (*(const mz_uint32 *) pCur_dict) & 0xFFFFFF; + mz_uint hash = + (first_trigram ^ + (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) & + TDEFL_LEVEL1_HASH_SIZE_MASK; + mz_uint probe_pos = d->m_hash[hash]; + d->m_hash[hash] = (mz_uint16) lookahead_pos; + + if (((cur_match_dist = + (mz_uint16) (lookahead_pos - probe_pos)) <= dict_size) + && + ((*(const mz_uint32 *) + (d->m_dict + + (probe_pos &= + TDEFL_LZ_DICT_SIZE_MASK)) & 0xFFFFFF) == first_trigram)) + { + const mz_uint16 *p = (const mz_uint16 *) pCur_dict; + const mz_uint16 *q = + (const mz_uint16 *) (d->m_dict + probe_pos); + mz_uint32 probe_len = 32; + do + { + } + while ((TDEFL_READ_UNALIGNED_WORD (++p) == + TDEFL_READ_UNALIGNED_WORD (++q)) + && (TDEFL_READ_UNALIGNED_WORD (++p) == + TDEFL_READ_UNALIGNED_WORD (++q)) + && (TDEFL_READ_UNALIGNED_WORD (++p) == + TDEFL_READ_UNALIGNED_WORD (++q)) + && (TDEFL_READ_UNALIGNED_WORD (++p) == + TDEFL_READ_UNALIGNED_WORD (++q)) + && (--probe_len > 0)); + cur_match_len = + ((mz_uint) (p - (const mz_uint16 *) pCur_dict) * 2) + + (mz_uint) (*(const mz_uint8 *) p == *(const mz_uint8 *) q); + if (!probe_len) + cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0; + + if ((cur_match_len < TDEFL_MIN_MATCH_LEN) + || ((cur_match_len == TDEFL_MIN_MATCH_LEN) + && (cur_match_dist >= 8U * 1024U))) + { + cur_match_len = 1; + *pLZ_code_buf++ = (mz_uint8) first_trigram; + *pLZ_flags = (mz_uint8) (*pLZ_flags >> 1); + d->m_huff_count[0][(mz_uint8) first_trigram]++; + } + else + { + mz_uint32 s0, s1; + cur_match_len = MZ_MIN (cur_match_len, lookahead_size); + + MZ_ASSERT ((cur_match_len >= TDEFL_MIN_MATCH_LEN) + && (cur_match_dist >= 1) + && (cur_match_dist <= TDEFL_LZ_DICT_SIZE)); + + cur_match_dist--; + + pLZ_code_buf[0] = + (mz_uint8) (cur_match_len - TDEFL_MIN_MATCH_LEN); + *(mz_uint16 *) (&pLZ_code_buf[1]) = + (mz_uint16) cur_match_dist; + pLZ_code_buf += 3; + *pLZ_flags = (mz_uint8) ((*pLZ_flags >> 1) | 0x80); + + s0 = s_tdefl_small_dist_sym[cur_match_dist & 511]; + s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8]; + d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++; + + d->m_huff_count[0][s_tdefl_len_sym + [cur_match_len - + TDEFL_MIN_MATCH_LEN]]++; + } + } + else + { + *pLZ_code_buf++ = (mz_uint8) first_trigram; + *pLZ_flags = (mz_uint8) (*pLZ_flags >> 1); + d->m_huff_count[0][(mz_uint8) first_trigram]++; + } + + if (--num_flags_left == 0) + { + num_flags_left = 8; + pLZ_flags = pLZ_code_buf++; + } + + total_lz_bytes += cur_match_len; + lookahead_pos += cur_match_len; + dict_size = + MZ_MIN (dict_size + cur_match_len, (mz_uint) TDEFL_LZ_DICT_SIZE); + + cur_pos = (cur_pos + cur_match_len) & TDEFL_LZ_DICT_SIZE_MASK; + MZ_ASSERT (lookahead_size >= cur_match_len); + lookahead_size -= cur_match_len; + + if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) + { + int n; + d->m_lookahead_pos = lookahead_pos; + d->m_lookahead_size = lookahead_size; + d->m_dict_size = dict_size; + d->m_total_lz_bytes = total_lz_bytes; + d->m_pLZ_code_buf = pLZ_code_buf; + d->m_pLZ_flags = pLZ_flags; + d->m_num_flags_left = num_flags_left; + if ((n = tdefl_flush_block (d, 0)) != 0) + return (n < 0) ? MZ_FALSE : MZ_TRUE; + total_lz_bytes = d->m_total_lz_bytes; + pLZ_code_buf = d->m_pLZ_code_buf; + pLZ_flags = d->m_pLZ_flags; + num_flags_left = d->m_num_flags_left; + } + } + + while (lookahead_size) + { + mz_uint8 lit = d->m_dict[cur_pos]; + + total_lz_bytes++; + *pLZ_code_buf++ = lit; + *pLZ_flags = (mz_uint8) (*pLZ_flags >> 1); + if (--num_flags_left == 0) + { + num_flags_left = 8; + pLZ_flags = pLZ_code_buf++; + } + + d->m_huff_count[0][lit]++; + + lookahead_pos++; + dict_size = MZ_MIN (dict_size + 1, (mz_uint) TDEFL_LZ_DICT_SIZE); + cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; + lookahead_size--; + + if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) + { + int n; + d->m_lookahead_pos = lookahead_pos; + d->m_lookahead_size = lookahead_size; + d->m_dict_size = dict_size; + d->m_total_lz_bytes = total_lz_bytes; + d->m_pLZ_code_buf = pLZ_code_buf; + d->m_pLZ_flags = pLZ_flags; + d->m_num_flags_left = num_flags_left; + if ((n = tdefl_flush_block (d, 0)) != 0) + return (n < 0) ? MZ_FALSE : MZ_TRUE; + total_lz_bytes = d->m_total_lz_bytes; + pLZ_code_buf = d->m_pLZ_code_buf; + pLZ_flags = d->m_pLZ_flags; + num_flags_left = d->m_num_flags_left; + } + } + } + + d->m_lookahead_pos = lookahead_pos; + d->m_lookahead_size = lookahead_size; + d->m_dict_size = dict_size; + d->m_total_lz_bytes = total_lz_bytes; + d->m_pLZ_code_buf = pLZ_code_buf; + d->m_pLZ_flags = pLZ_flags; + d->m_num_flags_left = num_flags_left; + return MZ_TRUE; + } +#endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN + + static __forceinline void tdefl_record_literal (tdefl_compressor * d, + mz_uint8 lit) + { + d->m_total_lz_bytes++; + *d->m_pLZ_code_buf++ = lit; + *d->m_pLZ_flags = (mz_uint8) (*d->m_pLZ_flags >> 1); + if (--d->m_num_flags_left == 0) + { + d->m_num_flags_left = 8; + d->m_pLZ_flags = d->m_pLZ_code_buf++; + } + d->m_huff_count[0][lit]++; + } + + static __forceinline void tdefl_record_match (tdefl_compressor * d, + mz_uint match_len, + mz_uint match_dist) + { + mz_uint32 s0, s1; + + MZ_ASSERT ((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) + && (match_dist <= TDEFL_LZ_DICT_SIZE)); + + d->m_total_lz_bytes += match_len; + + d->m_pLZ_code_buf[0] = (mz_uint8) (match_len - TDEFL_MIN_MATCH_LEN); + + match_dist -= 1; + d->m_pLZ_code_buf[1] = (mz_uint8) (match_dist & 0xFF); + d->m_pLZ_code_buf[2] = (mz_uint8) (match_dist >> 8); + d->m_pLZ_code_buf += 3; + + *d->m_pLZ_flags = (mz_uint8) ((*d->m_pLZ_flags >> 1) | 0x80); + if (--d->m_num_flags_left == 0) + { + d->m_num_flags_left = 8; + d->m_pLZ_flags = d->m_pLZ_code_buf++; + } + + s0 = s_tdefl_small_dist_sym[match_dist & 511]; + s1 = s_tdefl_large_dist_sym[match_dist >> 8]; + d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++; + + d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++; + } + + static mz_bool tdefl_compress_normal (tdefl_compressor * d) + { + const mz_uint8 *pSrc = d->m_pSrc; + size_t src_buf_left = d->m_src_buf_left; + tdefl_flush flush = d->m_flush; + + while ((src_buf_left) || ((flush) && (d->m_lookahead_size))) + { + mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos; + // Update dictionary and hash chains. Keeps the lookahead size equal to TDEFL_MAX_MATCH_LEN. + if ((d->m_lookahead_size + d->m_dict_size) >= + (TDEFL_MIN_MATCH_LEN - 1)) + { + mz_uint dst_pos = + (d->m_lookahead_pos + + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK, ins_pos = + d->m_lookahead_pos + d->m_lookahead_size - 2; + mz_uint hash = + (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << + TDEFL_LZ_HASH_SHIFT) ^ d->m_dict[(ins_pos + + 1) & + TDEFL_LZ_DICT_SIZE_MASK]; + mz_uint num_bytes_to_process = (mz_uint) MZ_MIN (src_buf_left, + TDEFL_MAX_MATCH_LEN + - + d->m_lookahead_size); + const mz_uint8 *pSrc_end = pSrc + num_bytes_to_process; + src_buf_left -= num_bytes_to_process; + d->m_lookahead_size += num_bytes_to_process; + while (pSrc != pSrc_end) + { + mz_uint8 c = *pSrc++; + d->m_dict[dst_pos] = c; + if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) + d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; + hash = + ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - + 1); + d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = + d->m_hash[hash]; + d->m_hash[hash] = (mz_uint16) (ins_pos); + dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; + ins_pos++; + } + } + else + { + while ((src_buf_left) + && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) + { + mz_uint8 c = *pSrc++; + mz_uint dst_pos = + (d->m_lookahead_pos + + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; + src_buf_left--; + d->m_dict[dst_pos] = c; + if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) + d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; + if ((++d->m_lookahead_size + d->m_dict_size) >= + TDEFL_MIN_MATCH_LEN) + { + mz_uint ins_pos = + d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2; + mz_uint hash = + ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << + (TDEFL_LZ_HASH_SHIFT * + 2)) ^ (d->m_dict[(ins_pos + + 1) & TDEFL_LZ_DICT_SIZE_MASK] << + TDEFL_LZ_HASH_SHIFT) ^ c) & + (TDEFL_LZ_HASH_SIZE - 1); + d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = + d->m_hash[hash]; + d->m_hash[hash] = (mz_uint16) (ins_pos); + } + } + } + d->m_dict_size = + MZ_MIN (TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size); + if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) + break; + + // Simple lazy/greedy parsing state machine. + len_to_move = 1; + cur_match_dist = 0; + cur_match_len = + d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - + 1); + cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; + if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS)) + { + if ((d->m_dict_size) + && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) + { + mz_uint8 c = + d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK]; + cur_match_len = 0; + while (cur_match_len < d->m_lookahead_size) + { + if (d->m_dict[cur_pos + cur_match_len] != c) + break; + cur_match_len++; + } + if (cur_match_len < TDEFL_MIN_MATCH_LEN) + cur_match_len = 0; + else + cur_match_dist = 1; + } + } + else + { + tdefl_find_match (d, d->m_lookahead_pos, d->m_dict_size, + d->m_lookahead_size, &cur_match_dist, + &cur_match_len); + } + if (((cur_match_len == TDEFL_MIN_MATCH_LEN) + && (cur_match_dist >= 8U * 1024U)) || (cur_pos == cur_match_dist) + || ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5))) + { + cur_match_dist = cur_match_len = 0; + } + if (d->m_saved_match_len) + { + if (cur_match_len > d->m_saved_match_len) + { + tdefl_record_literal (d, (mz_uint8) d->m_saved_lit); + if (cur_match_len >= 128) + { + tdefl_record_match (d, cur_match_len, cur_match_dist); + d->m_saved_match_len = 0; + len_to_move = cur_match_len; + } + else + { + d->m_saved_lit = d->m_dict[cur_pos]; + d->m_saved_match_dist = cur_match_dist; + d->m_saved_match_len = cur_match_len; + } + } + else + { + tdefl_record_match (d, d->m_saved_match_len, + d->m_saved_match_dist); + len_to_move = d->m_saved_match_len - 1; + d->m_saved_match_len = 0; + } + } + else if (!cur_match_dist) + tdefl_record_literal (d, d->m_dict[cur_pos]); + else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) + || (cur_match_len >= 128)) + { + tdefl_record_match (d, cur_match_len, cur_match_dist); + len_to_move = cur_match_len; + } + else + { + d->m_saved_lit = d->m_dict[cur_pos]; + d->m_saved_match_dist = cur_match_dist; + d->m_saved_match_len = cur_match_len; + } + // Move the lookahead forward by len_to_move bytes. + d->m_lookahead_pos += len_to_move; + MZ_ASSERT (d->m_lookahead_size >= len_to_move); + d->m_lookahead_size -= len_to_move; + d->m_dict_size = + MZ_MIN (d->m_dict_size + len_to_move, (mz_uint) TDEFL_LZ_DICT_SIZE); + // Check if it's time to flush the current LZ codes to the internal output buffer. + if ((d->m_pLZ_code_buf > + &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) + || ((d->m_total_lz_bytes > 31 * 1024) + && + (((((mz_uint) (d->m_pLZ_code_buf - d->m_lz_code_buf) * + 115) >> 7) >= d->m_total_lz_bytes) + || (d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS)))) + { + int n; + d->m_pSrc = pSrc; + d->m_src_buf_left = src_buf_left; + if ((n = tdefl_flush_block (d, 0)) != 0) + return (n < 0) ? MZ_FALSE : MZ_TRUE; + } + } + + d->m_pSrc = pSrc; + d->m_src_buf_left = src_buf_left; + return MZ_TRUE; + } + + static tdefl_status tdefl_flush_output_buffer (tdefl_compressor * d) + { + if (d->m_pIn_buf_size) + { + *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *) d->m_pIn_buf; + } + + if (d->m_pOut_buf_size) + { + size_t n = MZ_MIN (*d->m_pOut_buf_size - d->m_out_buf_ofs, + d->m_output_flush_remaining); + memcpy ((mz_uint8 *) d->m_pOut_buf + d->m_out_buf_ofs, + d->m_output_buf + d->m_output_flush_ofs, n); + d->m_output_flush_ofs += (mz_uint) n; + d->m_output_flush_remaining -= (mz_uint) n; + d->m_out_buf_ofs += n; + + *d->m_pOut_buf_size = d->m_out_buf_ofs; + } + + return (d->m_finished + && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE : + TDEFL_STATUS_OKAY; + } + + tdefl_status tdefl_compress (tdefl_compressor * d, const void *pIn_buf, + size_t * pIn_buf_size, void *pOut_buf, + size_t * pOut_buf_size, tdefl_flush flush) + { + if (!d) + { + if (pIn_buf_size) + *pIn_buf_size = 0; + if (pOut_buf_size) + *pOut_buf_size = 0; + return TDEFL_STATUS_BAD_PARAM; + } + + d->m_pIn_buf = pIn_buf; + d->m_pIn_buf_size = pIn_buf_size; + d->m_pOut_buf = pOut_buf; + d->m_pOut_buf_size = pOut_buf_size; + d->m_pSrc = (const mz_uint8 *) (pIn_buf); + d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0; + d->m_out_buf_ofs = 0; + d->m_flush = flush; + + if (((d->m_pPut_buf_func != NULL) == + ((pOut_buf != NULL) || (pOut_buf_size != NULL))) + || (d->m_prev_return_status != TDEFL_STATUS_OKAY) + || (d->m_wants_to_finish && (flush != TDEFL_FINISH)) || (pIn_buf_size + && + *pIn_buf_size + && !pIn_buf) + || (pOut_buf_size && *pOut_buf_size && !pOut_buf)) + { + if (pIn_buf_size) + *pIn_buf_size = 0; + if (pOut_buf_size) + *pOut_buf_size = 0; + return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM); + } + d->m_wants_to_finish |= (flush == TDEFL_FINISH); + + if ((d->m_output_flush_remaining) || (d->m_finished)) + return (d->m_prev_return_status = tdefl_flush_output_buffer (d)); + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN + if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) && + ((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) && + ((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS | + TDEFL_RLE_MATCHES)) == 0)) + { + if (!tdefl_compress_fast (d)) + return d->m_prev_return_status; + } + else +#endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN + { + if (!tdefl_compress_normal (d)) + return d->m_prev_return_status; + } + + if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) + && (pIn_buf)) + d->m_adler32 = + (mz_uint32) mz_adler32 (d->m_adler32, (const mz_uint8 *) pIn_buf, + d->m_pSrc - (const mz_uint8 *) pIn_buf); + + if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) + && (!d->m_output_flush_remaining)) + { + if (tdefl_flush_block (d, flush) < 0) + return d->m_prev_return_status; + d->m_finished = (flush == TDEFL_FINISH); + if (flush == TDEFL_FULL_FLUSH) + { + MZ_CLEAR_OBJ (d->m_hash); + MZ_CLEAR_OBJ (d->m_next); + d->m_dict_size = 0; + } + } + + return (d->m_prev_return_status = tdefl_flush_output_buffer (d)); + } + + tdefl_status tdefl_compress_buffer (tdefl_compressor * d, + const void *pIn_buf, size_t in_buf_size, + tdefl_flush flush) + { + MZ_ASSERT (d->m_pPut_buf_func); + return tdefl_compress (d, pIn_buf, &in_buf_size, NULL, NULL, flush); + } + + tdefl_status tdefl_init (tdefl_compressor * d, + tdefl_put_buf_func_ptr pPut_buf_func, + void *pPut_buf_user, int flags) + { + d->m_pPut_buf_func = pPut_buf_func; + d->m_pPut_buf_user = pPut_buf_user; + d->m_flags = (mz_uint) (flags); + d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3; + d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0; + d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3; + if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) + MZ_CLEAR_OBJ (d->m_hash); + d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size = + d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0; + d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished = + d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0; + d->m_pLZ_code_buf = d->m_lz_code_buf + 1; + d->m_pLZ_flags = d->m_lz_code_buf; + d->m_num_flags_left = 8; + d->m_pOutput_buf = d->m_output_buf; + d->m_pOutput_buf_end = d->m_output_buf; + d->m_prev_return_status = TDEFL_STATUS_OKAY; + d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0; + d->m_adler32 = 1; + d->m_pIn_buf = NULL; + d->m_pOut_buf = NULL; + d->m_pIn_buf_size = NULL; + d->m_pOut_buf_size = NULL; + d->m_flush = TDEFL_NO_FLUSH; + d->m_pSrc = NULL; + d->m_src_buf_left = 0; + d->m_out_buf_ofs = 0; + memset (&d->m_huff_count[0][0], 0, + sizeof (d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); + memset (&d->m_huff_count[1][0], 0, + sizeof (d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); + return TDEFL_STATUS_OKAY; + } + + tdefl_status tdefl_get_prev_return_status (tdefl_compressor * d) + { + return d->m_prev_return_status; + } + + mz_uint32 tdefl_get_adler32 (tdefl_compressor * d) + { + return d->m_adler32; + } + + mz_bool tdefl_compress_mem_to_output (const void *pBuf, size_t buf_len, + tdefl_put_buf_func_ptr pPut_buf_func, + void *pPut_buf_user, int flags) + { + tdefl_compressor *pComp; + mz_bool succeeded; + if (((buf_len) && (!pBuf)) || (!pPut_buf_func)) + return MZ_FALSE; + pComp = (tdefl_compressor *) MZ_MALLOC (sizeof (tdefl_compressor)); + if (!pComp) + return MZ_FALSE; + succeeded = + (tdefl_init (pComp, pPut_buf_func, pPut_buf_user, flags) == + TDEFL_STATUS_OKAY); + succeeded = succeeded + && (tdefl_compress_buffer (pComp, pBuf, buf_len, TDEFL_FINISH) == + TDEFL_STATUS_DONE); + MZ_FREE (pComp); + return succeeded; + } + + typedef struct + { + size_t m_size, m_capacity; + mz_uint8 *m_pBuf; + mz_bool m_expandable; + } tdefl_output_buffer; + + static mz_bool tdefl_output_buffer_putter (const void *pBuf, int len, + void *pUser) + { + tdefl_output_buffer *p = (tdefl_output_buffer *) pUser; + size_t new_size = p->m_size + len; + if (new_size > p->m_capacity) + { + size_t new_capacity = p->m_capacity; + mz_uint8 *pNew_buf; + if (!p->m_expandable) + return MZ_FALSE; + do + { + new_capacity = MZ_MAX (128U, new_capacity << 1U); + } + while (new_size > new_capacity); + pNew_buf = (mz_uint8 *) MZ_REALLOC (p->m_pBuf, new_capacity); + if (!pNew_buf) + return MZ_FALSE; + p->m_pBuf = pNew_buf; + p->m_capacity = new_capacity; + } + memcpy ((mz_uint8 *) p->m_pBuf + p->m_size, pBuf, len); + p->m_size = new_size; + return MZ_TRUE; + } + + void *tdefl_compress_mem_to_heap (const void *pSrc_buf, size_t src_buf_len, + size_t * pOut_len, int flags) + { + tdefl_output_buffer out_buf; + MZ_CLEAR_OBJ (out_buf); + if (!pOut_len) + return MZ_FALSE; + else + *pOut_len = 0; + out_buf.m_expandable = MZ_TRUE; + if (!tdefl_compress_mem_to_output + (pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) + return NULL; + *pOut_len = out_buf.m_size; + return out_buf.m_pBuf; + } + + size_t tdefl_compress_mem_to_mem (void *pOut_buf, size_t out_buf_len, + const void *pSrc_buf, size_t src_buf_len, + int flags) + { + tdefl_output_buffer out_buf; + MZ_CLEAR_OBJ (out_buf); + if (!pOut_buf) + return 0; + out_buf.m_pBuf = (mz_uint8 *) pOut_buf; + out_buf.m_capacity = out_buf_len; + if (!tdefl_compress_mem_to_output + (pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) + return 0; + return out_buf.m_size; + } + + static const mz_uint s_tdefl_num_probes[11] = + { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 }; + +// level may actually range from [0,10] (10 is a "hidden" max level, where we want a bit more compression and it's fine if throughput to fall off a cliff on some files). + mz_uint tdefl_create_comp_flags_from_zip_params (int level, int window_bits, + int strategy) + { + mz_uint comp_flags = s_tdefl_num_probes[(level >= 0) ? MZ_MIN (10, + level) : + MZ_DEFAULT_LEVEL] | ((level <= + 3) ? + TDEFL_GREEDY_PARSING_FLAG + : 0); + if (window_bits > 0) + comp_flags |= TDEFL_WRITE_ZLIB_HEADER; + + if (!level) + comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS; + else if (strategy == MZ_FILTERED) + comp_flags |= TDEFL_FILTER_MATCHES; + else if (strategy == MZ_HUFFMAN_ONLY) + comp_flags &= ~TDEFL_MAX_PROBES_MASK; + else if (strategy == MZ_FIXED) + comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS; + else if (strategy == MZ_RLE) + comp_flags |= TDEFL_RLE_MATCHES; + + return comp_flags; + } + +#ifdef _MSC_VER +#pragma warning (push) +#pragma warning (disable:4204) // nonstandard extension used : non-constant aggregate initializer (also supported by GNU C and C99, so no big deal) +#endif + +// Simple PNG writer function by Alex Evans, 2011. Released into the public domain: https://gist.github.com/908299, more context at +// http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/. + void *tdefl_write_image_to_png_file_in_memory (const void *pImage, int w, + int h, int num_chans, + size_t * pLen_out) + { + tdefl_compressor *pComp = + (tdefl_compressor *) MZ_MALLOC (sizeof (tdefl_compressor)); + tdefl_output_buffer out_buf; + int i, bpl = w * num_chans, y, z; + mz_uint32 c; + *pLen_out = 0; + if (!pComp) + return NULL; + MZ_CLEAR_OBJ (out_buf); + out_buf.m_expandable = MZ_TRUE; + out_buf.m_capacity = 57 + MZ_MAX (64, (1 + bpl) * h); + if (NULL == + (out_buf.m_pBuf = (mz_uint8 *) MZ_MALLOC (out_buf.m_capacity))) + { + MZ_FREE (pComp); + return NULL; + } + // write dummy header + for (z = 41; z; --z) + tdefl_output_buffer_putter (&z, 1, &out_buf); + // compress image data + tdefl_init (pComp, tdefl_output_buffer_putter, &out_buf, + TDEFL_DEFAULT_MAX_PROBES | TDEFL_WRITE_ZLIB_HEADER); + for (y = 0; y < h; ++y) + { + tdefl_compress_buffer (pComp, &z, 1, TDEFL_NO_FLUSH); + tdefl_compress_buffer (pComp, (mz_uint8 *) pImage + y * bpl, bpl, + TDEFL_NO_FLUSH); + } + if (tdefl_compress_buffer (pComp, NULL, 0, TDEFL_FINISH) != + TDEFL_STATUS_DONE) + { + MZ_FREE (pComp); + MZ_FREE (out_buf.m_pBuf); + return NULL; + } + // write real header + *pLen_out = out_buf.m_size - 41; + { + mz_uint8 pnghdr[41] = + { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, + 0x0d, 0x49, 0x48, 0x44, 0x52, + 0, 0, (mz_uint8) (w >> 8), (mz_uint8) w, 0, 0, (mz_uint8) (h >> 8), + (mz_uint8) h, 8, "\0\0\04\02\06"[num_chans], 0, 0, 0, 0, 0, 0, 0, + (mz_uint8) (*pLen_out >> 24), (mz_uint8) (*pLen_out >> 16), + (mz_uint8) (*pLen_out >> 8), (mz_uint8) * pLen_out, 0x49, 0x44, + 0x41, 0x54 + }; + c = (mz_uint32) mz_crc32 (MZ_CRC32_INIT, pnghdr + 12, 17); + for (i = 0; i < 4; ++i, c <<= 8) + ((mz_uint8 *) (pnghdr + 29))[i] = (mz_uint8) (c >> 24); + memcpy (out_buf.m_pBuf, pnghdr, 41); + } + // write footer (IDAT CRC-32, followed by IEND chunk) + if (!tdefl_output_buffer_putter + ("\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf)) + { + *pLen_out = 0; + MZ_FREE (pComp); + MZ_FREE (out_buf.m_pBuf); + return NULL; + } + c = + (mz_uint32) mz_crc32 (MZ_CRC32_INIT, out_buf.m_pBuf + 41 - 4, + *pLen_out + 4); + for (i = 0; i < 4; ++i, c <<= 8) + (out_buf.m_pBuf + out_buf.m_size - 16)[i] = (mz_uint8) (c >> 24); + // compute final size of file, grab compressed data buffer and return + *pLen_out += 57; + MZ_FREE (pComp); + return out_buf.m_pBuf; + } + +#ifdef _MSC_VER +#pragma warning (pop) +#endif + +// ------------------- .ZIP archive reading + +#ifndef MINIZ_NO_ARCHIVE_APIS + +#ifndef MINIZ_NO_TIME +#include +#endif + +#ifdef MINIZ_NO_STDIO +#define MZ_FILE void * +#else +#include +#include +#if defined(_MSC_VER) || defined(__MINGW32__) || defined(__MINGW64__) +#include +#define MZ_FILE FILE +#define MZ_FOPEN fopen +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#define MZ_FTELL64 _ftelli64 +#define MZ_FSEEK64 _fseeki64 +#define MZ_FILE_STAT_STRUCT _stat +#define MZ_FILE_STAT _stat +#define MZ_FFLUSH fflush +#define MZ_FREOPEN freopen +#define MZ_DELETE_FILE remove +#else +#include +#define MZ_FILE FILE +#define MZ_FOPEN fopen +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#define MZ_FTELL64 ftello +#define MZ_FSEEK64 fseeko +#define MZ_FILE_STAT_STRUCT stat +#define MZ_FILE_STAT stat +#define MZ_FFLUSH fflush +#define MZ_FREOPEN freopen +#define MZ_DELETE_FILE remove +#endif // #ifdef _MSC_VER +#endif // #ifdef MINIZ_NO_STDIO + +#define MZ_TOLOWER(c) ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c)) + +// Various ZIP archive enums. To completely avoid cross platform compiler alignment and platform endian issues, miniz.c doesn't use structs for any of this stuff. + enum + { + // ZIP archive identifiers and record sizes + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG = + 0x06054b50, MZ_ZIP_CENTRAL_DIR_HEADER_SIG = + 0x02014b50, MZ_ZIP_LOCAL_DIR_HEADER_SIG = 0x04034b50, + MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE = + 46, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE = 22, + // Central directory header record offsets + MZ_ZIP_CDH_SIG_OFS = 0, MZ_ZIP_CDH_VERSION_MADE_BY_OFS = + 4, MZ_ZIP_CDH_VERSION_NEEDED_OFS = 6, MZ_ZIP_CDH_BIT_FLAG_OFS = 8, + MZ_ZIP_CDH_METHOD_OFS = 10, MZ_ZIP_CDH_FILE_TIME_OFS = + 12, MZ_ZIP_CDH_FILE_DATE_OFS = 14, MZ_ZIP_CDH_CRC32_OFS = 16, + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS = 20, MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS = + 24, MZ_ZIP_CDH_FILENAME_LEN_OFS = 28, MZ_ZIP_CDH_EXTRA_LEN_OFS = 30, + MZ_ZIP_CDH_COMMENT_LEN_OFS = 32, MZ_ZIP_CDH_DISK_START_OFS = + 34, MZ_ZIP_CDH_INTERNAL_ATTR_OFS = 36, MZ_ZIP_CDH_EXTERNAL_ATTR_OFS = + 38, MZ_ZIP_CDH_LOCAL_HEADER_OFS = 42, + // Local directory header offsets + MZ_ZIP_LDH_SIG_OFS = 0, MZ_ZIP_LDH_VERSION_NEEDED_OFS = + 4, MZ_ZIP_LDH_BIT_FLAG_OFS = 6, MZ_ZIP_LDH_METHOD_OFS = + 8, MZ_ZIP_LDH_FILE_TIME_OFS = 10, + MZ_ZIP_LDH_FILE_DATE_OFS = 12, MZ_ZIP_LDH_CRC32_OFS = + 14, MZ_ZIP_LDH_COMPRESSED_SIZE_OFS = + 18, MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS = 22, + MZ_ZIP_LDH_FILENAME_LEN_OFS = 26, MZ_ZIP_LDH_EXTRA_LEN_OFS = 28, + // End of central directory offsets + MZ_ZIP_ECDH_SIG_OFS = 0, MZ_ZIP_ECDH_NUM_THIS_DISK_OFS = + 4, MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS = + 6, MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 8, + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS = 10, MZ_ZIP_ECDH_CDIR_SIZE_OFS = + 12, MZ_ZIP_ECDH_CDIR_OFS_OFS = 16, MZ_ZIP_ECDH_COMMENT_SIZE_OFS = 20, + }; + + typedef struct + { + void *m_p; + size_t m_size, m_capacity; + mz_uint m_element_size; + } mz_zip_array; + + struct mz_zip_internal_state_tag + { + mz_zip_array m_central_dir; + mz_zip_array m_central_dir_offsets; + mz_zip_array m_sorted_central_dir_offsets; + MZ_FILE *m_pFile; + void *m_pMem; + size_t m_mem_size; + size_t m_mem_capacity; + }; + +#define MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(array_ptr, element_size) (array_ptr)->m_element_size = element_size +#define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) ((element_type *)((array_ptr)->m_p))[index] + + static __forceinline void mz_zip_array_clear (mz_zip_archive * pZip, + mz_zip_array * pArray) + { + pZip->m_pFree (pZip->m_pAlloc_opaque, pArray->m_p); + memset (pArray, 0, sizeof (mz_zip_array)); + } + + static mz_bool mz_zip_array_ensure_capacity (mz_zip_archive * pZip, + mz_zip_array * pArray, + size_t min_new_capacity, + mz_uint growing) + { + void *pNew_p; + size_t new_capacity = min_new_capacity; + MZ_ASSERT (pArray->m_element_size); + if (pArray->m_capacity >= min_new_capacity) + return MZ_TRUE; + if (growing) + { + new_capacity = MZ_MAX (1, pArray->m_capacity); + while (new_capacity < min_new_capacity) + new_capacity *= 2; + } + if (NULL == + (pNew_p = + pZip->m_pRealloc (pZip->m_pAlloc_opaque, pArray->m_p, + pArray->m_element_size, new_capacity))) + return MZ_FALSE; + pArray->m_p = pNew_p; + pArray->m_capacity = new_capacity; + return MZ_TRUE; + } + + static __forceinline mz_bool mz_zip_array_reserve (mz_zip_archive * pZip, + mz_zip_array * pArray, + size_t new_capacity, + mz_uint growing) + { + if (new_capacity > pArray->m_capacity) + { + if (!mz_zip_array_ensure_capacity + (pZip, pArray, new_capacity, growing)) + return MZ_FALSE; + } + return MZ_TRUE; + } + + static __forceinline mz_bool mz_zip_array_resize (mz_zip_archive * pZip, + mz_zip_array * pArray, + size_t new_size, + mz_uint growing) + { + if (new_size > pArray->m_capacity) + { + if (!mz_zip_array_ensure_capacity (pZip, pArray, new_size, growing)) + return MZ_FALSE; + } + pArray->m_size = new_size; + return MZ_TRUE; + } + + static __forceinline mz_bool mz_zip_array_ensure_room (mz_zip_archive * + pZip, + mz_zip_array * + pArray, size_t n) + { + return mz_zip_array_reserve (pZip, pArray, pArray->m_size + n, MZ_TRUE); + } + + static __forceinline mz_bool mz_zip_array_push_back (mz_zip_archive * pZip, + mz_zip_array * pArray, + const void *pElements, + size_t n) + { + size_t orig_size = pArray->m_size; + if (!mz_zip_array_resize (pZip, pArray, orig_size + n, MZ_TRUE)) + return MZ_FALSE; + memcpy ((mz_uint8 *) pArray->m_p + orig_size * pArray->m_element_size, + pElements, n * pArray->m_element_size); + return MZ_TRUE; + } + +#ifndef MINIZ_NO_TIME + static time_t mz_zip_dos_to_time_t (int dos_time, int dos_date) + { + struct tm tm; + memset (&tm, 0, sizeof (tm)); + tm.tm_isdst = -1; + tm.tm_year = ((dos_date >> 9) & 127) + 1980 - 1900; + tm.tm_mon = ((dos_date >> 5) & 15) - 1; + tm.tm_mday = dos_date & 31; + tm.tm_hour = (dos_time >> 11) & 31; + tm.tm_min = (dos_time >> 5) & 63; + tm.tm_sec = (dos_time << 1) & 62; + return mktime (&tm); + } + + static void mz_zip_time_to_dos_time (time_t time, mz_uint16 * pDOS_time, + mz_uint16 * pDOS_date) + { + struct tm *tm = localtime (&time); + if (tm) + { + *pDOS_time = + (mz_uint16) (((tm->tm_hour) << 11) + ((tm->tm_min) << 5) + + ((tm->tm_sec) >> 1)); + *pDOS_date = + (mz_uint16) (((tm->tm_year + 1900 - 1980) << 9) + + ((tm->tm_mon + 1) << 5) + tm->tm_mday); + } + } +#endif + +#ifndef MINIZ_NO_STDIO + static mz_bool mz_zip_get_file_modified_time (const char *pFilename, + mz_uint16 * pDOS_time, + mz_uint16 * pDOS_date) + { +#ifdef MINIZ_NO_TIME + (void) pFilename; + *pDOS_date = *pDOS_time = 0; +#else + struct MZ_FILE_STAT_STRUCT file_stat; + if (MZ_FILE_STAT (pFilename, &file_stat) != 0) + return MZ_FALSE; + mz_zip_time_to_dos_time (file_stat.st_mtime, pDOS_time, pDOS_date); +#endif // #ifdef MINIZ_NO_TIME + return MZ_TRUE; + } + + static mz_bool mz_zip_set_file_times (const char *pFilename, + time_t access_time, + time_t modified_time) + { +#ifndef MINIZ_NO_TIME + struct utimbuf t; + t.actime = access_time; + t.modtime = modified_time; + return !utime (pFilename, &t); +#else + pFilename, access_time, modified_time; + return MZ_TRUE; +#endif // #ifndef MINIZ_NO_TIME + } +#endif + + static mz_bool mz_zip_reader_init_internal (mz_zip_archive * pZip, + mz_uint32 flags) + { + (void) flags; + if ((!pZip) || (pZip->m_pState) + || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) + return MZ_FALSE; + + if (!pZip->m_pAlloc) + pZip->m_pAlloc = def_alloc_func; + if (!pZip->m_pFree) + pZip->m_pFree = def_free_func; + if (!pZip->m_pRealloc) + pZip->m_pRealloc = def_realloc_func; + + pZip->m_zip_mode = MZ_ZIP_MODE_READING; + pZip->m_archive_size = 0; + pZip->m_central_directory_file_ofs = 0; + pZip->m_total_files = 0; + + if (NULL == + (pZip->m_pState = + (mz_zip_internal_state *) pZip->m_pAlloc (pZip->m_pAlloc_opaque, 1, + sizeof + (mz_zip_internal_state)))) + return MZ_FALSE; + memset (pZip->m_pState, 0, sizeof (mz_zip_internal_state)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE (&pZip->m_pState->m_central_dir, + sizeof (mz_uint8)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE (&pZip->m_pState->m_central_dir_offsets, + sizeof (mz_uint32)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE (&pZip->m_pState-> + m_sorted_central_dir_offsets, + sizeof (mz_uint32)); + return MZ_TRUE; + } + + static __forceinline mz_bool mz_zip_reader_filename_less (const mz_zip_array + * + pCentral_dir_array, + const mz_zip_array + * + pCentral_dir_offsets, + mz_uint l_index, + mz_uint r_index) + { + const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT (pCentral_dir_array, mz_uint8, + MZ_ZIP_ARRAY_ELEMENT + (pCentral_dir_offsets, + mz_uint32, l_index)), *pE; + const mz_uint8 *pR = &MZ_ZIP_ARRAY_ELEMENT (pCentral_dir_array, mz_uint8, + MZ_ZIP_ARRAY_ELEMENT + (pCentral_dir_offsets, + mz_uint32, r_index)); + mz_uint l_len = MZ_READ_LE16 (pL + MZ_ZIP_CDH_FILENAME_LEN_OFS), r_len = + MZ_READ_LE16 (pR + MZ_ZIP_CDH_FILENAME_LEN_OFS); + mz_uint8 l = 0, r = 0; + pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + pE = pL + MZ_MIN (l_len, r_len); + while (pL < pE) + { + if ((l = MZ_TOLOWER (*pL)) != (r = MZ_TOLOWER (*pR))) + break; + pL++; + pR++; + } + return (pL == pE) ? (l_len < r_len) : (l < r); + } + +#define MZ_SWAP_UINT32(a, b) do { mz_uint32 t = a; a = b; b = t; } MZ_MACRO_END + +// Heap sort of lowercased filenames, used to help accelerate plain central directory searches by mz_zip_reader_locate_file(). (Could also use qsort(), but it could allocate memory.) + static void + mz_zip_reader_sort_central_dir_offsets_by_filename (mz_zip_archive * pZip) + { + mz_zip_internal_state *pState = pZip->m_pState; + const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; + const mz_zip_array *pCentral_dir = &pState->m_central_dir; + mz_uint32 *pIndices = + &MZ_ZIP_ARRAY_ELEMENT (&pState->m_sorted_central_dir_offsets, mz_uint32, + 0); + const int size = pZip->m_total_files; + int start = (size - 2) >> 1, end; + while (start >= 0) + { + int child, root = start; + for (;;) + { + if ((child = (root << 1) + 1) >= size) + break; + child += (((child + 1) < size) + && + (mz_zip_reader_filename_less + (pCentral_dir, pCentral_dir_offsets, pIndices[child], + pIndices[child + 1]))); + if (!mz_zip_reader_filename_less + (pCentral_dir, pCentral_dir_offsets, pIndices[root], + pIndices[child])) + break; + MZ_SWAP_UINT32 (pIndices[root], pIndices[child]); + root = child; + } + start--; + } + + end = size - 1; + while (end > 0) + { + int child, root = 0; + MZ_SWAP_UINT32 (pIndices[end], pIndices[0]); + for (;;) + { + if ((child = (root << 1) + 1) >= end) + break; + child += (((child + 1) < end) + && mz_zip_reader_filename_less (pCentral_dir, + pCentral_dir_offsets, + pIndices[child], + pIndices[child + 1])); + if (!mz_zip_reader_filename_less + (pCentral_dir, pCentral_dir_offsets, pIndices[root], + pIndices[child])) + break; + MZ_SWAP_UINT32 (pIndices[root], pIndices[child]); + root = child; + } + end--; + } + } + + static mz_bool mz_zip_reader_read_central_dir (mz_zip_archive * pZip, + mz_uint32 flags) + { + mz_uint i, n, cdir_size, num_this_disk, cdir_disk_index; + mz_uint64 cdir_ofs; + mz_int64 cur_file_ofs; + const mz_uint8 *p; + mz_uint32 buf_u32[4096 / sizeof (mz_uint32)]; + mz_uint8 *pBuf = (mz_uint8 *) buf_u32; + // Basic sanity checks - reject files which are too small, and check the first 4 bytes of the file to make sure a local header is there. + if (pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return MZ_FALSE; + // Find the end of central directory record by scanning the file from the end towards the beginning. + cur_file_ofs = + MZ_MAX ((mz_int64) pZip->m_archive_size - (mz_int64) sizeof (buf_u32), + 0); + for (;;) + { + int i, n = (int) MZ_MIN (sizeof (buf_u32), + pZip->m_archive_size - cur_file_ofs); + if (pZip->m_pRead (pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != + (mz_uint) n) + return MZ_FALSE; + for (i = n - 4; i >= 0; --i) + if (MZ_READ_LE32 (pBuf + i) == MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) + break; + if (i >= 0) + { + cur_file_ofs += i; + break; + } + if ((!cur_file_ofs) + || ((pZip->m_archive_size - cur_file_ofs) >= + (0xFFFF + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE))) + return MZ_FALSE; + cur_file_ofs = MZ_MAX (cur_file_ofs - (sizeof (buf_u32) - 3), 0); + } + // Read and verify the end of central directory record. + if (pZip->m_pRead (pZip->m_pIO_opaque, cur_file_ofs, pBuf, + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return MZ_FALSE; + if ((MZ_READ_LE32 (pBuf + MZ_ZIP_ECDH_SIG_OFS) != + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) + || + ((pZip->m_total_files = + MZ_READ_LE16 (pBuf + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS)) != + MZ_READ_LE16 (pBuf + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS))) + return MZ_FALSE; + + num_this_disk = MZ_READ_LE16 (pBuf + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS); + cdir_disk_index = MZ_READ_LE16 (pBuf + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS); + if (((num_this_disk | cdir_disk_index) != 0) + && ((num_this_disk != 1) || (cdir_disk_index != 1))) + return MZ_FALSE; + + if ((cdir_size = + MZ_READ_LE32 (pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS)) < + pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) + return MZ_FALSE; + + cdir_ofs = MZ_READ_LE32 (pBuf + MZ_ZIP_ECDH_CDIR_OFS_OFS); + if ((cdir_ofs + (mz_uint64) cdir_size) > pZip->m_archive_size) + return MZ_FALSE; + + pZip->m_central_directory_file_ofs = cdir_ofs; + + if (pZip->m_total_files) + { + // Read the entire central directory into a heap block, and allocate another heap block to hold the unsorted central dir file record offsets, and another to hold the sorted indices. + if ((!mz_zip_array_resize + (pZip, &pZip->m_pState->m_central_dir, cdir_size, MZ_FALSE)) + || + (!mz_zip_array_resize + (pZip, &pZip->m_pState->m_central_dir_offsets, + pZip->m_total_files, MZ_FALSE)) + || + (!mz_zip_array_resize + (pZip, &pZip->m_pState->m_sorted_central_dir_offsets, + pZip->m_total_files, MZ_FALSE))) + return MZ_FALSE; + if (pZip->m_pRead (pZip->m_pIO_opaque, cdir_ofs, + pZip->m_pState->m_central_dir.m_p, + cdir_size) != cdir_size) + return MZ_FALSE; + + // Now create an index into the central directory file records, do some basic sanity checking on each record, and check for zip64 entries (which are not yet supported). + p = (const mz_uint8 *) pZip->m_pState->m_central_dir.m_p; + for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i) + { + mz_uint total_header_size, comp_size, decomp_size, disk_index; + if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) + || (MZ_READ_LE32 (p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG)) + return MZ_FALSE; + MZ_ZIP_ARRAY_ELEMENT (&pZip->m_pState->m_central_dir_offsets, + mz_uint32, i) = + (mz_uint32) (p - + (const mz_uint8 *) pZip->m_pState->m_central_dir. + m_p); + MZ_ZIP_ARRAY_ELEMENT (&pZip->m_pState-> + m_sorted_central_dir_offsets, mz_uint32, + i) = i; + comp_size = MZ_READ_LE32 (p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); + decomp_size = MZ_READ_LE32 (p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); + if (((!MZ_READ_LE32 (p + MZ_ZIP_CDH_METHOD_OFS)) + && (decomp_size != comp_size)) || (decomp_size && !comp_size) + || (decomp_size == 0xFFFFFFFF) || (comp_size == 0xFFFFFFFF)) + return MZ_FALSE; + disk_index = MZ_READ_LE16 (p + MZ_ZIP_CDH_DISK_START_OFS); + if ((disk_index != num_this_disk) && (disk_index != 1)) + return MZ_FALSE; + if (((mz_uint64) MZ_READ_LE32 (p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) + + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > + pZip->m_archive_size) + return MZ_FALSE; + if ((total_header_size = + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16 (p + + MZ_ZIP_CDH_FILENAME_LEN_OFS) + + MZ_READ_LE16 (p + MZ_ZIP_CDH_EXTRA_LEN_OFS) + + MZ_READ_LE16 (p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) > n) + return MZ_FALSE; + n -= total_header_size; + p += total_header_size; + } + } + + if ((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0) + mz_zip_reader_sort_central_dir_offsets_by_filename (pZip); + + return MZ_TRUE; + } + + mz_bool mz_zip_reader_init (mz_zip_archive * pZip, mz_uint64 size, + mz_uint32 flags) + { + if ((!pZip) || (!pZip->m_pRead)) + return MZ_FALSE; + if (!mz_zip_reader_init_internal (pZip, flags)) + return MZ_FALSE; + pZip->m_archive_size = size; + if (!mz_zip_reader_read_central_dir (pZip, flags)) + { + mz_zip_reader_end (pZip); + return MZ_FALSE; + } + return MZ_TRUE; + } + + static size_t mz_zip_mem_read_func (void *pOpaque, mz_uint64 file_ofs, + void *pBuf, size_t n) + { + mz_zip_archive *pZip = (mz_zip_archive *) pOpaque; + size_t s = + (file_ofs >= + pZip->m_archive_size) ? 0 : (size_t) MZ_MIN (pZip->m_archive_size - + file_ofs, n); + memcpy (pBuf, (const mz_uint8 *) pZip->m_pState->m_pMem + file_ofs, s); + return s; + } + + mz_bool mz_zip_reader_init_mem (mz_zip_archive * pZip, const void *pMem, + size_t size, mz_uint32 flags) + { + if (!mz_zip_reader_init_internal (pZip, flags)) + return MZ_FALSE; + pZip->m_archive_size = size; + pZip->m_pRead = mz_zip_mem_read_func; + pZip->m_pIO_opaque = pZip; + pZip->m_pState->m_pMem = (void *) pMem; + pZip->m_pState->m_mem_size = size; + if (!mz_zip_reader_read_central_dir (pZip, flags)) + { + mz_zip_reader_end (pZip); + return MZ_FALSE; + } + return MZ_TRUE; + } + +#ifndef MINIZ_NO_STDIO + static size_t mz_zip_file_read_func (void *pOpaque, mz_uint64 file_ofs, + void *pBuf, size_t n) + { + mz_zip_archive *pZip = (mz_zip_archive *) pOpaque; + mz_int64 cur_ofs = MZ_FTELL64 (pZip->m_pState->m_pFile); + if (((mz_int64) file_ofs < 0) + || (((cur_ofs != (mz_int64) file_ofs)) + && + (MZ_FSEEK64 + (pZip->m_pState->m_pFile, (mz_int64) file_ofs, SEEK_SET)))) + return 0; + return MZ_FREAD (pBuf, 1, n, pZip->m_pState->m_pFile); + } + + mz_bool mz_zip_reader_init_file (mz_zip_archive * pZip, + const char *pFilename, mz_uint32 flags) + { + mz_uint64 file_size; + MZ_FILE *pFile = MZ_FOPEN (pFilename, "rb"); + if (!pFile) + return MZ_FALSE; + if (MZ_FSEEK64 (pFile, 0, SEEK_END)) + { + MZ_FCLOSE (pFile); + return MZ_FALSE; + } + file_size = MZ_FTELL64 (pFile); + if (!mz_zip_reader_init_internal (pZip, flags)) + { + MZ_FCLOSE (pFile); + return MZ_FALSE; + } + pZip->m_pRead = mz_zip_file_read_func; + pZip->m_pIO_opaque = pZip; + pZip->m_pState->m_pFile = pFile; + pZip->m_archive_size = file_size; + if (!mz_zip_reader_read_central_dir (pZip, flags)) + { + mz_zip_reader_end (pZip); + return MZ_FALSE; + } + return MZ_TRUE; + } +#endif // #ifndef MINIZ_NO_STDIO + + mz_uint mz_zip_reader_get_num_files (mz_zip_archive * pZip) + { + return pZip ? pZip->m_total_files : 0; + } + + static __forceinline const mz_uint8 *mz_zip_reader_get_cdh (mz_zip_archive * + pZip, + mz_uint + file_index) + { + if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files) + || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) + return NULL; + return &MZ_ZIP_ARRAY_ELEMENT (&pZip->m_pState->m_central_dir, mz_uint8, + MZ_ZIP_ARRAY_ELEMENT (&pZip->m_pState-> + m_central_dir_offsets, + mz_uint32, + file_index)); + } + + mz_bool mz_zip_reader_is_file_encrypted (mz_zip_archive * pZip, + mz_uint file_index) + { + mz_uint m_bit_flag; + const mz_uint8 *p = mz_zip_reader_get_cdh (pZip, file_index); + if (!p) + return MZ_FALSE; + m_bit_flag = MZ_READ_LE16 (p + MZ_ZIP_CDH_BIT_FLAG_OFS); + return (m_bit_flag & 1); + } + + mz_bool mz_zip_reader_is_file_a_directory (mz_zip_archive * pZip, + mz_uint file_index) + { + mz_uint filename_len, internal_attr, external_attr; + const mz_uint8 *p = mz_zip_reader_get_cdh (pZip, file_index); + if (!p) + return MZ_FALSE; + + internal_attr = MZ_READ_LE16 (p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS); + external_attr = MZ_READ_LE32 (p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); + if ((!internal_attr) && ((external_attr & 0x10) != 0)) + return MZ_TRUE; + + filename_len = MZ_READ_LE16 (p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + if (filename_len) + { + if (*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/') + return MZ_TRUE; + } + + return MZ_FALSE; + } + + mz_bool mz_zip_reader_file_stat (mz_zip_archive * pZip, mz_uint file_index, + mz_zip_archive_file_stat * pStat) + { + mz_uint n; + const mz_uint8 *p = mz_zip_reader_get_cdh (pZip, file_index); + if ((!p) || (!pStat)) + return MZ_FALSE; + + // Unpack the central directory record. + pStat->m_file_index = file_index; + pStat->m_central_dir_ofs = + MZ_ZIP_ARRAY_ELEMENT (&pZip->m_pState->m_central_dir_offsets, mz_uint32, + file_index); + pStat->m_version_made_by = + MZ_READ_LE16 (p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS); + pStat->m_version_needed = + MZ_READ_LE16 (p + MZ_ZIP_CDH_VERSION_NEEDED_OFS); + pStat->m_bit_flag = MZ_READ_LE16 (p + MZ_ZIP_CDH_BIT_FLAG_OFS); + pStat->m_method = MZ_READ_LE16 (p + MZ_ZIP_CDH_METHOD_OFS); +#ifndef MINIZ_NO_TIME + pStat->m_time = + mz_zip_dos_to_time_t (MZ_READ_LE16 (p + MZ_ZIP_CDH_FILE_TIME_OFS), + MZ_READ_LE16 (p + MZ_ZIP_CDH_FILE_DATE_OFS)); +#endif + pStat->m_crc32 = MZ_READ_LE32 (p + MZ_ZIP_CDH_CRC32_OFS); + pStat->m_comp_size = MZ_READ_LE32 (p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); + pStat->m_uncomp_size = + MZ_READ_LE32 (p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); + pStat->m_internal_attr = MZ_READ_LE16 (p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS); + pStat->m_external_attr = MZ_READ_LE32 (p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); + pStat->m_local_header_ofs = + MZ_READ_LE32 (p + MZ_ZIP_CDH_LOCAL_HEADER_OFS); + + // Copy as much of the filename and comment as possible. + n = MZ_READ_LE16 (p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + n = MZ_MIN (n, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE - 1); + memcpy (pStat->m_filename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); + pStat->m_filename[n] = '\0'; + + n = MZ_READ_LE16 (p + MZ_ZIP_CDH_COMMENT_LEN_OFS); + n = MZ_MIN (n, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE - 1); + pStat->m_comment_size = n; + memcpy (pStat->m_comment, + p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16 (p + + MZ_ZIP_CDH_FILENAME_LEN_OFS) + + MZ_READ_LE16 (p + MZ_ZIP_CDH_EXTRA_LEN_OFS), n); + pStat->m_comment[n] = '\0'; + + return MZ_TRUE; + } + + mz_uint mz_zip_reader_get_filename (mz_zip_archive * pZip, + mz_uint file_index, char *pFilename, + mz_uint filename_buf_size) + { + mz_uint n; + const mz_uint8 *p = mz_zip_reader_get_cdh (pZip, file_index); + if (!p) + { + if (filename_buf_size) + pFilename[0] = '\0'; + return 0; + } + n = MZ_READ_LE16 (p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + if (filename_buf_size) + { + n = MZ_MIN (n, filename_buf_size - 1); + memcpy (pFilename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); + pFilename[n] = '\0'; + } + return n + 1; + } + + static __forceinline mz_bool mz_zip_reader_string_equal (const char *pA, + const char *pB, + mz_uint len, + mz_uint flags) + { + mz_uint i; + if (flags & MZ_ZIP_FLAG_CASE_SENSITIVE) + return 0 == memcmp (pA, pB, len); + for (i = 0; i < len; ++i) + if (MZ_TOLOWER (pA[i]) != MZ_TOLOWER (pB[i])) + return MZ_FALSE; + return MZ_TRUE; + } + + static __forceinline int mz_zip_reader_filename_compare (const mz_zip_array + * + pCentral_dir_array, + const mz_zip_array + * + pCentral_dir_offsets, + mz_uint l_index, + const char *pR, + mz_uint r_len) + { + const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT (pCentral_dir_array, mz_uint8, + MZ_ZIP_ARRAY_ELEMENT + (pCentral_dir_offsets, + mz_uint32, l_index)), *pE; + mz_uint l_len = MZ_READ_LE16 (pL + MZ_ZIP_CDH_FILENAME_LEN_OFS); + mz_uint8 l = 0, r = 0; + pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + pE = pL + MZ_MIN (l_len, r_len); + while (pL < pE) + { + if ((l = MZ_TOLOWER (*pL)) != (r = MZ_TOLOWER (*pR))) + break; + pL++; + pR++; + } + return (pL == pE) ? (int) (l_len - r_len) : (l - r); + } + + static int mz_zip_reader_locate_file_binary_search (mz_zip_archive * pZip, + const char *pFilename) + { + mz_zip_internal_state *pState = pZip->m_pState; + const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; + const mz_zip_array *pCentral_dir = &pState->m_central_dir; + mz_uint32 *pIndices = + &MZ_ZIP_ARRAY_ELEMENT (&pState->m_sorted_central_dir_offsets, mz_uint32, + 0); + const int size = pZip->m_total_files; + const mz_uint filename_len = (mz_uint) strlen (pFilename); + int l = 0, h = size - 1; + while (l <= h) + { + int m = (l + h) >> 1, file_index = pIndices[m], comp = + mz_zip_reader_filename_compare (pCentral_dir, pCentral_dir_offsets, + file_index, pFilename, + filename_len); + if (!comp) + return file_index; + else if (comp < 0) + l = m + 1; + else + h = m - 1; + } + return -1; + } + + int mz_zip_reader_locate_file (mz_zip_archive * pZip, const char *pName, + const char *pComment, mz_uint flags) + { + mz_uint file_index; + size_t name_len, comment_len; + if ((!pZip) || (!pZip->m_pState) || (!pName) + || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) + return -1; + if (((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == + 0) && (!pComment) + && (pZip->m_pState->m_sorted_central_dir_offsets.m_p)) + return mz_zip_reader_locate_file_binary_search (pZip, pName); + name_len = strlen (pName); + if (name_len > 0xFFFF) + return -1; + comment_len = pComment ? strlen (pComment) : 0; + if (comment_len > 0xFFFF) + return -1; + for (file_index = 0; file_index < pZip->m_total_files; file_index++) + { + const mz_uint8 *pHeader = + &MZ_ZIP_ARRAY_ELEMENT (&pZip->m_pState->m_central_dir, mz_uint8, + MZ_ZIP_ARRAY_ELEMENT (&pZip->m_pState-> + m_central_dir_offsets, + mz_uint32, + file_index)); + mz_uint filename_len = + MZ_READ_LE16 (pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS); + const char *pFilename = + (const char *) pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + if (filename_len < name_len) + continue; + if (comment_len) + { + mz_uint file_extra_len = + MZ_READ_LE16 (pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS), + file_comment_len = + MZ_READ_LE16 (pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS); + const char *pFile_comment = + pFilename + filename_len + file_extra_len; + if ((file_comment_len != comment_len) + || + (!mz_zip_reader_string_equal + (pComment, pFile_comment, file_comment_len, flags))) + continue; + } + if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len)) + { + int ofs = filename_len - 1; + do + { + if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') + || (pFilename[ofs] == ':')) + break; + } + while (--ofs >= 0); + ofs++; + pFilename += ofs; + filename_len -= ofs; + } + if ((filename_len == name_len) + && + (mz_zip_reader_string_equal + (pName, pFilename, filename_len, flags))) + return file_index; + } + return -1; + } + + mz_bool mz_zip_reader_extract_to_mem_no_alloc (mz_zip_archive * pZip, + mz_uint file_index, + void *pBuf, size_t buf_size, + mz_uint flags, + void *pUser_read_buf, + size_t user_read_buf_size) + { + int status = TINFL_STATUS_DONE; + mz_uint64 needed_size, cur_file_ofs, comp_remaining, out_buf_ofs = + 0, read_buf_size, read_buf_ofs = 0, read_buf_avail; + mz_zip_archive_file_stat file_stat; + void *pRead_buf; + mz_uint32 + local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof (mz_uint32) - + 1) / sizeof (mz_uint32)]; + mz_uint8 *pLocal_header = (mz_uint8 *) local_header_u32; + tinfl_decompressor inflator; + + if ((buf_size) && (!pBuf)) + return MZ_FALSE; + + if (!mz_zip_reader_file_stat (pZip, file_index, &file_stat)) + return MZ_FALSE; + + if (!file_stat.m_comp_size) + return MZ_TRUE; + + // Encryption and patch files are not supported. + if (file_stat.m_bit_flag & (1 | 32)) + return MZ_FALSE; + + // This function only supports stored and deflate. + if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) + && (file_stat.m_method != MZ_DEFLATED)) + return MZ_FALSE; + + // Ensure supplied output buffer is large enough. + needed_size = + (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat. + m_comp_size : file_stat.m_uncomp_size; + if (buf_size < needed_size) + return MZ_FALSE; + + // Read and parse the local directory entry. + cur_file_ofs = file_stat.m_local_header_ofs; + if (pZip->m_pRead (pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return MZ_FALSE; + if (MZ_READ_LE32 (pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + return MZ_FALSE; + + cur_file_ofs += + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16 (pLocal_header + + MZ_ZIP_LDH_FILENAME_LEN_OFS) + + MZ_READ_LE16 (pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) + return MZ_FALSE; + + if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) + { + // The file is stored or the caller has requested the compressed data. + if (pZip->m_pRead (pZip->m_pIO_opaque, cur_file_ofs, pBuf, + (size_t) needed_size) != needed_size) + return MZ_FALSE; + return ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) != 0) + || + (mz_crc32 + (MZ_CRC32_INIT, (const mz_uint8 *) pBuf, + (size_t) file_stat.m_uncomp_size) == file_stat.m_crc32); + } + + // Decompress the file either directly from memory or from a file input buffer. + tinfl_init (&inflator); + + if (pZip->m_pState->m_pMem) + { + // Read directly from the archive in memory. + pRead_buf = (mz_uint8 *) pZip->m_pState->m_pMem + cur_file_ofs; + read_buf_size = read_buf_avail = file_stat.m_comp_size; + comp_remaining = 0; + } + else if (pUser_read_buf) + { + // Use a user provided read buffer. + if (!user_read_buf_size) + return MZ_FALSE; + pRead_buf = (mz_uint8 *) pUser_read_buf; + read_buf_size = user_read_buf_size; + read_buf_avail = 0; + comp_remaining = file_stat.m_uncomp_size; + } + else + { + // Temporarily allocate a read buffer. + read_buf_size = + MZ_MIN (file_stat.m_comp_size, (mz_uint64) MZ_ZIP_MAX_IO_BUF_SIZE); + if (((0, sizeof (size_t) == sizeof (mz_uint32))) + && (read_buf_size > 0x7FFFFFFF)) + return MZ_FALSE; + if (NULL == + (pRead_buf = + pZip->m_pAlloc (pZip->m_pAlloc_opaque, 1, + (size_t) read_buf_size))) + return MZ_FALSE; + read_buf_avail = 0; + comp_remaining = file_stat.m_comp_size; + } + + do + { + size_t in_buf_size, out_buf_size = + (size_t) (file_stat.m_uncomp_size - out_buf_ofs); + if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) + { + read_buf_avail = MZ_MIN (read_buf_size, comp_remaining); + if (pZip->m_pRead (pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, + (size_t) read_buf_avail) != read_buf_avail) + { + status = TINFL_STATUS_FAILED; + break; + } + cur_file_ofs += read_buf_avail; + comp_remaining -= read_buf_avail; + read_buf_ofs = 0; + } + in_buf_size = (size_t) read_buf_avail; + status = + tinfl_decompress (&inflator, (mz_uint8 *) pRead_buf + read_buf_ofs, + &in_buf_size, (mz_uint8 *) pBuf, + (mz_uint8 *) pBuf + out_buf_ofs, &out_buf_size, + TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF | + (comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0)); + read_buf_avail -= in_buf_size; + read_buf_ofs += in_buf_size; + out_buf_ofs += out_buf_size; + } + while (status == TINFL_STATUS_NEEDS_MORE_INPUT); + + if (status == TINFL_STATUS_DONE) + { + // Make sure the entire file was decompressed, and check its CRC. + if ((out_buf_ofs != file_stat.m_uncomp_size) + || + (mz_crc32 + (MZ_CRC32_INIT, (const mz_uint8 *) pBuf, + (size_t) file_stat.m_uncomp_size) != file_stat.m_crc32)) + status = TINFL_STATUS_FAILED; + } + + if ((!pZip->m_pState->m_pMem) && (!pUser_read_buf)) + pZip->m_pFree (pZip->m_pAlloc_opaque, pRead_buf); + + return status == TINFL_STATUS_DONE; + } + + mz_bool mz_zip_reader_extract_file_to_mem_no_alloc (mz_zip_archive * pZip, + const char *pFilename, + void *pBuf, + size_t buf_size, + mz_uint flags, + void *pUser_read_buf, + size_t + user_read_buf_size) + { + int file_index = mz_zip_reader_locate_file (pZip, pFilename, NULL, flags); + if (file_index < 0) + return MZ_FALSE; + return mz_zip_reader_extract_to_mem_no_alloc (pZip, file_index, pBuf, + buf_size, flags, + pUser_read_buf, + user_read_buf_size); + } + + mz_bool mz_zip_reader_extract_to_mem (mz_zip_archive * pZip, + mz_uint file_index, void *pBuf, + size_t buf_size, mz_uint flags) + { + return mz_zip_reader_extract_to_mem_no_alloc (pZip, file_index, pBuf, + buf_size, flags, NULL, 0); + } + + mz_bool mz_zip_reader_extract_file_to_mem (mz_zip_archive * pZip, + const char *pFilename, + void *pBuf, size_t buf_size, + mz_uint flags) + { + return mz_zip_reader_extract_file_to_mem_no_alloc (pZip, pFilename, pBuf, + buf_size, flags, NULL, + 0); + } + + void *mz_zip_reader_extract_to_heap (mz_zip_archive * pZip, + mz_uint file_index, size_t * pSize, + mz_uint flags) + { + mz_uint64 comp_size, uncomp_size, alloc_size; + const mz_uint8 *p = mz_zip_reader_get_cdh (pZip, file_index); + void *pBuf; + + if (pSize) + *pSize = 0; + if (!p) + return NULL; + + comp_size = MZ_READ_LE32 (p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); + uncomp_size = MZ_READ_LE32 (p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); + + alloc_size = + (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? comp_size : uncomp_size; + if (((0, sizeof (size_t) == sizeof (mz_uint32))) + && (alloc_size > 0x7FFFFFFF)) + return NULL; + if (NULL == + (pBuf = + pZip->m_pAlloc (pZip->m_pAlloc_opaque, 1, (size_t) alloc_size))) + return NULL; + + if (!mz_zip_reader_extract_to_mem + (pZip, file_index, pBuf, (size_t) alloc_size, flags)) + { + pZip->m_pFree (pZip->m_pAlloc_opaque, pBuf); + return NULL; + } + + if (pSize) + *pSize = (size_t) alloc_size; + return pBuf; + } + + void *mz_zip_reader_extract_file_to_heap (mz_zip_archive * pZip, + const char *pFilename, + size_t * pSize, mz_uint flags) + { + int file_index = mz_zip_reader_locate_file (pZip, pFilename, NULL, flags); + if (file_index < 0) + { + if (pSize) + *pSize = 0; + return MZ_FALSE; + } + return mz_zip_reader_extract_to_heap (pZip, file_index, pSize, flags); + } + + mz_bool mz_zip_reader_extract_to_callback (mz_zip_archive * pZip, + mz_uint file_index, + mz_file_write_func pCallback, + void *pOpaque, mz_uint flags) + { + int status = TINFL_STATUS_DONE; + mz_uint file_crc32 = MZ_CRC32_INIT; + mz_uint64 read_buf_size, read_buf_ofs = + 0, read_buf_avail, comp_remaining, out_buf_ofs = 0, cur_file_ofs; + mz_zip_archive_file_stat file_stat; + void *pRead_buf = NULL; + void *pWrite_buf = NULL; + mz_uint32 + local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof (mz_uint32) - + 1) / sizeof (mz_uint32)]; + mz_uint8 *pLocal_header = (mz_uint8 *) local_header_u32; + + if (!mz_zip_reader_file_stat (pZip, file_index, &file_stat)) + return MZ_FALSE; + + if (!file_stat.m_comp_size) + return MZ_TRUE; + + // Encryption and patch files are not supported. + if (file_stat.m_bit_flag & (1 | 32)) + return MZ_FALSE; + + // This function only supports stored and deflate. + if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) + && (file_stat.m_method != MZ_DEFLATED)) + return MZ_FALSE; + + // Read and parse the local directory entry. + cur_file_ofs = file_stat.m_local_header_ofs; + if (pZip->m_pRead (pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return MZ_FALSE; + if (MZ_READ_LE32 (pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + return MZ_FALSE; + + cur_file_ofs += + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16 (pLocal_header + + MZ_ZIP_LDH_FILENAME_LEN_OFS) + + MZ_READ_LE16 (pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) + return MZ_FALSE; + + // Decompress the file either directly from memory or from a file input buffer. + if (pZip->m_pState->m_pMem) + { + pRead_buf = (mz_uint8 *) pZip->m_pState->m_pMem + cur_file_ofs; + read_buf_size = read_buf_avail = file_stat.m_comp_size; + comp_remaining = 0; + } + else + { + read_buf_size = + MZ_MIN (file_stat.m_comp_size, (mz_uint64) MZ_ZIP_MAX_IO_BUF_SIZE); + if (NULL == + (pRead_buf = + pZip->m_pAlloc (pZip->m_pAlloc_opaque, 1, + (size_t) read_buf_size))) + return MZ_FALSE; + read_buf_avail = 0; + comp_remaining = file_stat.m_comp_size; + } + + if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) + { + // The file is stored or the caller has requested the compressed data. + if (pZip->m_pState->m_pMem) + { + if (((0, sizeof (size_t) == sizeof (mz_uint32))) + && (file_stat.m_comp_size > 0xFFFFFFFF)) + return MZ_FALSE; + if (pCallback + (pOpaque, out_buf_ofs, pRead_buf, + (size_t) file_stat.m_comp_size) != file_stat.m_comp_size) + status = TINFL_STATUS_FAILED; + else if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + file_crc32 = + (mz_uint32) mz_crc32 (file_crc32, + (const mz_uint8 *) pRead_buf, + (size_t) file_stat.m_comp_size); + cur_file_ofs += file_stat.m_comp_size; + out_buf_ofs += file_stat.m_comp_size; + comp_remaining = 0; + } + else + { + while (comp_remaining) + { + read_buf_avail = MZ_MIN (read_buf_size, comp_remaining); + if (pZip->m_pRead + (pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, + (size_t) read_buf_avail) != read_buf_avail) + { + status = TINFL_STATUS_FAILED; + break; + } + + if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + file_crc32 = + (mz_uint32) mz_crc32 (file_crc32, + (const mz_uint8 *) pRead_buf, + (size_t) read_buf_avail); + + if (pCallback + (pOpaque, out_buf_ofs, pRead_buf, + (size_t) read_buf_avail) != read_buf_avail) + { + status = TINFL_STATUS_FAILED; + break; + } + cur_file_ofs += read_buf_avail; + out_buf_ofs += read_buf_avail; + comp_remaining -= read_buf_avail; + } + } + } + else + { + tinfl_decompressor inflator; + tinfl_init (&inflator); + + if (NULL == + (pWrite_buf = + pZip->m_pAlloc (pZip->m_pAlloc_opaque, 1, TINFL_LZ_DICT_SIZE))) + status = TINFL_STATUS_FAILED; + else + { + do + { + mz_uint8 *pWrite_buf_cur = + (mz_uint8 *) pWrite_buf + + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); + size_t in_buf_size, out_buf_size = + TINFL_LZ_DICT_SIZE - + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); + if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) + { + read_buf_avail = MZ_MIN (read_buf_size, comp_remaining); + if (pZip->m_pRead + (pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, + (size_t) read_buf_avail) != read_buf_avail) + { + status = TINFL_STATUS_FAILED; + break; + } + cur_file_ofs += read_buf_avail; + comp_remaining -= read_buf_avail; + read_buf_ofs = 0; + } + + in_buf_size = (size_t) read_buf_avail; + status = + tinfl_decompress (&inflator, + (const mz_uint8 *) pRead_buf + + read_buf_ofs, &in_buf_size, + (mz_uint8 *) pWrite_buf, pWrite_buf_cur, + &out_buf_size, + comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT + : 0); + read_buf_avail -= in_buf_size; + read_buf_ofs += in_buf_size; + + if (out_buf_size) + { + if (pCallback + (pOpaque, out_buf_ofs, pWrite_buf_cur, + out_buf_size) != out_buf_size) + { + status = TINFL_STATUS_FAILED; + break; + } + file_crc32 = + (mz_uint32) mz_crc32 (file_crc32, pWrite_buf_cur, + out_buf_size); + if ((out_buf_ofs += + out_buf_size) > file_stat.m_uncomp_size) + { + status = TINFL_STATUS_FAILED; + break; + } + } + } + while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) + || (status == TINFL_STATUS_HAS_MORE_OUTPUT)); + } + } +#if 0 + if ((status == TINFL_STATUS_DONE) + && (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) + { + // Make sure the entire file was decompressed, and check its CRC. + if ((out_buf_ofs != file_stat.m_uncomp_size) + || (file_crc32 != file_stat.m_crc32)) + status = TINFL_STATUS_FAILED; + } +#endif + if (!pZip->m_pState->m_pMem) + pZip->m_pFree (pZip->m_pAlloc_opaque, pRead_buf); + if (pWrite_buf) + pZip->m_pFree (pZip->m_pAlloc_opaque, pWrite_buf); + + return status == TINFL_STATUS_DONE; + } + + mz_bool mz_zip_reader_extract_file_to_callback (mz_zip_archive * pZip, + const char *pFilename, + mz_file_write_func + pCallback, void *pOpaque, + mz_uint flags) + { + int file_index = mz_zip_reader_locate_file (pZip, pFilename, NULL, flags); + if (file_index < 0) + return MZ_FALSE; + return mz_zip_reader_extract_to_callback (pZip, file_index, pCallback, + pOpaque, flags); + } + +#ifndef MINIZ_NO_STDIO + static size_t mz_zip_file_write_callback (void *pOpaque, mz_uint64 ofs, + const void *pBuf, size_t n) + { + (void) ofs; + return MZ_FWRITE (pBuf, 1, n, (MZ_FILE *) pOpaque); + } + + mz_bool mz_zip_reader_extract_to_file (mz_zip_archive * pZip, + mz_uint file_index, + const char *pDst_filename, + mz_uint flags) + { + mz_bool status; + mz_zip_archive_file_stat file_stat; + MZ_FILE *pFile; + if (!mz_zip_reader_file_stat (pZip, file_index, &file_stat)) + return MZ_FALSE; + pFile = MZ_FOPEN (pDst_filename, "wb"); + if (!pFile) + return MZ_FALSE; + status = + mz_zip_reader_extract_to_callback (pZip, file_index, + mz_zip_file_write_callback, pFile, + flags); + if (MZ_FCLOSE (pFile) == EOF) + return MZ_FALSE; +#ifndef MINIZ_NO_TIME + if (status) + mz_zip_set_file_times (pDst_filename, file_stat.m_time, + file_stat.m_time); +#endif + return status; + } +#endif // #ifndef MINIZ_NO_STDIO + + mz_bool mz_zip_reader_end (mz_zip_archive * pZip) + { + if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) + || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) + return MZ_FALSE; + + if (pZip->m_pState) + { + mz_zip_internal_state *pState = pZip->m_pState; + pZip->m_pState = NULL; + mz_zip_array_clear (pZip, &pState->m_central_dir); + mz_zip_array_clear (pZip, &pState->m_central_dir_offsets); + mz_zip_array_clear (pZip, &pState->m_sorted_central_dir_offsets); + +#ifndef MINIZ_NO_STDIO + if (pState->m_pFile) + { + MZ_FCLOSE (pState->m_pFile); + pState->m_pFile = NULL; + } +#endif // #ifndef MINIZ_NO_STDIO + + pZip->m_pFree (pZip->m_pAlloc_opaque, pState); + } + pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; + + return MZ_TRUE; + } + + mz_bool mz_zip_reader_extract_file_to_file (mz_zip_archive * pZip, + const char *pArchive_filename, + const char *pDst_filename, + mz_uint flags) + { + int file_index = + mz_zip_reader_locate_file (pZip, pArchive_filename, NULL, flags); + if (file_index < 0) + return MZ_FALSE; + return mz_zip_reader_extract_to_file (pZip, file_index, pDst_filename, + flags); + } + +// ------------------- .ZIP archive writing + +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + + static void mz_write_le16 (mz_uint8 * p, mz_uint16 v) + { + p[0] = (mz_uint8) v; + p[1] = (mz_uint8) (v >> 8); + } + static void mz_write_le32 (mz_uint8 * p, mz_uint32 v) + { + p[0] = (mz_uint8) v; + p[1] = (mz_uint8) (v >> 8); + p[2] = (mz_uint8) (v >> 16); + p[3] = (mz_uint8) (v >> 24); + } +#define MZ_WRITE_LE16(p, v) mz_write_le16((mz_uint8 *)(p), (mz_uint16)(v)) +#define MZ_WRITE_LE32(p, v) mz_write_le32((mz_uint8 *)(p), (mz_uint32)(v)) + + mz_bool mz_zip_writer_init (mz_zip_archive * pZip, mz_uint64 existing_size) + { + if ((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) + || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) + return MZ_FALSE; + + if (pZip->m_file_offset_alignment) + { + // Ensure user specified file offset alignment is a power of 2. + if (pZip->m_file_offset_alignment & + (pZip->m_file_offset_alignment - 1)) + return MZ_FALSE; + } + + if (!pZip->m_pAlloc) + pZip->m_pAlloc = def_alloc_func; + if (!pZip->m_pFree) + pZip->m_pFree = def_free_func; + if (!pZip->m_pRealloc) + pZip->m_pRealloc = def_realloc_func; + + pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; + pZip->m_archive_size = existing_size; + pZip->m_central_directory_file_ofs = 0; + pZip->m_total_files = 0; + + if (NULL == + (pZip->m_pState = + (mz_zip_internal_state *) pZip->m_pAlloc (pZip->m_pAlloc_opaque, 1, + sizeof + (mz_zip_internal_state)))) + return MZ_FALSE; + memset (pZip->m_pState, 0, sizeof (mz_zip_internal_state)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE (&pZip->m_pState->m_central_dir, + sizeof (mz_uint8)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE (&pZip->m_pState->m_central_dir_offsets, + sizeof (mz_uint32)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE (&pZip->m_pState-> + m_sorted_central_dir_offsets, + sizeof (mz_uint32)); + return MZ_TRUE; + } + + static size_t mz_zip_heap_write_func (void *pOpaque, mz_uint64 file_ofs, + const void *pBuf, size_t n) + { + mz_zip_archive *pZip = (mz_zip_archive *) pOpaque; + mz_zip_internal_state *pState = pZip->m_pState; + mz_uint64 new_size = MZ_MAX (file_ofs + n, pState->m_mem_size); + if ((!n) + || ((0, sizeof (size_t) == sizeof (mz_uint32)) + && (new_size > 0x7FFFFFFF))) + return 0; + if (new_size > pState->m_mem_capacity) + { + void *pNew_block; + size_t new_capacity = MZ_MAX (64, pState->m_mem_capacity); + while (new_capacity < new_size) + new_capacity *= 2; + if (NULL == + (pNew_block = + pZip->m_pRealloc (pZip->m_pAlloc_opaque, pState->m_pMem, 1, + new_capacity))) + return 0; + pState->m_pMem = pNew_block; + pState->m_mem_capacity = new_capacity; + } + memcpy ((mz_uint8 *) pState->m_pMem + file_ofs, pBuf, n); + pState->m_mem_size = (size_t) new_size; + return n; + } + + mz_bool mz_zip_writer_init_heap (mz_zip_archive * pZip, + size_t size_to_reserve_at_beginning, + size_t initial_allocation_size) + { + pZip->m_pWrite = mz_zip_heap_write_func; + pZip->m_pIO_opaque = pZip; + if (!mz_zip_writer_init (pZip, size_to_reserve_at_beginning)) + return MZ_FALSE; + if (0 != + (initial_allocation_size = + MZ_MAX (initial_allocation_size, size_to_reserve_at_beginning))) + { + if (NULL == + (pZip->m_pState->m_pMem = + pZip->m_pAlloc (pZip->m_pAlloc_opaque, 1, + initial_allocation_size))) + { + mz_zip_writer_end (pZip); + return MZ_FALSE; + } + pZip->m_pState->m_mem_capacity = initial_allocation_size; + } + return MZ_TRUE; + } + +#ifndef MINIZ_NO_STDIO + static size_t mz_zip_file_write_func (void *pOpaque, mz_uint64 file_ofs, + const void *pBuf, size_t n) + { + mz_zip_archive *pZip = (mz_zip_archive *) pOpaque; + mz_int64 cur_ofs = MZ_FTELL64 (pZip->m_pState->m_pFile); + if (((mz_int64) file_ofs < 0) + || (((cur_ofs != (mz_int64) file_ofs)) + && + (MZ_FSEEK64 + (pZip->m_pState->m_pFile, (mz_int64) file_ofs, SEEK_SET)))) + return 0; + return MZ_FWRITE (pBuf, 1, n, pZip->m_pState->m_pFile); + } + + mz_bool mz_zip_writer_init_file (mz_zip_archive * pZip, + const char *pFilename, + mz_uint64 size_to_reserve_at_beginning) + { + MZ_FILE *pFile; + pZip->m_pWrite = mz_zip_file_write_func; + pZip->m_pIO_opaque = pZip; + if (!mz_zip_writer_init (pZip, size_to_reserve_at_beginning)) + return MZ_FALSE; + if (NULL == (pFile = MZ_FOPEN (pFilename, "wb"))) + { + mz_zip_writer_end (pZip); + return MZ_FALSE; + } + pZip->m_pState->m_pFile = pFile; + if (size_to_reserve_at_beginning) + { + mz_uint64 cur_ofs = 0; + char buf[4096]; + MZ_CLEAR_OBJ (buf); + do + { + size_t n = + (size_t) MZ_MIN (sizeof (buf), size_to_reserve_at_beginning); + if (pZip->m_pWrite (pZip->m_pIO_opaque, cur_ofs, buf, n) != n) + { + mz_zip_writer_end (pZip); + return MZ_FALSE; + } + cur_ofs += n; + size_to_reserve_at_beginning -= n; + } + while (size_to_reserve_at_beginning); + } + return MZ_TRUE; + } +#endif // #ifndef MINIZ_NO_STDIO + + mz_bool mz_zip_writer_init_from_reader (mz_zip_archive * pZip, + const char *pFilename) + { + mz_zip_internal_state *pState; + if ((!pZip) || (!pZip->m_pState) + || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) + return MZ_FALSE; + // No sense in trying to write to an archive that's already at the support max size + if ((pZip->m_total_files == 0xFFFF) + || + ((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) + return MZ_FALSE; + + pState = pZip->m_pState; + + if (pState->m_pFile) + { +#ifdef MINIZ_NO_STDIO + pFilename; + return MZ_FALSE; +#else + // Archive is being read from stdio - try to reopen as writable. + if (pZip->m_pIO_opaque != pZip) + return MZ_FALSE; + if (!pFilename) + return MZ_FALSE; + pZip->m_pWrite = mz_zip_file_write_func; + if (NULL == + (pState->m_pFile = + MZ_FREOPEN (pFilename, "r+b", pState->m_pFile))) + { + // The mz_zip_archive is now in a bogus state because pState->m_pFile is NULL, so just close it. + mz_zip_reader_end (pZip); + return MZ_FALSE; + } +#endif // #ifdef MINIZ_NO_STDIO + } + else if (pState->m_pMem) + { + // Archive lives in a memory block. Assume it's from the heap that we can resize using the realloc callback. + if (pZip->m_pIO_opaque != pZip) + return MZ_FALSE; + pState->m_mem_capacity = pState->m_mem_size; + pZip->m_pWrite = mz_zip_heap_write_func; + } + // Archive is being read via a user provided read function - make sure the user has specified a write function too. + else if (!pZip->m_pWrite) + return MZ_FALSE; + + // Start writing new files at the archive's current central directory location. + pZip->m_archive_size = pZip->m_central_directory_file_ofs; + pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; + pZip->m_central_directory_file_ofs = 0; + + return MZ_TRUE; + } + + mz_bool mz_zip_writer_add_mem (mz_zip_archive * pZip, + const char *pArchive_name, const void *pBuf, + size_t buf_size, mz_uint level_and_flags) + { + return mz_zip_writer_add_mem_ex (pZip, pArchive_name, pBuf, buf_size, + NULL, 0, level_and_flags, 0, 0); + } + + typedef struct + { + mz_zip_archive *m_pZip; + mz_uint64 m_cur_archive_file_ofs; + mz_uint64 m_comp_size; + } mz_zip_writer_add_state; + + static mz_bool mz_zip_writer_add_put_buf_callback (const void *pBuf, + int len, void *pUser) + { + mz_zip_writer_add_state *pState = (mz_zip_writer_add_state *) pUser; + if ((int) pState->m_pZip->m_pWrite (pState->m_pZip->m_pIO_opaque, + pState->m_cur_archive_file_ofs, pBuf, + len) != len) + return MZ_FALSE; + pState->m_cur_archive_file_ofs += len; + pState->m_comp_size += len; + return MZ_TRUE; + } + + static mz_bool mz_zip_writer_create_local_dir_header (mz_zip_archive * pZip, + mz_uint8 * pDst, + mz_uint16 + filename_size, + mz_uint16 extra_size, + mz_uint64 uncomp_size, + mz_uint64 comp_size, + mz_uint32 + uncomp_crc32, + mz_uint16 method, + mz_uint16 bit_flags, + mz_uint16 dos_time, + mz_uint16 dos_date) + { + (void) pZip; + memset (pDst, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE); + MZ_WRITE_LE32 (pDst + MZ_ZIP_LDH_SIG_OFS, MZ_ZIP_LOCAL_DIR_HEADER_SIG); + MZ_WRITE_LE16 (pDst + MZ_ZIP_LDH_VERSION_NEEDED_OFS, method ? 20 : 0); + MZ_WRITE_LE16 (pDst + MZ_ZIP_LDH_BIT_FLAG_OFS, bit_flags); + MZ_WRITE_LE16 (pDst + MZ_ZIP_LDH_METHOD_OFS, method); + MZ_WRITE_LE16 (pDst + MZ_ZIP_LDH_FILE_TIME_OFS, dos_time); + MZ_WRITE_LE16 (pDst + MZ_ZIP_LDH_FILE_DATE_OFS, dos_date); + MZ_WRITE_LE32 (pDst + MZ_ZIP_LDH_CRC32_OFS, uncomp_crc32); + MZ_WRITE_LE32 (pDst + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS, comp_size); + MZ_WRITE_LE32 (pDst + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS, uncomp_size); + MZ_WRITE_LE16 (pDst + MZ_ZIP_LDH_FILENAME_LEN_OFS, filename_size); + MZ_WRITE_LE16 (pDst + MZ_ZIP_LDH_EXTRA_LEN_OFS, extra_size); + return MZ_TRUE; + } + + static mz_bool mz_zip_writer_create_central_dir_header (mz_zip_archive * + pZip, + mz_uint8 * pDst, + mz_uint16 + filename_size, + mz_uint16 + extra_size, + mz_uint16 + comment_size, + mz_uint64 + uncomp_size, + mz_uint64 comp_size, + mz_uint32 + uncomp_crc32, + mz_uint16 method, + mz_uint16 bit_flags, + mz_uint16 dos_time, + mz_uint16 dos_date, + mz_uint64 + local_header_ofs, + mz_uint32 + ext_attributes) + { + (void) pZip; + memset (pDst, 0, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); + MZ_WRITE_LE32 (pDst + MZ_ZIP_CDH_SIG_OFS, MZ_ZIP_CENTRAL_DIR_HEADER_SIG); + MZ_WRITE_LE16 (pDst + MZ_ZIP_CDH_VERSION_NEEDED_OFS, method ? 20 : 0); + MZ_WRITE_LE16 (pDst + MZ_ZIP_CDH_BIT_FLAG_OFS, bit_flags); + MZ_WRITE_LE16 (pDst + MZ_ZIP_CDH_METHOD_OFS, method); + MZ_WRITE_LE16 (pDst + MZ_ZIP_CDH_FILE_TIME_OFS, dos_time); + MZ_WRITE_LE16 (pDst + MZ_ZIP_CDH_FILE_DATE_OFS, dos_date); + MZ_WRITE_LE32 (pDst + MZ_ZIP_CDH_CRC32_OFS, uncomp_crc32); + MZ_WRITE_LE32 (pDst + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, comp_size); + MZ_WRITE_LE32 (pDst + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, uncomp_size); + MZ_WRITE_LE16 (pDst + MZ_ZIP_CDH_FILENAME_LEN_OFS, filename_size); + MZ_WRITE_LE16 (pDst + MZ_ZIP_CDH_EXTRA_LEN_OFS, extra_size); + MZ_WRITE_LE16 (pDst + MZ_ZIP_CDH_COMMENT_LEN_OFS, comment_size); + MZ_WRITE_LE32 (pDst + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS, ext_attributes); + MZ_WRITE_LE32 (pDst + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_header_ofs); + return MZ_TRUE; + } + + static mz_bool mz_zip_writer_add_to_central_dir (mz_zip_archive * pZip, + const char *pFilename, + mz_uint16 filename_size, + const void *pExtra, + mz_uint16 extra_size, + const void *pComment, + mz_uint16 comment_size, + mz_uint64 uncomp_size, + mz_uint64 comp_size, + mz_uint32 uncomp_crc32, + mz_uint16 method, + mz_uint16 bit_flags, + mz_uint16 dos_time, + mz_uint16 dos_date, + mz_uint64 local_header_ofs, + mz_uint32 ext_attributes) + { + mz_zip_internal_state *pState = pZip->m_pState; + mz_uint32 central_dir_ofs = (mz_uint32) pState->m_central_dir.m_size; + size_t orig_central_dir_size = pState->m_central_dir.m_size; + mz_uint8 central_dir_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; + + // No zip64 support yet + if ((local_header_ofs > 0xFFFFFFFF) + || + (((mz_uint64) pState->m_central_dir.m_size + + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size + + comment_size) > 0xFFFFFFFF)) + return MZ_FALSE; + + if (!mz_zip_writer_create_central_dir_header + (pZip, central_dir_header, filename_size, extra_size, comment_size, + uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, + dos_date, local_header_ofs, ext_attributes)) + return MZ_FALSE; + + if ((!mz_zip_array_push_back + (pZip, &pState->m_central_dir, central_dir_header, + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) + || + (!mz_zip_array_push_back + (pZip, &pState->m_central_dir, pFilename, filename_size)) + || + (!mz_zip_array_push_back + (pZip, &pState->m_central_dir, pExtra, extra_size)) + || + (!mz_zip_array_push_back + (pZip, &pState->m_central_dir, pComment, comment_size)) + || + (!mz_zip_array_push_back + (pZip, &pState->m_central_dir_offsets, ¢ral_dir_ofs, 1))) + { + // Try to push the central directory array back into its original state. + mz_zip_array_resize (pZip, &pState->m_central_dir, + orig_central_dir_size, MZ_FALSE); + return MZ_FALSE; + } + + return MZ_TRUE; + } + + static mz_bool mz_zip_writer_validate_archive_name (const char + *pArchive_name) + { + // Basic ZIP archive filename validity checks: Valid filenames cannot start with a forward slash, cannot contain a drive letter, and cannot use DOS-style backward slashes. + if (*pArchive_name == '/') + return MZ_FALSE; + while (*pArchive_name) + { + if ((*pArchive_name == '\\') || (*pArchive_name == ':')) + return MZ_FALSE; + pArchive_name++; + } + return MZ_TRUE; + } + + static mz_uint + mz_zip_writer_compute_padding_needed_for_file_alignment (mz_zip_archive * + pZip) + { + mz_uint32 n; + if (!pZip->m_file_offset_alignment) + return 0; + n = + (mz_uint32) (pZip->m_archive_size & + (pZip->m_file_offset_alignment - 1)); + return (pZip->m_file_offset_alignment - + n) & (pZip->m_file_offset_alignment - 1); + } + + static mz_bool mz_zip_writer_write_zeros (mz_zip_archive * pZip, + mz_uint64 cur_file_ofs, + mz_uint32 n) + { + char buf[4096]; + memset (buf, 0, MZ_MIN (sizeof (buf), n)); + while (n) + { + mz_uint32 s = MZ_MIN (sizeof (buf), n); + if (pZip->m_pWrite (pZip->m_pIO_opaque, cur_file_ofs, buf, s) != s) + return MZ_FALSE; + cur_file_ofs += s; + n -= s; + } + return MZ_TRUE; + } + + mz_bool mz_zip_writer_add_mem_ex (mz_zip_archive * pZip, + const char *pArchive_name, + const void *pBuf, size_t buf_size, + const void *pComment, + mz_uint16 comment_size, + mz_uint level_and_flags, + mz_uint64 uncomp_size, + mz_uint32 uncomp_crc32) + { + mz_uint16 method = 0, dos_time = 0, dos_date = 0; + mz_uint level, ext_attributes = 0, num_alignment_padding_bytes; + mz_uint64 local_dir_header_ofs = 0, cur_archive_file_ofs = 0, comp_size = + 0; + size_t archive_name_size; + mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; + tdefl_compressor *pComp = NULL; + mz_bool store_data_uncompressed; + mz_zip_internal_state *pState; + + if ((int) level_and_flags < 0) + level_and_flags = MZ_DEFAULT_LEVEL; + level = level_and_flags & 0xF; + store_data_uncompressed = ((!level) + || (level_and_flags & + MZ_ZIP_FLAG_COMPRESSED_DATA)); + + if ((!pZip) || (!pZip->m_pState) + || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) + && (!pBuf)) + || (!pArchive_name) || ((comment_size) && (!pComment)) + || (pZip->m_total_files == 0xFFFF) || (level > MZ_UBER_COMPRESSION)) + return MZ_FALSE; + + local_dir_header_ofs = pZip->m_archive_size; + cur_archive_file_ofs = pZip->m_archive_size; + pState = pZip->m_pState; + + if ((!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (uncomp_size)) + return MZ_FALSE; + // No zip64 support yet + if ((buf_size > 0xFFFFFFFF) || (uncomp_size > 0xFFFFFFFF)) + return MZ_FALSE; + if (!mz_zip_writer_validate_archive_name (pArchive_name)) + return MZ_FALSE; + +#ifndef MINIZ_NO_TIME + { + time_t cur_time; + time (&cur_time); + mz_zip_time_to_dos_time (cur_time, &dos_time, &dos_date); + } +#endif // #ifndef MINIZ_NO_TIME + + archive_name_size = strlen (pArchive_name); + if (archive_name_size > 0xFFFF) + return MZ_FALSE; + + num_alignment_padding_bytes = + mz_zip_writer_compute_padding_needed_for_file_alignment (pZip); + + // no zip64 support yet + if ((pZip->m_total_files == 0xFFFF) + || + ((pZip->m_archive_size + num_alignment_padding_bytes + + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + + comment_size + archive_name_size) > 0xFFFFFFFF)) + return MZ_FALSE; + + if ((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/')) + { + // Set DOS Subdirectory attribute bit. + ext_attributes |= 0x10; + // Subdirectories cannot contain data. + if ((buf_size) || (uncomp_size)) + return MZ_FALSE; + } + + // Try to do any allocations before writing to the archive, so if an allocation fails the file remains unmodified. (A good idea if we're doing an in-place modification.) + if ((!mz_zip_array_ensure_room + (pZip, &pState->m_central_dir, + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size)) + || + (!mz_zip_array_ensure_room (pZip, &pState->m_central_dir_offsets, 1))) + return MZ_FALSE; + + if ((!store_data_uncompressed) && (buf_size)) + { + if (NULL == + (pComp = + (tdefl_compressor *) pZip->m_pAlloc (pZip->m_pAlloc_opaque, 1, + sizeof (tdefl_compressor)))) + return MZ_FALSE; + } + + if (!mz_zip_writer_write_zeros + (pZip, cur_archive_file_ofs, + num_alignment_padding_bytes + sizeof (local_dir_header))) + { + pZip->m_pFree (pZip->m_pAlloc_opaque, pComp); + return MZ_FALSE; + } + local_dir_header_ofs += num_alignment_padding_bytes; + if (pZip->m_file_offset_alignment) + { + MZ_ASSERT ((local_dir_header_ofs & + (pZip->m_file_offset_alignment - 1)) == 0); + } + cur_archive_file_ofs += + num_alignment_padding_bytes + sizeof (local_dir_header); + + MZ_CLEAR_OBJ (local_dir_header); + if (pZip->m_pWrite + (pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, + archive_name_size) != archive_name_size) + { + pZip->m_pFree (pZip->m_pAlloc_opaque, pComp); + return MZ_FALSE; + } + cur_archive_file_ofs += archive_name_size; + + if (!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + { + uncomp_crc32 = + (mz_uint32) mz_crc32 (MZ_CRC32_INIT, (const mz_uint8 *) pBuf, + buf_size); + uncomp_size = buf_size; + if (uncomp_size <= 3) + { + level = 0; + store_data_uncompressed = MZ_TRUE; + } + } + + if (store_data_uncompressed) + { + if (pZip->m_pWrite (pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf, + buf_size) != buf_size) + { + pZip->m_pFree (pZip->m_pAlloc_opaque, pComp); + return MZ_FALSE; + } + + cur_archive_file_ofs += buf_size; + comp_size = buf_size; + + if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) + method = MZ_DEFLATED; + } + else if (buf_size) + { + mz_zip_writer_add_state state; + + state.m_pZip = pZip; + state.m_cur_archive_file_ofs = cur_archive_file_ofs; + state.m_comp_size = 0; + + if ((tdefl_init + (pComp, mz_zip_writer_add_put_buf_callback, &state, + tdefl_create_comp_flags_from_zip_params (level, -15, + MZ_DEFAULT_STRATEGY)) + != TDEFL_STATUS_OKAY) + || (tdefl_compress_buffer (pComp, pBuf, buf_size, TDEFL_FINISH) != + TDEFL_STATUS_DONE)) + { + pZip->m_pFree (pZip->m_pAlloc_opaque, pComp); + return MZ_FALSE; + } + + comp_size = state.m_comp_size; + cur_archive_file_ofs = state.m_cur_archive_file_ofs; + + method = MZ_DEFLATED; + } + + pZip->m_pFree (pZip->m_pAlloc_opaque, pComp); + pComp = NULL; + + // no zip64 support yet + if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF)) + return MZ_FALSE; + + if (!mz_zip_writer_create_local_dir_header + (pZip, local_dir_header, (mz_uint16) archive_name_size, 0, + uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date)) + return MZ_FALSE; + + if (pZip->m_pWrite + (pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, + sizeof (local_dir_header)) != sizeof (local_dir_header)) + return MZ_FALSE; + + if (!mz_zip_writer_add_to_central_dir + (pZip, pArchive_name, (mz_uint16) archive_name_size, NULL, 0, + pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, + 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes)) + return MZ_FALSE; + + pZip->m_total_files++; + pZip->m_archive_size = cur_archive_file_ofs; + + return MZ_TRUE; + } + +#ifndef MINIZ_NO_STDIO + mz_bool mz_zip_writer_add_file (mz_zip_archive * pZip, + const char *pArchive_name, + const char *pSrc_filename, + const void *pComment, + mz_uint16 comment_size, + mz_uint level_and_flags) + { + mz_uint uncomp_crc32 = MZ_CRC32_INIT, level, num_alignment_padding_bytes; + mz_uint16 method = 0, dos_time = 0, dos_date = 0, ext_attributes = 0; + mz_uint64 local_dir_header_ofs = 0, cur_archive_file_ofs = + 0, uncomp_size = 0, comp_size = 0; + size_t archive_name_size; + mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; + MZ_FILE *pSrc_file = NULL; + + if ((int) level_and_flags < 0) + level_and_flags = MZ_DEFAULT_LEVEL; + level = level_and_flags & 0xF; + + if ((!pZip) || (!pZip->m_pState) + || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) + || ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION)) + return MZ_FALSE; + if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) + return MZ_FALSE; + if (!mz_zip_writer_validate_archive_name (pArchive_name)) + return MZ_FALSE; + + archive_name_size = strlen (pArchive_name); + if (archive_name_size > 0xFFFF) + return MZ_FALSE; + local_dir_header_ofs = pZip->m_archive_size; + cur_archive_file_ofs = pZip->m_archive_size; + num_alignment_padding_bytes = + mz_zip_writer_compute_padding_needed_for_file_alignment (pZip); + + // no zip64 support yet + if ((pZip->m_total_files == 0xFFFF) + || + ((pZip->m_archive_size + num_alignment_padding_bytes + + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + + comment_size + archive_name_size) > 0xFFFFFFFF)) + return MZ_FALSE; + + if (!mz_zip_get_file_modified_time (pSrc_filename, &dos_time, &dos_date)) + return MZ_FALSE; + + pSrc_file = MZ_FOPEN (pSrc_filename, "rb"); + if (!pSrc_file) + return MZ_FALSE; + MZ_FSEEK64 (pSrc_file, 0, SEEK_END); + uncomp_size = MZ_FTELL64 (pSrc_file); + MZ_FSEEK64 (pSrc_file, 0, SEEK_SET); + + if (uncomp_size > 0xFFFFFFFF) + { + // No zip64 support yet + MZ_FCLOSE (pSrc_file); + return MZ_FALSE; + } + if (uncomp_size <= 3) + level = 0; + + if (!mz_zip_writer_write_zeros + (pZip, cur_archive_file_ofs, + num_alignment_padding_bytes + sizeof (local_dir_header))) + { + MZ_FCLOSE (pSrc_file); + return MZ_FALSE; + } + local_dir_header_ofs += num_alignment_padding_bytes; + if (pZip->m_file_offset_alignment) + { + MZ_ASSERT ((local_dir_header_ofs & + (pZip->m_file_offset_alignment - 1)) == 0); + } + cur_archive_file_ofs += + num_alignment_padding_bytes + sizeof (local_dir_header); + + MZ_CLEAR_OBJ (local_dir_header); + if (pZip->m_pWrite + (pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, + archive_name_size) != archive_name_size) + { + MZ_FCLOSE (pSrc_file); + return MZ_FALSE; + } + cur_archive_file_ofs += archive_name_size; + + if (uncomp_size) + { + mz_uint64 uncomp_remaining = uncomp_size; + void *pRead_buf = + pZip->m_pAlloc (pZip->m_pAlloc_opaque, 1, MZ_ZIP_MAX_IO_BUF_SIZE); + if (!pRead_buf) + { + MZ_FCLOSE (pSrc_file); + return MZ_FALSE; + } + + if (!level) + { + while (uncomp_remaining) + { + mz_uint n = + (mz_uint) MZ_MIN ((mz_uint64) MZ_ZIP_MAX_IO_BUF_SIZE, uncomp_remaining); + if ((MZ_FREAD (pRead_buf, 1, n, pSrc_file) != n) + || (pZip-> + m_pWrite (pZip->m_pIO_opaque, cur_archive_file_ofs, + pRead_buf, n) != n)) + { + pZip->m_pFree (pZip->m_pAlloc_opaque, pRead_buf); + MZ_FCLOSE (pSrc_file); + return MZ_FALSE; + } + uncomp_crc32 = + (mz_uint32) mz_crc32 (uncomp_crc32, + (const mz_uint8 *) pRead_buf, n); + uncomp_remaining -= n; + cur_archive_file_ofs += n; + } + comp_size = uncomp_size; + } + else + { + mz_bool result = MZ_FALSE; + mz_zip_writer_add_state state; + tdefl_compressor *pComp = + (tdefl_compressor *) pZip->m_pAlloc (pZip->m_pAlloc_opaque, 1, + sizeof (tdefl_compressor)); + if (!pComp) + { + pZip->m_pFree (pZip->m_pAlloc_opaque, pRead_buf); + MZ_FCLOSE (pSrc_file); + return MZ_FALSE; + } + + state.m_pZip = pZip; + state.m_cur_archive_file_ofs = cur_archive_file_ofs; + state.m_comp_size = 0; + + if (tdefl_init + (pComp, mz_zip_writer_add_put_buf_callback, &state, + tdefl_create_comp_flags_from_zip_params (level, -15, + MZ_DEFAULT_STRATEGY)) + != TDEFL_STATUS_OKAY) + { + pZip->m_pFree (pZip->m_pAlloc_opaque, pComp); + pZip->m_pFree (pZip->m_pAlloc_opaque, pRead_buf); + MZ_FCLOSE (pSrc_file); + return MZ_FALSE; + } + + for (;;) + { + size_t in_buf_size = (mz_uint32) MZ_MIN (uncomp_remaining, + (mz_uint64) MZ_ZIP_MAX_IO_BUF_SIZE); + tdefl_status status; + + if (MZ_FREAD (pRead_buf, 1, in_buf_size, pSrc_file) != + in_buf_size) + break; + + uncomp_crc32 = + (mz_uint32) mz_crc32 (uncomp_crc32, + (const mz_uint8 *) pRead_buf, + in_buf_size); + uncomp_remaining -= in_buf_size; + + status = + tdefl_compress_buffer (pComp, pRead_buf, in_buf_size, + uncomp_remaining ? TDEFL_NO_FLUSH : + TDEFL_FINISH); + if (status == TDEFL_STATUS_DONE) + { + result = MZ_TRUE; + break; + } + else if (status != TDEFL_STATUS_OKAY) + break; + } + + pZip->m_pFree (pZip->m_pAlloc_opaque, pComp); + + if (!result) + { + pZip->m_pFree (pZip->m_pAlloc_opaque, pRead_buf); + MZ_FCLOSE (pSrc_file); + return MZ_FALSE; + } + + comp_size = state.m_comp_size; + cur_archive_file_ofs = state.m_cur_archive_file_ofs; + + method = MZ_DEFLATED; + } + + pZip->m_pFree (pZip->m_pAlloc_opaque, pRead_buf); + } + + MZ_FCLOSE (pSrc_file); + pSrc_file = NULL; + + // no zip64 support yet + if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF)) + return MZ_FALSE; + + if (!mz_zip_writer_create_local_dir_header + (pZip, local_dir_header, (mz_uint16) archive_name_size, 0, + uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date)) + return MZ_FALSE; + + if (pZip->m_pWrite + (pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, + sizeof (local_dir_header)) != sizeof (local_dir_header)) + return MZ_FALSE; + + if (!mz_zip_writer_add_to_central_dir + (pZip, pArchive_name, (mz_uint16) archive_name_size, NULL, 0, + pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, + 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes)) + return MZ_FALSE; + + pZip->m_total_files++; + pZip->m_archive_size = cur_archive_file_ofs; + + return MZ_TRUE; + } +#endif // #ifndef MINIZ_NO_STDIO + + mz_bool mz_zip_writer_add_from_zip_reader (mz_zip_archive * pZip, + mz_zip_archive * pSource_zip, + mz_uint file_index) + { + mz_uint n, bit_flags, num_alignment_padding_bytes; + mz_uint64 comp_bytes_remaining, local_dir_header_ofs; + mz_uint64 cur_src_file_ofs, cur_dst_file_ofs; + mz_uint32 + local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof (mz_uint32) - + 1) / sizeof (mz_uint32)]; + mz_uint8 *pLocal_header = (mz_uint8 *) local_header_u32; + mz_uint8 central_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; + size_t orig_central_dir_size; + mz_zip_internal_state *pState; + void *pBuf; + const mz_uint8 *pSrc_central_header; + + if ((!pZip) || (!pZip->m_pState) + || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) + return MZ_FALSE; + if (NULL == + (pSrc_central_header = + mz_zip_reader_get_cdh (pSource_zip, file_index))) + return MZ_FALSE; + pState = pZip->m_pState; + + num_alignment_padding_bytes = + mz_zip_writer_compute_padding_needed_for_file_alignment (pZip); + + // no zip64 support yet + if ((pZip->m_total_files == 0xFFFF) + || + ((pZip->m_archive_size + num_alignment_padding_bytes + + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) > + 0xFFFFFFFF)) + return MZ_FALSE; + + cur_src_file_ofs = + MZ_READ_LE32 (pSrc_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS); + cur_dst_file_ofs = pZip->m_archive_size; + + if (pSource_zip->m_pRead + (pSource_zip->m_pIO_opaque, cur_src_file_ofs, pLocal_header, + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return MZ_FALSE; + if (MZ_READ_LE32 (pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + return MZ_FALSE; + cur_src_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; + + if (!mz_zip_writer_write_zeros + (pZip, cur_dst_file_ofs, num_alignment_padding_bytes)) + return MZ_FALSE; + cur_dst_file_ofs += num_alignment_padding_bytes; + local_dir_header_ofs = cur_dst_file_ofs; + if (pZip->m_file_offset_alignment) + { + MZ_ASSERT ((local_dir_header_ofs & + (pZip->m_file_offset_alignment - 1)) == 0); + } + + if (pZip->m_pWrite (pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header, + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return MZ_FALSE; + cur_dst_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; + + n = + MZ_READ_LE16 (pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + + MZ_READ_LE16 (pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + comp_bytes_remaining = + n + MZ_READ_LE32 (pSrc_central_header + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); + + if (NULL == + (pBuf = + pZip->m_pAlloc (pZip->m_pAlloc_opaque, 1, + (size_t) MZ_MAX (sizeof (mz_uint32) * 4, + MZ_MIN ((mz_uint64) MZ_ZIP_MAX_IO_BUF_SIZE, + comp_bytes_remaining))))) + return MZ_FALSE; + + while (comp_bytes_remaining) + { + n = (mz_uint) MZ_MIN ((mz_uint64) MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining); + if (pSource_zip->m_pRead + (pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, n) != n) + { + pZip->m_pFree (pZip->m_pAlloc_opaque, pBuf); + return MZ_FALSE; + } + cur_src_file_ofs += n; + + if (pZip->m_pWrite (pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != + n) + { + pZip->m_pFree (pZip->m_pAlloc_opaque, pBuf); + return MZ_FALSE; + } + cur_dst_file_ofs += n; + + comp_bytes_remaining -= n; + } + + bit_flags = MZ_READ_LE16 (pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS); + if (bit_flags & 8) + { + // Copy data descriptor + if (pSource_zip->m_pRead + (pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, + sizeof (mz_uint32) * 4) != sizeof (mz_uint32) * 4) + { + pZip->m_pFree (pZip->m_pAlloc_opaque, pBuf); + return MZ_FALSE; + } + + n = + sizeof (mz_uint32) * ((MZ_READ_LE32 (pBuf) == 0x08074b50) ? 4 : 3); + if (pZip->m_pWrite (pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != + n) + { + pZip->m_pFree (pZip->m_pAlloc_opaque, pBuf); + return MZ_FALSE; + } + + cur_src_file_ofs += n; + cur_dst_file_ofs += n; + } + pZip->m_pFree (pZip->m_pAlloc_opaque, pBuf); + + // no zip64 support yet + if (cur_dst_file_ofs > 0xFFFFFFFF) + return MZ_FALSE; + + orig_central_dir_size = pState->m_central_dir.m_size; + + memcpy (central_header, pSrc_central_header, + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); + MZ_WRITE_LE32 (central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, + local_dir_header_ofs); + if (!mz_zip_array_push_back + (pZip, &pState->m_central_dir, central_header, + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) + return MZ_FALSE; + + n = + MZ_READ_LE16 (pSrc_central_header + MZ_ZIP_CDH_FILENAME_LEN_OFS) + + MZ_READ_LE16 (pSrc_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS) + + MZ_READ_LE16 (pSrc_central_header + MZ_ZIP_CDH_COMMENT_LEN_OFS); + if (!mz_zip_array_push_back + (pZip, &pState->m_central_dir, + pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n)) + { + mz_zip_array_resize (pZip, &pState->m_central_dir, + orig_central_dir_size, MZ_FALSE); + return MZ_FALSE; + } + + if (pState->m_central_dir.m_size > 0xFFFFFFFF) + return MZ_FALSE; + n = (mz_uint32) pState->m_central_dir.m_size; + if (!mz_zip_array_push_back (pZip, &pState->m_central_dir_offsets, &n, 1)) + { + mz_zip_array_resize (pZip, &pState->m_central_dir, + orig_central_dir_size, MZ_FALSE); + return MZ_FALSE; + } + + pZip->m_total_files++; + pZip->m_archive_size = cur_dst_file_ofs; + + return MZ_TRUE; + } + + mz_bool mz_zip_writer_finalize_archive (mz_zip_archive * pZip) + { + mz_zip_internal_state *pState; + mz_uint64 central_dir_ofs, central_dir_size; + mz_uint8 hdr[MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE]; + + if ((!pZip) || (!pZip->m_pState) + || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) + return MZ_FALSE; + + pState = pZip->m_pState; + + // no zip64 support yet + if ((pZip->m_total_files > 0xFFFF) + || + ((pZip->m_archive_size + pState->m_central_dir.m_size + + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) + return MZ_FALSE; + + central_dir_ofs = 0; + central_dir_size = 0; + if (pZip->m_total_files) + { + // Write central directory + central_dir_ofs = pZip->m_archive_size; + central_dir_size = pState->m_central_dir.m_size; + pZip->m_central_directory_file_ofs = central_dir_ofs; + if (pZip->m_pWrite (pZip->m_pIO_opaque, central_dir_ofs, + pState->m_central_dir.m_p, + (size_t) central_dir_size) != central_dir_size) + return MZ_FALSE; + pZip->m_archive_size += central_dir_size; + } + + // Write end of central directory record + MZ_CLEAR_OBJ (hdr); + MZ_WRITE_LE32 (hdr + MZ_ZIP_ECDH_SIG_OFS, + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG); + MZ_WRITE_LE16 (hdr + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, + pZip->m_total_files); + MZ_WRITE_LE16 (hdr + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS, + pZip->m_total_files); + MZ_WRITE_LE32 (hdr + MZ_ZIP_ECDH_CDIR_SIZE_OFS, central_dir_size); + MZ_WRITE_LE32 (hdr + MZ_ZIP_ECDH_CDIR_OFS_OFS, central_dir_ofs); + + if (pZip->m_pWrite (pZip->m_pIO_opaque, pZip->m_archive_size, hdr, + sizeof (hdr)) != sizeof (hdr)) + return MZ_FALSE; +#ifndef MINIZ_NO_STDIO + if ((pState->m_pFile) && (MZ_FFLUSH (pState->m_pFile) == EOF)) + return MZ_FALSE; +#endif // #ifndef MINIZ_NO_STDIO + + pZip->m_archive_size += sizeof (hdr); + + pZip->m_zip_mode = MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED; + return MZ_TRUE; + } + + mz_bool mz_zip_writer_finalize_heap_archive (mz_zip_archive * pZip, + void **pBuf, size_t * pSize) + { + if ((!pZip) || (!pZip->m_pState) || (!pBuf) || (!pSize)) + return MZ_FALSE; + if (pZip->m_pWrite != mz_zip_heap_write_func) + return MZ_FALSE; + if (!mz_zip_writer_finalize_archive (pZip)) + return MZ_FALSE; + + *pBuf = pZip->m_pState->m_pMem; + *pSize = pZip->m_pState->m_mem_size; + pZip->m_pState->m_pMem = NULL; + pZip->m_pState->m_mem_size = pZip->m_pState->m_mem_capacity = 0; + return MZ_TRUE; + } + + mz_bool mz_zip_writer_end (mz_zip_archive * pZip) + { + mz_zip_internal_state *pState; + mz_bool status = MZ_TRUE; + if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) + || ((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) + && (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED))) + return MZ_FALSE; + + pState = pZip->m_pState; + pZip->m_pState = NULL; + mz_zip_array_clear (pZip, &pState->m_central_dir); + mz_zip_array_clear (pZip, &pState->m_central_dir_offsets); + mz_zip_array_clear (pZip, &pState->m_sorted_central_dir_offsets); + +#ifndef MINIZ_NO_STDIO + if (pState->m_pFile) + { + MZ_FCLOSE (pState->m_pFile); + pState->m_pFile = NULL; + } +#endif // #ifndef MINIZ_NO_STDIO + + if ((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem)) + { + pZip->m_pFree (pZip->m_pAlloc_opaque, pState->m_pMem); + pState->m_pMem = NULL; + } + + pZip->m_pFree (pZip->m_pAlloc_opaque, pState); + pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; + return status; + } + +#ifndef MINIZ_NO_STDIO + mz_bool mz_zip_add_mem_to_archive_file_in_place (const char *pZip_filename, + const char *pArchive_name, + const void *pBuf, + size_t buf_size, + const void *pComment, + mz_uint16 comment_size, + mz_uint level_and_flags) + { + mz_bool status, created_new_archive = MZ_FALSE; + mz_zip_archive zip_archive; + struct MZ_FILE_STAT_STRUCT file_stat; + MZ_CLEAR_OBJ (zip_archive); + if ((int) level_and_flags < 0) + level_and_flags = MZ_DEFAULT_LEVEL; + if ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) + || ((comment_size) && (!pComment)) + || ((level_and_flags & 0xF) > MZ_UBER_COMPRESSION)) + return MZ_FALSE; + if (!mz_zip_writer_validate_archive_name (pArchive_name)) + return MZ_FALSE; + if (MZ_FILE_STAT (pZip_filename, &file_stat) != 0) + { + // Create a new archive. + if (!mz_zip_writer_init_file (&zip_archive, pZip_filename, 0)) + return MZ_FALSE; + created_new_archive = MZ_TRUE; + } + else + { + // Append to an existing archive. + if (!mz_zip_reader_init_file + (&zip_archive, pZip_filename, + level_and_flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY)) + return MZ_FALSE; + if (!mz_zip_writer_init_from_reader (&zip_archive, pZip_filename)) + { + mz_zip_reader_end (&zip_archive); + return MZ_FALSE; + } + } + status = + mz_zip_writer_add_mem_ex (&zip_archive, pArchive_name, pBuf, buf_size, + pComment, comment_size, level_and_flags, 0, + 0); + // Always finalize, even if adding failed for some reason, so we have a valid central directory. (This may not always succeed, but we can try.) + status = status && mz_zip_writer_finalize_archive (&zip_archive); + status = status && mz_zip_writer_end (&zip_archive); + if ((!status) && (created_new_archive)) + { + // It's a new archive and something went wrong, so just delete it. + MZ_DELETE_FILE (pZip_filename); + } + return status; + } + + void *mz_zip_extract_archive_file_to_heap (const char *pZip_filename, + const char *pArchive_name, + size_t * pSize, mz_uint flags) + { + int file_index; + mz_zip_archive zip_archive; + void *p = NULL; + + if (pSize) + *pSize = 0; + + if ((!pZip_filename) || (!pArchive_name)) + return NULL; + + MZ_CLEAR_OBJ (zip_archive); + if (!mz_zip_reader_init_file + (&zip_archive, pZip_filename, + flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY)) + return NULL; + + if ((file_index = + mz_zip_reader_locate_file (&zip_archive, pArchive_name, NULL, + flags)) >= 0) + p = + mz_zip_reader_extract_to_heap (&zip_archive, file_index, pSize, + flags); + + mz_zip_reader_end (&zip_archive); + return p; + } + +#endif // #ifndef MINIZ_NO_STDIO + +#endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + +#endif // #ifndef MINIZ_NO_ARCHIVE_APIS + +#ifdef __cplusplus +} +#endif + +#endif // MINIZ_HEADER_FILE_ONLY + +/* + This is free and unencumbered software released into the public domain. + + Anyone is free to copy, modify, publish, use, compile, sell, or + distribute this software, either in source code form or as a compiled + binary, for any purpose, commercial or non-commercial, and by any + means. + + In jurisdictions that recognize copyright laws, the author or authors + of this software dedicate any and all copyright interest in the + software to the public domain. We make this dedication for the benefit + of the public at large and to the detriment of our heirs and + successors. We intend this dedication to be an overt act of + relinquishment in perpetuity of all present and future rights to this + software under copyright law. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + + For more information, please refer to +*/ diff --git a/server/src/am_config.cpp b/server/src/am_config.cpp new file mode 100644 index 0000000..a7f233e --- /dev/null +++ b/server/src/am_config.cpp @@ -0,0 +1,809 @@ +/* + * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. + * + * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + + +/* + * cm_config.cpp - + */ + +#include +#include +#include +#include +#include + +#if defined(WINDOWS) +#include +#include +#else +#include +#include +#endif + +#include "cm_porting.h" +#include "cm_config.h" +#include "cm_dep.h" +#include "cm_server_util.h" + +#define DEFAULT_MONITOR_INTERVAL 5 +#define DEFAULT_THREAD_NUM 8 +#define DEFAULT_AMS_PORT 8001 + +#define DEFAULT_ALLOW_MULTI_CON 0 /* no */ +#define DEFAULT_AUTOJOB_TIMEOUT 43200 /* timeout for all autojobs, 12 hours */ +#define MIN_AUTOJOB_TIMEOUT 60 /* min timeout for all autojobs, 60 sec */ + +#define MAX_THREAD_NUM 64 +#define MIN_THREAD_NUM 1 +/* Reject multi connection with "ALL USER" */ + +#define NUM_DBMT_FILE 23 + +#define DEFAULT_CWM_PATH_SHORT "/share/webmanager" +#define DEFAULT_SSL_CERTIFICATE "cm_ssl_cert.crt" +#define DEFAULT_SSL_PRIVATEKEY "cm_ssl_cert.key" + +#define DEFAULT_LOG_FILE_COUNT 10 +#define DEFAULT_LOG_FILE_SIZE (4 * 1024 * 1024) + +const char *autobackup_conf_entry[AUTOBACKUP_CONF_ENTRY_NUM] = +{ + "dbname", "backupid", "path", "period_type", "period_date", "time", + "level", "archivedel", "updatestatus", "storeold", "onoff", + "zip", "check", "mt", "bknum" +}; + +const char *autobackup_period_type[AUTOBACKUP_PERIOD_TYPE_NUM] = +{ + AUTO_BACKUP_PERIOD_TYPE_MONTHLY, AUTO_BACKUP_PERIOD_TYPE_WEEKLY, + AUTO_BACKUP_PERIOD_TYPE_DAILY, AUTO_BACKUP_PERIOD_TYPE_HOURLY, + AUTO_BACKUP_PERIOD_TYPE_SPECIAL +}; + +const char *autobackup_period_week[AUTOBACKUP_PERIOD_WEEK_NUM] = +{ + WEEK_SUNDAY_L, WEEK_MONDAY_L, WEEK_TUESDAY_L, WEEK_WEDNESDAY_L, + WEEK_THURSDAY_L, WEEK_FRIDAY_L, WEEK_SATURDAY_L +}; + +const char *autoaddvol_conf_entry[AUTOADDVOL_CONF_ENTRY_NUM] = +{ + "dbname", "data", "data_warn_outofspace", "data_ext_page", + "index", "index_warn_outofspace", "index_ext_page" +}; + +const char *autohistory_conf_entry[AUTOHISTORY_CONF_ENTRY_NUM] = +{ + "onoff", + "startyear", "startmonth", "startday", + "starthour", "startminute", "startsecond", + "endyear", "endmonth", "endday", + "endhour", "endminute", "endsecond", + "memory", "cpu" +}; + +const char *autounicas_conf_entry[AUTOUNICAS_CONF_ENTRY_NUM] = +{ + "bname", "cpumonitor", "busymonitor", "logcpu", "logbusy", + "cpurestart", "busyrestart", "cpulimit", "busytimelimit" +}; + +static T_DBMT_FILE_INFO dbmt_file[NUM_DBMT_FILE] = +{ + {FID_DBMT_CONF, DBMT_CONF_DIR, "cm.conf"}, + {FID_DBMT_PASS, DBMT_CONF_DIR, "cm.pass"}, + {FID_DBMT_ARNIADB_PASS, DBMT_CONF_DIR, "cmdb.pass"}, + {FID_CONN_LIST, DBMT_LOG_DIR, "conlist"}, + {FID_AUTO_ADDVOLDB_CONF, DBMT_CONF_DIR, "autoaddvoldb.conf"}, + {FID_AUTO_ADDVOLDB_LOG, DBMT_LOG_DIR, "autoaddvoldb.log"}, + {FID_AUTO_BACKUPDB_CONF, DBMT_CONF_DIR, "autobackupdb.conf"}, + {FID_AUTO_HISTORY_CONF, DBMT_CONF_DIR, "autohistory.conf"}, + {FID_AUTO_EXECQUERY_CONF, DBMT_CONF_DIR, "autoexecquery.conf"}, + {FID_PSVR_DBINFO_TEMP, DBMT_LOG_DIR, "cmdbinfo.temp"}, + {FID_LOCK_CONN_LIST, DBMT_TMP_DIR, "conlist.lock"}, + {FID_LOCK_PSVR_DBINFO, DBMT_TMP_DIR, "cmdbinfo.lock"}, + {FID_LOCK_SVR_LOG, DBMT_TMP_DIR, "cmlog.lock"}, + {FID_LOCK_DBMT_PASS, DBMT_TMP_DIR, "cmpass.lock"}, + {FID_DIAG_ACTIVITY_LOG, DBMT_CONF_DIR, "diagactivitylog.conf"}, + {FID_DIAG_STATUS_TEMPLATE, DBMT_CONF_DIR, "diagstatustemplate.conf"}, + {FID_DIAG_ACTIVITY_TEMPLATE, DBMT_CONF_DIR, "diagactivitytemplate.conf"}, + {FID_DIAG_SERVER_PID, DBMT_LOG_DIR, "diag.pid"}, + {FID_AMSERVER_PID, DBMT_PID_DIR, DBMT_ARN_AMS_PID}, + {FID_AMS_LOG, DBMT_LOG_DIR, "arn_manager.log"}, + {FID_AMS_ERROR_LOG, DBMT_LOG_DIR, "arn_manager.err"}, + {FID_AUTO_JOBS_CONF, DBMT_CONF_DIR, "autojobs.conf"}, + {FID_SHARD_CONF, DBMT_CONF_DIR, "shard.conf"}, +}; + +sys_config sco; + +static int check_file (char *fname, char *pname); +static int check_path (char *path, char *pname); + +void +sys_config_init (void) +{ + memset (&sco, 0, sizeof (sco)); +} + +int +uReadEnvVariables (char *progname) +{ + char tmpstrbuf[DBMT_ERROR_MSG_SIZE]; + tmpstrbuf[0] = '\0'; + +#if !defined (DO_NOT_USE_ARNIADBENV) + sco.szArniadb = getenv ("ARNIADB"); + sco.szArniadb_databases = getenv ("ARNIADB_DATABASES"); +#else + sco.szArniadb = ARNIADB_PREFIXDIR; + sco.szArniadb_databases = ARNIADB_VARDIR; +#endif + sco.szProgname = strdup (progname); /* not an env variable */ + if (sco.szArniadb == NULL) + { +#if !defined (DO_NOT_USE_ARNIADBENV) + snprintf (tmpstrbuf, DBMT_ERROR_MSG_SIZE, + "ARNIADB Manager Server : Environment variable ARNIADB not set. - %s\n", + sco.szProgname); +#else + snprintf (tmpstrbuf, DBMT_ERROR_MSG_SIZE, + "ARNIADB Manager Server : ARNIADB prefix directory was not set. - %s\n", + sco.szProgname); +#endif + ut_record_arniadb_utility_log_stderr (tmpstrbuf); + return -1; + } + if (sco.szArniadb_databases == NULL) + { +#if !defined (DO_NOT_USE_ARNIADBENV) + snprintf (tmpstrbuf, DBMT_ERROR_MSG_SIZE, + "ARNIADB Manager Server : Environment variable ARNIADB_DATABASES not set. - %s\n", + sco.szProgname); +#else + snprintf (tmpstrbuf, DBMT_ERROR_MSG_SIZE, + "ARNIADB Manager Server : ARNIADB databases directory was not set. - %s\n", + sco.szProgname); +#endif + ut_record_arniadb_utility_log_stderr (tmpstrbuf); + return -1; + } + +#if !defined (DO_NOT_USE_ARNIADBENV) + sco.dbmt_tmp_dir = + (char *) malloc (strlen (sco.szArniadb) + strlen (DBMT_TMP_DIR) + 2); +#else + sco.dbmt_tmp_dir = (char *) malloc (strlen (ARNIADB_TMPDIR) + 1); +#endif + if (sco.dbmt_tmp_dir == NULL) + { + perror ("malloc"); + return -1; + } +#if !defined (DO_NOT_USE_ARNIADBENV) +#ifdef WINDOWS + sprintf (sco.dbmt_tmp_dir, "%s\\%s", sco.szArniadb, DBMT_TMP_DIR); +#else + sprintf (sco.dbmt_tmp_dir, "%s/%s", sco.szArniadb, DBMT_TMP_DIR); +#endif +#else + sprintf (sco.dbmt_tmp_dir, "%s", ARNIADB_TMPDIR); +#endif + + return 1; +} + +/* Read cm.conf and fill system configuration structure */ +/* It fills the global variable 'sco' */ +int +uReadSystemConfig (void) +{ + FILE *conf_file; + char cbuf[1024]; + char ent_name[128], ent_val[128]; + const char *separator = " \t="; + char *token; + int cm_port = 0; + int str_len = 0; + char access_log_buf[PATH_MAX]; + char error_log_buf[PATH_MAX]; + + conf_file = fopen (conf_get_dbmt_file (FID_DBMT_CONF, cbuf), "rt"); + if (conf_file == NULL) + { + return -1; + } + + sco.iAMS_port = DEFAULT_AMS_PORT; + sco.iMonitorInterval = DEFAULT_MONITOR_INTERVAL; + sco.iAllow_AdminMultiCon = DEFAULT_ALLOW_MULTI_CON; + sco.iSupportWebManager = FALSE; + sco.iSupportMonStat = FALSE; + sco.iHttpTimeout = 500; + sco.iAutoJobTimeout = DEFAULT_AUTOJOB_TIMEOUT; + sco.iMaxLogFiles = DEFAULT_LOG_FILE_COUNT; + sco.iMaxLogFileSize = DEFAULT_LOG_FILE_SIZE; + strcpy (sco.szAutoUpdateURL, ""); + strcpy (sco.szAMSVersion, ""); + strncpy (sco.szTokenActiveTime, "7200", PATH_MAX); + snprintf (sco.szCWMPath, PATH_MAX, "%s%s", sco.szArniadb, + DEFAULT_CWM_PATH_SHORT); + + conf_get_dbmt_file (FID_AMS_LOG, access_log_buf); + conf_get_dbmt_file (FID_AMS_ERROR_LOG, error_log_buf); + + snprintf (sco.szAccessLog, PATH_MAX, "%s", access_log_buf); + snprintf (sco.szErrorLog, PATH_MAX, "%s", error_log_buf); + + while (fgets (cbuf, sizeof (cbuf), conf_file)) + { + ut_trim (cbuf); + if (cbuf[0] == '\0' || cbuf[0] == '#') + { + continue; + } + + /* + * put the first token into var ent_name, + * the separator is ' ', '\t', '=' + */ + if ((token = strtok (cbuf, separator)) == NULL) + { + continue; + } + ut_trim (token); + strcpy_limit (ent_name, token, sizeof (ent_name)); + + /* + * put the rest of the string into var ent_val. + */ + if ((token = strtok (NULL, "\0")) == NULL) + { + continue; + } + if (ut_trim (token) == NULL) + { + continue; + } + + /* + * if the first charactor is '=', + * the token should move one more step. + */ + if (token[0] == '=') + { + token++; + } + + if (ut_trim (token) == NULL) + { + continue; + } + strcpy_limit (ent_val, token, sizeof (ent_val)); + + if (strcasecmp (ent_name, "cm_port") == 0) + { + cm_port = atoi (ent_val); + sco.iAMS_port = cm_port; + } + else if (strcasecmp (ent_name, "MonitorInterval") == 0 || + strcasecmp (ent_name, "cm_process_monitor_interval") == 0) + { + sco.iMonitorInterval = atoi (ent_val); + + /* check value range of system parameters */ + if (sco.iMonitorInterval < DEFAULT_MONITOR_INTERVAL) + { + sco.iMonitorInterval = DEFAULT_MONITOR_INTERVAL; + } + + } + else if (strcasecmp (ent_name, "Allow_UserMultiCon") == 0 || + strcasecmp (ent_name, "allow_user_multi_connection") == 0) + { + if (strcasecmp (ent_val, "yes") == 0) + { + sco.iAllow_AdminMultiCon = 1; + } + else + { + sco.iAllow_AdminMultiCon = 0; + } + } + else if (strcasecmp (ent_name, "auto_job_timeout") == 0) + { + int timeout = atoi (ent_val); + if (MIN_AUTOJOB_TIMEOUT <= timeout) + { + sco.iAutoJobTimeout = timeout; + } + else + { + sco.iAutoJobTimeout = DEFAULT_AUTOJOB_TIMEOUT; + } + } + else if (strcasecmp (ent_name, "max_log_filesize") == 0) + { + str_len = (int) strlen(ent_val); + if ((ent_val[str_len - 1] == 'M') || (ent_val[str_len - 1] == 'm')) + { + ent_val[str_len - 1] = '\0'; + } + if (atoi (ent_val) > 0) + { + sco.iMaxLogFileSize = (atoi (ent_val) * 1024 * 1024); + } + } + else if (strcasecmp (ent_name, "max_log_files") == 0) + { + if (atoi (ent_val) > 0) + { + sco.iMaxLogFiles = atoi (ent_val); + } + } + else if (strcasecmp (ent_name, "support_web_manager") == 0) + { + if (strcasecmp (ent_val, "yes") == 0) + { + sco.iSupportWebManager = TRUE; + } + else + { + sco.iSupportWebManager = FALSE; + } + } + else if (strcasecmp (ent_name, "web_manager_path") == 0) + { + /* The path validation will be checked in uCheckSystemConfig */ + snprintf (sco.szCWMPath, PATH_MAX, "%s", ent_val); + } + + else if (strcasecmp (ent_name, "support_mon_statistic") == 0) + { + if (strcasecmp (ent_val, "yes") == 0) + { + sco.iSupportMonStat = TRUE; + } + else + { + sco.iSupportMonStat = FALSE; + } + } + else if (strcasecmp (ent_name, "http_timeout") == 0 || + strcasecmp (ent_name, "HttpTimeout") == 0) + { + sco.iHttpTimeout = atoi (ent_val); + } + else if (strcasecmp (ent_name, "auto_update_url") == 0 || + strcasecmp (ent_name, "AutoUpdateURL") == 0) + { + snprintf (sco.szAutoUpdateURL, PATH_MAX, "%s", ent_val); + } + else if (strcasecmp (ent_name, "arniadb_server_ver") == 0 || + strcasecmp (ent_name, "ArniadbServerVer") == 0) + { + snprintf (sco.szAMSVersion, PATH_MAX, "%s", ent_val); + } + else if (strcasecmp (ent_name, "token_active_time") == 0 || + strcasecmp (ent_name, "TokenActiveTime") == 0) + { + ut_trim (ent_val); + snprintf (sco.szTokenActiveTime, PATH_MAX, "%s", ent_val); + } + } + fclose (conf_file); + +#ifdef HOST_MONITOR_PROC + sco.hmtab1 = 1; + sco.hmtab2 = 1; + sco.hmtab3 = 1; +#ifdef HOST_MONITOR_IO + sco.hmtab4 = 1; +#else + sco.hmtab4 = 0; +#endif /* HOST_MONITOR_IO */ +#else + sco.hmtab1 = 0; + sco.hmtab2 = 0; + sco.hmtab3 = 0; + sco.hmtab4 = 0; +#endif /* HOST_MONITOR_PROC */ + + return 1; +} + +/* Check system configuration */ +/* It is to be called after uReadSystemConfig() */ +int +uCheckSystemConfig (char *progname) +{ + int retval; + char filepath[PATH_MAX]; + char tmpstrbuf[DBMT_ERROR_MSG_SIZE]; + + tmpstrbuf[0] = '\0'; + + if (progname == NULL) + { + fprintf (stderr, "progname should not be NULL.\n"); + return -1; + } + + /* create tmp directory */ + if (access (sco.dbmt_tmp_dir, F_OK) < 0) + { + mkdir (sco.dbmt_tmp_dir, 0755); + } + + /* ARNIADB databases.txt file check */ + sprintf (filepath, "%s/%s", sco.szArniadb_databases, ARNIADB_DATABASE_TXT); + if (access (filepath, F_OK) < 0) + { + FILE *fp; + fp = fopen (filepath, "w"); + if (fp) + { + fclose (fp); + } + } + retval = check_file (filepath, progname); + if (retval < 0) + { + return -1; + } + + if (check_file (conf_get_dbmt_file (FID_DBMT_PASS, filepath), progname) < 0) + { + return -1; + } + if (check_file (conf_get_dbmt_file (FID_DBMT_ARNIADB_PASS, filepath), progname) < 0) + { + return -1; + } + /* arniadb manager only support https connections, + * Thus private key and certificate must be checked before process starting. + */ + snprintf (sco.szSSLKey, PATH_MAX, "%s/conf/%s", sco.szArniadb, DEFAULT_SSL_PRIVATEKEY); + if (check_file (sco.szSSLKey, progname) < 0) + { + return -1; + } + snprintf (sco.szSSLCertificate, PATH_MAX, "%s/conf/%s", sco.szArniadb, DEFAULT_SSL_CERTIFICATE); + if (check_file (sco.szSSLCertificate, progname) < 0) + { + return -1; + } + +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (filepath, "%s/%s", sco.szArniadb, DBMT_LOG_DIR); +#else + sprintf (filepath, "%s", DBMT_LOG_DIR); +#endif + if (check_path (filepath, progname) < 0) + { + return -1; + } +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (filepath, "%s/%s", sco.szArniadb, DBMT_CONF_DIR); +#else + sprintf (filepath, "%s", DBMT_CONF_DIR); +#endif + if (check_path (filepath, progname) < 0) + { + return -1; + } +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (filepath, "%s/%s", sco.szArniadb, DBMT_TMP_DIR); +#else + sprintf (filepath, "%s", DBMT_TMP_DIR); +#endif + if (check_path (filepath, progname) < 0) + { + return -1; + } + + return 1; +} + +char * +conf_get_dbmt_file (T_DBMT_FILE_ID dbmt_fid, char *buf) +{ + int i; + + buf[0] = '\0'; + for (i = 0; i < NUM_DBMT_FILE; i++) + { + if (dbmt_fid == dbmt_file[i].fid) + { +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (buf, "%s/%s/%s", sco.szArniadb, dbmt_file[i].dir_name, + dbmt_file[i].file_name); +#else + sprintf (buf, "%s/%s", dbmt_file[i].dir_name, dbmt_file[i].file_name); +#endif + break; + } + } + return buf; +} + +char * +conf_get_dbmt_file2 (T_DBMT_FILE_ID dbmt_fid, char *buf) +{ + int i; + + buf[0] = '\0'; + for (i = 0; i < NUM_DBMT_FILE; i++) + { + if (dbmt_fid == dbmt_file[i].fid) + { + strcpy (buf, dbmt_file[i].file_name); + break; + } + } + return buf; +} + +int +auto_conf_delete (T_DBMT_FILE_ID fid, char *dbname) +{ + char conf_file[PATH_MAX], tmpfile[512]; + char conf_dbname[128]; + char strbuf[MAX_JOB_CONFIG_FILE_LINE_LENGTH]; + FILE *infp, *outfp; + + conf_get_dbmt_file (fid, conf_file); + if ((infp = fopen (conf_file, "r")) == NULL) + { + return -1; + } + sprintf (tmpfile, "%s/DBMT_task_ac_del.%d", sco.dbmt_tmp_dir, (int) getpid ()); + if ((outfp = fopen (tmpfile, "w")) == NULL) + { + fclose (infp); + return -1; + } + + while (fgets (strbuf, sizeof (strbuf), infp)) + { + if (sscanf (strbuf, "%127s", conf_dbname) < 1) + { + continue; + } + if (strcmp (dbname, conf_dbname) != 0) + { + fputs (strbuf, outfp); + } + } + fclose (infp); + fclose (outfp); + + if (move_file (tmpfile, conf_file) < 0) + { + return -1; + } + return 0; +} + +int +auto_conf_rename (T_DBMT_FILE_ID fid, char *src_dbname, char *dest_dbname) +{ + char conf_file[PATH_MAX], tmpfile[512]; + char conf_dbname[128]; + char strbuf[1024], *p; + FILE *infp, *outfp; + + conf_get_dbmt_file (fid, conf_file); + if ((infp = fopen (conf_file, "r")) == NULL) + { + return -1; + } + sprintf (tmpfile, "%s/DBMT_task_ac_ren.%d", sco.dbmt_tmp_dir, (int) getpid ()); + if ((outfp = fopen (tmpfile, "w")) == NULL) + { + fclose (infp); + return -1; + } + + while (fgets (strbuf, sizeof (strbuf), infp)) + { + if (sscanf (strbuf, "%127s", conf_dbname) < 1) + { + continue; + } + if (strcmp (conf_dbname, src_dbname) == 0) + { + p = strstr (strbuf, src_dbname); + p += strlen (src_dbname); + fprintf (outfp, "%s%s", dest_dbname, p); + } + else + { + fputs (strbuf, outfp); + } + } + fclose (infp); + fclose (outfp); + + if (move_file (tmpfile, conf_file) < 0) + { + return -1; + } + return 0; +} + +int +auto_conf_execquery_update_dbuser (const char *src_db_uid, + const char *dest_db_uid, + const char *dest_db_passwd) +{ + char conf_file_path[PATH_MAX], tmpfile_path[PATH_MAX]; + char dbname[64], query_id[64], db_uid[64], dbmt_uid[64]; + char *strbuf, *p; + int buf_len, get_len; + FILE *conf_file, *tmpfile; + + conf_get_dbmt_file (FID_AUTO_EXECQUERY_CONF, conf_file_path); + if ((conf_file = fopen (conf_file_path, "r")) == NULL) + { + return -1; + } + sprintf (tmpfile_path, "%s/DBMT_task_ac_swit.%d", sco.dbmt_tmp_dir, (int) getpid ()); + if ((tmpfile = fopen (tmpfile_path, "w")) == NULL) + { + fclose (conf_file); + return -1; + } + + strbuf = NULL; + buf_len = get_len = 0; + while ((get_len = ut_getline (&strbuf, &buf_len, conf_file)) != -1) + { + if (sscanf + (strbuf, "%64s %64s %64s %*s %64s", dbname, query_id, db_uid, dbmt_uid) < 4) + { + continue; + } + + if (uStringEqual (db_uid, src_db_uid)) + { + p = strstr (strbuf, dbmt_uid); + if (p) + { + p = strchr (p, ' '); + } + fprintf (tmpfile, "%s %s %s %s %s%s", dbname, query_id, dest_db_uid, + dest_db_passwd, dbmt_uid, p); + } + else + { + fputs (strbuf, tmpfile); + } + FREE_MEM (strbuf); + buf_len = 0; + } + + if (strbuf != NULL) + { + FREE_MEM (strbuf); + } + + fclose (conf_file); + fclose (tmpfile); + + if (move_file (tmpfile_path, conf_file_path) < 0) + { + return -1; + } + + return 0; +} + +int +auto_conf_execquery_delete_by_dbuser (const char *target_db_uid) +{ + char conf_file_path[PATH_MAX], tmpfile_path[PATH_MAX]; + char db_uid[64]; + char *strbuf; + int buf_len, get_len; + FILE *conf_file, *tmpfile; + + conf_get_dbmt_file (FID_AUTO_EXECQUERY_CONF, conf_file_path); + if ((conf_file = fopen (conf_file_path, "r")) == NULL) + { + return -1; + } + sprintf (tmpfile_path, "%s/DBMT_task_ac_del_user.%d", sco.dbmt_tmp_dir, (int) getpid ()); + if ((tmpfile = fopen (tmpfile_path, "w")) == NULL) + { + fclose (conf_file); + return -1; + } + + strbuf = NULL; + buf_len = get_len = 0; + while ((get_len = ut_getline (&strbuf, &buf_len, conf_file)) != -1) + { + if (sscanf (strbuf, "%*s %*s %64s", db_uid) < 1) + { + continue; + } + + if (uStringEqual (db_uid, target_db_uid)) + { + continue; + } + else + { + fputs (strbuf, tmpfile); + } + FREE_MEM (strbuf); + buf_len = 0; + } + + if (strbuf != NULL) + { + FREE_MEM (strbuf); + } + + fclose (conf_file); + fclose (tmpfile); + + if (move_file (tmpfile_path, conf_file_path) < 0) + { + return -1; + } + + return 0; +} + +static int +check_file (char *fname, char *pname) +{ + char tmpstrbuf[DBMT_ERROR_MSG_SIZE]; + + tmpstrbuf[0] = '\0'; + + if (access (fname, F_OK | R_OK | W_OK) < 0) + { + snprintf (tmpstrbuf, DBMT_ERROR_MSG_SIZE, + "ARNIADB Manager Server : %s - %s. - %s\n", fname, strerror (errno), pname); + ut_record_arniadb_utility_log_stderr (tmpstrbuf); + return -1; + } + return 1; +} + +static int +check_path (char *dirname, char *pname) +{ + /* check if directory exists */ + char tmpstrbuf[DBMT_ERROR_MSG_SIZE]; + + tmpstrbuf[0] = '\0'; + + if (access (dirname, F_OK | W_OK | R_OK | X_OK) < 0) + { + snprintf (tmpstrbuf, DBMT_ERROR_MSG_SIZE, + "ARNIADB Manager Server : %s - %s. - %s\n", dirname, strerror (errno), pname); + ut_record_arniadb_utility_log_stderr (tmpstrbuf); + return -1; + } + return 1; +} diff --git a/server/src/am_config.h b/server/src/am_config.h new file mode 100644 index 0000000..b779b2a --- /dev/null +++ b/server/src/am_config.h @@ -0,0 +1,629 @@ +/* + * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. + * + * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + + +/* + * cm_config.h - + */ + +#ifndef _CM_CONFIG_H_ +#define _CM_CONFIG_H_ + +#include +#include +#include "cm_porting.h" + +#define MAX_INSTALLED_DB 256 +#define MAX_UNICAS_PROC 40 + +#define MIN_ENCRYPT_LEN 32 +#define ENCRYPT_SIGN "@" +#define ENCRYPT_ARG(arg) (ENCRYPT_SIGN arg) + +#define AUTOBACKUP_CONF_ENTRY_NUM 15 +#define AUTOADDVOL_CONF_ENTRY_NUM 7 +#define AUTOHISTORY_CONF_ENTRY_NUM 15 +#define AUTOUNICAS_CONF_ENTRY_NUM 9 +#define AUTOEXECQUERY_CONF_ENTRY_NUM 9 +#define AUTOBACKUP_PERIOD_TYPE_NUM 5 +#define AUTOBACKUP_PERIOD_WEEK_NUM 7 + +#define AMS_NAME "arn_manager" + +#if !defined (DO_NOT_USE_ARNIADBENV) +#define DBMT_CONF_DIR "conf" +#define DBMT_LOG_DIR "log/manager" +#define DBMT_PID_DIR "var/manager" +#define DBMT_MON_DATA_DIR "var/manager/mon_data" +#define DBMT_TMP_DIR "tmp" +#else +#define DBMT_CONF_DIR ARNIADB_CONFDIR +#define DBMT_LOG_DIR ARNIADB_VARDIR "/manager" +#define DBMT_PID_DIR ARNIADB_VARDIR "/manager" +#define DBMT_MON_DATA_DIR ARNIADB_VARDIR "/manager/mon_data" +#define DBMT_TMP_DIR ARNIADB_TMPDIR +#endif + +#define DBMT_ARN_AMS_PID "arn_manager.pid" + +/* utility option list, from executables/utility.h */ +#define UTIL_OPTION_CREATEDB "createdb" +#define UTIL_OPTION_RENAMEDB "renamedb" +#define UTIL_OPTION_COPYDB "copydb" +#define UTIL_OPTION_DELETEDB "deletedb" +#define UTIL_OPTION_BACKUPDB "backupdb" +#define UTIL_OPTION_RESTOREDB "restoredb" +#define UTIL_OPTION_ADDVOLDB "addvoldb" +#define UTIL_OPTION_SPACEDB "spacedb" +#define UTIL_OPTION_LOCKDB "lockdb" +#define UTIL_OPTION_KILLTRAN "killtran" +#define UTIL_OPTION_TRANLIST "tranlist" +#define UTIL_OPTION_OPTIMIZEDB "optimizedb" +#define UTIL_OPTION_INSTALLDB "installdb" +#define UTIL_OPTION_DIAGDB "diagdb" +#define UTIL_OPTION_PATCHDB "emergency_patchlog" +#define UTIL_OPTION_CHECKDB "checkdb" +#define UTIL_OPTION_ALTERDBHOST "alterdbhost" +#define UTIL_OPTION_PLANDUMP "plandump" +#define UTIL_OPTION_ESTIMATE_DATA "estimate_data" +#define UTIL_OPTION_ESTIMATE_INDEX "estimate_index" +#define UTIL_OPTION_LOADDB "loaddb" +#define UTIL_OPTION_UNLOADDB "unloaddb" +#define UTIL_OPTION_COMPACTDB "compactdb" +#define UTIL_OPTION_PARAMDUMP "paramdump" +#define UTIL_OPTION_CHANGEMODE "changemode" +#define UTIL_OPTION_COPYLOGDB "copylogdb" +#define UTIL_OPTION_APPLYLOGDB "applylogdb" +#define UTIL_OPTION_LOGFILEDUMP "logfiledump" + +/* killtran option list */ +#define KILLTRAN_KILL_TRANSACTION_INDEX_S 'i' +#define KILLTRAN_KILL_TRANSACTION_INDEX_L "kill-transaction-index" +#define KILLTRAN_KILL_USER_NAME_S 11701 +#define KILLTRAN_KILL_USER_NAME_L "kill-user-name" +#define KILLTRAN_KILL_HOST_NAME_S 11702 +#define KILLTRAN_KILL_HOST_NAME_L "kill-host-name" +#define KILLTRAN_KILL_PROGRAM_NAME_S 11703 +#define KILLTRAN_KILL_PROGRAM_NAME_L "kill-program-name" +#define KILLTRAN_KILL_SQL_ID_S 11704 +#define KILLTRAN_KILL_SQL_ID_L "kill-sql-id" +#define KILLTRAN_KILL_QUERY_INFO_S 'q' +#define KILLTRAN_KILL_QUERY_INFO_L "query-exec-info" +#define KILLTRAN_DBA_PASSWORD_S 'p' +#define KILLTRAN_DBA_PASSWORD_L "dba-password" +#define KILLTRAN_DISPLAY_INFORMATION_S 'd' +#define KILLTRAN_DISPLAY_INFORMATION_L "display-information" +#define KILLTRAN_FORCE_S 'f' +#define KILLTRAN_FORCE_L "force" + +/* tranlist option list */ +#define TRANLIST_USER_S 'u' +#define TRANLIST_USER_L "user" +#define TRANLIST_PASSWORD_S 'p' +#define TRANLIST_PASSWORD_L "password" + + +/* sqlx option list */ +#define ASQL_SA_MODE_S 'S' +#define ASQL_SA_MODE_L "SA-mode" +#define ASQL_CS_MODE_S 'C' +#define ASQL_CS_MODE_L "CS-mode" +#define ASQL_USER_S 'u' +#define ASQL_USER_L "user" +#define ASQL_PASSWORD_S 'p' +#define ASQL_PASSWORD_L "password" +#define ASQL_ERROR_CONTINUE_S 'e' +#define ASQL_ERROR_CONTINUE_L "error-continue" +#define ASQL_INPUT_FILE_S 'i' +#define ASQL_INPUT_FILE_L "input-file" +#define ASQL_OUTPUT_FILE_S 'o' +#define ASQL_OUTPUT_FILE_L "output-file" +#define ASQL_SINGLE_LINE_S 's' +#define ASQL_SINGLE_LINE_L "single-line" +#define ASQL_COMMAND_S 'c' +#define ASQL_COMMAND_L "command" +#define ASQL_LINE_OUTPUT_S 'l' +#define ASQL_LINE_OUTPUT_L "line-output" +#define ASQL_READ_ONLY_S 'r' +#define ASQL_READ_ONLY_L "read-only" +#define ASQL_NO_AUTO_COMMIT_S 12010 +#define ASQL_NO_AUTO_COMMIT_L "no-auto-commit" +#define ASQL_NO_PAGER_S 12011 +#define ASQL_NO_PAGER_L "no-pager" +#define ASQL_SYSADM_S 12012 +#define ASQL_SYSADM_L "sysadm" + +/* addvoldb option list */ +#define ADDVOL_VOLUME_NAME_S 'n' +#define ADDVOL_VOLUME_NAME_L "volume-name" +#define ADDVOL_FILE_PATH_S 'F' +#define ADDVOL_FILE_PATH_L "file-path" +#define ADDVOL_COMMENT_S 10702 +#define ADDVOL_COMMENT_L "comment" +#define ADDVOL_PURPOSE_S 'p' +#define ADDVOL_PURPOSE_L "purpose" +#define ADDVOL_SA_MODE_S 'S' +#define ADDVOL_SA_MODE_L "SA-mode" +#define ADDVOL_CS_MODE_S 'C' +#define ADDVOL_CS_MODE_L "CS-mode" +#define ADDVOL_DB_VOLUMN_SIZE_L "db-volume-size" + +/* backupdb option list */ +#define BACKUP_DESTINATION_PATH_S 'D' +#define BACKUP_DESTINATION_PATH_L "destination-path" +#define BACKUP_REMOVE_ARCHIVE_S 'r' +#define BACKUP_REMOVE_ARCHIVE_L "remove-archive" +#define BACKUP_LEVEL_S 'l' +#define BACKUP_LEVEL_L "level" +#define BACKUP_OUTPUT_FILE_S 'o' +#define BACKUP_OUTPUT_FILE_L "output-file" +#define BACKUP_SA_MODE_S 'S' +#define BACKUP_SA_MODE_L "SA-mode" +#define BACKUP_CS_MODE_S 'C' +#define BACKUP_CS_MODE_L "CS-mode" +#define BACKUP_NO_CHECK_S 10506 +#define BACKUP_NO_CHECK_L "no-check" +#define BACKUP_THREAD_COUNT_S 't' +#define BACKUP_THREAD_COUNT_L "thread-count" +#define BACKUP_COMPRESS_S 'z' +#define BACKUP_COMPRESS_L "compress" +#define BACKUP_EXCEPT_ACTIVE_LOG_S 'e' +#define BACKUP_EXCEPT_ACTIVE_LOG_L "except-active-log" +#define BACKUP_SAFE_PAGE_ID_S 10510 +#define BACKUP_SAFE_PAGE_ID_L "safe-page-id" + +/* restoredb option list */ +#define RESTORE_UP_TO_DATE_S 'd' +#define RESTORE_UP_TO_DATE_L "up-to-date" +#define RESTORE_LIST_S 10601 +#define RESTORE_LIST_L "list" +#define RESTORE_BACKUP_FILE_PATH_S 'B' +#define RESTORE_BACKUP_FILE_PATH_L "backup-file-path" +#define RESTORE_LEVEL_S 'l' +#define RESTORE_LEVEL_L "level" +#define RESTORE_PARTIAL_RECOVERY_S 'p' +#define RESTORE_PARTIAL_RECOVERY_L "partial-recovery" +#define RESTORE_OUTPUT_FILE_S 'o' +#define RESTORE_OUTPUT_FILE_L "output-file" +#define RESTORE_REPLICATION_MODE_S 'r' +#define RESTORE_REPLICATION_MODE_L "replication-mode" +#define RESTORE_USE_DATABASE_LOCATION_PATH_S 'u' +#define RESTORE_USE_DATABASE_LOCATION_PATH_L "use-database-location-path" + + +/* spacedb option list */ +#define SPACE_OUTPUT_FILE_S 'o' +#define SPACE_OUTPUT_FILE_L "output-file" +#define SPACE_SA_MODE_S 'S' +#define SPACE_SA_MODE_L "SA-mode" +#define SPACE_CS_MODE_S 'C' +#define SPACE_CS_MODE_L "CS-mode" +#define SPACE_SIZE_UNIT_S 10803 +#define SPACE_SIZE_UNIT_L "size-unit" + +/* checkdb option list */ +#define CHECK_SA_MODE_S 'S' +#define CHECK_SA_MODE_L "SA-mode" +#define CHECK_CS_MODE_S 'C' +#define CHECK_CS_MODE_L "CS-mode" +#define CHECK_REPAIR_S 'r' +#define CHECK_REPAIR_L "repair" + +/* renamedb option list */ +#define RENAME_EXTENTED_VOLUME_PATH_S 'E' +#define RENAME_EXTENTED_VOLUME_PATH_L "extended-volume-path" +#define RENAME_CONTROL_FILE_S 'i' +#define RENAME_CONTROL_FILE_L "control-file" +#define RENAME_DELETE_BACKUP_S 'd' +#define RENAME_DELETE_BACKUP_L "delete-backup" + + +/* copydb option list */ +#define COPY_SERVER_NAME_S 10300 +#define COPY_SERVER_NAME_L "server-name" +#define COPY_FILE_PATH_S 'F' +#define COPY_FILE_PATH_L "file-path" +#define COPY_LOG_PATH_S 'L' +#define COPY_LOG_PATH_L "log-path" +#define COPY_EXTENTED_VOLUME_PATH_S 'E' +#define COPY_EXTENTED_VOLUME_PATH_L "extended-volume-path" +#define COPY_CONTROL_FILE_S 'i' +#define COPY_CONTROL_FILE_L "control-file" +#define COPY_REPLACE_S 'r' +#define COPY_REPLACE_L "replace" +#define COPY_DELETE_SOURCE_S 'd' +#define COPY_DELETE_SOURCE_L "delete-source" +#define COPY_LOB_BASE_PATH_S "B" +#define COPY_LOB_BASE_PATH_L "lob-base-path" + +/* deletedb option list */ +#define DELETE_OUTPUT_FILE_S 'o' +#define DELETE_OUTPUT_FILE_L "output-file" +#define DELETE_DELETE_BACKUP_S 'd' +#define DELETE_DELETE_BACKUP_L "delete-backup" + + +/* createdb option list */ +#define CREATE_PAGES_S 'p' +#define CREATE_PAGES_L "pages" +#define CREATE_COMMENT_S 10102 +#define CREATE_COMMENT_L "comment" +#define CREATE_FILE_PATH_S 'F' +#define CREATE_FILE_PATH_L "file-path" +#define CREATE_LOG_PATH_S 'L' +#define CREATE_LOG_PATH_L "log-path" +#define CREATE_SERVER_NAME_S 10105 +#define CREATE_SERVER_NAME_L "server-name" +#define CREATE_REPLACE_S 'r' +#define CREATE_REPLACE_L "replace" +#define CREATE_MORE_VOLUME_FILE_S 10107 +#define CREATE_MORE_VOLUME_FILE_L "more-volume-file" +#define CREATE_USER_DEFINITION_FILE_S 10108 +#define CREATE_USER_DEFINITION_FILE_L "user-definition-file" +#define CREATE_ASQL_INITIALIZATION_FILE_S 10109 +#define CREATE_ASQL_INITIALIZATION_FILE_L "asql-initialization-file" +#define CREATE_OUTPUT_FILE_S 'o' +#define CREATE_OUTPUT_FILE_L "output-file" +#define CREATE_VERBOSE_S 'v' +#define CREATE_VERBOSE_L "verbose" +#define CREATE_CHARSET_S 10112 +#define CREATE_CHARSET_L "charset" +#define CREATE_DB_PAGE_SIZE_L "db-page-size" +#define CREATE_LOG_PAGE_SIZE_L "log-page-size" +#define CREATE_DB_VOLUMN_SIZE_L "db-volume-size" +#define CREATE_LOG_VOLUMN_SIZE_L "log-volume-size" + +/* loaddb option list */ +#define LOAD_USER_S 'u' +#define LOAD_USER_L "user" +#define LOAD_PASSWORD_S 'p' +#define LOAD_PASSWORD_L "password" +#define LOAD_CHECK_ONLY_S 11802 +#define LOAD_CHECK_ONLY_L "data-file-check-only" +#define LOAD_LOAD_ONLY_S 'l' +#define LOAD_LOAD_ONLY_L "load-only" +#define LOAD_ESTIMATED_SIZE_S 11804 +#define LOAD_ESTIMATED_SIZE_L "estimated-size" +#define LOAD_VERBOSE_S 'v' +#define LOAD_VERBOSE_L "verbose" +#define LOAD_NO_STATISTICS_S 11806 +#define LOAD_NO_STATISTICS_L "no-statistics" +#define LOAD_PERIODIC_COMMIT_S 'c' +#define LOAD_PERIODIC_COMMIT_L "periodic-commit" +#define LOAD_NO_OID_S 11808 +#define LOAD_NO_OID_L "no-oid" +#define LOAD_SCHEMA_FILE_S 's' +#define LOAD_SCHEMA_FILE_L "schema-file" +#define LOAD_INDEX_FILE_S 'i' +#define LOAD_INDEX_FILE_L "index-file" +#define LOAD_IGNORE_LOGGING_S 11811 +#define LOAD_IGNORE_LOGGING_L "no-logging" +#define LOAD_DATA_FILE_S 'd' +#define LOAD_DATA_FILE_L "data-file" +#define LOAD_ERROR_CONTROL_FILE_S 'e' +#define LOAD_ERROR_CONTROL_FILE_L "error-control-file" +#define LOAD_IGNORE_CLASS_S 11814 +#define LOAD_IGNORE_CLASS_L "ignore-class-file" +#define LOAD_SA_MODE_S 'S' +#define LOAD_SA_MODE_L "SA-mode" +#define LOAD_CS_MODE_S 11815 +#define LOAD_CS_MODE_L "CS-hidden" + +/* unloaddb option list */ +#define UNLOAD_INPUT_CLASS_FILE_S 'i' +#define UNLOAD_INPUT_CLASS_FILE_L "input-class-file" +#define UNLOAD_INCLUDE_REFERENCE_S 11901 +#define UNLOAD_INCLUDE_REFERENCE_L "include-reference" +#define UNLOAD_INPUT_CLASS_ONLY_S 11902 +#define UNLOAD_INPUT_CLASS_ONLY_L "input-class-only" +#define UNLOAD_LO_COUNT_S 11903 +#define UNLOAD_LO_COUNT_L "lo-count" +#define UNLOAD_ESTIMATED_SIZE_S 11904 +#define UNLOAD_ESTIMATED_SIZE_L "estimated-size" +#define UNLOAD_CACHED_PAGES_S 11905 +#define UNLOAD_CACHED_PAGES_L "cached-pages" +#define UNLOAD_OUTPUT_PATH_S 'O' +#define UNLOAD_OUTPUT_PATH_L "output-path" +#define UNLOAD_SCHEMA_ONLY_S 's' +#define UNLOAD_SCHEMA_ONLY_L "schema-only" +#define UNLOAD_DATA_ONLY_S 'd' +#define UNLOAD_DATA_ONLY_L "data-only" +#define UNLOAD_OUTPUT_PREFIX_S 11909 +#define UNLOAD_OUTPUT_PREFIX_L "output-prefix" +#define UNLOAD_HASH_FILE_S 11910 +#define UNLOAD_HASH_FILE_L "hash-file" +#define UNLOAD_VERBOSE_S 'v' +#define UNLOAD_VERBOSE_L "verbose" +#define UNLOAD_USE_DELIMITER_S 11912 +#define UNLOAD_USE_DELIMITER_L "use-delimiter" +#define UNLOAD_SA_MODE_S 'S' +#define UNLOAD_SA_MODE_L "SA-mode" +#define UNLOAD_CS_MODE_S 'C' +#define UNLOAD_CS_MODE_L "CS-mode" +#define UNLOAD_USER_S "u" +#define UNLOAD_USER_L "user" +#define UNLOAD_PASSWORD_S "p" +#define UNLOAD_PASSWORD_L "password" + +/* compactdb option list */ +#define COMPACT_VERBOSE_S 'v' +#define COMPACT_VERBOSE_L "verbose" +#define COMPACT_SA_MODE_S 'S' +#define COMPACT_SA_MODE_L "SA-mode" +#define COMPACT_CS_MODE_S 'C' +#define COMPACT_CS_MODE_L "CS-mode" + +/* paramdump option list */ +#define PARAMDUMP_BOTH_S 'b' +#define PARAMDUMP_BOTH_L "both" +#define PARAMDUMP_SA_MODE_S 'S' +#define PARAMDUMP_SA_MODE_L "SA-mode" +#define PARAMDUMP_CS_MODE_S 'C' +#define PARAMDUMP_CS_MODE_L "CS-mode" + +/* plandump option list */ +#define PLANDUMP_DROP_S 'd' +#define PLANDUMP_DROP_L "drop" + +/* lockdb option list */ +#define LOCK_OUTPUT_FILE_S 'o' +#define LOCK_OUTPUT_FILE_L "output-file" + +/* changemode option list */ +#define CHANGEMODE_MODE_S 'm' +#define CHANGEMODE_MODE_L "mode" +#define CHANGEMODE_WAIT_S 'w' +#define CHANGEMODE_WAIT_L "wait" +#define CHANGEMODE_FORCE_S 'f' +#define CHANGEMODE_FORCE_L "force" + +#if defined(WINDOWS) +#define UTIL_EXE_EXT ".exe" +#else +#define UTIL_EXE_EXT "" +#endif +#if defined(WINDOWS) +#define UTIL_SCRIPT_EXT ".bat" +#else +#define UTIL_SCRIPT_EXT ".sh" +#endif +#define UTIL_MASTER_NAME "arn_master" UTIL_EXE_EXT +#define UTIL_COMMDB_NAME "arn_commdb" UTIL_EXE_EXT +#define UTIL_ARNIADB_NAME "arn_server" UTIL_EXE_EXT +#define UTIL_BROKER_NAME "arniadb_broker" UTIL_EXE_EXT +#define UTIL_MONITOR_NAME "broker_monitor" UTIL_EXE_EXT +#define UTIL_REPL_SERVER_NAME "repl_server" UTIL_EXE_EXT +#define UTIL_REPL_AGENT_NAME "repl_agent" UTIL_EXE_EXT +#define UTIL_ADMIN_NAME "arn_admin" UTIL_EXE_EXT +#define UTIL_SQLX_NAME "sqlx" UTIL_EXE_EXT +#define UTIL_ASQL_NAME "asql" UTIL_EXE_EXT +#define UTIL_ARNIADB_REL_NAME "arniadb_rel" UTIL_EXE_EXT +#define UTIL_OLD_COMMDB_NAME "commdb" UTIL_EXE_EXT +#define UTIL_ARNIADB "arniadb" UTIL_EXE_EXT +#define UTIL_CM_SERVER AMS_NAME UTIL_EXE_EXT +#define UTIL_BROKER_CHANGER "broker_changer" UTIL_EXE_EXT + +#define COMMDB_SERVER_STOP "-S" +#define COMMDB_SERVER_STATUS "-P" +#define COMMDB_REPL_STATUS "-R" +#define COMMDB_ALL_STATUS "-O" +#define COMMDB_ALL_STOP "-A" + +#define PRINT_CMD_SERVER "server" +#define PRINT_CMD_SHARD "shard" +#define PRINT_CMD_REPL_SERVER "repl_server" +#define PRINT_CMD_REPL_AGENT "repl_agent" +#define PRINT_CMD_START "start" +#define PRINT_CMD_STOP "stop" +#define PRINT_CMD_STATUS "status" +#define PRINT_CMD_RELOAD "reload" +#define PRINT_CMD_ON "on" +#define PRINT_CMD_OFF "off" + +#define PRINT_CMD_HEARTBEAT "heartbeat" +#define PRINT_CMD_LIST "list" +#define PRINT_CMD_DEACT "deact" +#define PRINT_CMD_ACT "act" + +/* from perf_monitor.h */ +#define MAX_SERVER_THREAD_COUNT 500 + +/* rename auto_conf_* function name more readably */ +#define auto_conf_execquery_delete(FID, DBNAME) auto_conf_delete(FID, DBNAME) +#define auto_conf_execquery_rename(FID, OLD, NEW) auto_conf_rename(FID, OLD, NEW) +#define auto_conf_addvol_delete(FID, DBNAME) auto_conf_delete(FID, DBNAME) +#define auto_conf_backup_delete(FID, DBNAME) auto_conf_delete(FID, DBNAME) +#define auto_conf_history_delete(FID, DBNAME) auto_conf_delete(FID, DBNAME) +#define auto_conf_start_delete(FID, DBNAME) auto_conf_delete(FID, DBNAME) +#define auto_conf_addvol_rename(FID, OLD, NEW) auto_conf_rename(FID, OLD, NEW) +#define auto_conf_backup_rename(FID, OLD, NEW) auto_conf_rename(FID, OLD, NEW) +#define auto_conf_history_rename(FID, OLD, NEW) auto_conf_rename(FID, OLD, NEW) +#define auto_conf_start_rename(FID, OLD, NEW) auto_conf_rename(FID, OLD, NEW) + +/* auto backup database plan - period_type */ +#define AUTO_BACKUP_PERIOD_TYPE_MONTHLY "Monthly" +#define AUTO_BACKUP_PERIOD_TYPE_WEEKLY "Weekly" +#define AUTO_BACKUP_PERIOD_TYPE_DAILY "Daily" +#define AUTO_BACKUP_PERIOD_TYPE_HOURLY "Hourly" +#define AUTO_BACKUP_PERIOD_TYPE_SPECIAL "Special" + +/* week */ +#define WEEK_SUNDAY_L "Sunday" +#define WEEK_SUNDAY_S "Sun" +#define WEEK_CAPITAL_SUNDAY_L "SUNDAY" +#define WEEK_CAPITAL_SUNDAY_S "SUN" +#define WEEK_MONDAY_L "Monday" +#define WEEK_MONDAY_S "Mon" +#define WEEK_CAPITAL_MONDAY_L "MONDAY" +#define WEEK_CAPITAL_MONDAY_S "MON" +#define WEEK_TUESDAY_L "Tuesday" +#define WEEK_TUESDAY_S "Tue" +#define WEEK_CAPITAL_TUESDAY_L "TUESDAY" +#define WEEK_CAPITAL_TUESDAY_S "TUE" +#define WEEK_WEDNESDAY_L "Wednesday" +#define WEEK_WEDNESDAY_S "Wed" +#define WEEK_CAPITAL_WEDNESDAY_L "WEDNESDAY" +#define WEEK_CAPITAL_WEDNESDAY_S "WED" +#define WEEK_THURSDAY_L "Thursday" +#define WEEK_THURSDAY_S "Thu" +#define WEEK_CAPITAL_THURSDAY_L "THURSDAY" +#define WEEK_CAPITAL_THURSDAY_S "THU" +#define WEEK_FRIDAY_L "Friday" +#define WEEK_FRIDAY_S "Fri" +#define WEEK_CAPITAL_FRIDAY_L "FRIDAY" +#define WEEK_CAPITAL_FRIDAY_S "FRI" +#define WEEK_SATURDAY_L "Saturday" +#define WEEK_SATURDAY_S "Sat" +#define WEEK_CAPITAL_SATURDAY_L "SATURDAY" +#define WEEK_CAPITAL_SATURDAY_S "SAT" + +#define ACCESS_LOG "access_log" +#define ACCESS_ERR "access_err" + +#define HA_MODE 2 + +typedef enum +{ + AMS_TRAN_UNKNOWN_ISOLATION = 0x00, /* 0 0000 */ + AMS_TRAN_COMMIT_CLASS_UNCOMMIT_INSTANCE = 0x01, /* 0 0001 */ + AMS_TRAN_DEGREE_1_CONSISTENCY = 0x01, /* Alias of above */ + + AMS_TRAN_COMMIT_CLASS_COMMIT_INSTANCE = 0x02, /* 0 0010 */ + AMS_TRAN_DEGREE_2_CONSISTENCY = 0x02, /* Alias of above */ + + AMS_TRAN_REP_CLASS_UNCOMMIT_INSTANCE = 0x03, /* 0 0011 */ + AMS_TRAN_READ_UNCOMMITTED = 0x03, /* Alias of above */ + + AMS_TRAN_REP_CLASS_COMMIT_INSTANCE = 0x04, /* 0 0100 */ + AMS_TRAN_READ_COMMITTED = 0x04, /* Alias of above */ + AMS_TRAN_CURSOR_STABILITY = 0x04, /* Alias of above */ + + AMS_TRAN_REP_CLASS_REP_INSTANCE = 0x05, /* 0 0101 */ + AMS_TRAN_REP_READ = 0x05, /* Alias of above */ + AMS_TRAN_DEGREE_2_9999_CONSISTENCY = 0x05, /* Alias of above */ + + AMS_TRAN_SERIALIZABLE = 0x06, /* 0 0110 */ + AMS_TRAN_DEGREE_3_CONSISTENCY = 0x06, /* Alias of above */ + AMS_TRAN_NO_PHANTOM_READ = 0x06, /* Alias of above */ + + AMS_TRAN_DEFAULT_ISOLATION = AMS_TRAN_REP_CLASS_UNCOMMIT_INSTANCE, + +} AMS_DB_TRAN_ISOLATION; /* extract from dbi.h */ + + +typedef enum +{ + FID_DBMT_CONF, + FID_DBMT_PASS, + FID_DBMT_ARNIADB_PASS, + FID_CONN_LIST, + FID_AUTO_ADDVOLDB_CONF, + FID_AUTO_ADDVOLDB_LOG, + FID_AUTO_BACKUPDB_CONF, + FID_AUTO_HISTORY_CONF, + FID_AUTO_EXECQUERY_CONF, + FID_PSVR_DBINFO_TEMP, + FID_LOCK_CONN_LIST, + FID_LOCK_PSVR_DBINFO, + FID_LOCK_SVR_LOG, + FID_LOCK_DBMT_PASS, + FID_DIAG_ACTIVITY_LOG, + FID_DIAG_STATUS_TEMPLATE, + FID_DIAG_ACTIVITY_TEMPLATE, + FID_DIAG_SERVER_PID, + FID_AMSERVER_PID, + FID_AMS_LOG, + FID_AMS_ERROR_LOG, + FID_AUTO_JOBS_CONF, + FID_SHARD_CONF, +} T_DBMT_FILE_ID; + +typedef struct +{ + T_DBMT_FILE_ID fid; + char dir_name[PATH_MAX]; + char file_name[32]; +} T_DBMT_FILE_INFO; + +typedef struct +{ + /* + * program name (either fserver or pserver) + */ + char *szProgname; + + /* + * ARNIADB environment variables + */ + char *szArniadb; /* ARNIADB */ + char *szArniadb_databases; /* ARNIADB_DATABASES */ + + char *dbmt_tmp_dir; + + int iMonitorInterval; + char sMonStatDataPath[PATH_MAX]; + char szCWMPath[PATH_MAX]; + char szSSLKey[PATH_MAX]; + char szSSLCertificate[PATH_MAX]; + int iAllow_AdminMultiCon; + int iAutoJobTimeout; + int iAMS_port; + int iSupportWebManager; + int iSupportMonStat; + int iHttpTimeout; + char szAutoUpdateURL[PATH_MAX]; + char szAMSVersion[PATH_MAX]; + char szTokenActiveTime[PATH_MAX]; + int hmtab1, hmtab2, hmtab3, hmtab4; + char szAccessLog[PATH_MAX]; + char szErrorLog[PATH_MAX]; + int iMaxLogFileSize; + int iMaxLogFiles; +} sys_config; + +void sys_config_init (void); +int uReadEnvVariables (char *progname); +int uCheckSystemConfig (char *progname); +int uReadSystemConfig (void); + +char *conf_get_dbmt_file (T_DBMT_FILE_ID dbmt_fid, char *buf); +char *conf_get_dbmt_file2 (T_DBMT_FILE_ID dbmt_fid, char *buf); + +extern sys_config sco; +extern const char *autobackup_conf_entry[AUTOBACKUP_CONF_ENTRY_NUM]; +extern const char *autoaddvol_conf_entry[AUTOADDVOL_CONF_ENTRY_NUM]; +extern const char *autohistory_conf_entry[AUTOHISTORY_CONF_ENTRY_NUM]; +extern const char *autounicas_conf_entry[AUTOUNICAS_CONF_ENTRY_NUM]; +extern const char *autobackup_period_type[AUTOBACKUP_PERIOD_TYPE_NUM]; +extern const char *autobackup_period_week[AUTOBACKUP_PERIOD_WEEK_NUM]; + +extern int arniadb_version_major; +extern int arniadb_version_minor; +void find_and_parse_arn_admin_version (int &major_version, int &minor_version); +#define IS_INVALID_ARNIADB_VERS_MAJOR(major) (major <= 0) + +extern int auto_conf_delete (T_DBMT_FILE_ID fid, char *dbname); +extern int auto_conf_rename (T_DBMT_FILE_ID fid, char *src_dbname, + char *dest_dbname); +extern int auto_conf_execquery_update_dbuser (const char *src_db_uid, + const char *dest_db_uid, + const char *dest_db_passwd); +extern int auto_conf_execquery_delete_by_dbuser (const char *db_uid); + +#endif /* _CM_CONFIG_H_ */ diff --git a/server/src/am_connect_info.cpp b/server/src/am_connect_info.cpp new file mode 100644 index 0000000..d26bb8a --- /dev/null +++ b/server/src/am_connect_info.cpp @@ -0,0 +1,547 @@ +/* + * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. + * + * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + + +/* + * cm_connect_info.cpp - + */ + +#include +#include +#include +#include + +#if defined(WINDOWS) +#include +#else +#include +#endif + +#include "cm_porting.h" +#include "cm_server_util.h" +#include "cm_config.h" +#include "cm_connect_info.h" + +int +dbmt_con_search (const char *ip, const char *port, char *cli_ver) +{ + FILE *infile; + int lfd, retval; + int get_len, buf_len; + char *strbuf; + char sbuf[512]; + char ip_t[20], port_t[10]; + + /* check if ip is an existing ip */ + retval = 0; + lfd = uCreateLockFile (conf_get_dbmt_file (FID_LOCK_CONN_LIST, sbuf)); + if (lfd < 0) + { + return ERR_TMPFILE_OPEN_FAIL; + } + + infile = fopen (conf_get_dbmt_file (FID_CONN_LIST, sbuf), "r"); + if (infile != NULL) + { + strbuf = NULL; + buf_len = get_len = 0; + while ((get_len = ut_getline (&strbuf, &buf_len, infile)) != -1) + { + /* remove character '\n' */ + strbuf[strlen (strbuf) - 1] = '\0'; + + if (sscanf (strbuf, "%19s %9s", ip_t, port_t) == 2 + && uStringEqual (ip, ip_t) && uStringEqual (port, port_t)) + { + retval = 1; + sscanf (strbuf, "%*s %*s %*s %*s %14s", cli_ver); + break; + } + FREE_MEM (strbuf); + buf_len = 0; + } + fclose (infile); + + if (strbuf != NULL) + { + FREE_MEM (strbuf); + } + } + uRemoveLockFile (lfd); + + return retval; +} + +int +dbmt_con_add (const char *ip, const char *port, const char *cli_ver, + const char *user_name) +{ + FILE *outfile; + char strbuf[512]; + int lock_fd, retval; + + lock_fd = uCreateLockFile (conf_get_dbmt_file (FID_LOCK_CONN_LIST, strbuf)); + if (lock_fd < 0) + { + return -1; + } + + retval = -1; + outfile = fopen (conf_get_dbmt_file (FID_CONN_LIST, strbuf), "a"); + if (outfile != NULL) + { + time_to_str (time (NULL), "%04d/%02d/%02d %02d:%02d:%02d", strbuf, + TIME_STR_FMT_DATE_TIME); + fprintf (outfile, "%s %s %s %s %s\n", ip, port, strbuf, cli_ver, user_name); + fclose (outfile); + retval = 0; + } + uRemoveLockFile (lock_fd); + + return retval; +} + +int +dbmt_con_delete (const char *ip, const char *port) +{ + char ip_t[20]; + char port_t[10]; + char version[16]; + char c_date[16]; + char c_time[16]; + char *strbuf; + int buf_len, get_len; + FILE *infile, *outfile; + char tmpfile[512]; + char conn_list_file[512]; + int lock_fd, retval; + + lock_fd = + uCreateLockFile (conf_get_dbmt_file (FID_LOCK_CONN_LIST, tmpfile)); + if (lock_fd < 0) + { + return -1; + } + + conf_get_dbmt_file (FID_CONN_LIST, conn_list_file); + infile = fopen (conn_list_file, "r"); + sprintf (tmpfile, "%s/DBMT_util_014.%d", sco.dbmt_tmp_dir, (int) getpid ()); + outfile = fopen (tmpfile, "w"); + + if (infile == NULL || outfile == NULL) + { + if (infile != NULL) + { + fclose (infile); + } + if (outfile != NULL) + { + fclose (outfile); + } + retval = -1; + } + else + { + strbuf = NULL; + buf_len = get_len = 0; + while ((get_len = ut_getline (&strbuf, &buf_len, infile)) != -1) + { + ut_trim (strbuf); + sscanf (strbuf, "%19s %9s %15s %15s %15s", ip_t, port_t, c_date, + c_time, version); + + if (!uStringEqual (ip, ip_t) || !uStringEqual (port, port_t)) + { + fprintf (outfile, "%s\n", strbuf); + } + FREE_MEM (strbuf); + buf_len = 0; + } + fclose (outfile); + fclose (infile); + + if (strbuf != NULL) + { + FREE_MEM (strbuf); + } + + move_file (tmpfile, conn_list_file); + retval = 0; + } + uRemoveLockFile (lock_fd); + + return retval; +} + +int +dbmt_con_read_dbinfo (T_DBMT_CON_DBINFO *dbinfo, const char *ip, + const char *port, const char *dbname, char *_dbmt_error) +{ + FILE *infile; + int lfd, retval = -1; + char ip_t[20], port_t[10]; + char *prev, *next, *tok[2]; + char *strbuf = NULL; + char sbuf[512]; + int buf_len, get_len; + + lfd = uCreateLockFile (conf_get_dbmt_file (FID_LOCK_CONN_LIST, sbuf)); + if (lfd < 0) + { + strcpy (_dbmt_error, "Open conlist.lock fail"); + return retval; + } + + infile = fopen (conf_get_dbmt_file (FID_CONN_LIST, sbuf), "r"); + if (infile == NULL) + { + strcpy (_dbmt_error, "Open conlist fail"); + goto con_read_dbinfo_err; + } + + strbuf = NULL; + buf_len = get_len = 0; + while ((get_len = ut_getline (&strbuf, &buf_len, infile)) != -1) + { + /* remove character '\n' */ + strbuf[strlen (strbuf) - 1] = '\0'; + + if (sscanf (strbuf, "%19s %9s", ip_t, port_t) == 2 && + uStringEqual (ip, ip_t) && uStringEqual (port, port_t)) + { + /* locate dbinfo_list */ + int i = 0; + prev = strbuf; + while (*prev != '\0') + { + if (isspace (*prev)) + { + ++i; + } + ++prev; + if (i == 6) + { + break; + } + } + if (i == 5) + { + strcpy (_dbmt_error, "No db exists now"); + retval = 0; + goto con_read_dbinfo_err; + } + else if (i < 5) + { + strcpy (_dbmt_error, "Conlist format error"); + goto con_read_dbinfo_err; + } + + /* parse every dbinfo */ + while (prev != NULL) + { + next = strchr (prev, ';'); + if (next != NULL) + { + *next = '\0'; + next++; + } + + if (string_tokenize2 (prev, tok, 2, ':') < 0) + { + strcpy (_dbmt_error, "Conlist format error"); + goto con_read_dbinfo_err; + } + + if (uStringEqual (dbname, tok[0])) + { + strcpy_limit (dbinfo->dbname, tok[0], + sizeof (dbinfo->dbname)); + prev = tok[1]; + if (string_tokenize2 (prev, tok, 2, ',') < 0) + { + strcpy (_dbmt_error, "Conlist format error"); + goto con_read_dbinfo_err; + } + strcpy_limit (dbinfo->uid, tok[0], sizeof (dbinfo->uid)); + strcpy_limit (dbinfo->passwd, tok[1], + sizeof (dbinfo->passwd)); + + retval = 1; + break; + } + + /* parse the next dbinfo */ + prev = next; + } + break; + } + FREE_MEM (strbuf); + buf_len = 0; + } + + if (retval == -1 && strlen (_dbmt_error) == 0) + { + retval = 0; + strcpy (_dbmt_error, "Database not found"); + } + +con_read_dbinfo_err: + if (infile) + { + fclose (infile); + } + if (strbuf != NULL) + { + FREE_MEM (strbuf); + } + + uRemoveLockFile (lfd); + + return retval; +} + +int +dbmt_con_write_dbinfo (T_DBMT_CON_DBINFO *dbinfo, const char *ip, + const char *port, const char *dbname, int creat_flag, + char *_dbmt_error) +{ + FILE *infile, *outfile; + int lfd, retval = -1; + char tmpfile[512], conn_list_file[512]; + char date[15], time[10]; + char *prev, *next, *tok[2]; + char *strbuf = NULL; + char sbuf[512]; + int buf_len, get_len; + + T_DBMT_CON_INFO con_info; + memset (&con_info, 0, sizeof (T_DBMT_CON_INFO)); + + lfd = uCreateLockFile (conf_get_dbmt_file (FID_LOCK_CONN_LIST, sbuf)); + if (lfd < 0) + { + strcpy (_dbmt_error, "Open conlist.lock fail"); + return retval; + } + + conf_get_dbmt_file (FID_CONN_LIST, conn_list_file); + sprintf (tmpfile, "%s/DBMT_util_014.%d", sco.dbmt_tmp_dir, (int) getpid ()); + + infile = fopen (conf_get_dbmt_file (FID_CONN_LIST, sbuf), "r"); + outfile = fopen (tmpfile, "w"); + if (infile == NULL || outfile == NULL) + { + if (infile != NULL) + { + fclose (infile); + infile = NULL; + } + if (outfile != NULL) + { + fclose (outfile); + outfile = NULL; + } + + strcpy (_dbmt_error, "Open conlist fail"); + goto con_write_dbinfo_err; + } + + strbuf = NULL; + buf_len = get_len = 0; + while ((get_len = ut_getline (&strbuf, &buf_len, infile)) != -1) + { + /* remove character '\next' */ + strbuf[strlen (strbuf) - 1] = '\0'; + if (con_info.con_dbinfo != NULL) + { + FREE_MEM (con_info.con_dbinfo); + } + memset (&con_info, 0, sizeof (con_info)); + + if (sscanf + (strbuf, "%19s %9s %10s %8s %15s %64s", con_info.cli_ip, + con_info.cli_port, date, time, con_info.cli_ver, + con_info.user_name) == 6 + && uStringEqual (ip, con_info.cli_ip) + && uStringEqual (port, con_info.cli_port)) + { + /* locate dbinfo_list */ + int i = 0; + T_DBMT_CON_DBINFO tmp_dbinfo; + prev = strbuf; + while (*prev != '\0') + { + if (isspace (*prev)) + { + ++i; + } + ++prev; + if (i == 6) + { + break; + } + } + if (i < 6 && creat_flag == 0) + { + strcpy (_dbmt_error, "Conlist format error"); + goto con_write_dbinfo_err; + } + + /* parse every dbinfo */ + while (prev != NULL) + { + next = strchr (prev, ';'); + if (next != NULL) + { + *next = '\0'; + next++; + } + + memset (&tmp_dbinfo, 0, sizeof (T_DBMT_CON_DBINFO)); + + if (string_tokenize2 (prev, tok, 2, ':') < 0) + { + if (creat_flag == 0) + { + strcpy (_dbmt_error, "Conlist format error"); + goto con_write_dbinfo_err; + } + else + { + creat_flag = 0; + /* no db exists, add dbinfo */ + tmp_dbinfo = *dbinfo; + } + } + else + { + if (uStringEqual (dbname, tok[0])) + { + /* db exists, update dbinfo */ + creat_flag = 0; + tmp_dbinfo = *dbinfo; + } + else + { + /* just record dbinfo */ + strcpy_limit (tmp_dbinfo.dbname, tok[0], + sizeof (tmp_dbinfo.dbname) - 1); + prev = tok[1]; + if (string_tokenize2 (prev, tok, 2, ',') < 0) + { + strcpy (_dbmt_error, "Conlist format error"); + goto con_write_dbinfo_err; + } + strcpy_limit (tmp_dbinfo.uid, tok[0], + sizeof (tmp_dbinfo.uid)); + strcpy_limit (tmp_dbinfo.passwd, tok[1], + sizeof (tmp_dbinfo.passwd)); + } + } + + con_info.con_dbinfo = + (T_DBMT_CON_DBINFO *) increase_capacity (con_info.con_dbinfo, + sizeof (T_DBMT_CON_DBINFO), + con_info.num_con_dbinfo, + con_info.num_con_dbinfo + 1); + if (con_info.con_dbinfo == NULL) + { + strcpy (_dbmt_error, "Malloc fail"); + goto con_write_dbinfo_err; + } + con_info.num_con_dbinfo++; + con_info.con_dbinfo[con_info.num_con_dbinfo - 1] = tmp_dbinfo; + + /* parse the next dbinfo */ + prev = next; + } + /* db not found, create it */ + if (creat_flag == 1) + { + con_info.con_dbinfo = + (T_DBMT_CON_DBINFO *) increase_capacity (con_info.con_dbinfo, + sizeof (T_DBMT_CON_DBINFO), + con_info.num_con_dbinfo, + con_info.num_con_dbinfo + 1); + if (con_info.con_dbinfo == NULL) + { + strcpy (_dbmt_error, "Malloc fail"); + goto con_write_dbinfo_err; + } + con_info.num_con_dbinfo++; + con_info.con_dbinfo[con_info.num_con_dbinfo - 1] = *dbinfo; + } + + /* update conlist file content */ + fprintf (outfile, "%s %s %s %s %s %s ", con_info.cli_ip, + con_info.cli_port, date, time, con_info.cli_ver, + con_info.user_name); + for (i = 0; i < con_info.num_con_dbinfo; i++) + { + fprintf (outfile, "%s:%s,%s", con_info.con_dbinfo[i].dbname, + con_info.con_dbinfo[i].uid, con_info.con_dbinfo[i].passwd); + if (i != (con_info.num_con_dbinfo - 1)) + { + fprintf (outfile, ";"); + } + } + fprintf (outfile, "\n"); + + retval = 0; + } + else + { + fprintf (outfile, "%s\n", strbuf); + } + FREE_MEM (strbuf); + buf_len = 0; + } + +con_write_dbinfo_err: + if (infile) + { + fclose (infile); + } + if (outfile) + { + fclose (outfile); + } + if (strbuf != NULL) + { + FREE_MEM (strbuf); + } + if (con_info.con_dbinfo != NULL) + { + FREE_MEM (con_info.con_dbinfo); + } + move_file (tmpfile, conn_list_file); + + uRemoveLockFile (lfd); + + return retval; +} + +void +dbmt_con_set_dbinfo (T_DBMT_CON_DBINFO *dbinfo, const char *dbname, + const char *uid, const char *passwd) +{ + strcpy_limit (dbinfo->dbname, dbname, sizeof (dbinfo->dbname)); + strcpy_limit (dbinfo->uid, uid, sizeof (dbinfo->uid)); + strcpy_limit (dbinfo->passwd, passwd, sizeof (dbinfo->passwd)); +} diff --git a/server/src/am_connect_info.h b/server/src/am_connect_info.h new file mode 100644 index 0000000..f5a909a --- /dev/null +++ b/server/src/am_connect_info.h @@ -0,0 +1,62 @@ +/* + * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. + * + * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + + +/* + * cm_connect_info.h - + */ + +#ifndef _CM_CONNECT_INFO_H_ +#define _CM_CONNECT_INFO_H_ + +#define DBMT_USER_NAME_LEN 64 + +/* conlist */ +typedef struct +{ + char dbname[DBMT_USER_NAME_LEN]; + char uid[32]; + char passwd[80]; +} T_DBMT_CON_DBINFO; + +typedef struct +{ + char user_name[DBMT_USER_NAME_LEN]; + char cli_ip[20]; + char cli_port[10]; + char cli_ver[15]; + int num_con_dbinfo; + T_DBMT_CON_DBINFO *con_dbinfo; +} T_DBMT_CON_INFO; + +int dbmt_con_search (const char *ip, const char *port, char *cli_ver); +int dbmt_con_add (const char *ip, const char *port, const char *cli_ver, + const char *user_name); +int dbmt_con_delete (const char *ip, const char *port); + +int dbmt_con_read_dbinfo (T_DBMT_CON_DBINFO *dbinfo, const char *ip, + const char *port, const char *dbname, + char *_dbmt_error); +int dbmt_con_write_dbinfo (T_DBMT_CON_DBINFO *dbinfo, const char *ip, + const char *port, const char *dbname, + int creat_flag, char *_dbmt_error); +void dbmt_con_set_dbinfo (T_DBMT_CON_DBINFO *dbinfo, const char *dbname, + const char *uid, const char *passwd); + +#endif /* _CM_CONNECT_INFO_H_ */ diff --git a/server/src/am_http_server.cpp b/server/src/am_http_server.cpp new file mode 100644 index 0000000..71f795b --- /dev/null +++ b/server/src/am_http_server.cpp @@ -0,0 +1,664 @@ +/* + * Copyright (C) 2013 Search Solution Corporation. All rights reserved by Search Solution. + * + * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +/* +* cm_http_server.cpp - +*/ + +#include +#include +#include +#include +#include + +#include "cm_http_server.h" +#include "cm_log.h" + +using namespace std; + +static void http_error_404 (struct evhttp_request *req, int fd); +static void server_setup_certs (SSL_CTX *ctx, const char *certificate_chain,const char *private_key); +static void web_error_404 (struct evhttp_request *req); +static void locking_callback (int mode, int type, const char *file, int line); + +#if !defined(WINDOWS) && !defined(__BEOS__) +static void thread_id_callback (CRYPTO_THREADID *tid); +#endif + +static char uri_root[512] = "/"; +static char *userAgent = NULL; +static MUTEX_T *lock_array = NULL; + +/* + * This struct is used to get type of the files to browser. + * if git contains ico etc. web browser will loading them one by one. + */ +typedef const struct +{ + const char *extension; + const char *content_type; +} table_entry; + +table_entry content_type_table[] = +{ + { "txt", "text/plain" }, + { "c", "text/plain" }, + { "h", "text/plain" }, + { "properties", "text/plain" }, + { "html", "text/html" }, + { "htm", "text/htm" }, + { "css", "text/css" }, + { "gif", "image/gif" }, + { "jpg", "image/jpeg" }, + { "jpeg", "image/jpeg" }, + { "png", "image/png" }, + { "ico", "image/x-icon" }, + { "js", "application/x-javascript" }, + { NULL, NULL }, +}; + +/** + * @brief guess_content_type + * This is a magic function, Try to guess a good content-type for 'path' + * @param path + * Full path + * @return + * Return the type of file that in content_type_table[], + * Other return application/misc to browser. + */ +static const char *guess_content_type (const char *path) +{ + const char *last_period = NULL; + const char *extension = NULL; + table_entry *ent = NULL; + + last_period = strrchr (path, '.'); + + if (!last_period || strchr (last_period, '/')) + { + return "application/misc"; /* no exension */ + } + + extension = last_period + 1; + if (extension == NULL) + { + return "application/misc"; /* no exension */ + } + + for (ent = &content_type_table[0]; ent->extension; ++ent) + { + if (!evutil_ascii_strcasecmp (ent->extension, extension)) + { + return ent->content_type; + } + } + + return "application/misc"; +} + +#ifdef WINDOWS +/** + * @brief isDirectory + * To check the path is file or path in windows OS. + * @param path + * Full path + * @return + * If file:0, + * else: 1 + */ +int isDirectory (char *path) +{ + DWORD fileAttributes = GetFileAttributes (path); + + if (fileAttributes != INVALID_FILE_ATTRIBUTES) + { + return (fileAttributes & FILE_ATTRIBUTE_DIRECTORY); + } + else + { + return 0; + } +} +#endif + +/** + * @brief load_webfiles_cb + * This callback gets invoked when we get any http request that doesn't match + * any other callback. Like any evhttp server callback, it has a simple job: + * it must eventually call evhttp_send_error() or evhttp_send_reply(). + * It is a real http server,if want add SSL connection. must be called after: + * create_sslconn_cb and init_SSL + * @param req + * http reuqest + * See also: struct evhttp_request + * @param arg + * The path or the files that need to be called. + * @return + */ +void load_webfiles_cb (struct evhttp_request *req, void *arg) +{ + struct evbuffer *evb = NULL; + const char *docroot = (char *)arg; + const char *uri = NULL; + struct evhttp_uri *decoded = NULL; + const char *path = NULL; + const char *default_path = "/index.html"; + char *decoded_path = NULL; + char *whole_path = NULL; + size_t len; + int fd = -1; + struct stat st; + int disable_directrory_listing = 1; + const char *get_query = NULL; + const char *type = "application/misc"; + +#ifdef WINDOWS + WIN32_FIND_DATA FileData; + HANDLE handle; +#endif + + /* This is be debug print */ + struct evkeyvalq *headers = NULL; + struct evkeyval *header = NULL; + + if (sco.iSupportWebManager == FALSE) + { + web_error_404 (req); + LOG_WARN ("-- Web server: Not config support_web_manager"); + goto done; + } + + headers = evhttp_request_get_input_headers (req); + for (header = headers->tqh_first; header; + header = header->next.tqe_next) + { + if (string (header->key).compare ("User-Agent") == 0) + { + userAgent = header->value; + } + } + + /* Decode the URI */ + uri = evhttp_request_get_uri (req); + decoded = evhttp_uri_parse (uri); + if (!decoded) + { + evhttp_send_error (req, HTTP_BADREQUEST, 0); + LOG_WARN ("-- %s -- %s -- Web server: bad request for [%s]", req->remote_host, userAgent, uri); + return; + } + + get_query = evhttp_uri_get_query (decoded); + /* Basic path routing. */ + path = evhttp_uri_get_path (decoded); + + if (!path) + { + path = default_path; + } + if (strcmp (path, "/") == 0) + { + path = default_path; + } + /* We need to decode it, to see what path the user really wanted. */ + decoded_path = evhttp_uridecode (path, 0, NULL); + + if (decoded_path == NULL) + { + http_error_404 (req, fd); + LOG_WARN ("-- %s -- %s -- Web server: bad request for [%s]", req->remote_host, userAgent, uri); + goto done; + } + + /* Don't allow any ".."s in the path, to avoid exposing stuff outside + * of the docroot. This test is both overzealous and underzealous: + * it forbids aceptable paths like "/this/one..here", but it doesn't + * do anything to prevent symlink following." + */ + if (strstr (decoded_path, "..")) + { + http_error_404 (req, fd); + goto done; + } + + len = strlen (decoded_path) + strlen (docroot) + 2; + + if (! (whole_path = (char *)malloc (len))) + { + http_error_404 (req, fd); + LOG_WARN ("-- %s -- %s -- Web server: bad request for [%s]", req->remote_host, userAgent, uri); + goto done; + } + evutil_snprintf (whole_path, len, "%s%s", docroot, decoded_path); + if (stat (whole_path, &st) < 0 ) + { + http_error_404 (req, fd); + LOG_WARN ("-- %s -- %s -- Web server: bad request for [%s]", req->remote_host, userAgent, uri); + goto done; + } + + /* This holds the content we're sending. */ + evb = evbuffer_new (); +#ifdef WINDOWS + const char *name = "unknown"; + handle = FindFirstFile (whole_path, &FileData); + if (handle == INVALID_HANDLE_VALUE) + { + goto done; + } + + if (isDirectory (whole_path)) + { + const char *trailing_slash = ""; + if (!strlen (path) || path[strlen (path)-1] != '/') + { + trailing_slash = "/"; + } + + evbuffer_add_printf (evb, "\n \n" + " %s\n" + " \n" + " \n" + " \n" + "

%s

\n" + "
    \n", + decoded_path, /* XXX html-escape this. */ + uri_root, path, /* XXX html-escape this? */ + trailing_slash, + decoded_path /* XXX html-escape this */); + + while (FindNextFile (handle, &FileData)) + { + name = FileData.cFileName; + evbuffer_add_printf (evb, + "
  • %s\n", + name, name);/* XXX escape this */ + } + FindClose (handle); + evbuffer_add_printf (evb, "
\n"); + evhttp_add_header (evhttp_request_get_output_headers (req), + "Content-Type", "text/html"); + } +#else + // directory listing security + if (S_ISDIR (st.st_mode) && disable_directrory_listing) + { + http_error_404 (req, fd); + LOG_WARN ("-- %s -- %s -- Web server: bad request for [%s]", req->remote_host, userAgent, uri); + goto done; + } + + if (S_ISDIR (st.st_mode)) + { + /* If it's a directory, read the comments and make a little + * index page + */ + DIR *d; + struct dirent *ent; + const char *trailing_slash = ""; + if (!strlen (path) || path[strlen (path)-1] != '/') + { + trailing_slash = "/"; + } + + if (! (d = opendir (whole_path))) + { + http_error_404 (req, fd); + LOG_WARN ("-- %s -- %s -- Web server: bad request for [%s]", req->remote_host, userAgent, uri); + goto done; + } + + evbuffer_add_printf (evb, "\n \n" + " %s\n" + " \n" + " \n" + " \n" + "

%s

\n" + "
    \n", + decoded_path, /* XXX html-escape this. */ + uri_root, path, /* XXX html-escape this? */ + trailing_slash, + decoded_path /* XXX html-escape this */); + + while ((ent = readdir (d))) + { + const char *name = ent->d_name; + evbuffer_add_printf (evb, + "
  • %s\n", + name, name);/* XXX escape this */ + } + evbuffer_add_printf (evb, "
\n"); + closedir (d); + evhttp_add_header (evhttp_request_get_output_headers (req), + "Content-Type", "text/html"); + } +#endif + else + { + /* Otherwise it's a file; add it to the buffer to get + * sent via sendfile + */ + type = guess_content_type (decoded_path); + /* O_BINARY is used to open the files that + * contains unicode. otherwise,open files will be failed. + */ + if ((fd = open (whole_path, O_RDONLY|O_BINARY)) < 0) + { + http_error_404 (req, fd); + LOG_WARN ("-- %s -- %s -- Web server: bad request for [%s]", req->remote_host, userAgent, uri); + goto done; + } + + if (fstat (fd, &st) < 0) + { + /* Make sure the length still matches, now that we + * opened the file :/ + */ + http_error_404 (req, fd); + LOG_WARN ("-- %s -- %s -- Web server: bad request for [%s]", req->remote_host, userAgent, uri); + goto done; + } + evhttp_add_header (evhttp_request_get_output_headers (req), + "Content-Type", type); + evbuffer_add_file (evb, fd, 0, st.st_size); + } + + evhttp_send_reply (req, 200, "OK", evb); + +done: + if (decoded) + { + evhttp_uri_free (decoded); + } + if (decoded_path) + { + free (decoded_path); + } + if (whole_path) + { + free (whole_path); + } + if (evb) + { + evbuffer_free (evb); + } +} + +/** + * @brief create_sslconn_cb + * This callback is responsible for creating a new SSL connection + * and wrapping it in an OpenSSL bufferevent. This is the way + * we implement an https server instead of a plain old http server. + * @param base + * See also: struct event_base and bufferevent_openssl_socket_new + * @param arg + * It must be struct SSL_CTX, + * See also: SSL_CTX + * @return bufferevent + */ +struct bufferevent *create_sslconn_cb (struct event_base *base, void *arg) +{ + struct bufferevent *r = NULL; + SSL_CTX *ctx = (SSL_CTX *) arg; + + r = bufferevent_openssl_socket_new (base, + -1, + SSL_new (ctx), + BUFFEREVENT_SSL_ACCEPTING, + BEV_OPT_CLOSE_ON_FREE); + if (r == NULL) + { + LOG_ERROR ("-- Web server: Failed to create SSL connection."); + return NULL; + } + + bufferevent_openssl_set_allow_dirty_shutdown(r, 1); + return r; +} + +/** + * @brief server_setup_certs + * Used to init SSL certificate and private key. + * @param ctx + * Used to generate SSL_CTX + * @param certificate_chain + * certificate chain file. It can be full path,also can be the name of file. + * @param private_key + * private key file. It can be full path,also can be the name of file. + * @return + */ +static void server_setup_certs (SSL_CTX *ctx, + const char *certificate_chain, + const char *private_key) +{ + if (1 != SSL_CTX_use_certificate_chain_file (ctx, certificate_chain)) + { + LOG_ERROR ("-- Web server: OpenSSL error: Cannot initialize certificate file."); + exit (-1); + } + if (1 != SSL_CTX_use_PrivateKey_file (ctx, private_key, SSL_FILETYPE_PEM)) + { + LOG_ERROR ("-- Web server: OpenSSL error: Cannot initialize private key file."); + exit (-1); + } + if (1 != SSL_CTX_check_private_key (ctx)) + { + LOG_ERROR ("-- Web server: OpenSSL error: Invalid CTX private key."); + exit (-1); + } +} + +/** + * @brief thread_setup_SSL + * Setup the necessary resources to ensure that OpenSSL can safely + * be used in multi-threaded environment. + * @return + */ +void thread_setup_SSL (void) +{ + int total_locks, i; + + total_locks = CRYPTO_num_locks (); + + lock_array = (MUTEX_T *) OPENSSL_malloc (total_locks * sizeof (MUTEX_T)); + + for (i = 0; i < total_locks; i++) + { + MUTEX_INIT (lock_array[i]); + } + +#if !defined(WINDOWS) && !defined(__BEOS__) + /* It's unnecessary to define or set the thread-id callback functions for + * WINDOWS and BEOS platform, since they have been defined in OpenSSL kernel. + * Please refer to the source code implemented CRYPTO_THREADID_current() + * function in crypto/cryptlib.c from OpenSSL. + */ + CRYPTO_THREADID_set_callback (thread_id_callback); +#endif + + CRYPTO_set_locking_callback (locking_callback); +} + +#if !defined(WINDOWS) && !defined(__BEOS__) +/** + * @brief thread_id_callback + * Callback function to get thread id for OpenSSL thread safety. + * @param tid + * The thread id to be set. + * @return + */ +static void thread_id_callback (CRYPTO_THREADID *tid) +{ + CRYPTO_THREADID_set_numeric (tid, (unsigned long) pthread_self ()); +} +#endif + +/** + * @brief locking_callback + * Callback function to get lock for OpenSSL thread safety. + * @param mode + * The lock mode (lock or unlock) as required by OpenSSL. + * @param type + * The lock type as required and internally used by OpenSSL. + * @param file + * The source code file name as required and internally used by OpenSSL. + * @param line + * The source code line number as required and internally used by OpenSSL. + * @return + */ +static void locking_callback (int mode, int type, const char *file, int line) +{ + if (mode & CRYPTO_LOCK) + { + MUTEX_LOCK (lock_array[type]); + } + else + { + MUTEX_UNLOCK (lock_array[type]); + } +} + +/** + * @brief thread_cleanup_SSL + * Cleanup the allocated resources which is used for OpenSSL thread safety. + * @return + */ +void thread_cleanup_SSL (void) +{ + int total_locks, i; + + CRYPTO_set_locking_callback (NULL); + + if (lock_array != NULL) + { + total_locks = CRYPTO_num_locks (); + + for (i = 0; i < total_locks; i++) + { + MUTEX_DESTROY (lock_array[i]); + } + + OPENSSL_free (lock_array); + lock_array = NULL; + } +} + +/** + * @brief init_SSL + * init the ssl methods,loading key and crt files, + * return ctx that used to create ssl connections. + * See also: create_sslconn_cb + * @param certificate_chain + * certificate chain file. It can be full path,also can be the name of file. + * @param private_key + * private key file. It can be full path,also can be the name of file. + * @return SSL_CTX + */ +SSL_CTX *init_SSL (const char *certificate_chain,const char *private_key) +{ + + SSL_CTX *ctx = NULL; + /* init SSL libray is must. */ + SSL_library_init (); + /* We just use SSLv3,do not support SSLv2. */ + + ctx = SSL_CTX_new (TLSv1_server_method ()); + if (!ctx) + { + LOG_ERROR ("-- Web server: Fail to generate CTX for openSSL."); + } + SSL_CTX_set_options (ctx, + SSL_OP_SINGLE_DH_USE | + SSL_OP_SINGLE_ECDH_USE | + SSL_OP_NO_SSLv3 | + SSL_OP_NO_SSLv2); + + /* Find and set up our server certificate. */ + server_setup_certs (ctx, certificate_chain, private_key); + return ctx; +} + +/** + * @brief http_error_404 + * Used to report 404 error to browser using libevent.and close fd + * @param req + * http request + * See also: struct evhttp_request + * @param fd + * if fd >= 0, close it. + * @return + * See also: evhttp_send_error + */ + +static void http_error_404 (struct evhttp_request *req, int fd) +{ + const char *uri = evhttp_request_get_uri (req); +#define ERROR_FORMAT "" \ + "404 Not Found" \ + "" \ + "

404 Not Found

" \ + "

Request: %s not found

"\ + "
"\ + "
Arniadb Manager Server
"\ + "\n" + + struct evbuffer *buf = evbuffer_new (); + if (buf == NULL) + { + /* if we cannot allocate memory; we just drop the connection */ + LOG_WARN ("-- Web server: http_error_404 cannot create a buffer."); + return; + } + evbuffer_add_printf (buf, ERROR_FORMAT, uri); + evhttp_send_reply (req, 404, "404 Not Found", buf); + evbuffer_free (buf); +#undef ERROR_FORMAT + if (fd >= 0) + { + close (fd); + } +} + +/** + * @brief web_error_404 + * Used to report 404 error to browser when use did not start web server: in cm.conf + * @param + * @return + * See also: evhttp_send_error + */ + +static void web_error_404 (struct evhttp_request *req) +{ + +#define ERROR_FORMAT "" \ + "404 Not Found" \ + "" \ + "

404 Not Found

" \ + "

Web Manager was not started, please configure it rightly

"\ + "
"\ + "
Arniadb Manager Server
"\ + "\n" + + struct evbuffer *buf = evbuffer_new (); + + evbuffer_add_printf (buf, ERROR_FORMAT); + evhttp_send_reply (req, 404, "Not Found", buf); + evbuffer_free (buf); +#undef ERROR_FORMAT +} diff --git a/server/src/am_http_server.h b/server/src/am_http_server.h new file mode 100644 index 0000000..72a800f --- /dev/null +++ b/server/src/am_http_server.h @@ -0,0 +1,112 @@ +/* + * Copyright (C) 2013 Search Solution Corporation. All rights reserved by Search Solution. + * + * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +/* +* cm_http_server.h +*/ + +#include + +#ifdef WINDOWS +#ifndef S_ISDIR +# define S_ISDIR(m) (((m) & (_S_IFMT)) == (_S_IFDIR)) +#endif +#include +#include +#include +#include +#include +#else +#include +#include +#include +#include +#endif + +#include +#include + +#ifdef _EVENT_HAVE_NETINET_IN_H +#include +# ifdef _XOPEN_SOURCE_EXTENDED +# include +# endif +#endif +#ifndef O_BINARY +#define O_BINARY 0x8000 //used for open files that contains some unicodes +#endif + + +/** + * @brief load_webfiles_cb + * This callback gets invoked when we get any http request that doesn't match + * any other callback. Like any evhttp server callback, it has a simple job: + * it must eventually call evhttp_send_error() or evhttp_send_reply(). + * It is a real http server,if want add SSL connection. must be called after: + * create_sslconn_cb and init_SSL + * @param req + * http reuqest + * See also: struct evhttp_request + * @param arg + * The path or the files that need to be called. + * @return + */ +void load_webfiles_cb (struct evhttp_request *req, void *arg); + +/** + * @brief create_sslconn_cb + * This callback is responsible for creating a new SSL connection + * and wrapping it in an OpenSSL bufferevent. This is the way + * we implement an https server instead of a plain old http server. + * @param base + * See also: struct event_base and bufferevent_openssl_socket_new + * @param arg + * It must be struct SSL_CTX, + * See also: SSL_CTX + * @return bufferevent + */ +struct bufferevent *create_sslconn_cb (struct event_base *base, void *arg); + +/** + * @brief init_SSL + * init the ssl methods,loading key and crt files, + * return ctx that used to create ssl connections. + * See also: create_sslconn_cb + * @param certificate_chain + * certificate chain file. It can be full path,also can be the name of file. + * @param private_key + * private key file. It can be full path,also can be the name of file. + * @return SSL_CTX + */ +SSL_CTX *init_SSL (const char *certificate_chain,const char *private_key); + +/** + * @brief thread_setup_SSL + * Setup the necessary resources to ensure that OpenSSL can safely + * be used in multi-threaded environment. + * @return + */ +void thread_setup_SSL (void); + +/** + * @brief thread_cleanup_SSL + * Cleanup the allocated resources which is used for OpenSSL thread safety. + * @return + */ +void thread_cleanup_SSL (void); diff --git a/server/src/am_httpd.cpp b/server/src/am_httpd.cpp new file mode 100644 index 0000000..63acd6d --- /dev/null +++ b/server/src/am_httpd.cpp @@ -0,0 +1,921 @@ +/* + * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. + * + * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +/* +* cm_httpd.cpp +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef WINDOWS +#include +#include "cm_win_wsa.h" +#include +#include +#include +#else +#include +#include +#include +#include +#include +#include +#endif + +#include "cm_log.h" +#include "cm_server_util.h" +#include "cm_config.h" +#include "cm_autojob.h" +#include "cm_auto_task.h" +#include "cm_cci_interface.h" +#include "cm_server_interface.h" +#include "cm_server_stat.h" +#include "cm_server_extend_interface.h" +#include "cm_mon_stat.h" +#include "cm_http_server.h" + +//#include "cm_utf8.h" +using namespace std; + +#define DEFAULT_THRD_NUM 24 +#define DEFAULT_HTTP_TIMEOUT 6 * 60 //second +#define NUM_OF_FILES_IN_URL 3 +#define STAT_MONITOR_INTERVAL 1 // seconds + +static THREAD_FUNC automation_start (void *ud); +static THREAD_FUNC aj_thread_r (void *aj); +static void start_auto_thread (void); + +T_EMGR_VERSION CLIENT_VERSION = EMGR_MAKE_VER (8, 4); + +#ifdef WINDOWS +T_THREAD auto_task_tid = NULL; +#else +T_THREAD auto_task_tid = 0; +#endif + +typedef struct aj_thread_info_t +{ + T_THREAD thread_id; + time_t cur_time; + time_t prev_check_time; + ajob *ajob_list; + time_t stime; + int is_running; +} aj_thread_info; + +aj_thread_info aj_tinfo; + +MUTEX_T aj_thread_mutex; + +struct worker_context +{ + struct event_base *base; + struct evhttp *httpd; + struct event *timer; + bool first; +#ifdef WINDOWS + HANDLE ths; +#else + pthread_t ths; +#endif +}; + +int arniadb_version_major = -1; +int arniadb_version_minor = -1; + +int +bind_socket (int port) +{ + int r; + int nfd; + struct sockaddr_in addr; + int one = 1; + int flags = 1; + nfd = (int) socket (AF_INET, SOCK_STREAM, 0); + if (nfd < 0) + { + return -1; + } + + setsockopt (nfd, SOL_SOCKET, SO_REUSEADDR, (char *) &one, sizeof (int)); + + memset (&addr, 0, sizeof (addr)); + addr.sin_family = AF_INET; + addr.sin_port = htons (port); + r = bind (nfd, (struct sockaddr *) &addr, sizeof (addr)); + if (r < 0) + { + close (nfd); + return -1; + } + r = listen (nfd, 10240); + if (r < 0) + { + close (nfd); + return -1; + } +#ifdef WINDOWS + ioctlsocket (nfd, FIONBIO, (unsigned long *) &flags); +#else + if ((flags = fcntl (nfd, F_GETFL, 0)) != -1) + { + fcntl (nfd, F_SETFL, flags | O_NONBLOCK); + } +#endif + + return nfd; +} + +#ifdef WINDOWS +DWORD WINAPI +dispatch_thread (void *arg) +#else +void * +dispatch_thread (void *arg) +#endif +{ + struct worker_context *work_ctx = (struct worker_context *) arg; + event_base_dispatch ((struct event_base *) work_ctx->base); + + if (work_ctx->timer) + { + event_free (work_ctx->timer); + } + if (work_ctx->httpd) + { + evhttp_free (work_ctx->httpd); + } + if (work_ctx->base) + { + event_base_free (work_ctx->base); + } +#ifdef WINDOWS + return 0; +#else + return NULL; +#endif +} + +void +arn_add_private_param (struct evhttp_request *req, Json::Value &root) +{ + root["_CLIENTIP"] = req->remote_host; + root["_CLIENTPORT"] = req->remote_port; + root["_STAMP"] = 1; + root["_PROGNAME"] = AMS_NAME; +} + +void +arn_generic_request_handler (struct evhttp_request *req, void *arg) +{ + struct evbuffer *input; + struct evkeyvalq *headers; + char *body; + // char *inustr, *outustr; + string task_name; + int len; + struct evbuffer *evb; + Json::Value root, response; + Json::Reader reader; + Json::StyledWriter writer; + char *data = NULL; + + input = evhttp_request_get_input_buffer (req); + if (input == NULL) + { + evhttp_send_reply (req, HTTP_BADREQUEST, "", NULL); + return; + } + + len = (int) evbuffer_get_length (input); + if (len <= 0) + { + evhttp_send_reply (req, HTTP_BADREQUEST, "", NULL); + return; + } + + data = (char *) evbuffer_pullup(input, len); + if (data == NULL) + { + evhttp_send_reply (req, HTTP_BADREQUEST, "", NULL); + return; + } + + + body = (char *) malloc (len + 1); + if (body == NULL) + { + evhttp_send_reply (req, HTTP_BADREQUEST, "", NULL); + return; + } + + memset (body, 0x00, len+1); + memcpy (body, data, len); + + if (evbuffer_drain (input, len) < 0) + { + free (body); + evhttp_send_reply (req, HTTP_BADREQUEST, "", NULL); + return; + } + + if (!reader.parse (body, root)) + { + free (body); + //utf8_clean(inustr); + evhttp_send_reply (req, HTTP_BADREQUEST, "Error JSON format", NULL); + return; + } + + arn_add_private_param (req, root); + + if (!strcmp ((char *) arg, "cci")) + { + arn_cci_request_handler (root, response); + } + else if (!strcmp ((char *) arg, "cm_api")) + { + arn_cm_request_handler (root, response); + } + + //outustr = utf8_encode(writer.write(response).c_str()); + //printf("---------------------\n%s\n", outustr); + evb = evbuffer_new (); + if (NULL == evb) + { + free (body); + //utf8_clean(inustr); + //utf8_clean(outustr); + return evhttp_send_reply (req, HTTP_BADREQUEST, "", NULL); + } + + headers = evhttp_request_get_output_headers (req); + if (headers) + { + evhttp_add_header (headers, "Content-Type", "text/plain;charset=utf-8"); + } + + evbuffer_add_printf (evb, "%s", writer.write (response).c_str ()); + evhttp_send_reply (req, HTTP_OK, "OK", evb); + evbuffer_free (evb); + free (body); + //utf8_clean(inustr); + //utf8_clean(outustr); + + return; +} + +static int arn_loop_flag = 1; + +void +arn_ctrl_request_handler (struct evhttp_request *req, void *arg) +{ + evhttp_send_reply (req, HTTP_OK, "", NULL); + arn_loop_flag = 0; + return; +} + +void +arn_post_request_handler (struct evhttp_request *req, void *arg) +{ + string post_msg = "{ \"success\" : true }"; + string req_uri (req->uri); + char token[TOKEN_ENC_LENGTH]; + size_t token_pos; + int code; + string reason; + size_t fname_pos = 0; + size_t tmp_pos = 0; + struct evbuffer *evb = evbuffer_new(); + + code = HTTP_OK; + reason = "OK"; + token[0] = '\0'; + token_pos = 0; + + string cookie (evhttp_find_header (req->input_headers, "COOKIE")); + token_pos = cookie.find ("token="); + if (token_pos == string::npos) + { + goto send_nok_reply; + } + + cookie.copy (token, TOKEN_ENC_LENGTH - 1, token_pos + strlen ("token=")); + token[TOKEN_ENC_LENGTH - 1] = '\0'; + if (ext_ut_validate_token (token)) + { + goto send_reply; + } + + for (int index = 0; index < NUM_OF_FILES_IN_URL; ++index) + { + char fname[PATH_MAX]; + string fname_path = string (sco.dbmt_tmp_dir) + "/"; + fname[0] = '\0'; + fname_pos = req_uri.find ("fname=", tmp_pos); + if (fname_pos == string::npos && index == 0) + { + goto send_nok_reply; + } + else if (fname_pos == string::npos) + { + goto send_reply; + } + + fname_pos += strlen ("fname="); + tmp_pos = req_uri.find ("&", fname_pos); + if (tmp_pos == string::npos) + { + tmp_pos = req_uri.length(); + } + req_uri.copy (fname, tmp_pos - fname_pos + 1, fname_pos); + fname[tmp_pos - fname_pos] = '\0'; + if (strcmp (fname, "") != 0 || strcmp (fname, "&") != 0) + { + if (strstr (fname, "..") || strstr (fname, "\\") || strstr (fname, "/")) + { + continue; + } + fname_path += fname; + unlink (fname_path.c_str()); + } + } + +send_nok_reply: + post_msg = "{ \"failure\" : true }"; + code = HTTP_NOTFOUND; + reason = "NOK"; + +send_reply: + if (evb) + { + evbuffer_add_printf (evb, "%s", post_msg.c_str()); + } + evhttp_send_reply (req, code, reason.c_str(), evb); + if (evb) + { + evbuffer_free (evb); + } + return; +} + +void +arn_timeout_cb (evutil_socket_t fd, short event, void *arg) +{ + struct worker_context *work_ctx = (struct worker_context *) arg; + if (!arn_loop_flag) + { + event_base_loopexit (work_ctx->base, NULL); + } +} + + +/** + * @brief callback function to gather monitoring data + */ +void +start_monitor_stat_cb (evutil_socket_t fd, short event, void *arg) +{ + struct timeval stat_tv = { STAT_MONITOR_INTERVAL, 0 }; + + struct worker_context *work_ctx = (struct worker_context *) arg; + if (!arn_loop_flag) + { + event_base_loopexit (work_ctx->base, NULL); + return; + } + + // [CUBRIDSUS-11917]sleep the thread for a while when the ARNIADB is starting + if (work_ctx->first) + { + SLEEP_SEC (MIN_INTERVAL - 1); + work_ctx->first = false; + } + + if (sco.iSupportMonStat == TRUE) + { + (cm_mon_stat::get_instance())->gather_mon_data(); + } + + evtimer_add (work_ctx->timer, &stat_tv); +} + +void +start_monitor_auto_jobs_cb (evutil_socket_t fd, short event, void *arg) +{ + struct timeval auto_task_tv = { sco.iMonitorInterval, 0 }; + struct worker_context *work_ctx = (struct worker_context *) arg; + if (!arn_loop_flag) + { + event_base_loopexit (work_ctx->base, NULL); + return; + } +#ifdef WINDOWS + unsigned long thread_status; + GetExitCodeThread ((HANDLE) auto_task_tid, &thread_status); + + if (thread_status != STILL_ACTIVE) + { + auto_task_tid = NULL; + LOG_WARN ("Restart auto jobs thread when exit abnormally."); + start_auto_thread (); + } +#else + int pthread_kill_err = ESRCH; + /* ESRCH - Thread is not exist. + EINVAL - Signal is invalid. + */ + pthread_kill_err = pthread_kill (auto_task_tid, 0); + if (pthread_kill_err == ESRCH) + { + auto_task_tid = 0; + LOG_WARN ("Restart auto jobs thread when exit abnormally."); + start_auto_thread (); + } +#endif + + evtimer_add (work_ctx->timer, &auto_task_tv); +} + +int +start_service () +{ + struct worker_context *start_ctx[DEFAULT_THRD_NUM]; + char tmpstrbuf[DBMT_ERROR_MSG_SIZE]; + struct timeval tv = { sco.iMonitorInterval, 0 }; + int nfd, err, i = 0; + + tmpstrbuf[0] = '\0'; +#ifdef WINDOWS + wsa_initialize (); +#endif + + thread_setup_SSL (); + + SSL_CTX *ctx = init_SSL (sco.szSSLCertificate, sco.szSSLKey); + + nfd = bind_socket (sco.iAMS_port); + + if (nfd < 0) + { + snprintf (tmpstrbuf, DBMT_ERROR_MSG_SIZE, + "ARNIADB Manager Server : The port %d is still used by other process.\n", + sco.iAMS_port); + ut_record_arniadb_utility_log_stderr (tmpstrbuf); + return -1; + } + + for (i = 0; i < DEFAULT_THRD_NUM; i++) + { + start_ctx[i] = (struct worker_context *) malloc (sizeof (struct worker_context)); + if (start_ctx[i] == NULL) + { + continue; + } + + start_ctx[i]->base = event_base_new (); + if (start_ctx[i]->base == NULL) + { + continue; + } + + start_ctx[i]->first = true; +#ifndef WINDOWS + start_ctx[i]->ths = 0; +#endif + + if (i > 1) /* DEFAULT_THRD_NUM - 1 for request handler */ + { + start_ctx[i]->timer = event_new (start_ctx[i]->base, -1, EV_PERSIST, arn_timeout_cb, (void *) start_ctx[i]); + if (start_ctx[i]->timer == NULL) + { + continue; + } + + start_ctx[i]->httpd = evhttp_new (start_ctx[i]->base); + if (start_ctx[i]->httpd == NULL) + { + continue; + } + + err = evhttp_accept_socket (start_ctx[i]->httpd, nfd); + if (err != 0) + { + continue; + } + + evhttp_set_timeout (start_ctx[i]->httpd, DEFAULT_HTTP_TIMEOUT); + /* This is the magic that lets evhttp use SSL. */ + evhttp_set_bevcb (start_ctx[i]->httpd, create_sslconn_cb, ctx); + evhttp_set_cb (start_ctx[i]->httpd, "/cci", + arn_generic_request_handler, (void *) "cci"); + evhttp_set_cb (start_ctx[i]->httpd, "/cm_api", arn_generic_request_handler, (void *) "cm_api"); + evhttp_set_cb (start_ctx[i]->httpd, "/ctrl", arn_ctrl_request_handler, NULL); + evhttp_set_cb (start_ctx[i]->httpd, "/upload", arn_post_request_handler, NULL); + /* Start web server*/ + evhttp_set_gencb (start_ctx[i]->httpd, load_webfiles_cb, (void *) sco.szCWMPath); + } + else if (i == 1) + { + /* index 1 for starting monitor of auto jobs */ + start_ctx[i]->timer = event_new (start_ctx[i]->base, -1, EV_TIMEOUT, start_monitor_auto_jobs_cb, + (void *) start_ctx[i]); + if (start_ctx[i]->timer == NULL) + { + ut_record_arniadb_utility_log_stderr ("ARNIADB Manager Server : Failed to start monitor of auto job.\n"); + return -1; + } + start_ctx[i]->httpd = NULL; + } + else + { + /* index 0 for monitoring status job */ + start_ctx[i]->timer = event_new (start_ctx[i]->base, -1, EV_TIMEOUT, start_monitor_stat_cb, + (void *) start_ctx[i]); + if (start_ctx[i]->timer == NULL) + { + ut_record_arniadb_utility_log_stderr ( + "ARNIADB Manager Server : Failed to start monitoring state job.\n"); + return -1; /* Start monitor status job failed */ + } + start_ctx[i]->httpd = NULL; + } + if (i == 0) + { + struct timeval stat_tv = { 1, 0 }; + evtimer_add (start_ctx[i]->timer, &stat_tv); + } + else if (i == 1) + { + struct timeval auto_task_tv = { sco.iMonitorInterval, 0 }; + evtimer_add (start_ctx[i]->timer, &auto_task_tv); + } + else + { + evtimer_add (start_ctx[i]->timer, &tv); + } +#ifdef WINDOWS + start_ctx[i]->ths = + CreateThread (NULL, 0, dispatch_thread, start_ctx[i], 0, NULL); +#else + pthread_create (& (start_ctx[i]->ths), NULL, dispatch_thread, + (void *) start_ctx[i]); +#endif + } + + for (i = 0; i < DEFAULT_THRD_NUM; i++) + { +#ifdef WINDOWS + if (start_ctx[i]->ths != INVALID_HANDLE_VALUE) + { + WaitForSingleObject (start_ctx[i]->ths, INFINITE); + } +#else + if (start_ctx[i]->ths != 0) + { + pthread_join (start_ctx[i]->ths, NULL); + } +#endif + if (start_ctx[i] != NULL) + { + free (start_ctx[i]); + } + } + + thread_cleanup_SSL (); + +#ifdef WINDOWS + WSACleanup (); +#endif + + return 0; +} + +void +stop_service () +{ + FILE *pidfile = NULL; + int pidnum = -1; + char arn_manager_pid_file[PATH_MAX]; + char connect_list_file[PATH_MAX]; + + arn_manager_pid_file[0] = '\0'; + connect_list_file[0] = '\0'; + + conf_get_dbmt_file (FID_AMSERVER_PID, arn_manager_pid_file); + if (access (arn_manager_pid_file, F_OK) < 0) + { + ut_record_arniadb_utility_log_stderr ("ARNIADB Manager Server : The server is not running.\n"); + } + else + { + pidfile = fopen (arn_manager_pid_file, "rt"); + if (pidfile != NULL) + { + fscanf (pidfile, "%d", &pidnum); + fclose (pidfile); + } + + if ((pidfile == NULL) || ((kill (pidnum, SIGTERM)) < 0)) + { + ut_record_arniadb_utility_log_stderr ("ARNIADB Manager Server : Failed to stop the server.\n"); + } + else + { + unlink (conf_get_dbmt_file (FID_AMSERVER_PID, arn_manager_pid_file)); + unlink (conf_get_dbmt_file (FID_CONN_LIST, connect_list_file)); + } + } + + return; +} + +static int +get_processid () +{ + FILE *pidfile = NULL; + int pidnum = -1; + char pid_file_name[512]; + + conf_get_dbmt_file (FID_AMSERVER_PID, pid_file_name); + + if (access (pid_file_name, F_OK) < 0) + { + return 0; + } + + pidfile = fopen (pid_file_name, "rt"); + if (pidfile != NULL) + { + fscanf (pidfile, "%d", &pidnum); + fclose (pidfile); + } + if (pidfile == NULL || ((kill (pidnum, 0) < 0) && (errno == ESRCH)) + || (is_amserver_process (pidnum, UTIL_CM_SERVER) == 0)) + { + unlink (pid_file_name); + return 0; + } + + return pidnum; +} + +static void +print_usage (char *pname) +{ + printf ("Usage: %s [command]\n", pname); + printf ("commands are :\n"); + printf (" start - start the server.\n"); + printf (" stop - stop the server.\n"); +} + +static void +init_files () +{ + char strbuf[PATH_MAX]; + strbuf[0] = '\0'; + + /* remove any temporary files from previous run */ + unlink (conf_get_dbmt_file (FID_CONN_LIST, strbuf)); + unlink (conf_get_dbmt_file (FID_PSVR_DBINFO_TEMP, strbuf)); + unlink (conf_get_dbmt_file (FID_AMSERVER_PID, strbuf)); +} + +static THREAD_FUNC +automation_start (void *ud) +{ + ajob ajob_list[AUTOJOB_SIZE]; + int i; + time_t prev_check_time, cur_time; + char strbuf[512]; + + strbuf[0] = '\0'; + + aj_tinfo.is_running = 0; + MUTEX_INIT (aj_thread_mutex); + + /* set up automation list */ + aj_initialize (ajob_list, ud); + for (i = 0; i < AUTOJOB_SIZE; ++i) + { + if (ajob_list[i].ajob_loader) + { + ajob_list[i].ajob_loader (& (ajob_list[i])); + } + } + + prev_check_time = time (NULL); + for (;;) + { + SLEEP_SEC (sco.iMonitorInterval); + cur_time = time (NULL); + + MUTEX_LOCK (aj_thread_mutex); + if (0 != aj_tinfo.is_running) + { + if (cur_time - aj_tinfo.stime > sco.iAutoJobTimeout) + { + THREAD_CANCEL (aj_tinfo.thread_id); + snprintf (strbuf, sizeof (strbuf), "%s - - -", ACCESS_LOG); + write_manager_access_log (strbuf, + "Auto jobs execute too long, Cancel the thread"); + aj_tinfo.is_running = 0; + } + } + if (0 == aj_tinfo.is_running) + { + T_THREAD tid; + aj_thread_info *ptr_aj_tinfo; + aj_tinfo.ajob_list = ajob_list; + aj_tinfo.cur_time = cur_time; + aj_tinfo.prev_check_time = prev_check_time; + ptr_aj_tinfo = &aj_tinfo; + THREAD_BEGIN (tid, aj_thread_r, ptr_aj_tinfo); + aj_tinfo.is_running = 1; + aj_tinfo.thread_id = tid; + aj_tinfo.stime = cur_time; + prev_check_time = cur_time; + } + MUTEX_UNLOCK (aj_thread_mutex); + } + +#if defined(WINDOWS) + return; +#else + return NULL; +#endif +} + +static THREAD_FUNC +aj_thread_r (void *aj) +{ + struct stat statbuf; + aj_thread_info *aj_tinfo_local = (aj_thread_info *) aj; + ajob *ajob_list = aj_tinfo_local->ajob_list; + time_t cur_time = aj_tinfo_local->cur_time; + time_t prev_check_time = aj_tinfo_local->prev_check_time; + int i; + + for (i = 0; i < AUTOJOB_SIZE; ++i) + { + /* check automation configure file and see if it has changed since last access */ + stat (ajob_list[i].config_file, &statbuf); + if (ajob_list[i].last_modi != statbuf.st_mtime) + { + ajob_list[i].last_modi = statbuf.st_mtime; + if (ajob_list[i].ajob_loader) + { + ajob_list[i].ajob_loader (& (ajob_list[i])); + } + } + + /* if unchanged, go ahead and check value */ + if (ajob_list[i].is_on && ajob_list[i].ajob_handler) + { + ajob_list[i].ajob_handler (ajob_list[i].hd, prev_check_time, cur_time); + } + } + + MUTEX_LOCK (aj_thread_mutex); + if (aj_tinfo_local->stime == cur_time) + { + aj_tinfo_local->is_running = 0; + } + MUTEX_UNLOCK (aj_thread_mutex); + +#if defined(WINDOWS) + return; +#else + return NULL; +#endif +} + +static void +start_auto_thread (void) +{ + int i = 0; + userdata *ud = NULL; + + if ((ud = (userdata *) calloc (1, sizeof (userdata))) == NULL) + { + exit (1); + } + /* initialize memory for active databases information */ + for (i = 0; i < MAX_INSTALLED_DB; ++i) + { + ud->dbvect[i] = 0; + } + + THREAD_BEGIN (auto_task_tid, automation_start, ud); +} + +int +main (int argc, char **argv) +{ + char dbmt_file[PATH_MAX]; + char tmpstrbuf[DBMT_ERROR_MSG_SIZE]; + int pidnum = 0; + + tmpstrbuf[0] = '\0'; + + arn_cm_init_env (); + if (argc >= 2) + { + if (strcmp (argv[1], "stop") == 0) + { + stop_service (); + exit (0); + } + else if (strcmp (argv[1], "--version") == 0) + { + fprintf (stdout, "ARNIADB Manager Server ver : %s\n", + makestring (BUILD_NUMBER)); + exit (0); + } + else if (strcmp (argv[1], "getpid") == 0) + { + pidnum = get_processid (); + if (pidnum > 0) + { + fprintf (stdout, "%d\n", pidnum); + } + exit (0); + } + else if (strcmp (argv[1], PRINT_CMD_START) != 0) + { + snprintf (tmpstrbuf, DBMT_ERROR_MSG_SIZE, "ARNIADB Manager Server : Invalid command - %s\n", argv[1]); + ut_record_arniadb_utility_log_stderr (tmpstrbuf); + print_usage (argv[0]); + exit (1); + } + } + + if ((pidnum = get_processid ()) > 0) + { + snprintf (tmpstrbuf, DBMT_ERROR_MSG_SIZE, + "ARNIADB Manager Server : The [pid=%d] process has been running.\n", pidnum); + ut_record_arniadb_utility_log_stderr (tmpstrbuf); + return 0; + } + + ut_daemon_start (); + + init_files (); + +#ifndef WINDOWS + signal (SIGPIPE, SIG_IGN); +#endif + + if (ut_write_pid (conf_get_dbmt_file (FID_AMSERVER_PID, dbmt_file)) < 0) + { + snprintf (tmpstrbuf, DBMT_ERROR_MSG_SIZE, + "ARNIADB Manager Server : Fail to store the pid file in (%s).\n", dbmt_file); + ut_record_arniadb_utility_log_stderr (tmpstrbuf); + exit (1); + } + + start_auto_thread (); + + find_and_parse_arn_admin_version (arniadb_version_major, arniadb_version_minor); + LOG_INFO ("started '%s' with Engine Version: %d.%d", argv[0], arniadb_version_major, arniadb_version_minor); + + start_service (); + + return 0; +} diff --git a/server/src/am_job_task.cpp b/server/src/am_job_task.cpp new file mode 100644 index 0000000..1f8985a --- /dev/null +++ b/server/src/am_job_task.cpp @@ -0,0 +1,16143 @@ +/* + * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. + * + * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + + +/* + * cm_job_task.cpp - + */ + +#include +#include +#include +#include +#include +#include /* isalpha(), isspace() */ +#include +#include + +#if defined(WINDOWS) +#include +#include +#include +#include +#include +#else +#include /* umask() */ +#include /* umask(), stat() */ +#include +#include /* strfind() */ +#include +#include +#include /* wait() */ +#include /* opendir() ... */ +#include /* getpwuid_r() */ +#include +#include +#include +#include +#if !defined(HPUX) +#include +#endif +#endif + +#include "cm_log.h" +#include "cm_stat.h" +#include "cm_porting.h" +#include "cm_server_util.h" +#include "cm_job_task.h" +#include "cm_auto_task.h" +#include "cm_dep.h" +#include "cm_config.h" +#include "cm_cmd_exec.h" +#include "cm_user.h" +#include "cm_text_encryption.h" +#include "cm_connect_info.h" +#include "cm_server_autoupdate.h" + +#include "openssl/pem.h" +#include "openssl/conf.h" +#include "openssl/x509v3.h" +#include "openssl/md5.h" +#ifndef OPENSSL_NO_ENGINE +#include "openssl/engine.h" +#endif + +#include +#include + +#include + +using namespace std; + +#define PATTERN_LOG 1 +#define PATTERN_VOL 2 + +#define MAX_MSG_LINE 10000 + +#define DBMT_ERR_MSG_SET(ERR_BUF, MSG) \ + strncpy(ERR_BUF, MSG, DBMT_ERROR_MSG_SIZE - 1) +#define ARNIADB_ERR_MSG_SET(ERR_BUF) \ + DBMT_ERR_MSG_SET(ERR_BUF, db_error_string(1)) + +#define MAX_BROKER_NAMELENGTH 128 +#define MAX_AS_COUNT 200 +#define SET_LONGLONG_STR(STR, LL_VALUE) sprintf(STR, "%lld", (long long) LL_VALUE); + +#define QUERY_BUFFER_MAX 4096 + +#if !defined(WINDOWS) +#define STRING_APPEND(buffer_p, avail_size_holder, ...) \ + do { \ + if (avail_size_holder > 0) { \ + int n = snprintf (buffer_p, avail_size_holder, __VA_ARGS__); \ + if (n > 0) { \ + if ((size_t) n < avail_size_holder) { \ + buffer_p += n; avail_size_holder -= n; \ + } else { \ + buffer_p += (avail_size_holder - 1); \ + avail_size_holder = 0; \ + } \ + } \ + } \ + } while (0) +#else /* !WINDOWS */ +#define STRING_APPEND(buffer_p, avail_size_holder, ...) \ + do { \ + if (avail_size_holder > 0) { \ + int n = _snprintf (buffer_p, avail_size_holder, __VA_ARGS__); \ + if (n < 0 || (size_t) n >= avail_size_holder) { \ + buffer_p += (avail_size_holder - 1); \ + avail_size_holder = 0; \ + *buffer_p = '\0'; \ + } else { \ + buffer_p += n; avail_size_holder -= n; \ + } \ + } \ + } while (0) +#endif /* !WINDOWS */ + +extern T_EMGR_VERSION CLIENT_VERSION; +extern T_USER_TOKEN_INFO *user_token_info; + +typedef struct +{ + char dbname[DB_NAME_LEN]; + char server_mode[64]; + char server_msg[1024]; +} T_DB_MODE_INFO; + +typedef struct +{ + char hostname[MAXHOSTNAMELEN]; + char dbname[DB_NAME_LEN]; + char logpath[PATH_MAX]; + char state[64]; + int pid; + char mode[16]; /* mode of copylogdb proc. */ +} T_HA_LOG_PROC_INFO; + +typedef struct +{ + char dbname[DB_NAME_LEN]; + int pid; + char state[64]; +} T_HA_DB_PROC_INFO; + +typedef struct +{ + char dbname[DB_NAME_LEN]; + int num_ap; + int num_cp; + T_DB_MODE_INFO *dbmode_info; + T_HA_DB_PROC_INFO *dbproc_info; + T_HA_LOG_PROC_INFO *applylogdb_info; + T_HA_LOG_PROC_INFO *copylogdb_info; +} T_HA_DBSERVER_INFO; + +typedef struct +{ + char hostname[MAXHOSTNAMELEN]; + char ip[64]; + char state[64]; + int priority; +} T_HA_NODE_INFO; + +typedef struct +{ + int num_dbinfo; + int num_nodeinfo; + T_HA_DBSERVER_INFO *db_info; + T_HA_NODE_INFO *node_info; + char current_node[MAXHOSTNAMELEN]; + char current_node_state[64]; +} T_HA_SERVER_INFO_ALL; + +typedef struct +{ + INT64 delay_time; + INT64 insert_counter; + INT64 update_counter; + INT64 delete_counter; + INT64 commit_counter; + INT64 fail_counter; +} T_STANDBY_SERVER_STAT; + +typedef struct +{ + INT64 num_req; + INT64 num_query; + INT64 num_tran; + INT64 num_long_query; + INT64 num_long_tran; + INT64 num_error_query; + int num_busy_count; + int num_session; +} T_BROKER_DIAGDATA; + +#define MAX_STATDUMP_PROC 16 + typedef struct + { + int pid; + char dbname [DB_NAME_LEN]; + int status; + } T_STATDUMP_STAT; + + static T_STATDUMP_STAT *statdump_daemon = NULL; + + #define STATD_IDLE 0 + #define STATD_RUNNING 1 + + +#if defined(WINDOWS) +static void replace_colon (char *path); +#endif + +static char *to_upper_str (char *str, char *buf); +static char *to_lower_str (char *str, char *buf); +static int uca_conf_write (T_CM_BROKER_CONF *uc_conf, char *del_broekr, + char *_dbmt_error); +static char *get_user_name (int uid, char *name_buf); +static const char *_op_get_port_from_config (T_CM_BROKER_CONF *uc_conf, + char *broker_name); + +static int _tsParseSpacedb (nvplist *req, nvplist *res, char *dbname, + char *_dbmt_error, GeneralSpacedbResult *cmd_res); +static void _ts_gen_spaceinfo (nvplist *res, const char *filename, + const char *dbinstalldir, const char *type, int pagesize); + +static void _tsAppendDBMTUserList (nvplist *res, T_DBMT_USER *dbmt_user, + int return_dbmt_pwd, char *_dbmt_error); +static int _ts_lockdb_parse_us (nvplist *res, FILE *infile); + +static int get_dbitemdir (char *item_dir, size_t item_dir_size, char *dbname, + char *err_buf, int itemtype); +static int get_dblogdir (char *log_dir, size_t log_dir_size, char *dbname, + char *err_buf); +static int get_dbvoldir (char *vol_dir, size_t vol_dir_size, char *dbname, + char *err_buf); +static int op_make_triggerinput_file_add (nvplist *req, char *input_filename); +static int op_make_triggerinput_file_drop (nvplist *req, char *input_filename); +static int op_make_triggerinput_file_alter (nvplist *req, char *input_filename); + +static int get_broker_info_from_filename (char *path, char *br_name, int *as_id); +static char *_ts_get_error_log_param (char *dbname); + +static char *cm_get_abs_file_path (const char *filename, char *buf); +static int check_dbpath (char *dir, char *_dbmt_error); + +static int file_to_nvpairs (char *filepath, nvplist *res); +static int file_to_nvp_by_separator (FILE *fp, nvplist *res, char separator); +static int obsolete_version_autoexecquery_conf (const char *conf_line); +static int alter_dblocation (const char *dbname, const char *new_dbpath); +static void print_db_stat_to_res (T_CM_DB_PROC_STAT *db_stat, nvplist *res); +static int record_ha_topology_to_struct (FILE *infile, int get_all_dbmode, + char *dblist, char *_dbmt_error, T_HA_SERVER_INFO_ALL **all_info_out); +static char *get_mode_from_output_file (char *mode, int buf_len, + FILE *outputfile, char *_dbmt_error); +static void dbinfo_list_free (T_HA_SERVER_INFO_ALL *all_info); +static void print_dbinfo_list_to_res (T_HA_SERVER_INFO_ALL *all_info, + nvplist *res); +static void print_ha_proc_info (T_HA_LOG_PROC_INFO *ha_log_proc, + int elem_num, int is_copylogdb, nvplist *res); +static int dbname_exist_in_dbinfo_list (int nitem, char *dbname, + T_HA_SERVER_INFO_ALL *all_info); +static char *get_ip_from_hostname (char *hostname, char *ipaddr, int ip_len); +static int parse_standby_server_stat (T_STANDBY_SERVER_STAT *stat, + FILE *outfile, char *_dbmt_error); +static int analyze_heartbeat_cmd_outfile (FILE *infile, char *_dbmt_error); +static char *arn_admin_cmd_name (char *cmd_name, int buf_len); +static int cmd_get_db_mode (T_DB_MODE_INFO *dbmode, char *dbname, + char *dbmt_error); +static int fill_dbmode_into_dbinfo_list (T_HA_SERVER_INFO_ALL **all_info, + char *_dbmt_error); +static int parse_ha_proc_msg_to_all_info_array (char *buf, char *_dbmt_error, + T_HA_SERVER_INFO_ALL **all_info, int *nitem, + int *nalloc, int *nproc_alloc, int get_all_dbmode, + char *dblist); +static int parse_ha_node_to_all_info_array (char *buf, T_HA_SERVER_INFO_ALL **all_info, + int *node_alloc, char *_dbmt_error); +static int is_name_in_list (char *dbname, char *dblist); +static int cmd_heartbeat_list (T_HA_SERVER_INFO_ALL **all_info, + int get_all_dbmode, char *dblist, char *_dbmt_error); +static int cmd_heartbeat_act (char *_dbmt_error); +static int cmd_heartbeat_deact (char *_dbmt_error); +static int cmd_changemode (char *dbname, char *modify, char *force, + char *server_mode_out, int mode_len, char *_dbmt_error); +static int run_asql_statement (const char *sql_stat, char *dbname, + char *dbuser, char *dbpasswd, char *outfilepath, char *_dbmt_error); + +static void set_copylogdb_mode (T_HA_LOG_PROC_INFO *copylogdb); + +static int _op_get_session_from_broker (char *broker_list, + T_CM_CAS_INFO_ALL *cas_info_all); +static void _op_print_br_diagdata_to_res (nvplist *res, + T_BROKER_DIAGDATA br_diagdata); +static int _write_conf_to_file (nvplist *req, char *conf_path); +static int _get_folders_with_keyword (char *search_folder_path, + const char *keyword, nvplist *res, char *_dbmt_error); +static int _get_block_from_log (FILE *fp, char *block_buf, int len); +static int +_update_nvplist_name (nvplist *ref, const char *name, const char *value); +static int +_get_confpath_by_name (const char *conf_name, char *conf_path, int buflen); + +static void _write_auto_update_log (char *line_buf, int is_success); +static char *_get_format_time (); +static void read_stdout_stderr_as_err (char *tmp_out_file, char *tmp_err_file, + char *_dbmt_error); +static int _run_child (const char *const argv[], int wait_flag, + char *task_name, char *stdout_file, char *_dbmt_error); +static int _check_backup_info (const char *conf_item[], int check_backupid, + char *_dbmt_error); +static int _verify_user_passwd (char *dbname, char *dbuser, char *dbpasswd, + char *_dbmt_error); +static int _add_extensions (X509 *cert, int nid, char *value); +static void _add_issuer_info (X509_NAME *name, const char *item_name, + char *item_value); +static int _make_cert (nvplist *req, X509 **x509p, EVP_PKEY **pkeyp, + int bits, char *_dbmt_error); +static int _hash_cert (char *hash_value, char *file_path); +static int _is_default_cert (char *_dbmt_error); +static int _is_exist_default_backup_cert (char *_dbmt_error); +static int _backup_cert (char *_dbmt_error); +static int _recover_cert (char *_dbmt_error); + +static int find_statdumpd_info (char *dbname); +static int find_new_statdumpd_info (); + +static int +_verify_user_passwd (char *dbname, char *dbuser, char *dbpasswd, + char *_dbmt_error) +{ + int retval = ERR_NO_ERROR; + + /* every user can access db_user table. */ + const char *sql_stat = "select 1 from db_root"; + + if (dbname == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "dbname"); + return ERR_PARAM_MISSING; + } + + if (dbuser == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "dbuser"); + return ERR_PARAM_MISSING; + } + + /* + * using asql to verify the user's password. + */ + retval = run_asql_statement (sql_stat, dbname, dbuser, dbpasswd, NULL, _dbmt_error); /* asql */ + + return retval; +} + +static int +_run_child (const char *const argv[], int wait_flag, char *task_name, + char *stdout_file, char *_dbmt_error) +{ + char tmp_out_file[PATH_MAX]; + char tmp_err_file[PATH_MAX]; + + int exit_code = 0; + int ret_val = ERR_NO_ERROR; + + tmp_out_file[0] = '\0'; + tmp_err_file[0] = '\0'; + + if (stdout_file == NULL) + { + snprintf (tmp_out_file, PATH_MAX, "%s/%s.%u.out.tmp", + sco.dbmt_tmp_dir, task_name, getpid ()); + } + else + { + snprintf (tmp_out_file, PATH_MAX, stdout_file); + } + snprintf (tmp_err_file, PATH_MAX, "%s/%s.%u.err.tmp", + sco.dbmt_tmp_dir, task_name, getpid ()); + + if (run_child + (argv, wait_flag, NULL, tmp_out_file, tmp_err_file, &exit_code) < 0) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", argv[0]); + ret_val = ERR_SYSTEM_CALL; + goto rm_return; + } + + if (read_error_file (tmp_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) + { + ret_val = ERR_WITH_MSG; + goto rm_return; + } + + if (exit_code != EXIT_SUCCESS) + { + read_stdout_stderr_as_err (tmp_out_file, NULL, _dbmt_error); + ret_val = ERR_WITH_MSG; + goto rm_return; + } + +rm_return: + if (stdout_file == NULL) + { + unlink (tmp_out_file); + } + unlink (tmp_err_file); + return ret_val; +} + +int +ts_add_nvp_time (nvplist *ref, const char *name, time_t t, const char *fmt, + int type) +{ + char strbuf[64]; + if (t == 0) + { + return (nv_add_nvp (ref, name, "")); + } + else + { + time_to_str (t, fmt, strbuf, type); + return (nv_add_nvp (ref, name, strbuf)); + } +} + +/* if arniadb.conf's error_log is null, construct it by default value if existing */ +static char * +_ts_get_error_log_param (char *dbname) +{ + char *tok[2]; + FILE *infile; + char buf[PATH_MAX], dbdir[PATH_MAX]; + + if ((uRetrieveDBDirectory (dbname, dbdir)) != ERR_NO_ERROR) + { + return NULL; + } + +#if !defined (DO_NOT_USE_ARNIADBENV) + snprintf (buf, PATH_MAX - 1, "%s/conf/%s", sco.szArniadb, ARNIADB_ARNIADB_CONF); +#else + snprintf (buf, PATH_MAX - 1, "%s/%s", ARNIADB_CONFDIR, ARNIADB_ARNIADB_CONF); +#endif + + if ((infile = fopen (buf, "r")) == NULL) + { + return NULL; + } + + while (fgets (buf, sizeof (buf), infile)) + { + ut_trim (buf); + if (isalpha ((int) buf[0])) + { + if (string_tokenize2 (buf, tok, 2, '=') < 0) + { + continue; + } + if (uStringEqual (tok[0], "error_log")) + { + fclose (infile); + if (tok[1][0] == '\0') + { + return NULL; + } +#if defined(WINDOWS) + unix_style_path (tok[1]); +#endif + return (strdup (tok[1])); + } + } + } + fclose (infile); + return NULL; +} + +int +ts_get_broker_diagdata (nvplist *cli_request, nvplist *cli_response, + char *_dbmt_error) +{ + int i; + char *broker_list = NULL; + T_CM_BROKER_INFO_ALL uc_info; + T_CM_BROKER_INFO *br_info = NULL; + T_BROKER_DIAGDATA br_diagdata; + T_CM_ERROR error; + int get_all_diagdata = 0; + + memset (&br_diagdata, 0, sizeof (T_BROKER_DIAGDATA)); + + /* get broker info, if broker name is NULL then get all of them, + else get specified broker diagdata. */ + broker_list = nv_get_val (cli_request, "bname"); + + if (broker_list == NULL) + { + get_all_diagdata = 1; + } + + if (cm_get_broker_info (&uc_info, &error) < 0) + { + strcpy (_dbmt_error, error.err_msg); + return ERR_NO_ERROR; + } + + ts_add_nvp_time (cli_response, "time", time (NULL), + "%04d/%02d/%02d %02d:%02d:%02d", TIME_STR_FMT_DATE_TIME); + + for (i = 0; i < uc_info.num_info; i++) + { + br_info = uc_info.br_info + i; + + if (strcmp (br_info->status, "OFF") == 0) + { + continue; + } + + if (get_all_diagdata || is_name_in_list (br_info->name, broker_list)) + { + int session = 0; + T_CM_CAS_INFO_ALL cas_info_all; + + session = _op_get_session_from_broker (br_info->name, &cas_info_all); + + if (session < 0) + { + strcpy_limit (_dbmt_error, "Couldn't get session from broker", DBMT_ERROR_MSG_SIZE); + return ERR_WITH_MSG; + } + + br_diagdata.num_req += br_info->num_req; + br_diagdata.num_query += br_info->num_query; + br_diagdata.num_tran += br_info->num_tran; + br_diagdata.num_long_query += br_info->num_long_query; + br_diagdata.num_long_tran += br_info->num_long_tran; + br_diagdata.num_error_query += br_info->num_error_query; + br_diagdata.num_busy_count += br_info->num_busy_count; + br_diagdata.num_session += session; + + /* if the bname_list is not NULL, then get each broker diagdata. */ + if (get_all_diagdata == 0) + { + nv_add_nvp (cli_response, "open", "broker"); + nv_add_nvp (cli_response, "bname", br_info->name); + _op_print_br_diagdata_to_res (cli_response, br_diagdata); + nv_add_nvp (cli_response, "close", "broker"); + + /* init br_diagdata to get the next broker diagdata. */ + memset (&br_diagdata, 0, sizeof (T_BROKER_DIAGDATA)); + } + + /* free spaces that malloced in cm_cas_info_free */ + cm_cas_info_free (&cas_info_all, NULL); + } + } + + /* free spaces that malloced in cm_broker_info_free */ + cm_broker_info_free (&uc_info); + + /* return the sum of the diagdata to res, when bname token is NULL. */ + if (get_all_diagdata) + { + _op_print_br_diagdata_to_res (cli_response, br_diagdata); + } + + return ERR_NO_ERROR; +} + +static int +_op_get_session_from_broker (char *broker_list, + T_CM_CAS_INFO_ALL *cas_info_all) +{ + int i; + int session_t = 0; + T_CM_CAS_INFO *as_info = NULL; + T_CM_ERROR error; + + if (cm_get_cas_info (broker_list, cas_info_all, NULL, &error) < 0) + { + return -1; + } + + for (i = 0; i < cas_info_all->num_info; i++) + { + as_info = cas_info_all->as_info + i; + if (uStringEqual (as_info->status, "BUSY")) + { + session_t += 1; + } + } + return session_t; +} + +static void +_op_print_br_diagdata_to_res (nvplist *res, T_BROKER_DIAGDATA br_diagdata) +{ +#ifdef JSON_SUPPORT + nv_add_nvp (res, "open", "cas_mon"); +#else + nv_add_nvp (res, "cas_mon", "start"); +#endif + + /* + * "cas_mon_act_session" is left for campatibility, from version 8.3.1 + * the "cas_mon_session" is used instead of "cas_mon_act_session" + */ + nv_add_nvp_int (res, "cas_mon_act_session", br_diagdata.num_busy_count); + + nv_add_nvp_int (res, "cas_mon_session", br_diagdata.num_busy_count); + nv_add_nvp_int (res, "cas_mon_active", br_diagdata.num_session); + nv_add_nvp_int64 (res, "cas_mon_req", br_diagdata.num_req); + nv_add_nvp_int64 (res, "cas_mon_query", br_diagdata.num_query); + nv_add_nvp_int64 (res, "cas_mon_tran", br_diagdata.num_tran); + nv_add_nvp_int64 (res, "cas_mon_long_query", br_diagdata.num_long_query); + nv_add_nvp_int64 (res, "cas_mon_long_tran", br_diagdata.num_long_tran); + nv_add_nvp_int64 (res, "cas_mon_error_query", br_diagdata.num_error_query); + +#ifdef JSON_SUPPORT + nv_add_nvp (res, "close", "cas_mon"); +#else + nv_add_nvp (res, "cas_mon", "end"); +#endif +} + +int +ts_get_diagdata (nvplist *cli_request, nvplist *cli_response, + char *_dbmt_error) +{ + int i; + /*T_CM_DIAG_MONITOR_DB_VALUE server_result; */ + char *db_name, *broker_name; + char *mon_db, *mon_cas; + T_CM_BROKER_INFO_ALL uc_info; + T_CM_BROKER_INFO *br_info; + int num_busy_count = 0; + INT64 num_req, num_query, num_tran, num_long_query, num_long_tran, + num_error_query; + T_CM_ERROR error; + + db_name = nv_get_val (cli_request, "db_name"); + mon_db = nv_get_val (cli_request, "mon_db"); + mon_cas = nv_get_val (cli_request, "mon_cas"); + + /* + if (cm_get_diag_data (&server_result, db_name, mon_db) == 0) + { + #ifdef JSON_SUPPORT + nv_add_nvp (cli_response, "open", "db_mon"); + #else + nv_add_nvp (cli_response, "db_mon", "start"); + #endif + nv_add_nvp_int64 (cli_response, "mon_arn_query_open_page", + server_result.query_open_page); + nv_add_nvp_int64 (cli_response, "mon_arn_query_opened_page", + server_result.query_opened_page); + nv_add_nvp_int64 (cli_response, "mon_arn_query_slow_query", + server_result.query_slow_query); + nv_add_nvp_int64 (cli_response, "mon_arn_query_full_scan", + server_result.query_full_scan); + nv_add_nvp_int64 (cli_response, "mon_arn_lock_deadlock", + server_result.lock_deadlock); + nv_add_nvp_int64 (cli_response, "mon_arn_lock_request", + server_result.lock_request); + nv_add_nvp_int64 (cli_response, "mon_arn_conn_cli_request", + server_result.conn_cli_request); + nv_add_nvp_int64 (cli_response, "mon_arn_conn_aborted_clients", + server_result.conn_aborted_clients); + nv_add_nvp_int64 (cli_response, "mon_arn_conn_conn_req", + server_result.conn_conn_req); + nv_add_nvp_int64 (cli_response, "mon_arn_conn_conn_reject", + server_result.conn_conn_reject); + nv_add_nvp_int64 (cli_response, "mon_arn_buffer_page_write", + server_result.buffer_page_write); + nv_add_nvp_int64 (cli_response, "mon_arn_buffer_page_read", + server_result.buffer_page_read); + #ifdef JSON_SUPPORT + nv_add_nvp (cli_response, "close", "db_mon"); + #else + nv_add_nvp (cli_response, "db_mon", "end"); + #endif + } + */ + + if (mon_cas != NULL && strcmp (mon_cas, "yes") == 0) + { + num_req = num_query = num_tran = num_long_query = num_long_tran = + num_error_query = 0; + + broker_name = nv_get_val (cli_request, "broker_name"); + + if (cm_get_broker_info (&uc_info, &error) < 0) + { + strcpy (_dbmt_error, error.err_msg); + return ERR_NO_ERROR; + } + + for (i = 0; i < uc_info.num_info; i++) + { + br_info = uc_info.br_info + i; + + if (strcmp (br_info->status, "OFF") != 0 && + (broker_name == NULL || strcasecmp (broker_name, br_info->name) == 0)) + { + num_req += br_info->num_req; + num_query += br_info->num_query; + num_tran += br_info->num_tran; + num_long_query += br_info->num_long_query; + num_long_tran += br_info->num_long_tran; + num_error_query += br_info->num_error_query; + num_busy_count += br_info->num_busy_count; + } + } +#ifdef JSON_SUPPORT + nv_add_nvp (cli_response, "open", "cas_mon"); +#else + nv_add_nvp (cli_response, "cas_mon", "start"); +#endif + nv_add_nvp_int (cli_response, "cas_mon_act_session", num_busy_count); + nv_add_nvp_int64 (cli_response, "cas_mon_req", num_req); + nv_add_nvp_int64 (cli_response, "cas_mon_query", num_query); + nv_add_nvp_int64 (cli_response, "cas_mon_tran", num_tran); + nv_add_nvp_int64 (cli_response, "cas_mon_long_query", num_long_query); + nv_add_nvp_int64 (cli_response, "cas_mon_long_tran", num_long_tran); + nv_add_nvp_int64 (cli_response, "cas_mon_error_query", num_error_query); + +#ifdef JSON_SUPPORT + nv_add_nvp (cli_response, "close", "cas_mon"); +#else + nv_add_nvp (cli_response, "cas_mon", "end"); +#endif + } + + return ERR_NO_ERROR; +} + +int +ts_userinfo (nvplist *req, nvplist *res, char *_dbmt_error) +{ + int retval; + + retval = cm_ts_userinfo (req, res, _dbmt_error); + + if (retval != ERR_NO_ERROR) + { + return retval; + } + + _update_nvplist_name (res, "name", ENCRYPT_ARG ("name")); + _update_nvplist_name (res, "id", ENCRYPT_ARG ("id")); + + return ERR_NO_ERROR; +} + +int +ts_create_user (nvplist *req, nvplist *res, char *_dbmt_error) +{ + return cm_ts_create_user (req, res, _dbmt_error); +} + +int +ts_delete_user (nvplist *req, nvplist *res, char *_dbmt_error) +{ + int retval; + char *db_uid = nv_get_val (req, "username"); + + if ((retval = cm_ts_delete_user (req, res, _dbmt_error)) == ERR_NO_ERROR) + { + auto_conf_execquery_delete_by_dbuser (db_uid); + } + + return retval; +} + +int +ts_update_user (nvplist *req, nvplist *res, char *_dbmt_error) +{ + T_DBMT_USER dbmt_user; + const char *new_db_user_name; + const char *new_db_user_pass; + char *db_name; + int i, ret; + + new_db_user_name = nv_get_val (req, "username"); + new_db_user_pass = nv_get_val (req, "userpass"); + db_name = nv_get_val (req, "_DBNAME"); + + if (new_db_user_pass) + { + if (uStringEqual (new_db_user_pass, "__NULL__") + || uStringEqual (new_db_user_pass, "")) + { + sprintf (_dbmt_error, "%s", "user password is empty!"); + return ERR_WITH_MSG; + } + } + + ret = cm_ts_update_user (req, res, _dbmt_error); + if (ret != ERR_NO_ERROR) + { + return ret; + } + +#ifndef PK_AUTHENTICAITON + if (new_db_user_pass) + { + char hexacoded[PASSWD_ENC_LENGTH]; + /* update cmdb.pass dbinfo */ + if (dbmt_user_read (&dbmt_user, _dbmt_error) == ERR_NO_ERROR) + { + int src_dbinfo; + + for (i = 0; i < dbmt_user.num_dbmt_user; i++) + { + src_dbinfo = + dbmt_user_search (& (dbmt_user.user_info[i]), db_name); + if (src_dbinfo < 0) + { + continue; + } + if (strcmp + (dbmt_user.user_info[i].dbinfo[src_dbinfo].uid, new_db_user_name) != 0) + { + continue; + } + } + dbmt_user_write_auth (&dbmt_user, _dbmt_error); + dbmt_user_free (&dbmt_user); + } + + /* update db_user's passwd in autoexecquery.conf */ + uEncrypt (PASSWD_LENGTH, new_db_user_pass, hexacoded); + auto_conf_execquery_update_dbuser (new_db_user_name, new_db_user_name, hexacoded); + } +#endif + return ERR_NO_ERROR; +} + + +int +ts_class_info (nvplist *req, nvplist *res, char *_dbmt_error) +{ + return cm_ts_class_info (req, res, _dbmt_error); +} + +int +ts_class (nvplist *req, nvplist *res, char *_dbmt_error) +{ + return cm_ts_class (req, res, _dbmt_error); +} + +#if defined(WINDOWS) +static void +replace_colon (char *path) +{ + char *p; + for (p = path; *p; p++) + { + if (*p == '|') + { + *p = ':'; + } + } +} +#endif + +int +ts_update_attribute (nvplist *req, nvplist *res, char *_dbmt_error) +{ + return cm_ts_update_attribute (req, res, _dbmt_error); +} + +int +ts2_get_unicas_info (nvplist *in, nvplist *out, char *_dbmt_error) +{ + T_CM_BROKER_INFO_ALL uc_info; + int i; + T_CM_BROKER_CONF uc_conf; + T_CM_ERROR error; + char *broker_name; + + broker_name = nv_get_val (in, "bname"); + memset (&uc_info, 0, sizeof (T_CM_BROKER_INFO_ALL)); + if (cm_get_broker_conf (&uc_conf, NULL, &error) < 0) + { + strcpy (_dbmt_error, error.err_msg); + return ERR_WITH_MSG; + } + if (cm_get_broker_info (&uc_info, &error) < 0) + { + char *p; + int tmp_val; + + strcpy (_dbmt_error, error.err_msg); + nv_add_nvp (out, "open", "brokersinfo"); + for (i = 0; i < uc_conf.num_broker; i++) + { + /* + *add broker info to response according to the requested + * dbname.if dbname is null, then print all the brokers. + */ + if ((broker_name != NULL) && + (uc_info.br_info != NULL) && + (strcmp (uc_info.br_info[i].name, broker_name) != 0)) + { + continue; + } + nv_add_nvp (out, "open", "broker"); + nv_add_nvp (out, "name", + cm_br_conf_get_value (& (uc_conf.br_conf[i]), "%")); + nv_add_nvp (out, "port", + cm_br_conf_get_value (& (uc_conf.br_conf[i]), "BROKER_PORT")); + nv_add_nvp (out, "appl_server_shm_id", + cm_br_conf_get_value (& (uc_conf.br_conf[i]), "APPL_SERVER_SHM_ID")); + p = cm_br_conf_get_value (& (uc_conf.br_conf[i]), "SOURCE_ENV"); + tmp_val = 1; + if (p == NULL || *p == '\0') + { + tmp_val = 0; + } + nv_add_nvp_int (out, "source_env", tmp_val); + p = cm_br_conf_get_value (& (uc_conf.br_conf[i]), "ACCESS_LIST"); + tmp_val = 1; + if (p == NULL || *p == '\0') + { + tmp_val = 0; + } + nv_add_nvp_int (out, "access_list", tmp_val); + nv_add_nvp (out, "close", "broker"); + } + nv_add_nvp (out, "close", "brokersinfo"); + nv_add_nvp (out, "brokerstatus", "OFF"); + } + else + { + char *shmid; + nv_add_nvp (out, "open", "brokersinfo"); + for (i = 0; i < uc_info.num_info; i++) + { + /* + *add broker info to response according to the requested + * dbname.if dbname is null, then print all the brokers. + */ + if ((broker_name != NULL) && + (uc_info.br_info != NULL) && + (strcmp (uc_info.br_info[i].name, broker_name) != 0)) + { + continue; + } + nv_add_nvp (out, "open", "broker"); + nv_add_nvp (out, "name", uc_info.br_info[i].name); + nv_add_nvp (out, "type", uc_info.br_info[i].as_type); + if (strcmp (uc_info.br_info[i].status, "OFF") != 0) + { + nv_add_nvp_int (out, "pid", uc_info.br_info[i].pid); + nv_add_nvp_int (out, "port", uc_info.br_info[i].port); + nv_add_nvp_int (out, "as", uc_info.br_info[i].num_as); + nv_add_nvp_int (out, "jq", uc_info.br_info[i].num_job_q); +#ifdef GET_PSINFO + nv_add_nvp_int (out, "thr", uc_info.br_info[i].num_thr); + nv_add_nvp_float (out, "cpu", uc_info.br_info[i].pcpu, "%.2f"); + nv_add_nvp_int (out, "time", uc_info.br_info[i].cpu_time); +#endif + nv_add_nvp_int (out, "req", uc_info.br_info[i].num_req); + nv_add_nvp_int64 (out, "tran", uc_info.br_info[i].num_tran); + nv_add_nvp_int64 (out, "query", uc_info.br_info[i].num_query); + nv_add_nvp_int64 (out, "long_tran", uc_info.br_info[i].num_long_tran); + nv_add_nvp_int64 (out, "long_query", uc_info.br_info[i].num_long_query); + nv_add_nvp_int64 (out, "error_query", uc_info.br_info[i].num_error_query); + nv_add_nvp_float (out, "long_tran_time", + uc_info.br_info[i].long_transaction_time / 1000.0f, "%.2f"); + nv_add_nvp_float (out, "long_query_time", + uc_info.br_info[i].long_query_time / 1000.0f, "%.2f"); + + nv_add_nvp (out, "keep_conn", uc_info.br_info[i].keep_connection); + + nv_add_nvp (out, "auto", uc_info.br_info[i].auto_add); + nv_add_nvp (out, "ses", uc_info.br_info[i].session_timeout); + nv_add_nvp (out, "sqll", uc_info.br_info[i].sql_log_mode); + nv_add_nvp (out, "log", uc_info.br_info[i].log_dir); + nv_add_nvp (out, "access_mode", uc_info.br_info[i].access_mode); + } + else + { + nv_add_nvp (out, "port", _op_get_port_from_config (&uc_conf, uc_info.br_info[i].name)); + } + nv_add_nvp (out, "state", uc_info.br_info[i].status); + nv_add_nvp_int (out, "source_env", + uc_info.br_info[i].source_env_flag); + nv_add_nvp_int (out, "access_list", + uc_info.br_info[i].access_list_flag); + shmid = + cm_br_conf_get_value (cm_conf_find_broker (&uc_conf, uc_info.br_info[i].name), + "APPL_SERVER_SHM_ID"); + nv_add_nvp (out, "appl_server_shm_id", shmid); + nv_add_nvp (out, "close", "broker"); + } + nv_add_nvp (out, "close", "brokersinfo"); + nv_add_nvp (out, "brokerstatus", "ON"); + cm_broker_info_free (&uc_info); + } + + cm_broker_conf_free (&uc_conf); + return ERR_NO_ERROR; +} + + +int +ts2_start_unicas (nvplist *in, nvplist *out, char *_dbmt_error) +{ + T_CM_ERROR error; + if (cm_broker_env_start (&error) < 0) + { + strcpy (_dbmt_error, error.err_msg); + return ERR_WITH_MSG; + } + + return ERR_NO_ERROR; +} + +int +ts2_stop_unicas (nvplist *in, nvplist *out, char *_dbmt_error) +{ + T_CM_ERROR error; + if (cm_broker_env_stop (&error) < 0) + { + strcpy (_dbmt_error, error.err_msg); + return ERR_WITH_MSG; + } + + return ERR_NO_ERROR; +} + +int +ts2_get_admin_log_info (nvplist *in, nvplist *out, char *_dbmt_error) +{ + char buf[PATH_MAX]; + struct stat statbuf; + + cm_get_broker_file (UC_FID_ADMIN_LOG, buf); + + if (stat (buf, &statbuf) != 0) + { + return ERR_STAT; + } + nv_add_nvp (out, "open", "adminloginfo"); + nv_add_nvp (out, "path", buf); + nv_add_nvp (out, "owner", get_user_name (statbuf.st_uid, buf)); + nv_add_nvp_int (out, "size", statbuf.st_size); + ts_add_nvp_time (out, "lastupdate", statbuf.st_mtime, "%04d.%02d.%02d", NV_ADD_DATE); + nv_add_nvp (out, "close", "adminloginfo"); + + return ERR_NO_ERROR; +} + +int +ts2_get_logfile_info (nvplist *in, nvplist *out, char *_dbmt_error) +{ +#if defined(WINDOWS) + HANDLE handle; + WIN32_FIND_DATA data; + char find_file[PATH_MAX]; + int found; +#else + DIR *dp; + struct dirent *dirp; +#endif + struct stat statbuf; + T_CM_BROKER_CONF uc_conf; + char logdir[PATH_MAX], err_logdir[PATH_MAX], access_logdir[PATH_MAX]; + const char *v; + char *bname, *from, buf[1024], scriptdir[PATH_MAX]; + char *cur_file; + T_CM_ERROR error; + + bname = nv_get_val (in, "broker"); + from = nv_get_val (in, "from"); + nv_add_nvp (out, "broker", bname); + nv_add_nvp (out, "from", from); + nv_add_nvp (out, "open", "logfileinfo"); + + if (bname == NULL) + { + strcpy (_dbmt_error, "broker"); + return ERR_PARAM_MISSING; + } + chdir (sco.szArniadb); + if (cm_get_broker_conf (&uc_conf, NULL, &error) < 0) + { + strcpy (_dbmt_error, error.err_msg); + return ERR_WITH_MSG; + } + v = cm_br_conf_get_value (cm_conf_find_broker (&uc_conf, bname), "ERROR_LOG_DIR"); + if (v == NULL) + { + v = BROKER_LOG_DIR "/error_log"; + } + cm_get_abs_file_path (v, err_logdir); + + v = cm_br_conf_get_value (cm_conf_find_broker (&uc_conf, bname), "LOG_DIR"); + if (v == NULL) + { + v = BROKER_LOG_DIR "/sql_log"; + } + cm_get_abs_file_path (v, logdir); + + cm_get_abs_file_path (BROKER_LOG_DIR, access_logdir); + + cm_broker_conf_free (&uc_conf); + +#if defined(WINDOWS) + snprintf (find_file, PATH_MAX - 1, "%s/*", access_logdir); + handle = FindFirstFile (find_file, &data); + if (handle != INVALID_HANDLE_VALUE) +#else + dp = opendir (access_logdir); + if (dp != NULL) +#endif + { +#if defined(WINDOWS) + for (found = 1; found; found = FindNextFile (handle, &data)) +#else + while ((dirp = readdir (dp)) != NULL) +#endif + { +#if defined(WINDOWS) + cur_file = data.cFileName; +#else + cur_file = dirp->d_name; +#endif + if (strstr (cur_file, bname) != NULL) + { + nv_add_nvp (out, "open", "logfile"); + if (strstr (cur_file, "access") != NULL) + { + nv_add_nvp (out, "type", "access"); + } + snprintf (buf, sizeof (buf) - 1, "%s/%s", access_logdir, cur_file); + nv_add_nvp (out, "path", buf); + stat (buf, &statbuf); + nv_add_nvp (out, "owner", get_user_name (statbuf.st_uid, buf)); + nv_add_nvp_int (out, "size", statbuf.st_size); + ts_add_nvp_time (out, "lastupdate", statbuf.st_mtime, "%04d.%02d.%02d", NV_ADD_DATE); + nv_add_nvp (out, "close", "logfile"); + } + } +#if defined(WINDOWS) + FindClose (handle); +#else + closedir (dp); +#endif + } +#if defined(WINDOWS) + snprintf (find_file, PATH_MAX - 1, "%s/*", err_logdir); + handle = FindFirstFile (find_file, &data); + if (handle != INVALID_HANDLE_VALUE) +#else + dp = opendir (err_logdir); + if (dp != NULL) +#endif + { +#if defined(WINDOWS) + for (found = 1; found; found = FindNextFile (handle, &data)) +#else + while ((dirp = readdir (dp)) != NULL) +#endif + { +#if defined(WINDOWS) + cur_file = data.cFileName; +#else + cur_file = dirp->d_name; +#endif + if (strstr (cur_file, bname) != NULL) + { + nv_add_nvp (out, "open", "logfile"); + if (strstr (cur_file, "access") != NULL) + { + nv_add_nvp (out, "type", "access"); + } + else if (strstr (cur_file, "err") != NULL) + { + nv_add_nvp (out, "type", "error"); + } + snprintf (buf, sizeof (buf) - 1, "%s/%s", err_logdir, cur_file); + nv_add_nvp (out, "path", buf); + stat (buf, &statbuf); + nv_add_nvp (out, "owner", get_user_name (statbuf.st_uid, buf)); + nv_add_nvp_int (out, "size", statbuf.st_size); + ts_add_nvp_time (out, "lastupdate", statbuf.st_mtime, "%04d.%02d.%02d", NV_ADD_DATE); + nv_add_nvp (out, "close", "logfile"); + } + } +#if defined(WINDOWS) + FindClose (handle); +#else + closedir (dp); +#endif + } +#if defined(WINDOWS) + snprintf (find_file, PATH_MAX - 1, "%s/*", logdir); + handle = FindFirstFile (find_file, &data); + if (handle != INVALID_HANDLE_VALUE) +#else + dp = opendir (logdir); + if (dp != NULL) +#endif + { +#if defined(WINDOWS) + for (found = 1; found; found = FindNextFile (handle, &data)) +#else + while ((dirp = readdir (dp)) != NULL) +#endif + { +#if defined(WINDOWS) + cur_file = data.cFileName; +#else + cur_file = dirp->d_name; +#endif + if (strstr (cur_file, bname) != NULL) + { + nv_add_nvp (out, "open", "logfile"); + if (strstr (cur_file, "access") != NULL) + { + nv_add_nvp (out, "type", "access"); + } + snprintf (buf, sizeof (buf) - 1, "%s/%s", logdir, cur_file); + nv_add_nvp (out, "path", buf); + stat (buf, &statbuf); + nv_add_nvp (out, "owner", get_user_name (statbuf.st_uid, buf)); + nv_add_nvp_int (out, "size", statbuf.st_size); + ts_add_nvp_time (out, "lastupdate", statbuf.st_mtime, "%04d.%02d.%02d", NV_ADD_DATE); + nv_add_nvp (out, "close", "logfile"); + } + } +#if defined(WINDOWS) + FindClose (handle); +#else + closedir (dp); +#endif + } + snprintf (scriptdir, PATH_MAX - 1, "%s", logdir); +#if defined(WINDOWS) + snprintf (find_file, PATH_MAX - 1, "%s/*", scriptdir); + handle = FindFirstFile (find_file, &data); + if (handle != INVALID_HANDLE_VALUE) +#else + dp = opendir (scriptdir); + if (dp != NULL) +#endif + { + + sprintf (bname, "%s_", bname); +#if defined(WINDOWS) + for (found = 1; found; found = FindNextFile (handle, &data)) +#else + while ((dirp = readdir (dp)) != NULL) +#endif + { +#if defined(WINDOWS) + cur_file = data.cFileName; +#else + cur_file = dirp->d_name; +#endif + + if (strstr (cur_file, bname) != NULL) + { + nv_add_nvp (out, "open", "logfile"); + nv_add_nvp (out, "type", "script"); + snprintf (buf, sizeof (buf) - 1, "%s/%s", scriptdir, cur_file); + nv_add_nvp (out, "path", buf); + stat (buf, &statbuf); + nv_add_nvp (out, "owner", get_user_name (statbuf.st_uid, buf)); + nv_add_nvp_int (out, "size", statbuf.st_size); + ts_add_nvp_time (out, "lastupdate", statbuf.st_mtime, "%04d.%02d.%02d", NV_ADD_DATE); + nv_add_nvp (out, "close", "logfile"); + } + } +#if defined(WINDOWS) + FindClose (handle); +#else + closedir (dp); +#endif + } + nv_add_nvp (out, "close", "logfileinfo"); + + return ERR_NO_ERROR; +} + +int +ts2_get_add_broker_info (nvplist *in, nvplist *out, char *_dbmt_error) +{ + FILE *infile; + char broker_conf_path[PATH_MAX], strbuf[1024]; + + cm_get_broker_file (UC_FID_ARNIADB_BROKER_CONF, broker_conf_path); + + if (access (broker_conf_path, F_OK) < 0) + { + return ERR_FILE_OPEN_FAIL; + } + + infile = fopen (broker_conf_path, "r"); + if (infile == NULL) + { + strcpy (_dbmt_error, broker_conf_path); + return ERR_FILE_OPEN_FAIL; + } + + nv_add_nvp (out, "confname", "broker"); + nv_add_nvp (out, "open", "conflist"); + + while (fgets (strbuf, sizeof (strbuf), infile) != NULL) + { + uRemoveCRLF (strbuf); + nv_add_nvp (out, "confdata", strbuf); + } + nv_add_nvp (out, "close", "conflist"); + fclose (infile); + + return ERR_NO_ERROR; +} + +int +ts2_delete_broker (nvplist *in, nvplist *out, char *_dbmt_error) +{ + char *bname; + int retval = ERR_NO_ERROR; + T_CM_BROKER_CONF uc_conf; + T_CM_ERROR error; + + if ((bname = nv_get_val (in, "bname")) == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "bname"); + return ERR_PARAM_MISSING; + } + + if (cm_get_broker_conf (&uc_conf, NULL, &error) < 0) + { + strcpy (_dbmt_error, error.err_msg); + return ERR_WITH_MSG; + } + + retval = uca_conf_write (&uc_conf, bname, _dbmt_error); + + cm_broker_conf_free (&uc_conf); + + return retval; +} + + +int +ts2_get_broker_status (nvplist *in, nvplist *out, char *_dbmt_error) +{ + T_CM_CAS_INFO_ALL as_info_set; + T_CM_JOB_INFO_ALL job_info_set; + T_CM_ERROR error; + char *bname, buf[1024]; + char *blist; + int more_than_one_broker = 0; + int i; + + if ((blist = nv_get_val (in, "bname")) == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "bname"); + return ERR_PARAM_MISSING; + } + + /* if there is more than one brokers, there should be more than one ',' separator. */ + if (strstr (blist, ",") != NULL) + { + more_than_one_broker = 1; + } + + while (blist != NULL) + { + bname = blist; + + if ((blist = strchr (blist, ',')) != NULL) + { + blist[0] = '\0'; + blist++; + } + + ut_trim (bname); + + if (more_than_one_broker != 0) + { + nv_add_nvp (out, "open", "broker"); + } + + nv_add_nvp (out, "bname", bname); + ts_add_nvp_time (out, "time", time (NULL), + "%04d/%02d/%02d %02d:%02d:%02d", TIME_STR_FMT_DATE_TIME); + if (cm_get_cas_info (bname, &as_info_set, &job_info_set, &error) >= 0) + { + for (i = 0; i < as_info_set.num_info; i++) + { + if (strcmp (as_info_set.as_info[i].service_flag, "ON") != 0) + { + continue; + } + + nv_add_nvp (out, "open", "asinfo"); + + nv_add_nvp_int (out, "as_id", as_info_set.as_info[i].id); + nv_add_nvp_int (out, "as_pid", as_info_set.as_info[i].pid); + nv_add_nvp_int (out, "as_c", + as_info_set.as_info[i].num_request); + /* add "as_port" nvp in windows: + as_port only shows up on windows platform. */ +#if defined(WINDOWS) + nv_add_nvp_int (out, "as_port", as_info_set.as_info[i].as_port); +#endif + nv_add_nvp_int (out, "as_psize", as_info_set.as_info[i].psize); + nv_add_nvp (out, "as_status", as_info_set.as_info[i].status); + nv_add_nvp_float (out, "as_cpu", as_info_set.as_info[i].pcpu, "%.2f"); + cm_cpu_time_str (as_info_set.as_info[i].cpu_time, buf); + nv_add_nvp (out, "as_ctime", buf); + ts_add_nvp_time (out, "as_lat", + as_info_set.as_info[i].last_access_time, + "%02d/%02d/%02d %02d:%02d:%02d", NV_ADD_DATE_TIME); + nv_add_nvp (out, "as_cur", as_info_set.as_info[i].log_msg); + nv_add_nvp_int64 (out, "as_num_query", as_info_set.as_info[i].num_queries_processed); + nv_add_nvp_int64 (out, "as_num_tran", as_info_set.as_info[i].num_transactions_processed); + nv_add_nvp_int64 (out, "as_long_query", as_info_set.as_info[i].num_long_queries); + nv_add_nvp_int64 (out, "as_long_tran", as_info_set.as_info[i].num_long_transactions); + nv_add_nvp_int64 (out, "as_error_query", as_info_set.as_info[i].num_error_queries); + nv_add_nvp (out, "as_dbname", as_info_set.as_info[i].database_name); + nv_add_nvp (out, "as_dbhost", as_info_set.as_info[i].database_host); + ts_add_nvp_time (out, "as_lct", as_info_set.as_info[i].last_connect_time, + "%02d/%02d/%02d %02d:%02d:%02d", NV_ADD_DATE_TIME); + /* add "as_client_ip" nvp. */ + nv_add_nvp (out, "as_client_ip", as_info_set.as_info[i].clt_ip_addr); + nv_add_nvp (out, "close", "asinfo"); + } + for (i = 0; i < job_info_set.num_info; i++) + { + nv_add_nvp (out, "open", "jobinfo"); + nv_add_nvp_int (out, "job_id", job_info_set.job_info[i].id); + nv_add_nvp_int (out, "job_priority", + job_info_set.job_info[i].priority); + nv_add_nvp (out, "job_ip", job_info_set.job_info[i].ipstr); + ts_add_nvp_time (out, "job_time", + job_info_set.job_info[i].recv_time, "%02d:%02d:%02d", NV_ADD_TIME); + snprintf (buf, sizeof (buf) - 1, "%s:%s", + job_info_set.job_info[i].script, job_info_set.job_info[i].prgname); + nv_add_nvp (out, "job_request", buf); + nv_add_nvp (out, "close", "jobinfo"); + } + cm_cas_info_free (&as_info_set, &job_info_set); + } + if (more_than_one_broker != 0) + { + nv_add_nvp (out, "close", "broker"); + } + } + + return ERR_NO_ERROR; +} + + + +int +ts2_set_broker_conf (nvplist *in, nvplist *out, char *_dbmt_error) +{ + FILE *outfile; + char broker_conf_path[PATH_MAX]; + char *conf, *confdata; + int nv_len, i; + + cm_get_broker_file (UC_FID_ARNIADB_BROKER_CONF, broker_conf_path); + + if ((outfile = fopen (broker_conf_path, "w")) == NULL) + { + return ERR_TMPFILE_OPEN_FAIL; + } + + nv_len = in->nvplist_leng; + for (i = 1; i < nv_len; i++) + { + nv_lookup (in, i, &conf, &confdata); + if ((conf != NULL) && (strcmp (conf, "confdata") == 0)) + { + if (confdata == NULL) + { + fprintf (outfile, "\n"); + } + else + { + fprintf (outfile, "%s\n", confdata); + } + } + } + + fclose (outfile); + + return ERR_NO_ERROR; +} + + +int +ts2_start_broker (nvplist *in, nvplist *out, char *_dbmt_error) +{ + char *bname; + T_CM_ERROR error; + + if ((bname = nv_get_val (in, "bname")) == NULL) + { + strcpy (_dbmt_error, "broker name"); + return ERR_PARAM_MISSING; + } + + if (cm_broker_on (bname, &error) < 0) + { + strcpy (_dbmt_error, error.err_msg); + return ERR_WITH_MSG; + } + return ERR_NO_ERROR; +} + +int +ts2_stop_broker (nvplist *in, nvplist *out, char *_dbmt_error) +{ + char *bname; + T_CM_ERROR error; + + if ((bname = nv_get_val (in, "bname")) == NULL) + { + strcpy (_dbmt_error, "broker name"); + return ERR_PARAM_MISSING; + } + + if (cm_broker_off (bname, &error) < 0) + { + strcpy (_dbmt_error, error.err_msg); + return ERR_WITH_MSG; + } + return ERR_NO_ERROR; +} + +int +ts2_restart_broker_as (nvplist *in, nvplist *out, char *_dbmt_error) +{ + char *bname, *asnum; + T_CM_ERROR error; + T_CM_BROKER_INFO_ALL uc_info; + + int num_as = 0; + + bname = nv_get_val (in, "bname"); + asnum = nv_get_val (in, "asnum"); + + if (bname == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "bname"); + return ERR_PARAM_MISSING; + } + + if (asnum == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "asnum"); + return ERR_PARAM_MISSING; + } + + if (cm_get_broker_info (&uc_info, &error) < 0) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", error.err_msg); + return ERR_WITH_MSG; + } + + num_as = atoi (asnum); + if ((num_as <= 0) || (num_as > uc_info.br_info->num_as)) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, + "Broker query id(%d) is not exist.", num_as); + return ERR_WITH_MSG; + } + + if (cm_broker_as_restart (bname, num_as, &error) < 0) + { + strcpy (_dbmt_error, error.err_msg); + return ERR_WITH_MSG; + } + return ERR_NO_ERROR; +} + +int +ts_set_sysparam (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char conf_path[PATH_MAX]; + char *conf_name; + + conf_name = nv_get_val (req, "confname"); + if (conf_name == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "confname"); + return ERR_PARAM_MISSING; + } + + if (_get_confpath_by_name (conf_name, conf_path, sizeof (conf_path)) < 0) + { + strcpy (_dbmt_error, "confname error"); + return ERR_WITH_MSG; + } + + if (_write_conf_to_file (req, conf_path) < 0) + { + return ERR_TMPFILE_OPEN_FAIL; + } + + return ERR_NO_ERROR; +} + +int +ts_get_all_sysparam (nvplist *req, nvplist *res, char *_dbmt_error) +{ + FILE *infile; + char conf_path[PATH_MAX], strbuf[1024 * 200]; + char *conf_name; + + conf_name = nv_get_val (req, "confname"); + if (conf_name == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "confname"); + return ERR_PARAM_MISSING; + } + + if (_get_confpath_by_name (conf_name, conf_path, sizeof (conf_path)) < 0) + { + strcpy (_dbmt_error, "confname error"); + return ERR_WITH_MSG; + } + + if (access (conf_path, F_OK) < 0) + { + return ERR_FILE_OPEN_FAIL; + } + + infile = fopen (conf_path, "r"); + if (infile == NULL) + { + strcpy (_dbmt_error, conf_path); + return ERR_FILE_OPEN_FAIL; + } + + nv_add_nvp (res, "confname", conf_name); + nv_add_nvp (res, "open", "conflist"); + + while (fgets (strbuf, sizeof (strbuf), infile) != NULL) + { + uRemoveCRLF (strbuf); + nv_add_nvp (res, "confdata", strbuf); + } + nv_add_nvp (res, "close", "conflist"); + fclose (infile); + + return ERR_NO_ERROR; +} + +static int +_get_confpath_by_name (const char *conf_name, char *conf_path, int buflen) +{ + int retval = 0; + + if (uStringEqual (conf_name, "arniadbconf")) + { + snprintf (conf_path, buflen - 1, "%s/conf/%s", sco.szArniadb, + ARNIADB_ARNIADB_CONF); + } + else if (uStringEqual (conf_name, "cmconf")) + { + snprintf (conf_path, buflen - 1, "%s/conf/%s", sco.szArniadb, + ARNIADB_DBMT_CONF); + } + else if (uStringEqual (conf_name, "haconf")) + { + snprintf (conf_path, buflen - 1, "%s/conf/%s", sco.szArniadb, + ARNIADB_HA_CONF); + } + else if (uStringEqual (conf_name, "databases")) + { + snprintf (conf_path, buflen - 1, "%s/%s", sco.szArniadb_databases, + ARNIADB_DATABASE_TXT); + } + else + { + snprintf (conf_path, buflen - 1, "%s/conf/%s", sco.szArniadb, conf_name); + } + + return retval; +} + +static int +_write_conf_to_file (nvplist *req, char *conf_path) +{ + char *conf, *conf_data; + int nv_len, i; + FILE *outfile = NULL; + + if ((outfile = fopen (conf_path, "w")) == NULL) + { + return -1; + } + + nv_len = req->nvplist_leng; + for (i = 1; i < nv_len; i++) + { + nv_lookup (req, i, &conf, &conf_data); + if ((conf != NULL) && (strcmp (conf, "confdata") == 0)) + { + if (conf_data == NULL) + { + fprintf (outfile, "\n"); + } + else + { + fprintf (outfile, "%s\n", conf_data); + } + } + } + + fclose (outfile); + + return 0; +} + +int +tsCreateDBMTUser (nvplist *req, nvplist *res, char *_dbmt_error) +{ + int num_authinfo = 0, num_dbmt_user; + char *dbmt_id, *passwd_p; + int i, retval; + char dbmt_passwd[PASSWD_ENC_LENGTH]; + T_DBMT_USER dbmt_user; + T_DBMT_USER_AUTHINFO *authinfo = NULL; + + const char *casauth, *dbcreate, *status_monitor; + + memset (&dbmt_user, 0, sizeof (T_DBMT_USER)); + + if ((dbmt_id = nv_get_val (req, "targetid")) == NULL) + { + sprintf (_dbmt_error, "%s", "target id"); + return ERR_PARAM_MISSING; + } + if ((passwd_p = nv_get_val (req, "password")) == NULL) + { + sprintf (_dbmt_error, "%s", "password"); + return ERR_PARAM_MISSING; + } + + if (0 != IsValidUserName (dbmt_id)) + { + sprintf (_dbmt_error, + "Invalid user name!User name should begin with a letter,and can only contain letters, digits, or underscore."); + return ERR_WITH_MSG; + } + + if (strlen (passwd_p) > PASSWD_LENGTH) + { + sprintf (_dbmt_error, "invalid password!"); + return ERR_WITH_MSG; + } + + uEncrypt (PASSWD_LENGTH, passwd_p, dbmt_passwd); + + if ((retval = dbmt_user_read (&dbmt_user, _dbmt_error)) != ERR_NO_ERROR) + { + return retval; + } + num_dbmt_user = dbmt_user.num_dbmt_user; + for (i = 0; i < num_dbmt_user; i++) + { + if (strcmp (dbmt_user.user_info[i].user_name, dbmt_id) == 0) + { + dbmt_user_free (&dbmt_user); + sprintf (_dbmt_error, "%s", dbmt_id); + return ERR_DBMTUSER_EXIST; + } + } + + /* set authority info */ + if ((casauth = nv_get_val (req, "casauth")) == NULL) + { + casauth = ""; + } + authinfo = + (T_DBMT_USER_AUTHINFO *) increase_capacity (authinfo, + sizeof (T_DBMT_USER_AUTHINFO), + num_authinfo, num_authinfo + 1); + if (authinfo == NULL) + { + dbmt_user_free (&dbmt_user); + return ERR_MEM_ALLOC; + } + num_authinfo++; + dbmt_user_set_authinfo (& (authinfo[num_authinfo - 1]), "unicas", casauth); + + if ((dbcreate = nv_get_val (req, "dbcreate")) == NULL) + { + dbcreate = ""; + } + authinfo = + (T_DBMT_USER_AUTHINFO *) increase_capacity (authinfo, + sizeof (T_DBMT_USER_AUTHINFO), + num_authinfo, num_authinfo + 1); + if (authinfo == NULL) + { + dbmt_user_free (&dbmt_user); + return ERR_MEM_ALLOC; + } + num_authinfo++; + dbmt_user_set_authinfo (& (authinfo[num_authinfo - 1]), "dbcreate", dbcreate); + + if ((status_monitor = nv_get_val (req, "statusmonitorauth")) == NULL) + { + status_monitor = ""; + } + authinfo = + (T_DBMT_USER_AUTHINFO *) increase_capacity (authinfo, + sizeof (T_DBMT_USER_AUTHINFO), + num_authinfo, num_authinfo + 1); + if (authinfo == NULL) + { + dbmt_user_free (&dbmt_user); + return ERR_MEM_ALLOC; + } + num_authinfo++; + dbmt_user_set_authinfo (& (authinfo[num_authinfo - 1]), "statusmonitorauth", status_monitor); + + /* set user info */ + dbmt_user.user_info = + (T_DBMT_USER_INFO *) increase_capacity (dbmt_user.user_info, + sizeof (T_DBMT_USER_INFO), + num_dbmt_user, num_dbmt_user + 1); + if (dbmt_user.user_info == NULL) + { + dbmt_user_free (&dbmt_user); + if (authinfo != NULL) + { + free (authinfo); + } + return ERR_MEM_ALLOC; + } + num_dbmt_user++; + dbmt_user_set_userinfo (& (dbmt_user.user_info[num_dbmt_user - 1]), dbmt_id, + dbmt_passwd, num_authinfo, authinfo, 0, NULL); + dbmt_user.num_dbmt_user = num_dbmt_user; + + retval = dbmt_user_write_auth (&dbmt_user, _dbmt_error); + if (retval != ERR_NO_ERROR) + { + dbmt_user_free (&dbmt_user); + return retval; + } + dbmt_user_write_pass (&dbmt_user, _dbmt_error); + + /* add dblist */ + retval = ut_get_dblist (res, 0); + if (retval != ERR_NO_ERROR) + { + ut_error_log (req, "error while adding database lists to response"); + return retval; + } + + _tsAppendDBMTUserList (res, &dbmt_user, 0, _dbmt_error); + dbmt_user_free (&dbmt_user); + + return tsUpdateDBMTUser (req, res, _dbmt_error); +} + + +int +tsDeleteDBMTUser (nvplist *req, nvplist *res, char *_dbmt_error) +{ + T_DBMT_USER dbmt_user; + char *dbmt_id; + int i, retval, usr_index; + char file[PATH_MAX]; + + if ((dbmt_id = nv_get_val (req, "targetid")) == NULL) + { + sprintf (_dbmt_error, "%s", "target id"); + return ERR_PARAM_MISSING; + } + + if ((retval = dbmt_user_read (&dbmt_user, _dbmt_error)) != ERR_NO_ERROR) + { + return retval; + } + + usr_index = -1; + for (i = 0; i < dbmt_user.num_dbmt_user; i++) + { + if (strcmp (dbmt_user.user_info[i].user_name, dbmt_id) == 0) + { + dbmt_user.user_info[i].user_name[0] = '\0'; + usr_index = i; + break; + } + } + if (usr_index < 0) + { + strcpy (_dbmt_error, conf_get_dbmt_file2 (FID_DBMT_ARNIADB_PASS, file)); + dbmt_user_free (&dbmt_user); + return ERR_FILE_INTEGRITY; + } + + retval = dbmt_user_write_auth (&dbmt_user, _dbmt_error); + if (retval != ERR_NO_ERROR) + { + dbmt_user_free (&dbmt_user); + return retval; + } + dbmt_user_write_pass (&dbmt_user, _dbmt_error); + + /* add dblist */ + retval = ut_get_dblist (res, 0); + if (retval != ERR_NO_ERROR) + { + return retval; + } + + _tsAppendDBMTUserList (res, &dbmt_user, 0, _dbmt_error); + dbmt_user_free (&dbmt_user); + + return ERR_NO_ERROR; +} + +int +tsUpdateDBMTUser (nvplist *req, nvplist *res, char *_dbmt_error) +{ + int i, j, usr_index, retval; + int cas_idx = -1, dbcreate_idx = -1, status_monitor_idx = -1; + char *dbmt_id; + char file[PATH_MAX]; + T_DBMT_USER dbmt_user; + T_DBMT_USER_DBINFO *usr_dbinfo = NULL; + T_DBMT_USER_AUTHINFO *usr_authinfo = NULL; + int num_dbinfo = 0, num_authinfo = 0; + char *z_name, *z_value; + char *dbname, *dbid, *dbpassword, *casauth, *dbcreate, *status_monitor; + char *broker_address; + + int is_update_auth = 0; + + memset (&dbmt_user, 0, sizeof (T_DBMT_USER)); + + if ((dbmt_id = nv_get_val (req, "targetid")) == NULL) + { + sprintf (_dbmt_error, "%s", "target id"); + return ERR_PARAM_MISSING; + } + + for (i = 0; i < req->nvplist_leng; ++i) + { + dbname = dbid = dbpassword = NULL; + broker_address = NULL; + + nv_lookup (req, i, &z_name, &z_value); + + if (uStringEqual (z_name, "open") + && uStringEqual (z_value, "authoritylist")) + { + is_update_auth = 1; + continue; + } + + if (uStringEqual (z_name, "open") && uStringEqual (z_value, "dbauth")) + { + nv_lookup (req, ++i, &z_name, &z_value); + while (!uStringEqual (z_name, "close")) + { + if (uStringEqual (z_name, "dbname")) + { + dbname = z_value; + } + else if (uStringEqual (z_name, "dbid")) + { + dbid = z_value; + } + else if (uStringEqual (z_name, "dbpassword")) + { + dbpassword = z_value; + } + else if (uStringEqual (z_name, "dbbrokeraddress")) + { + broker_address = z_value; + } + else + { + if (usr_dbinfo != NULL) + { + free (usr_dbinfo); + } + return ERR_REQUEST_FORMAT; + } + nv_lookup (req, ++i, &z_name, &z_value); + if (i >= req->nvplist_leng) + { + break; + } + } + } + if (dbname == NULL || dbid == NULL) + { + continue; + } + usr_dbinfo = + (T_DBMT_USER_DBINFO *) increase_capacity (usr_dbinfo, + sizeof (T_DBMT_USER_DBINFO), + num_dbinfo, num_dbinfo + 1); + if (usr_dbinfo == NULL) + { + return ERR_MEM_ALLOC; + } + num_dbinfo++; + dbmt_user_set_dbinfo (& (usr_dbinfo[num_dbinfo - 1]), dbname, "admin", + dbid, broker_address); + } + + if ((casauth = nv_get_val (req, "casauth")) != NULL) + { + cas_idx = num_authinfo; + + } + if ((dbcreate = nv_get_val (req, "dbcreate")) != NULL) + { + dbcreate_idx = num_authinfo + 1; + + } + if ((status_monitor = nv_get_val (req, "statusmonitorauth")) != NULL) + { + status_monitor_idx = num_authinfo + 2; + + } + + if ((casauth != NULL) || (dbcreate != NULL)) + { + usr_authinfo = + (T_DBMT_USER_AUTHINFO *) increase_capacity (usr_authinfo, + sizeof (T_DBMT_USER_AUTHINFO), + num_authinfo, num_authinfo + 3); + if (usr_authinfo == NULL) + { + free (usr_dbinfo); + return ERR_MEM_ALLOC; + } + num_authinfo += 3; + } + + if (casauth != NULL && cas_idx >= 0) + { + dbmt_user_set_authinfo (& (usr_authinfo[cas_idx]), "unicas", casauth); + } + if (dbcreate != NULL && dbcreate_idx >= 0) + { + dbmt_user_set_authinfo (& (usr_authinfo[dbcreate_idx]), "dbcreate", dbcreate); + } + if (status_monitor != NULL && status_monitor_idx >= 0) + { + dbmt_user_set_authinfo (& (usr_authinfo[status_monitor_idx]), + "statusmonitorauth", status_monitor); + } + + if ((retval = dbmt_user_read (&dbmt_user, _dbmt_error)) != ERR_NO_ERROR) + { + if (usr_dbinfo != NULL) + { + free (usr_dbinfo); + } + if (usr_authinfo != NULL) + { + free (usr_authinfo); + } + return retval; + } + + usr_index = -1; + for (i = 0; i < dbmt_user.num_dbmt_user; i++) + { + if (strcmp (dbmt_user.user_info[i].user_name, dbmt_id) == 0) + { + usr_index = i; + break; + } + } + if (usr_index < 0) + { + strcpy (_dbmt_error, conf_get_dbmt_file2 (FID_DBMT_ARNIADB_PASS, file)); + dbmt_user_free (&dbmt_user); + if (usr_dbinfo != NULL) + { + free (usr_dbinfo); + } + if (usr_authinfo != NULL) + { + free (usr_authinfo); + } + return ERR_FILE_INTEGRITY; + } + + /* auth info */ + if (dbmt_user.user_info[usr_index].authinfo == NULL) + { + dbmt_user.user_info[usr_index].num_authinfo = num_authinfo; + dbmt_user.user_info[usr_index].authinfo = usr_authinfo; + usr_authinfo = NULL; + + } + else if (usr_authinfo != NULL) + { + T_DBMT_USER_INFO *current_user_info = + (T_DBMT_USER_INFO *) & (dbmt_user.user_info[usr_index]); + + for (j = 0; j < num_authinfo; j++) + { + int find_idx = -1; + for (i = 0; i < current_user_info->num_authinfo; i++) + { + if (strcmp (current_user_info->authinfo[i].domain, usr_authinfo[j].domain) == 0) + { + find_idx = i; + break; + } + } + if (find_idx == -1) + { + current_user_info->authinfo = + (T_DBMT_USER_AUTHINFO *) increase_capacity (current_user_info->authinfo, + sizeof (T_DBMT_USER_AUTHINFO), + current_user_info->num_authinfo, + current_user_info->num_authinfo + 1); + if (current_user_info->authinfo == NULL) + { + if (usr_dbinfo) + { + free (usr_dbinfo); + } + if (usr_authinfo) + { + free (usr_authinfo); + } + return ERR_MEM_ALLOC; + } + current_user_info->num_authinfo++; + find_idx = current_user_info->num_authinfo - 1; + } + dbmt_user_set_authinfo (& (current_user_info->authinfo[find_idx]), + usr_authinfo[j].domain, usr_authinfo[j].auth); + } + } + + /* db info */ + if (dbmt_user.user_info[usr_index].dbinfo == NULL) + { + dbmt_user.user_info[usr_index].num_dbinfo = num_dbinfo; + dbmt_user.user_info[usr_index].dbinfo = usr_dbinfo; + usr_dbinfo = NULL; + + } + else if (usr_dbinfo != NULL) + { + T_DBMT_USER_INFO *current_user_info = + (T_DBMT_USER_INFO *) & (dbmt_user.user_info[usr_index]); + + for (j = 0; j < num_dbinfo; j++) + { + int find_idx = -1; + for (i = 0; i < current_user_info->num_dbinfo; i++) + { + if (strcmp (current_user_info->dbinfo[i].dbname, usr_dbinfo[j].dbname) == 0) + { + find_idx = i; + break; + } + } + if (find_idx == -1) + { + current_user_info->dbinfo = + (T_DBMT_USER_DBINFO *) increase_capacity (current_user_info->dbinfo, + sizeof (T_DBMT_USER_DBINFO), + current_user_info->num_dbinfo, + current_user_info->num_dbinfo + 1); + if (current_user_info->dbinfo == NULL) + { + FREE_MEM (usr_dbinfo); + FREE_MEM (usr_authinfo); + return ERR_MEM_ALLOC; + } + current_user_info->num_dbinfo++; + find_idx = current_user_info->num_dbinfo - 1; + } + dbmt_user_set_dbinfo (& (current_user_info->dbinfo[find_idx]), + usr_dbinfo[j].dbname, usr_dbinfo[j].auth, + usr_dbinfo[j].uid, usr_dbinfo[j].broker_address); + } + } + + retval = dbmt_user_write_auth (&dbmt_user, _dbmt_error); + if (retval != ERR_NO_ERROR) + { + dbmt_user_free (&dbmt_user); + if (usr_dbinfo) + { + free (usr_dbinfo); + } + if (usr_authinfo) + { + free (usr_authinfo); + } + return retval; + } + + /* add dblist */ + retval = ut_get_dblist (res, 0); + if (retval != ERR_NO_ERROR) + { + return retval; + } + + _tsAppendDBMTUserList (res, &dbmt_user, 0, _dbmt_error); + dbmt_user_free (&dbmt_user); + if (usr_dbinfo) + { + free (usr_dbinfo); + } + if (usr_authinfo) + { + free (usr_authinfo); + } + return ERR_NO_ERROR; +} + +int +tsChangeDBMTUserPasswd (nvplist *req, nvplist *res, char *_dbmt_error) +{ + T_DBMT_USER dbmt_user; + int i, retval, usr_index; + char *dbmt_id, *new_passwd; + char file[PATH_MAX]; + + if ((dbmt_id = nv_get_val (req, "targetid")) == NULL) + { + sprintf (_dbmt_error, "%s", "target id"); + return ERR_PARAM_MISSING; + } + if ((new_passwd = nv_get_val (req, "newpassword")) == NULL) + { + sprintf (_dbmt_error, "%s", "new password"); + return ERR_PARAM_MISSING; + } + + if (!strcmp (new_passwd, "")) + { + sprintf (_dbmt_error, "%s", "NULL password"); + return ERR_WITH_MSG; + } + + if ((retval = dbmt_user_read (&dbmt_user, _dbmt_error)) != ERR_NO_ERROR) + { + return retval; + } + usr_index = -1; + for (i = 0; i < dbmt_user.num_dbmt_user; i++) + { + if (strcmp (dbmt_user.user_info[i].user_name, dbmt_id) == 0) + { + if (new_passwd == NULL) + { + dbmt_user.user_info[i].user_passwd[0] = '\0'; + } + else + { + char hexacoded[PASSWD_ENC_LENGTH]; + + uEncrypt (PASSWD_LENGTH, new_passwd, hexacoded); + strcpy (dbmt_user.user_info[i].user_passwd, hexacoded); + } + usr_index = i; + break; + } + } + if (usr_index < 0) + { + strcpy (_dbmt_error, conf_get_dbmt_file2 (FID_DBMT_ARNIADB_PASS, file)); + dbmt_user_free (&dbmt_user); + return ERR_FILE_INTEGRITY; + } + + retval = dbmt_user_write_pass (&dbmt_user, _dbmt_error); + if (retval != ERR_NO_ERROR) + { + dbmt_user_free (&dbmt_user); + return retval; + } + + /* add dblist */ + retval = ut_get_dblist (res, 0); + if (retval != ERR_NO_ERROR) + { + return retval; + } + + _tsAppendDBMTUserList (res, &dbmt_user, 0, _dbmt_error); + dbmt_user_free (&dbmt_user); + + return ERR_NO_ERROR; +} + + +int +tsGetDBMTUserInfo (nvplist *req, nvplist *res, char *_dbmt_error) +{ + T_DBMT_USER dbmt_user; + int retval; + + retval = ut_get_dblist (res, 0); + if (retval != ERR_NO_ERROR) + { + return retval; + } + retval = dbmt_user_read (&dbmt_user, _dbmt_error); + if (retval != ERR_NO_ERROR) + { + return retval; + } + _tsAppendDBMTUserList (res, &dbmt_user, 1, _dbmt_error); + dbmt_user_free (&dbmt_user); + + return ERR_NO_ERROR; +} + +int +tsCreateDB (nvplist *req, nvplist *res, char *_dbmt_error) +{ + int retval = ERR_NO_ERROR; + char *dbname = NULL; + char *dbmt_user_name = NULL; + char *charset = NULL; + + char *dbpagenum = NULL; + char *dbpagesize = NULL; + char *logpagenum = NULL; + char *logpagesize = NULL; + char dbvolsize[512]; + char logvolsize[512]; + + char *genvolpath = NULL; + char *logvolpath = NULL; +#if defined(WINDOWS) + char logvolpath_buf[1024]; +#endif + char *overwrite_config_file = NULL; + char targetdir[PATH_MAX]; + char extvolfile[PATH_MAX]; + char createdb_err_file[PATH_MAX]; + char *ip, *port; + T_DBMT_USER dbmt_user; + T_DBMT_CON_DBINFO con_dbinfo; + char cmd_name[ARNIADB_CMD_NAME_LEN]; + const char *argv[20]; + int argc = 0; + int gen_dir_created, log_dir_created, ext_dir_created; + + targetdir[0] = '\0'; + extvolfile[0] = '\0'; + createdb_err_file[0] = '\0'; + + gen_dir_created = log_dir_created = ext_dir_created = 0; + + if ((dbname = nv_get_val (req, "dbname")) == NULL) + { + strcpy (_dbmt_error, "database name"); + return ERR_PARAM_MISSING; + } + + if ((dbpagenum = nv_get_val (req, "numpage")) == NULL) + { + strcpy (_dbmt_error, "numpage"); + return ERR_PARAM_MISSING; + } + + if ((dbpagesize = nv_get_val (req, "pagesize")) == NULL) + { + strcpy (_dbmt_error, "pagesize"); + return ERR_PARAM_MISSING; + } + + if ((logpagenum = nv_get_val (req, "logsize")) == NULL) + { + strcpy (_dbmt_error, "logsize"); + return ERR_PARAM_MISSING; + } + + if ((logpagesize = nv_get_val (req, "logpagesize")) == NULL) + { + strcpy (_dbmt_error, "logpagesize"); + return ERR_PARAM_MISSING; + } + + if ((dbmt_user_name = nv_get_val (req, "_ID")) == NULL) + { + strcpy (_dbmt_error, "_ID"); + return ERR_PARAM_MISSING; + } + + if ((charset = nv_get_val (req, "charset")) == NULL) + { + strcpy (_dbmt_error, "charset"); + return ERR_PARAM_MISSING; + } + + genvolpath = nv_get_val (req, "genvolpath"); + logvolpath = nv_get_val (req, "logvolpath"); + overwrite_config_file = nv_get_val (req, "overwrite_config_file"); + + if (genvolpath == NULL) + { + strcpy (_dbmt_error, "volumn path"); + return ERR_PARAM_MISSING; + } + + if ((retval = check_dbpath (genvolpath, _dbmt_error)) != ERR_NO_ERROR) + { + return retval; + } + + if (logvolpath != NULL && logvolpath[0] == '\0') + { + logvolpath = NULL; + } + + if (logvolpath != NULL + && (retval = check_dbpath (logvolpath, _dbmt_error)) != ERR_NO_ERROR) + { + return retval; + } + + /* caculate dbvolsize & logvolsize */ + snprintf (dbvolsize, sizeof (dbvolsize) - 1, "%lldB", + ((long long) atoi (dbpagesize) * (long long) atoi (dbpagenum))); + snprintf (logvolsize, sizeof (logvolsize) - 1, "%lldB", + ((long long) atoi (logpagesize) * (long long) atoi (logpagenum))); + + /* create directory */ + strcpy (targetdir, genvolpath); + if (access (genvolpath, F_OK) < 0) + { + retval = uCreateDir (genvolpath); + if (retval != ERR_NO_ERROR) + { + return retval; + } + else + { + gen_dir_created = 1; + } + } + + if (logvolpath != NULL && access (logvolpath, F_OK) < 0) + { + retval = uCreateDir (logvolpath); + if (retval != ERR_NO_ERROR) + { + return retval; + } + else + { + log_dir_created = 1; + } + } + + if (access (genvolpath, W_OK) < 0) + { + sprintf (_dbmt_error, "%s: %s\n", genvolpath, strerror (errno)); + return ERR_WITH_MSG; + } + + if (logvolpath != NULL && access (logvolpath, W_OK) < 0) + { + sprintf (_dbmt_error, "%s: %s\n", genvolpath, strerror (errno)); + return ERR_WITH_MSG; + } + + /* copy config file to the directory and update config file */ + if ((overwrite_config_file == NULL) /* for backword compatibility */ + || (strcasecmp (overwrite_config_file, "NO") != 0)) + { + char strbuf[1024]; + FILE *infile = NULL; + FILE *outfile = NULL; + char dstrbuf[PATH_MAX]; + +#if !defined (DO_NOT_USE_ARNIADBENV) + snprintf (dstrbuf, PATH_MAX - 1, "%s/conf/%s", sco.szArniadb, + ARNIADB_ARNIADB_CONF); +#else + snprintf (dstrbuf, PATH_MAX - 1, "%s/%s", ARNIADB_CONFDIR, + ARNIADB_ARNIADB_CONF); +#endif + infile = fopen (dstrbuf, "r"); + if (infile == NULL) + { + strcpy (_dbmt_error, dstrbuf); + return ERR_FILE_OPEN_FAIL; + } + + snprintf (dstrbuf, PATH_MAX - 1, "%s/%s", targetdir, ARNIADB_ARNIADB_CONF); + outfile = fopen (dstrbuf, "w"); + if (outfile == NULL) + { + fclose (infile); + strcpy (_dbmt_error, dstrbuf); + return ERR_FILE_OPEN_FAIL; + } + + while (fgets (strbuf, sizeof (strbuf), infile)) + { + const char *param; + + param = "data_buffer_pages"; + if (!strncmp (strbuf, param, strlen (param)) + && nv_get_val (req, param)) + { + fprintf (outfile, "%s=%s\n", param, nv_get_val (req, param)); + continue; + } + + param = "media_failure_support"; + if (!strncmp (strbuf, param, strlen (param)) + && nv_get_val (req, param)) + { + fprintf (outfile, "%s=%s\n", param, nv_get_val (req, param)); + continue; + } + + param = "max_clients"; + if (!strncmp (strbuf, param, strlen (param)) + && nv_get_val (req, param)) + { + fprintf (outfile, "%s=%s\n", param, nv_get_val (req, param)); + continue; + } + + fputs (strbuf, outfile); + } + fclose (infile); + fclose (outfile); + } + + /* remove warning out of space message. + * judge creation failed if created page size is smaller then + * 343 page, write message with volumn expend to error file. + */ + if (0) + { + FILE *infile = NULL; + FILE *outfile = NULL; + char oldfilename[PATH_MAX]; + char newfilename[PATH_MAX]; + memset (oldfilename, '\0', sizeof (oldfilename)); + memset (newfilename, '\0', sizeof (newfilename)); + + snprintf (oldfilename, PATH_MAX - 1, "%s/%s", targetdir, + ARNIADB_ARNIADB_CONF); + infile = fopen (oldfilename, "r"); + if (infile == NULL) + { + strcpy (_dbmt_error, oldfilename); + return ERR_FILE_OPEN_FAIL; + } + + snprintf (newfilename, PATH_MAX - 1, "%s/temparniadb.conf", targetdir); + outfile = fopen (newfilename, "w"); + if (outfile == NULL) + { + fclose (infile); + strcpy (_dbmt_error, newfilename); + return ERR_FILE_OPEN_FAIL; + } + + fclose (infile); + fclose (outfile); + + unlink (oldfilename); + rename (newfilename, oldfilename); + } + + /* construct spec file */ + if (1) + { + int pos, len, i; + char *tn, *tv; + FILE *outfile; + char buf[1024], *val[3]; +#if defined(WINDOWS) + char val2_buf[1024]; +#endif + + snprintf (extvolfile, PATH_MAX - 1, "%s/extvol.spec", targetdir); + outfile = fopen (extvolfile, "w"); + if (outfile == NULL) + { + strcpy (_dbmt_error, extvolfile); + return ERR_FILE_OPEN_FAIL; + } + + nv_locate (req, "exvol", &pos, &len); + for (i = pos; i < len + pos; ++i) + { + nv_lookup (req, i, &tn, &tv); + if (tv == NULL) + { + continue; + } + strcpy (buf, tv); + if (string_tokenize2 (buf, val, 3, ';') < 0) + { + continue; + } + +#if defined(WINDOWS) + val[2] = nt_style_path (val[2], val2_buf); +#endif + fprintf (outfile, "NAME %s PATH %s PURPOSE %s NPAGES %s\n\n", + tn, val[2], val[0], val[1]); + /* create directory, if needed */ + if (access (val[2], F_OK) < 0) + { + retval = uCreateDir (val[2]); + if (retval != ERR_NO_ERROR) + { + fclose (outfile); + return retval; + } + else + { + ext_dir_created = 1; + } + } + } + fclose (outfile); + } + + /* construct command */ + arniadb_cmd_name (cmd_name); +#if defined(WINDOWS) + nt_style_path (targetdir, targetdir); +#endif + argv[argc++] = cmd_name; + argv[argc++] = UTIL_OPTION_CREATEDB; + + argv[argc++] = "--" CREATE_FILE_PATH_L; + argv[argc++] = targetdir; + + argv[argc++] = "--" CREATE_DB_VOLUMN_SIZE_L; + argv[argc++] = dbvolsize; + + argv[argc++] = "--" CREATE_LOG_VOLUMN_SIZE_L; + argv[argc++] = logvolsize; + + if (dbpagesize) + { + argv[argc++] = "--" CREATE_DB_PAGE_SIZE_L; + argv[argc++] = dbpagesize; + } + if (logpagesize) + { + argv[argc++] = "--" CREATE_LOG_PAGE_SIZE_L; + argv[argc++] = logpagesize; + } + if (logvolpath) + { +#if defined(WINDOWS) + logvolpath = nt_style_path (logvolpath, logvolpath_buf); + /* + remove_end_of_dir_ch(logvolpath); + */ +#endif + argv[argc++] = "--" CREATE_LOG_PATH_L; + argv[argc++] = logvolpath; + } + if (extvolfile[0] != '\0') + { + argv[argc++] = "--" CREATE_MORE_VOLUME_FILE_L; + argv[argc++] = extvolfile; + } + + argv[argc++] = dbname; + argv[argc++] = charset; + argv[argc++] = NULL; + + snprintf (createdb_err_file, PATH_MAX, "%s/createdb_err_file.%d.tmp", + sco.dbmt_tmp_dir, (int) getpid ()); + + retval = run_child (argv, 1, NULL, NULL, createdb_err_file, NULL); /* createdb */ + + if (read_error_file (createdb_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) + { + int pos, len, i; + char *tn, *tv; + char buf[1024], *val[3]; + + if ((access (genvolpath, F_OK) == 0) && (gen_dir_created)) + { + uRemoveDir (genvolpath, REMOVE_DIR_FORCED); + } + if ((logvolpath != NULL) && (access (logvolpath, F_OK) == 0) + && (log_dir_created)) + { + uRemoveDir (logvolpath, REMOVE_DIR_FORCED); + } + + nv_locate (req, "exvol", &pos, &len); + for (i = pos; i < len + pos; ++i) + { + nv_lookup (req, i, &tn, &tv); + if (tv == NULL) + { + continue; + } + strcpy (buf, tv); + if (string_tokenize2 (buf, val, 3, ';') < 0) + { + continue; + } + if ((access (val[2], F_OK) == 0) && (ext_dir_created)) + { + uRemoveDir (val[2], REMOVE_DIR_FORCED); /* ext vol path */ + } + } + unlink (createdb_err_file); + return ERR_WITH_MSG; + } + unlink (createdb_err_file); + + if (retval < 0) + { + int pos, len, i; + char *tn, *tv; + char buf[1024], *val[3]; + + if (access (genvolpath, F_OK) == 0) + { + uRemoveDir (genvolpath, REMOVE_DIR_FORCED); + } + if (logvolpath != NULL && access (logvolpath, F_OK) == 0) + { + uRemoveDir (logvolpath, REMOVE_DIR_FORCED); + } + + nv_locate (req, "exvol", &pos, &len); + for (i = pos; i < len + pos; ++i) + { + nv_lookup (req, i, &tn, &tv); + if (tv == NULL) + { + continue; + } + strcpy (buf, tv); + if (string_tokenize2 (buf, val, 3, ';') < 0) + { + continue; + } + if (access (val[2], F_OK) == 0) + { + uRemoveDir (val[2], REMOVE_DIR_FORCED); /* ext vol path */ + } + } + + sprintf (_dbmt_error, "%s", argv[0]); + return ERR_SYSTEM_CALL; + } + + /* add dbinfo to cmdb.pass */ + if (dbmt_user_read (&dbmt_user, _dbmt_error) == ERR_NO_ERROR) + { + int i; + T_DBMT_USER_DBINFO tmp_dbinfo; + + memset (&tmp_dbinfo, 0, sizeof (tmp_dbinfo)); + dbmt_user_set_dbinfo (&tmp_dbinfo, dbname, dbmt_user_name, "dba", ""); + + dbmt_user_db_delete (&dbmt_user, dbname); + for (i = 0; i < dbmt_user.num_dbmt_user; i++) + { + if (strcmp (dbmt_user.user_info[i].user_name, dbmt_user_name) == 0) + { + if (dbmt_user_add_dbinfo + (& (dbmt_user.user_info[i]), &tmp_dbinfo) == ERR_NO_ERROR) + { + dbmt_user_write_auth (&dbmt_user, _dbmt_error); + } + break; + } + } + dbmt_user_free (&dbmt_user); + } + + /* add dbinfo to conlist */ + memset (&con_dbinfo, 0, sizeof (con_dbinfo)); + dbmt_con_set_dbinfo (&con_dbinfo, dbname, "dba", ""); + ip = nv_get_val (req, "_IP"); + port = nv_get_val (req, "_PORT"); + dbmt_con_write_dbinfo (&con_dbinfo, ip, port, dbname, 1, _dbmt_error); + + /* restore warn out of space value */ + if (0) + { + char strbuf[1024]; + FILE *infile = NULL; + FILE *outfile = NULL; + char oldfilename[PATH_MAX]; + char newfilename[PATH_MAX]; + memset (oldfilename, '\0', sizeof (oldfilename)); + memset (newfilename, '\0', sizeof (newfilename)); + + snprintf (oldfilename, PATH_MAX - 1, "%s/%s", targetdir, + ARNIADB_ARNIADB_CONF); + infile = fopen (oldfilename, "r"); + if (infile == NULL) + { + strcpy (_dbmt_error, oldfilename); + return ERR_FILE_OPEN_FAIL; + } + + snprintf (newfilename, PATH_MAX - 1, "%s/temparniadb.conf", targetdir); + outfile = fopen (newfilename, "w"); + if (outfile == NULL) + { + fclose (infile); + strcpy (_dbmt_error, newfilename); + return ERR_FILE_OPEN_FAIL; + } + + while (fgets (strbuf, sizeof (strbuf), infile)) + { + const char *p; + p = "warn_outofspace_factor"; + if (!strncmp (strbuf, p, strlen (p))) + { + fprintf (outfile, "%s", p); + continue; + } + + fputs (strbuf, outfile); + } + fclose (infile); + fclose (outfile); + + unlink (oldfilename); + rename (newfilename, oldfilename); + } + + if ((overwrite_config_file == NULL) /* for backward compatibility */ + || (strcasecmp (overwrite_config_file, "NO") != 0)) + { + char strbuf[PATH_MAX]; + + snprintf (strbuf, PATH_MAX - 1, "%s/%s", targetdir, ARNIADB_ARNIADB_CONF); + unlink (strbuf); + } + + if (extvolfile[0] != '\0') + { + unlink (extvolfile); + } + return ERR_NO_ERROR; +} + +int +tsDeleteDB (nvplist *req, nvplist *res, char *_dbmt_error) +{ + T_DBMT_USER dbmt_user; + int retval = ERR_NO_ERROR; + char *dbname = NULL, *delbackup; + char arniadb_err_file[PATH_MAX]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; + const char *argv[6]; + int argc = 0; + + /*dbvol path & db log path. */ + char dbvolpath[PATH_MAX]; + char dblogpath[PATH_MAX]; + + arniadb_err_file[0] = '\0'; + + if ((dbname = nv_get_val (req, "_DBNAME")) == NULL) + { + sprintf (_dbmt_error, "%s", "database name"); + return ERR_PARAM_MISSING; + } + + if (_isRegisteredDB (dbname) == 0) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", dbname); + return ERR_DB_NONEXISTANT; + } + + delbackup = nv_get_val (req, "delbackup"); + + arniadb_cmd_name (cmd_name); + argv[argc++] = cmd_name; + argv[argc++] = UTIL_OPTION_DELETEDB; + if (uStringEqual (delbackup, "y")) + { + argv[argc++] = "--" DELETE_DELETE_BACKUP_L; + } + argv[argc++] = dbname; + argv[argc++] = NULL; + + snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", + sco.dbmt_tmp_dir, "deletedb", getpid ()); + + /*get dbvolpath and dblogpath. */ + get_dbvoldir (dbvolpath, sizeof (dbvolpath), dbname, arniadb_err_file); + get_dblogdir (dblogpath, sizeof (dblogpath), dbname, arniadb_err_file); + + retval = run_child (argv, 1, NULL, NULL, arniadb_err_file, NULL); /* deletedb */ + + if (read_error_file (arniadb_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) + { + if (access (arniadb_err_file, F_OK) == 0) + { + unlink (arniadb_err_file); + } + return ERR_WITH_MSG; + } + if (access (arniadb_err_file, F_OK) == 0) + { + unlink (arniadb_err_file); + } + if (retval < 0) + { + strcpy (_dbmt_error, argv[0]); + return ERR_SYSTEM_CALL; + } + + auto_conf_addvol_delete (FID_AUTO_ADDVOLDB_CONF, dbname); + auto_conf_backup_delete (FID_AUTO_BACKUPDB_CONF, dbname); + auto_conf_history_delete (FID_AUTO_HISTORY_CONF, dbname); + auto_conf_execquery_delete (FID_AUTO_EXECQUERY_CONF, dbname); + + if (dbmt_user_read (&dbmt_user, _dbmt_error) == ERR_NO_ERROR) + { + dbmt_user_db_delete (&dbmt_user, dbname); + dbmt_user_write_auth (&dbmt_user, _dbmt_error); + dbmt_user_free (&dbmt_user); + } + + /* The following delete sequence can delete folder hierarchy like : + * / + * and /. + */ + rmdir (dbvolpath); + rmdir (dblogpath); + rmdir (dbvolpath); + + return ERR_NO_ERROR; +} + +int +tsRenameDB (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char *dbname = NULL; + char *newdbname = NULL; + char *exvolpath = NULL; + char *advanced = NULL; + char *forcedel = NULL; + char task_name[TASKNAME_LEN]; + + const char *argv[10]; + + int argc = 0; + int retval = 0; + T_DB_SERVICE_MODE db_mode; + T_DBMT_USER dbmt_user; + + char cmd_name[ARNIADB_CMD_NAME_LEN]; + char tmpfile[PATH_MAX]; + + cmd_name[0] = '\0'; + tmpfile[0] = '\0'; + task_name[0] = '\0'; + + if ((dbname = nv_get_val (req, "_DBNAME")) == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "dbname"); + return ERR_PARAM_MISSING; + } + if ((newdbname = nv_get_val (req, "rename")) == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "rename"); + return ERR_PARAM_MISSING; + } + if ((exvolpath = nv_get_val (req, "exvolpath")) == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "exvolpath"); + return ERR_PARAM_MISSING; + } + if ((advanced = nv_get_val (req, "advanced")) == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "advanced"); + return ERR_PARAM_MISSING; + } + if ((forcedel = nv_get_val (req, "forcedel")) == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "forcedel"); + return ERR_PARAM_MISSING; + } + + db_mode = uDatabaseMode (dbname, NULL); + if (db_mode == DB_SERVICE_MODE_SA) + { + sprintf (_dbmt_error, "%s", dbname); + return ERR_STANDALONE_MODE; + } + else if (db_mode == DB_SERVICE_MODE_CS) + { + sprintf (_dbmt_error, "%s", dbname); + return ERR_DB_ACTIVE; + } + + arniadb_cmd_name (cmd_name); + argv[argc++] = cmd_name; + argv[argc++] = UTIL_OPTION_RENAMEDB; + + if (uStringEqual (advanced, "on")) + { + FILE *outfile; + int i, flag = 0, line = 0; + char *n, *v; +#if defined(WINDOWS) + char n_buf[1024], v_buf[1024]; +#endif + char *p; + + snprintf (tmpfile, PATH_MAX - 1, "%s/DBMT_task_%d.%d", sco.dbmt_tmp_dir, + TS_RENAMEDB, (int) getpid ()); + if ((outfile = fopen (tmpfile, "w")) == NULL) + { + return ERR_TMPFILE_OPEN_FAIL; + } + for (i = 0; i < req->nvplist_leng; i++) + { + nv_lookup (req, i, &n, &v); + if (n == NULL || v == NULL) + { + fclose (outfile); + if (v != NULL) + { + strcpy (_dbmt_error, v); + return ERR_DIR_CREATE_FAIL; + } + else + { + strcpy (_dbmt_error, "Lost all parameters."); + return ERR_WITH_MSG; + } + } + + if (!strcmp (n, "open") && !strcmp (v, "volume")) + { + flag = 1; + } + else if (!strcmp (n, "close") && !strcmp (v, "volume")) + { + flag = 0; + break; + } + else if (flag == 1) + { +#if defined(WINDOWS) + replace_colon (n); + replace_colon (v); +#endif + p = strrchr (v, '/'); + if (p) + { + *p = '\0'; + } + if (uCreateDir (v) != ERR_NO_ERROR) + { + fclose (outfile); + strcpy (_dbmt_error, v); + return ERR_DIR_CREATE_FAIL; + } + if (p) + { + *p = '/'; + } +#if defined(WINDOWS) + n = nt_style_path (n, n_buf); + v = nt_style_path (v, v_buf); +#endif + fprintf (outfile, "%d %s %s\n", line++, n, v); + + } /* close "else if (flag == 1)" */ + } /* close "for" loop */ + fclose (outfile); + argv[argc++] = "--" RENAME_CONTROL_FILE_L; + argv[argc++] = tmpfile; + } /* close "if (adv_flag != NULL)" */ + else if (exvolpath != NULL && !uStringEqual (exvolpath, "none")) + { + if (uCreateDir (exvolpath) != ERR_NO_ERROR) + { + strcpy (_dbmt_error, exvolpath); + return ERR_DIR_CREATE_FAIL; + } + argv[argc++] = "--" RENAME_EXTENTED_VOLUME_PATH_L; + argv[argc++] = exvolpath; + } + + if (uStringEqual (forcedel, "y")) + { + argv[argc++] = "--" RENAME_DELETE_BACKUP_L; + } + + argv[argc++] = dbname; + argv[argc++] = newdbname; + argv[argc++] = NULL; + + strncpy (task_name, "renamedb", TASKNAME_LEN); + retval = _run_child (argv, 1, task_name, NULL, _dbmt_error); + if (retval != ERR_NO_ERROR) + { + return retval; + } + + auto_conf_addvol_rename (FID_AUTO_ADDVOLDB_CONF, dbname, newdbname); + auto_conf_backup_rename (FID_AUTO_BACKUPDB_CONF, dbname, newdbname); + auto_conf_history_rename (FID_AUTO_HISTORY_CONF, dbname, newdbname); + auto_conf_execquery_rename (FID_AUTO_EXECQUERY_CONF, dbname, newdbname); + + if (dbmt_user_read (&dbmt_user, _dbmt_error) == ERR_NO_ERROR) + { + int i, j; + for (i = 0; i < dbmt_user.num_dbmt_user; i++) + { + for (j = 0; j < dbmt_user.user_info[i].num_dbinfo; j++) + { + if (strcmp (dbmt_user.user_info[i].dbinfo[j].dbname, dbname) == 0) + { + strcpy (dbmt_user.user_info[i].dbinfo[j].dbname, newdbname); + } + } + } + dbmt_user_write_auth (&dbmt_user, _dbmt_error); + dbmt_user_free (&dbmt_user); + } + + return ERR_NO_ERROR; +} + +int +tsStartDB (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char *dbname; + char err_buf[ERR_MSG_SIZE]; + T_DB_SERVICE_MODE db_mode; + int retval; + + if ((dbname = nv_get_val (req, "_DBNAME")) == NULL) + { + sprintf (_dbmt_error, "%s", "database name"); + return ERR_PARAM_MISSING; + } + + db_mode = uDatabaseMode (dbname, NULL); + if (db_mode == DB_SERVICE_MODE_SA) + { + sprintf (_dbmt_error, "%s", dbname); + return ERR_STANDALONE_MODE; + } + if (db_mode == DB_SERVICE_MODE_CS) + { + return ERR_NO_ERROR; + } + + retval = cmd_start_server (dbname, err_buf, sizeof (err_buf)); + if (retval < 0) + { + DBMT_ERR_MSG_SET (_dbmt_error, err_buf); + return ERR_WITH_MSG; + } + else if (retval == 1) + { + DBMT_ERR_MSG_SET (_dbmt_error, err_buf); + } + + /* recount active db num and write to file */ + uWriteDBnfo (); + + return retval == 0 ? ERR_NO_ERROR : ERR_WARNING; +} + +int +tsStopDB (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char *dbname; + + if ((dbname = nv_get_val (req, "_DBNAME")) == NULL) + { + sprintf (_dbmt_error, "%s", "database name"); + return ERR_PARAM_MISSING; + } + + if (cmd_stop_server (dbname, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) + { + return ERR_WITH_MSG; + } + + /* recount active db num and write to file */ + uWriteDBnfo (); + + return ERR_NO_ERROR; +} + +int +tsDbspaceInfo (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char *dbname = NULL; + int retval = ERR_NO_ERROR; + const char *err_message; + char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; + int ha_mode = 0; + T_ARNIADB_MODE arniadb_mode; + GeneralSpacedbResult *cmd_res; + T_DB_SERVICE_MODE db_mode; + + /* get dbname */ + if ((dbname = nv_get_val (req, "_DBNAME")) == NULL) + { + sprintf (_dbmt_error, "%s", "database name"); + return ERR_PARAM_MISSING; + } + + db_mode = uDatabaseMode (dbname, &ha_mode); + if (db_mode == DB_SERVICE_MODE_SA) + { + sprintf (_dbmt_error, "%s", dbname); + return ERR_STANDALONE_MODE; + } + + nv_add_nvp (res, "dbname", dbname); + nv_add_nvp (res, "pagesize", "-1"); + nv_add_nvp (res, "logpagesize", "-1"); + + arniadb_mode = + (db_mode == DB_SERVICE_MODE_NONE) ? ARNIADB_MODE_SA : ARNIADB_MODE_CS; + + if (ha_mode != 0) + { + append_host_to_dbname (dbname_at_hostname, dbname, sizeof (dbname_at_hostname)); + cmd_res = cmd_spacedb (dbname_at_hostname, arniadb_mode); + } + else + { + cmd_res = cmd_spacedb (dbname, arniadb_mode); + } + + err_message = cmd_res->get_err_msg(); + + if (cmd_res == NULL) + { + sprintf (_dbmt_error, "spacedb %s", dbname); + retval = ERR_SYSTEM_CALL; + } + else if (cmd_res->has_error()) + { + strcpy (_dbmt_error, err_message); + retval = ERR_WITH_MSG; + } + else + { + retval = _tsParseSpacedb (req, res, dbname, _dbmt_error, cmd_res); + } + + delete cmd_res; + return retval; +} + +static int +nv_append_nvp (nvplist *dest, const nvplist *src) +{ + int i; + + if (dest == NULL || src == NULL) + { + return -1; + } + + for (i = 0; i < src->nvplist_size; ++i) + { + if (src->nvpairs[i] == NULL + || dst_buffer (src->nvpairs[i]->name) == NULL) + { + continue; + } + + nv_add_nvp (dest, dst_buffer (src->nvpairs[i]->name), + dst_buffer (src->nvpairs[i]->value)); + } + + return 1; +} + +int +ts_dbs_spaceInfo (nvplist *req, nvplist *res, char *_dbmt_error) +{ + int i, sect, sect_len; + char *tval; + nvplist *cli_request; + nvplist *cli_response; + + cli_request = nv_create (5, NULL, "\n", ":", "\n"); + cli_response = nv_create (5, NULL, "\n", ":", "\n"); + nv_add_nvp (cli_request, "_DBNAME", ""); + + nv_locate (req, "dblist", §, §_len); + if (sect >= 0) + { + for (i = 0; i < sect_len; ++i) + { + nv_lookup (req, sect + i, NULL, &tval); + nv_update_val (cli_request, "_DBNAME", tval); + nv_add_nvp (res, "open", tval); + if (tsDbspaceInfo (cli_request, cli_response, _dbmt_error) == ERR_NO_ERROR) + { + nv_append_nvp (res, cli_response); + } + nv_reset_nvp (cli_response); + nv_add_nvp (res, "close", tval); + } + } + nv_destroy (cli_request); + nv_destroy (cli_response); + return ERR_NO_ERROR; +} + +int +tsRunAddvoldb (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char *dbname = NULL; + char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; + int ha_mode = 0; + char *volpu = NULL; + char *volpath = NULL; + char *dbvolsize = NULL; + char dbvolsize_t[512]; +#if defined(WINDOWS) + char volpath_buf[PATH_MAX]; +#endif + char *volname = NULL; + char db_dir[PATH_MAX]; + T_DB_SERVICE_MODE db_mode; + char err_file[PATH_MAX]; + int ret; + char cmd_name[ARNIADB_CMD_NAME_LEN]; + const char *argv[15]; + int argc = 0; + int free_space_mb; + + err_file[0] = '\0'; + + if ((dbname = nv_get_val (req, "_DBNAME")) == NULL) + { + sprintf (_dbmt_error, "%s", "database name"); + return ERR_PARAM_MISSING; + } + + db_mode = uDatabaseMode (dbname, &ha_mode); + if (db_mode == DB_SERVICE_MODE_SA) + { + sprintf (_dbmt_error, "%s", dbname); + return ERR_STANDALONE_MODE; + } + + if ((volpu = nv_get_val (req, "purpose")) == NULL) + { + sprintf (_dbmt_error, "%s", "purpose"); + return ERR_PARAM_MISSING; + } + + volpath = nv_get_val (req, "path"); + volname = nv_get_val (req, "volname"); + + if ((dbvolsize = nv_get_val (req, "size_need_mb")) == NULL) + { + sprintf (_dbmt_error, "%s", "size_nee_mb"); + return ERR_PARAM_MISSING; + } + + if (uRetrieveDBDirectory (dbname, db_dir) != ERR_NO_ERROR) + { + strcpy (_dbmt_error, dbname); + return ERR_DBDIRNAME_NULL; + } + + /* check permission of the directory */ + if (access (db_dir, W_OK | X_OK | R_OK) < 0) + { + sprintf (_dbmt_error, "%s", db_dir); + return ERR_PERMISSION; + } + + if (volpath == NULL) + { + volpath = db_dir; + } + + if (access (volpath, F_OK) < 0) + { + if (uCreateDir (volpath) != ERR_NO_ERROR) + { + sprintf (_dbmt_error, "%s", volpath); + return ERR_DIR_CREATE_FAIL; + } + } + + free_space_mb = ut_disk_free_space (volpath); + if (dbvolsize && (free_space_mb < atoi (dbvolsize))) + { + sprintf (_dbmt_error, "Not enough free space in disk."); + return ERR_WITH_MSG; + } + + /* + * Get the dbvolsize, the format looks like: size_need_mb:2.047(MB) + */ + snprintf (dbvolsize_t, sizeof (dbvolsize_t) - 1, "%lldB", + (long long) (atof (dbvolsize) * BYTES_IN_M)); + + arniadb_cmd_name (cmd_name); + argv[argc++] = cmd_name; + argv[argc++] = UTIL_OPTION_ADDVOLDB; + + if (db_mode == DB_SERVICE_MODE_NONE) + { + argv[argc++] = "--" ADDVOL_SA_MODE_L; + } + +#if defined(WINDOWS) + volpath = nt_style_path (volpath, volpath_buf); +#endif + + argv[argc++] = "--" ADDVOL_FILE_PATH_L; + argv[argc++] = volpath; + + if (volname) + { + argv[argc++] = "--" ADDVOL_VOLUME_NAME_L; + argv[argc++] = volname; + } + + argv[argc++] = "--" ADDVOL_DB_VOLUMN_SIZE_L; + argv[argc++] = dbvolsize_t; + + argv[argc++] = "--" ADDVOL_PURPOSE_L; + argv[argc++] = volpu; + + if (ha_mode != 0) + { + append_host_to_dbname (dbname_at_hostname, dbname, sizeof (dbname_at_hostname)); + argv[argc++] = dbname_at_hostname; + } + else + { + argv[argc++] = dbname; + } + + argv[argc++] = NULL; + + snprintf (err_file, PATH_MAX, "%s/%s.%u.err.tmp", sco.dbmt_tmp_dir, "runaddvoldb", getpid ()); + + ret = run_child (argv, 1, NULL, NULL, err_file, NULL); /* addvoldb */ + if (read_error_file (err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) + { + if (access (err_file, F_OK) == 0) + { + unlink (err_file); + } + return ERR_WITH_MSG; + } + + if (access (err_file, F_OK) == 0) + { + unlink (err_file); + } + if (ret < 0) + { + sprintf (_dbmt_error, "%s", argv[0]); + return ERR_SYSTEM_CALL; + } + + nv_add_nvp (res, "dbname", dbname); + nv_add_nvp (res, "purpose", volpu); + + return ERR_NO_ERROR; +} + +int +ts_copydb (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char *srcdbname = NULL; + char *destdbname = NULL; + char *logpath = NULL; + char *destdbpath = NULL; + char *exvolpath = NULL; + int move_flag = 0; + int overwrite_flag = 0; + int adv_flag = 0; + char tmpfile[PATH_MAX], cmd_name[ARNIADB_CMD_NAME_LEN], + lob_base_path[PATH_MAX]; + char src_conf_file[PATH_MAX], dest_conf_file[PATH_MAX], conf_dir[PATH_MAX]; + int i = -1; + int retval = -1; + char arniadb_err_file[PATH_MAX]; + T_DBMT_USER dbmt_user; + T_DB_SERVICE_MODE db_mode; + const char *argv[15]; + int argc = 0; + + /* init var */ + tmpfile[0] = '\0'; + cmd_name[0] = '\0'; + lob_base_path[0] = '\0'; + src_conf_file[0] = '\0'; + dest_conf_file[0] = '\0'; + conf_dir[0] = '\0'; + arniadb_err_file[0] = '\0'; + + if ((srcdbname = nv_get_val (req, "srcdbname")) == NULL) + { + strcpy (_dbmt_error, "source database name"); + return ERR_PARAM_MISSING; + } + if ((destdbname = nv_get_val (req, "destdbname")) == NULL) + { + strcpy (_dbmt_error, "destination database name"); + return ERR_PARAM_MISSING; + } + + adv_flag = uStringEqual (nv_get_val (req, "advanced"), "on") ? 1 : 0; + overwrite_flag = uStringEqual (nv_get_val (req, "overwrite"), "y") ? 1 : 0; + move_flag = uStringEqual (nv_get_val (req, "move"), "y") ? 1 : 0; + + if ((logpath = nv_get_val (req, "logpath")) == NULL) + { + strcpy (_dbmt_error, "log path"); + return ERR_PARAM_MISSING; + } + if ((destdbpath = nv_get_val (req, "destdbpath")) == NULL && adv_flag == 0) + { + strcpy (_dbmt_error, "database directory path"); + return ERR_PARAM_MISSING; + } + if ((exvolpath = nv_get_val (req, "exvolpath")) == NULL && adv_flag == 0) + { + strcpy (_dbmt_error, "extended volume path"); + return ERR_PARAM_MISSING; + } + + db_mode = uDatabaseMode (srcdbname, NULL); + if (db_mode == DB_SERVICE_MODE_SA) + { + sprintf (_dbmt_error, "%s", srcdbname); + return ERR_STANDALONE_MODE; + } + else if (db_mode == DB_SERVICE_MODE_CS) + { + sprintf (_dbmt_error, "%s", srcdbname); + return ERR_DB_ACTIVE; + } + + /* create command */ + arniadb_cmd_name (cmd_name); + argv[argc++] = cmd_name; + argv[argc++] = UTIL_OPTION_COPYDB; + argv[argc++] = "--" COPY_LOG_PATH_L; + argv[argc++] = logpath; + + if (adv_flag) + { + FILE *outfile; + int flag = 0, line = 0; + char *n, *v; +#if defined(WINDOWS) + char n_buf[1024], v_buf[1024]; +#endif + char *p; + + snprintf (tmpfile, PATH_MAX - 1, "%s/DBMT_task_%d.%d", sco.dbmt_tmp_dir, TS_COPYDB, (int) getpid ()); + if ((outfile = fopen (tmpfile, "w")) == NULL) + { + return ERR_TMPFILE_OPEN_FAIL; + } + for (i = 0; i < req->nvplist_leng; i++) + { + nv_lookup (req, i, &n, &v); + if (n == NULL || v == NULL) + { + fclose (outfile); + if (v != NULL) + { + strcpy (_dbmt_error, v); + } + return ERR_DIR_CREATE_FAIL; + } + + if (!strcmp (n, "open") && !strcmp (v, "volume")) + { + flag = 1; + } + else if (!strcmp (n, "close") && !strcmp (v, "volume")) + { + flag = 0; + } + else if (flag == 1) + { +#if defined(WINDOWS) + replace_colon (n); + replace_colon (v); +#endif + p = strrchr (v, '/'); + if (p) + { + *p = '\0'; + } + snprintf (lob_base_path, PATH_MAX - 1, "%s/lob", v); + if (uCreateDir (lob_base_path) != ERR_NO_ERROR) + { + fclose (outfile); + strcpy (_dbmt_error, lob_base_path); + return ERR_DIR_CREATE_FAIL; + } + if (p) + { + *p = '/'; + } +#if defined(WINDOWS) + n = nt_style_path (n, n_buf); + v = nt_style_path (v, v_buf); +#endif + fprintf (outfile, "%d %s %s\n", line++, n, v); + } + } + fclose (outfile); + argv[argc++] = "--" COPY_CONTROL_FILE_L; + argv[argc++] = tmpfile; + } + else + { + /* adv_flag == 0 */ + snprintf (lob_base_path, PATH_MAX - 1, "%s/lob", destdbpath); + if (uCreateDir (lob_base_path) != ERR_NO_ERROR) + { + strcpy (_dbmt_error, lob_base_path); + return ERR_DIR_CREATE_FAIL; + } + if (uCreateDir (exvolpath) != ERR_NO_ERROR) + { + strcpy (_dbmt_error, exvolpath); + return ERR_DIR_CREATE_FAIL; + } + argv[argc++] = "--" COPY_FILE_PATH_L; + argv[argc++] = destdbpath; + argv[argc++] = "--" COPY_EXTENTED_VOLUME_PATH_L; + argv[argc++] = exvolpath; + } + if (overwrite_flag) + { + argv[argc++] = "--" COPY_REPLACE_L; + } + argv[argc++] = "-" COPY_LOB_BASE_PATH_S; + argv[argc++] = lob_base_path; + argv[argc++] = srcdbname; + argv[argc++] = destdbname; + argv[argc++] = NULL; + + if (uCreateDir (logpath) != ERR_NO_ERROR) + { + strcpy (_dbmt_error, logpath); + return ERR_DIR_CREATE_FAIL; + } + + snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", + sco.dbmt_tmp_dir, "copydb", getpid ()); + + retval = run_child (argv, 1, NULL, NULL, arniadb_err_file, NULL); /* copydb */ + if (adv_flag) + { + unlink (tmpfile); + } + if (read_error_file (arniadb_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) + { + if (access (arniadb_err_file, F_OK) == 0) + { + unlink (arniadb_err_file); + } + return ERR_WITH_MSG; + } + if (access (arniadb_err_file, F_OK) == 0) + { + unlink (arniadb_err_file); + } + if (retval < 0) + { + strcpy (_dbmt_error, argv[0]); + return ERR_SYSTEM_CALL; + } + + /* copy config file */ + if (uRetrieveDBDirectory (srcdbname, conf_dir) != ERR_NO_ERROR) + { + strcpy (_dbmt_error, srcdbname); + return ERR_DBDIRNAME_NULL; + } + snprintf (src_conf_file, sizeof (src_conf_file) - 1, "%s/%s", conf_dir, ARNIADB_ARNIADB_CONF); + + if (uRetrieveDBDirectory (destdbname, conf_dir) != ERR_NO_ERROR) + { + strcpy (_dbmt_error, destdbname); + return ERR_DBDIRNAME_NULL; + } + snprintf (dest_conf_file, sizeof (dest_conf_file) - 1, "%s/%s", conf_dir, ARNIADB_ARNIADB_CONF); + + /* Doesn't copy if src and desc is same */ + if (strcmp (src_conf_file, dest_conf_file) != 0) + { + file_copy (src_conf_file, dest_conf_file); + } + + /* if move, delete exist database */ + if (move_flag) + { + char cmd_name[ARNIADB_CMD_NAME_LEN]; + const char *argv[5]; + + arniadb_cmd_name (cmd_name); + argv[0] = cmd_name; + argv[1] = UTIL_OPTION_DELETEDB; + argv[2] = srcdbname; + argv[3] = NULL; + retval = run_child (argv, 1, NULL, NULL, NULL, NULL); /* deletedb */ + if (retval < 0) + { + strcpy (_dbmt_error, argv[0]); + return ERR_SYSTEM_CALL; + } + } + + /* cmdb.pass update after delete */ + if (dbmt_user_read (&dbmt_user, _dbmt_error) != ERR_NO_ERROR) + { + goto copydb_finale; + } + + dbmt_user_db_delete (&dbmt_user, destdbname); + for (i = 0; i < dbmt_user.num_dbmt_user; i++) + { + int dbinfo_idx; + T_DBMT_USER_DBINFO tmp_info; + + dbinfo_idx = dbmt_user_search (& (dbmt_user.user_info[i]), srcdbname); + if (dbinfo_idx < 0) + { + continue; + } + tmp_info = dbmt_user.user_info[i].dbinfo[dbinfo_idx]; + strcpy (tmp_info.dbname, destdbname); + if (dbmt_user_add_dbinfo (& (dbmt_user.user_info[i]), &tmp_info) != ERR_NO_ERROR) + { + dbmt_user_free (&dbmt_user); + goto copydb_finale; + } + } + if (move_flag) + { + dbmt_user_db_delete (&dbmt_user, srcdbname); + } + dbmt_user_write_auth (&dbmt_user, _dbmt_error); + dbmt_user_free (&dbmt_user); + +copydb_finale: + return ERR_NO_ERROR; +} + +int +ts_plandump (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char *dbname = NULL; + char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; + int ha_mode = 0; + T_DB_SERVICE_MODE db_mode; + char cmd_name[ARNIADB_CMD_NAME_LEN]; + char *plandrop = NULL; + const char *argv[10]; + int argc = 0; + char arniadb_err_file[PATH_MAX]; + char tmpfilepath[PATH_MAX]; + int retval = ERR_NO_ERROR; + + arniadb_err_file[0] = '\0'; + + if ((dbname = nv_get_val (req, "dbname")) == NULL) + { + strcpy (_dbmt_error, "database name"); + return ERR_PARAM_MISSING; + } + plandrop = nv_get_val (req, "plandrop"); + + /* + * check the running mode of current database, + * return error if it is DB_SERVICE_MODE_SA. + */ + db_mode = uDatabaseMode (dbname, &ha_mode); + if (db_mode == DB_SERVICE_MODE_SA) + { + sprintf (_dbmt_error, "%s", dbname); + return ERR_STANDALONE_MODE; + } + + arniadb_cmd_name (cmd_name); + argv[argc++] = cmd_name; + argv[argc++] = UTIL_OPTION_PLANDUMP; + if (uStringEqual (plandrop, "y")) + { + argv[argc++] = "--" PLANDUMP_DROP_L; + } + + if (ha_mode != 0) + { + append_host_to_dbname (dbname_at_hostname, dbname, + sizeof (dbname_at_hostname)); + argv[argc++] = dbname_at_hostname; + } + else + { + argv[argc++] = dbname; + } + + argv[argc++] = NULL; + + snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", + sco.dbmt_tmp_dir, "plandump", getpid ()); + + /* + * create a new tmp file to record the content + * that returned by plandump. + */ + snprintf (tmpfilepath, PATH_MAX - 1, "%s/DBMT_task_%d.%d", + sco.dbmt_tmp_dir, TS_PLANDUMP, (int) getpid ()); + + if (run_child (argv, 1, NULL, tmpfilepath, arniadb_err_file, NULL) < 0) /* plandump */ + { + strcpy (_dbmt_error, argv[0]); + retval = ERR_SYSTEM_CALL; + goto rm_tmpfile; + } + + if (read_error_file (arniadb_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) + { + retval = ERR_WITH_MSG; + goto rm_tmpfile; + } + + /* add file content to response line by line. */ + nv_add_nvp (res, "open", "log"); + if (file_to_nvpairs (tmpfilepath, res) < 0) + { + retval = ERR_TMPFILE_OPEN_FAIL; + } + nv_add_nvp (res, "close", "log"); + +rm_tmpfile: + unlink (tmpfilepath); + if (access (arniadb_err_file, F_OK) == 0) + { + unlink (arniadb_err_file); + } + return retval; +} + +int +ts_paramdump (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char *dbname = NULL; + char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; + int ha_mode = 0; + char *bothclientserver = NULL; + T_DB_SERVICE_MODE db_mode; + char cmd_name[ARNIADB_CMD_NAME_LEN]; + const char *argv[10]; + int argc = 0; + char arniadb_err_file[PATH_MAX]; + FILE *infile = NULL; + char tmpfilepath[PATH_MAX]; + int retval = ERR_NO_ERROR; + + arniadb_err_file[0] = '\0'; + + if ((dbname = nv_get_val (req, "dbname")) == NULL) + { + strcpy (_dbmt_error, "database name"); + return ERR_PARAM_MISSING; + } + + /* add both & SA & CS mode. */ + bothclientserver = nv_get_val (req, "both"); + + /* + * check the running mode of current database, + * return error if it is DB_SERVICE_MODE_SA. + */ + db_mode = uDatabaseMode (dbname, &ha_mode); + if (db_mode == DB_SERVICE_MODE_SA) + { + sprintf (_dbmt_error, "%s", dbname); + return ERR_STANDALONE_MODE; + } + + arniadb_cmd_name (cmd_name); + argv[argc++] = cmd_name; + argv[argc++] = UTIL_OPTION_PARAMDUMP; + if (db_mode == DB_SERVICE_MODE_NONE) + { + argv[argc++] = "--" PARAMDUMP_SA_MODE_L; + } + else + { + argv[argc++] = "--" PARAMDUMP_CS_MODE_L; + } + + if (uStringEqual (bothclientserver, "y")) + { + argv[argc++] = "--" PARAMDUMP_BOTH_L; + } + + if (ha_mode != 0) + { + append_host_to_dbname (dbname_at_hostname, dbname, sizeof (dbname_at_hostname)); + argv[argc++] = dbname_at_hostname; + } + else + { + argv[argc++] = dbname; + } + + argv[argc++] = NULL; + + snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", sco.dbmt_tmp_dir, "paramdump", getpid ()); + + /* + * create a new tmp file to record the content + * that returned by plandump. + */ + snprintf (tmpfilepath, PATH_MAX - 1, "%s/DBMT_task_%d.%d", sco.dbmt_tmp_dir, TS_PARAMDUMP, (int) getpid ()); + + if (run_child (argv, 1, NULL, tmpfilepath, arniadb_err_file, NULL) < 0) /* paramdump */ + { + strcpy (_dbmt_error, argv[0]); + retval = ERR_SYSTEM_CALL; + goto rm_tmpfile; + } + + if (read_error_file (arniadb_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) + { + retval = ERR_WITH_MSG; + goto rm_tmpfile; + } + + /* add dbname to response. */ + nv_add_nvp (res, "dbname", dbname); + + if ((infile = fopen (tmpfilepath, "r")) == NULL) + { + retval = ERR_TMPFILE_OPEN_FAIL; + goto rm_tmpfile; + } + + /* add file content to response line by line. */ + if (file_to_nvp_by_separator (infile, res, '=') < 0) + { + const char *tmperr = "Can't parse tmpfile of paramdump."; + strncpy (_dbmt_error, tmperr, strlen (tmperr)); + retval = ERR_WITH_MSG; + fclose (infile); + goto rm_tmpfile; + } + /* close tmp file. */ + fclose (infile); + +rm_tmpfile: + unlink (tmpfilepath); + if (access (arniadb_err_file, F_OK) == 0) + { + unlink (arniadb_err_file); + } + return retval; +} + +int +ts_optimizedb (nvplist *req, nvplist *res, char *_dbmt_error) +{ + return cm_ts_optimizedb (req, res, _dbmt_error); +} + +int +ts_checkdb (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; + char task_name[TASKNAME_LEN]; + const char *argv[7]; + T_DB_SERVICE_MODE db_mode; + + int ha_mode = 0; + int argc = 0; + int retval = 0; + + char *dbname = NULL; + char *repair_db = NULL; + + dbname_at_hostname[0] = '\0'; + cmd_name[0] = '\0'; + + if ((repair_db = nv_get_val (req, "repairdb")) == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "repairdb"); + return ERR_PARAM_MISSING; + } + + if ((dbname = nv_get_val (req, "dbname")) == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "dbname"); + return ERR_PARAM_MISSING; + } + if (_isRegisteredDB (dbname) == 0) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", dbname); + return ERR_DB_NONEXISTANT; + } + + db_mode = uDatabaseMode (dbname, &ha_mode); + if (db_mode == DB_SERVICE_MODE_SA) + { + sprintf (_dbmt_error, "%s", dbname); + return ERR_STANDALONE_MODE; + } + + arniadb_cmd_name (cmd_name); + argv[argc++] = cmd_name; + argv[argc++] = UTIL_OPTION_CHECKDB; + if (db_mode == DB_SERVICE_MODE_NONE) + { + argv[argc++] = "--" CHECK_SA_MODE_L; + } + else + { + argv[argc++] = "--" CHECK_CS_MODE_L; + } + + if (uStringEqual (repair_db, "y")) + { + argv[argc++] = "--" CHECK_REPAIR_L; + } + + if (ha_mode != 0) + { + append_host_to_dbname (dbname_at_hostname, dbname, + sizeof (dbname_at_hostname)); + argv[argc++] = dbname_at_hostname; + } + else + { + argv[argc++] = dbname; + } + + argv[argc++] = NULL; + + strncpy (task_name, "checkdb", TASKNAME_LEN); + retval = _run_child (argv, 1, task_name, NULL, _dbmt_error); + + return retval; +} + +int +ts_statdump (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char *dbname; + char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; + int ha_mode = 0; + T_CM_DB_EXEC_STAT exec_stat; + T_CM_ERROR err_buf; + int retval = -1; + T_DB_SERVICE_MODE db_mode; + + memset (&exec_stat, 0, sizeof (T_CM_DB_EXEC_STAT)); + memset (&err_buf, 0, sizeof (T_CM_ERROR)); + + /* check the parameters of input. */ + if ((dbname = nv_get_val (req, "dbname")) == NULL) + { + strcpy (_dbmt_error, "dbname"); + retval = ERR_PARAM_MISSING; + goto statdump_finale; + } + + /* check the database mode. */ + db_mode = uDatabaseMode (dbname, &ha_mode); + if (db_mode == DB_SERVICE_MODE_SA) + { + sprintf (_dbmt_error, "%s", dbname); + retval = ERR_STANDALONE_MODE; + goto statdump_finale; + } + + if (ha_mode != 0) + { + append_host_to_dbname (dbname_at_hostname, dbname, sizeof (dbname_at_hostname)); + retval = cm_get_db_exec_stat (dbname_at_hostname, &exec_stat, &err_buf); + } + else + { + retval = cm_get_db_exec_stat (dbname, &exec_stat, &err_buf); + } + + /* call cm_get_db_exec_stat to get stat infomation. */ + if (retval < 0) + { + /* return error with message if the operation is not success. */ + strcpy (_dbmt_error, err_buf.err_msg); + retval = ERR_WITH_MSG; + goto statdump_finale; + } + + /* set res with parameter in exec_stat. */ + nv_add_nvp (res, "dbname", dbname); + ts_add_nvp_time (res, "time", time (NULL), "%04d/%02d/%02d %02d:%02d:%02d", TIME_STR_FMT_DATE_TIME); + + /* Execution statistics for the file io */ + nv_add_nvp_int (res, "num_file_creates", exec_stat.file_num_creates); + nv_add_nvp_int (res, "num_file_removes", exec_stat.file_num_removes); + nv_add_nvp_int (res, "num_file_ioreads", exec_stat.file_num_ioreads); + nv_add_nvp_int (res, "num_file_iowrites", exec_stat.file_num_iowrites); + nv_add_nvp_int (res, "num_file_iosynches", exec_stat.file_num_iosynches); + nv_add_nvp_int (res, "num_file_page_allocs", exec_stat.file_num_page_allocs); + nv_add_nvp_int (res, "num_file_page_deallocs", exec_stat.file_num_page_deallocs); + + /* Execution statistics for the page buffer manager */ + nv_add_nvp_int (res, "num_data_page_fetches", exec_stat.pb_num_fetches); + nv_add_nvp_int (res, "num_data_page_dirties", exec_stat.pb_num_dirties); + nv_add_nvp_int (res, "num_data_page_ioreads", exec_stat.pb_num_ioreads); + nv_add_nvp_int (res, "num_data_page_iowrites", exec_stat.pb_num_iowrites); + + /* Execution statistics for the log manager */ + nv_add_nvp_int (res, "num_log_page_ioreads", exec_stat.log_num_ioreads); + nv_add_nvp_int (res, "num_log_page_iowrites", exec_stat.log_num_iowrites); + nv_add_nvp_int (res, "num_log_append_records", exec_stat.log_num_appendrecs); + nv_add_nvp_int (res, "num_log_archives", exec_stat.log_num_archives); +#if 0 //no use + nv_add_nvp_int (res, "num_log_start_checkpoints", exec_stat.log_num_start_checkpoints); + nv_add_nvp_int (res, "num_log_end_checkpoints", exec_stat.log_num_end_checkpoints); +#endif + nv_add_nvp_int (res, "num_log_wals", exec_stat.log_num_wals); + + /* Execution statistics for the lock manager */ + nv_add_nvp_int (res, "num_page_locks_acquired", exec_stat.lk_num_acquired_on_pages); + nv_add_nvp_int (res, "num_object_locks_acquired", exec_stat.lk_num_acquired_on_objects); + nv_add_nvp_int (res, "num_page_locks_converted", exec_stat.lk_num_converted_on_pages); + nv_add_nvp_int (res, "num_object_locks_converted", exec_stat.lk_num_converted_on_objects); + nv_add_nvp_int (res, "num_page_locks_re_requested", exec_stat.lk_num_re_requested_on_pages); + nv_add_nvp_int (res, "num_object_locks_re_requested", exec_stat.lk_num_re_requested_on_objects); + nv_add_nvp_int (res, "num_page_locks_waits", exec_stat.lk_num_waited_on_pages); + nv_add_nvp_int (res, "num_object_locks_waits", exec_stat.lk_num_waited_on_objects); + + /* Execution statistics for transactions */ + nv_add_nvp_int (res, "num_tran_commits", exec_stat.tran_num_commits); + nv_add_nvp_int (res, "num_tran_rollbacks", exec_stat.tran_num_rollbacks); + nv_add_nvp_int (res, "num_tran_savepoints", exec_stat.tran_num_savepoints); + nv_add_nvp_int (res, "num_tran_start_topops", exec_stat.tran_num_start_topops); + nv_add_nvp_int (res, "num_tran_end_topops", exec_stat.tran_num_end_topops); + nv_add_nvp_int (res, "num_tran_interrupts", exec_stat.tran_num_interrupts); + + /* Execution statistics for the btree manager */ + nv_add_nvp_int (res, "num_btree_inserts", exec_stat.bt_num_inserts); + nv_add_nvp_int (res, "num_btree_deletes", exec_stat.bt_num_deletes); + nv_add_nvp_int (res, "num_btree_updates", exec_stat.bt_num_updates); + nv_add_nvp_int (res, "num_btree_covered", exec_stat.bt_num_covered); + nv_add_nvp_int (res, "num_btree_noncovered", exec_stat.bt_num_noncovered); + nv_add_nvp_int (res, "num_btree_resumes", exec_stat.bt_num_resumes); + nv_add_nvp_int (res, "num_btree_multirange_optimization", exec_stat.bt_num_multi_range_opt); + nv_add_nvp_int (res, "num_btree_splits", exec_stat.bt_num_splits); + nv_add_nvp_int (res, "num_btree_merges", exec_stat.bt_num_merges); + nv_add_nvp_int (res, "num_btree_get_stats", exec_stat.bt_num_get_stats); + + /* Execution statistics for the query manager */ + nv_add_nvp_int (res, "num_query_selects", exec_stat.qm_num_selects); + nv_add_nvp_int (res, "num_query_inserts", exec_stat.qm_num_inserts); + nv_add_nvp_int (res, "num_query_deletes", exec_stat.qm_num_deletes); + nv_add_nvp_int (res, "num_query_updates", exec_stat.qm_num_updates); + nv_add_nvp_int (res, "num_query_sscans", exec_stat.qm_num_sscans); + nv_add_nvp_int (res, "num_query_iscans", exec_stat.qm_num_iscans); + nv_add_nvp_int (res, "num_query_lscans", exec_stat.qm_num_lscans); + nv_add_nvp_int (res, "num_query_setscans", exec_stat.qm_num_setscans); + nv_add_nvp_int (res, "num_query_methscans", exec_stat.qm_num_methscans); + nv_add_nvp_int (res, "num_query_nljoins", exec_stat.qm_num_nljoins); + nv_add_nvp_int (res, "num_query_mjoins", exec_stat.qm_num_mjoins); + nv_add_nvp_int (res, "num_query_objfetches", exec_stat.qm_num_objfetches); + nv_add_nvp_int (res, "num_query_holdable_cursors", exec_stat.qm_num_holdable_cursors); + + /* Execution statistics for external sort */ + nv_add_nvp_int (res, "num_sort_io_pages", exec_stat.sort_num_io_pages); + nv_add_nvp_int (res, "num_sort_data_pages", exec_stat.sort_num_data_pages); + + /* Execution statistics for network communication */ + nv_add_nvp_int (res, "num_network_requests", exec_stat.net_num_requests); + + /* flush control stat */ + nv_add_nvp_int (res, "num_adaptive_flush_pages", exec_stat.fc_num_pages); + nv_add_nvp_int (res, "num_adaptive_flush_log_pages", exec_stat.fc_num_log_pages); + nv_add_nvp_int (res, "num_adaptive_flush_max_pages", exec_stat.fc_tokens); + + /* prior lsa info */ + nv_add_nvp_int (res, "num_prior_lsa_list_size", exec_stat.prior_lsa_list_size); + nv_add_nvp_int (res, "num_prior_lsa_list_maxed", exec_stat.prior_lsa_list_maxed); + nv_add_nvp_int (res, "num_prior_lsa_list_removed", exec_stat.prior_lsa_list_removed); + + /* best space info */ + nv_add_nvp_int (res, "num_heap_stats_bestspace_entries", exec_stat.hf_stats_bestspace_entries); + nv_add_nvp_int (res, "num_heap_stats_bestspace_maxed", exec_stat.hf_stats_bestspace_maxed); + + /* HA replication delay */ + nv_add_nvp_int (res, "time_ha_replication_delay", exec_stat.ha_repl_delay); + + /* Execution statistics for Plan cache */ + nv_add_nvp_int (res, "num_plan_cache_add", exec_stat.pc_num_add); + nv_add_nvp_int (res, "num_plan_cache_lookup", exec_stat.pc_num_lookup); + nv_add_nvp_int (res, "num_plan_cache_hit", exec_stat.pc_num_hit); + nv_add_nvp_int (res, "num_plan_cache_miss", exec_stat.pc_num_miss); + nv_add_nvp_int (res, "num_plan_cache_full", exec_stat.pc_num_full); + nv_add_nvp_int (res, "num_plan_cache_delete", exec_stat.pc_num_delete); + nv_add_nvp_int (res, "num_plan_cache_invalid_xasl_id", exec_stat.pc_num_invalid_xasl_id); + nv_add_nvp_int (res, "num_plan_cache_query_string_hash_entries", exec_stat.pc_num_query_string_hash_entries); + nv_add_nvp_int (res, "num_plan_cache_xasl_id_hash_entries", exec_stat.pc_num_xasl_id_hash_entries); + nv_add_nvp_int (res, "num_plan_cache_class_oid_hash_entries", exec_stat.pc_num_class_oid_hash_entries); + + /* Other statistics */ + nv_add_nvp_int (res, "data_page_buffer_hit_ratio", exec_stat.pb_hit_ratio); + + retval = ERR_NO_ERROR; + +statdump_finale: + return retval; +} + +int +ts_compactdb (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char cmd_name[ARNIADB_CMD_NAME_LEN]; + char out_file[PATH_MAX]; + char err_file[PATH_MAX]; + + const char *argv[10]; + T_DB_SERVICE_MODE db_mode; + + int exit_code = 0; + int argc = 0; + int retval = ERR_NO_ERROR; + int createtmpfile = 0; + + char *dbname = NULL; + char *verbose = NULL; + + cmd_name[0] = '\0'; + out_file[0] = '\0'; + err_file[0] = '\0'; + + dbname = nv_get_val (req, "dbname"); + if (dbname == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "dbname"); + return ERR_PARAM_MISSING; + } + if (_isRegisteredDB (dbname) == 0) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", dbname); + return ERR_DB_NONEXISTANT; + } + + verbose = nv_get_val (req, "verbose"); + if (verbose == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "verbose"); + return ERR_PARAM_MISSING; + } + + db_mode = uDatabaseMode (dbname, NULL); + if (db_mode == DB_SERVICE_MODE_SA) + { + sprintf (_dbmt_error, "%s", dbname); + return ERR_STANDALONE_MODE; + } + + arniadb_cmd_name (cmd_name); + argv[argc++] = cmd_name; + argv[argc++] = UTIL_OPTION_COMPACTDB; + if (uStringEqual (verbose, "y")) + { + argv[argc++] = "--" COMPACT_VERBOSE_L; + createtmpfile = 1; + } + + if (db_mode == DB_SERVICE_MODE_CS) + { + argv[argc++] = "--" COMPACT_CS_MODE_L; + } + else if (db_mode == DB_SERVICE_MODE_NONE) + { + argv[argc++] = "--" COMPACT_SA_MODE_L; + } + + argv[argc++] = dbname; + argv[argc++] = NULL; + + if (createtmpfile != 0) + { + snprintf (out_file, PATH_MAX, "%s/DBMT_task_%d.%d", + sco.dbmt_tmp_dir, TS_COMPACTDB, (int) getpid ()); + } + else + { + snprintf (out_file, PATH_MAX, "%s/%s.%u.out.tmp", + sco.dbmt_tmp_dir, "compactdb", getpid ()); + } + + snprintf (err_file, PATH_MAX, "%s/%s.%u.err.tmp", + sco.dbmt_tmp_dir, "compactdb", getpid ()); + + if (run_child (argv, 1, NULL, out_file, err_file, &exit_code) < 0) + { + /* compactdb */ + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", argv[0]); + retval = ERR_SYSTEM_CALL; + goto rm_tmpfile; + } + + if (read_error_file (err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) + { + retval = ERR_WITH_MSG; + goto rm_tmpfile; + } + + if (exit_code != EXIT_SUCCESS) + { + read_stdout_stderr_as_err (out_file, NULL, _dbmt_error); + retval = ERR_WITH_MSG; + goto rm_tmpfile; + } + + if (createtmpfile != 0) + { + nv_add_nvp (res, "open", "log"); + /* add file content to response line by line. */ + if (file_to_nvpairs (out_file, res) < 0) + { + retval = ERR_TMPFILE_OPEN_FAIL; + } + nv_add_nvp (res, "close", "log"); + } + +rm_tmpfile: + unlink (out_file); + unlink (err_file); + return retval; +} + +int +ts_backupdb (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char *dbname, *level, *removelog, *volname, *backupdir, *check; + char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; + int ha_mode = 0; + char *mt, *zip, *safe_replication; + char backupfilepath[PATH_MAX]; + char inputfilepath[PATH_MAX]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; + char sp_option[256]; + const char *argv[16]; + int argc = 0; + FILE *inputfile; + T_DB_SERVICE_MODE db_mode; + char arniadb_err_file[PATH_MAX]; + + arniadb_err_file[0] = '\0'; + + if ((dbname = nv_get_val (req, "dbname")) == NULL) + { + strcpy (_dbmt_error, "database name"); + return ERR_PARAM_MISSING; + } + + db_mode = uDatabaseMode (dbname, &ha_mode); + if (db_mode == DB_SERVICE_MODE_SA) + { + sprintf (_dbmt_error, "%s", dbname); + return ERR_STANDALONE_MODE; + } + level = nv_get_val (req, "level"); + volname = nv_get_val (req, "volname"); + backupdir = nv_get_val (req, "backupdir"); + removelog = nv_get_val (req, "removelog"); + check = nv_get_val (req, "check"); + mt = nv_get_val (req, "mt"); + zip = nv_get_val (req, "zip"); + safe_replication = nv_get_val (req, "safereplication"); + + if (backupdir == NULL) + { + strcpy (_dbmt_error, "backupdir"); + return ERR_PARAM_MISSING; + } + + snprintf (backupfilepath, PATH_MAX - 1, "%s/%s", backupdir, volname); + + /* create directory */ + if (access (backupfilepath, F_OK) < 0) + { + if (uCreateDir (backupfilepath) != ERR_NO_ERROR) + { + strcpy (_dbmt_error, backupfilepath); + return ERR_DIR_CREATE_FAIL; + } + } + + arniadb_cmd_name (cmd_name); + argv[argc++] = cmd_name; + argv[argc++] = UTIL_OPTION_BACKUPDB; + if (db_mode == DB_SERVICE_MODE_NONE) + { + argv[argc++] = "--" BACKUP_SA_MODE_L; + } + else + { + argv[argc++] = "--" BACKUP_CS_MODE_L; + } + argv[argc++] = "--" BACKUP_LEVEL_L; + argv[argc++] = level; + argv[argc++] = "--" BACKUP_DESTINATION_PATH_L; + argv[argc++] = backupfilepath; + if (uStringEqual (removelog, "y")) + { + argv[argc++] = "--" BACKUP_REMOVE_ARCHIVE_L; + } + if (uStringEqual (check, "n")) + { + argv[argc++] = "--" BACKUP_NO_CHECK_L; + } + if (mt != NULL) + { + argv[argc++] = "--" BACKUP_THREAD_COUNT_L; + argv[argc++] = mt; + } + if (zip != NULL && uStringEqual (zip, "y")) + { + argv[argc++] = "--" BACKUP_COMPRESS_L; + } + + if (safe_replication != NULL && uStringEqual (safe_replication, "y")) + { + snprintf (sp_option, sizeof (sp_option) - 1, + "--safe-page-id `repl_safe_page %s`", dbname); + argv[argc++] = sp_option; + } + + if (ha_mode != 0) + { + append_host_to_dbname (dbname_at_hostname, dbname, + sizeof (dbname_at_hostname)); + argv[argc++] = dbname_at_hostname; + } + else + { + argv[argc++] = dbname; + } + + argv[argc++] = NULL; + + snprintf (inputfilepath, PATH_MAX - 1, "%s/DBMT_task_%d.%d", + sco.dbmt_tmp_dir, TS_BACKUPDB, (int) getpid ()); + inputfile = fopen (inputfilepath, "w"); + if (inputfile) + { + fprintf (inputfile, "y"); + fclose (inputfile); + } + else + { + return ERR_FILE_OPEN_FAIL; + } + + snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", + sco.dbmt_tmp_dir, "backupdb", getpid ()); + + if (run_child (argv, 1, inputfilepath, NULL, arniadb_err_file, NULL) < 0) + { + /* backupdb */ + strcpy (_dbmt_error, argv[0]); + unlink (inputfilepath); + if (access (arniadb_err_file, F_OK) == 0) + { + unlink (arniadb_err_file); + } + return ERR_SYSTEM_CALL; + } + + unlink (inputfilepath); + + if (read_error_file (arniadb_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) + { + if (access (arniadb_err_file, F_OK) == 0) + { + unlink (arniadb_err_file); + } + return ERR_WITH_MSG; + } + + if (access (arniadb_err_file, F_OK) == 0) + { + unlink (arniadb_err_file); + } + return ERR_NO_ERROR; +} + +int +ts_unloaddb (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char *dbname, *targetdir, *usehash, *hashdir, *target, *s1, *s2, + *ref, *classonly, *delimit, *estimate, *prefix, *cach, *lofile, + buf[PATH_MAX], infofile[PATH_MAX], tmpfile[PATH_MAX], temp[PATH_MAX], + n[256], v[256], cname[256], p1[64], p2[8], p3[8]; + + char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; + int ha_mode = 0; + char cmd_name[ARNIADB_CMD_NAME_LEN]; + char arniadb_err_file[PATH_MAX]; + FILE *infile, *outfile; + int i, flag = 0, no_class = 0, index_exist = 0, trigger_exist = 0; + struct stat statbuf; + const char *argv[30]; + int argc = 0; + T_DB_SERVICE_MODE db_mode; + char fullpath[PATH_MAX]; + char dba_user[32] = "dba"; + char *dbuser = NULL; + char *dbpasswd = NULL; + + arniadb_err_file[0] = '\0'; + + dbname = nv_get_val (req, "dbname"); + if (dbname == NULL) + { + strcpy (_dbmt_error, "database name"); + return ERR_PARAM_MISSING; + } + + targetdir = nv_get_val (req, "targetdir"); + usehash = nv_get_val (req, "usehash"); + hashdir = nv_get_val (req, "hashdir"); + target = nv_get_val (req, "target"); + ref = nv_get_val (req, "ref"); + classonly = nv_get_val (req, "classonly"); + delimit = nv_get_val (req, "delimit"); + estimate = nv_get_val (req, "estimate"); + prefix = nv_get_val (req, "prefix"); + cach = nv_get_val (req, "cach"); + lofile = nv_get_val (req, "lofile"); + dbuser = nv_get_val (req, "dbuser"); + dbpasswd = nv_get_val (req, "dbpasswd"); + + if (target == NULL) + { + strcpy (_dbmt_error, "target"); + return ERR_PARAM_MISSING; + } + + db_mode = uDatabaseMode (dbname, &ha_mode); + if (db_mode == DB_SERVICE_MODE_SA) + { + sprintf (_dbmt_error, "%s", dbname); + return ERR_STANDALONE_MODE; + } + + if (targetdir == NULL) + { + strcpy (_dbmt_error, "targetdir"); + return ERR_PARAM_MISSING; + } + + if (strcmp (targetdir, "+D") == 0) + { + snprintf (fullpath, sizeof (fullpath) - 1, "%s/files/", sco.szCWMPath); + } + else + { + snprintf (fullpath, sizeof (fullpath) - 1, "%s", targetdir); + } + + if (access (fullpath, F_OK) < 0) + { + if (uCreateDir (fullpath) != ERR_NO_ERROR) + { + strcpy (_dbmt_error, targetdir); + return ERR_DIR_CREATE_FAIL; + } + } + + /* Verify password for dbuser */ + if (dbuser == NULL) + { + dbuser = dba_user; + } + if (_verify_user_passwd (dbname, dbuser, dbpasswd, _dbmt_error) != ERR_NO_ERROR) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, + "Invalid password or missing password for database(%s): dbuser(%s).", dbname, dbuser); + return ERR_WITH_MSG; + } + /* makeup upload class list file */ + snprintf (tmpfile, PATH_MAX - 1, "%s/DBMT_task_101.%d", sco.dbmt_tmp_dir, (int) getpid ()); + if ((outfile = fopen (tmpfile, "w")) == NULL) + { + return ERR_TMPFILE_OPEN_FAIL; + } + for (i = 0; i < req->nvplist_leng; i++) + { + nv_lookup (req, i, &s1, &s2); + if (s1 == NULL) + { + continue; + } + + if (!strcmp (s1, "open")) + { + flag = 1; + } + else if (!strcmp (s1, "close")) + { + flag = 0; + } + else if (flag == 1 && !strcmp (s1, "classname")) + { + snprintf (buf, sizeof (buf) - 1, "%s\n", s2); + fputs (buf, outfile); + no_class++; + } + } + fclose (outfile); + + /* makeup command and execute */ + arniadb_cmd_name (cmd_name); + argv[argc++] = cmd_name; + argv[argc++] = UTIL_OPTION_UNLOADDB; + if (db_mode == DB_SERVICE_MODE_NONE) + { + argv[argc++] = "--" UNLOAD_SA_MODE_L; + } + else + { + argv[argc++] = "--" UNLOAD_CS_MODE_L; + } + if (no_class > 0) + { + argv[argc++] = "--" UNLOAD_INPUT_CLASS_FILE_L; + argv[argc++] = tmpfile; + } + argv[argc++] = "--" UNLOAD_OUTPUT_PATH_L; + argv[argc++] = fullpath; + if ((usehash != NULL) && (strcmp (usehash, "yes") == 0)) + { + argv[argc++] = "--" UNLOAD_HASH_FILE_L; + argv[argc++] = hashdir; + } + + if (strcmp (target, "both") == 0) + { + argv[argc++] = "--" UNLOAD_SCHEMA_ONLY_L; + argv[argc++] = "--" UNLOAD_DATA_ONLY_L; + } + else if (strcmp (target, "schema") == 0) + { + argv[argc++] = "--" UNLOAD_SCHEMA_ONLY_L; + } + else if (strcmp (target, "object") == 0) + { + argv[argc++] = "--" UNLOAD_DATA_ONLY_L; + } + + if (uStringEqual (ref, "yes")) + { + argv[argc++] = "--" UNLOAD_INCLUDE_REFERENCE_L; + } + if (uStringEqual (classonly, "yes")) + { + argv[argc++] = "--" UNLOAD_INPUT_CLASS_ONLY_L; + } + if (uStringEqual (delimit, "yes")) + { + argv[argc++] = "--" UNLOAD_USE_DELIMITER_L; + } + if (estimate != NULL && !uStringEqual (estimate, "none")) + { + argv[argc++] = "--" UNLOAD_ESTIMATED_SIZE_L; + argv[argc++] = estimate; + } + if (prefix != NULL && !uStringEqual (prefix, "none")) + { + argv[argc++] = "--" UNLOAD_OUTPUT_PREFIX_L; + argv[argc++] = prefix; + } + if (cach != NULL && !uStringEqual (cach, "none")) + { + argv[argc++] = "--" UNLOAD_CACHED_PAGES_L; + argv[argc++] = cach; + } + if (lofile != NULL && !uStringEqual (lofile, "none")) + { + argv[argc++] = "--" UNLOAD_LO_COUNT_L; + argv[argc++] = lofile; + } + + if (ha_mode != 0) + { + append_host_to_dbname (dbname_at_hostname, dbname, + sizeof (dbname_at_hostname)); + argv[argc++] = dbname_at_hostname; + } + else + { + argv[argc++] = dbname; + } + + argv[argc++] = "--" UNLOAD_USER_L; + argv[argc++] = dbuser; + + if (dbpasswd != NULL) + { + argv[argc++] = "--" UNLOAD_PASSWORD_L; + argv[argc++] = dbpasswd; + } + + argv[argc++] = NULL; + + snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", + sco.dbmt_tmp_dir, "unloaddb", getpid ()); + + if (run_child (argv, 1, NULL, NULL, arniadb_err_file, NULL) < 0) + { + /* unloaddb */ + strcpy (_dbmt_error, argv[0]); + unlink (tmpfile); + if (access (arniadb_err_file, F_OK) == 0) + { + unlink (arniadb_err_file); + } + return ERR_SYSTEM_CALL; + } + + if (read_error_file (arniadb_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) + { + unlink (tmpfile); + if (access (arniadb_err_file, F_OK) == 0) + { + unlink (arniadb_err_file); + } + return ERR_WITH_MSG; + } + if (access (arniadb_err_file, F_OK) == 0) + { + unlink (arniadb_err_file); + } + unlink (tmpfile); + + /* makeup upload result information in unload.log file */ + snprintf (buf, sizeof (buf) - 1, "%s_unloaddb.log", dbname); + nv_add_nvp (res, "open", "result"); + if ((infile = fopen (buf, "rt")) != NULL) + { + flag = 0; + while (fgets (buf, sizeof (buf), infile)) + { + if (buf[0] == '-') + { + flag++; + } + else if (flag == 2 && + sscanf (buf, "%255s %*s %63s %7s %*s %7s", cname, p1, p2, p3) == 4) + { + snprintf (buf, sizeof (buf) - 1, "%s %s/%s", p1, p2, p3); + nv_add_nvp (res, cname, buf); + } + } + fclose (infile); + } + nv_add_nvp (res, "close", "result"); + unlink ("unload.log"); + + /* save uploaded result file to 'unloaddb.info' file */ + flag = 0; + snprintf (infofile, PATH_MAX - 1, "%s/unloaddb.info", + sco.szArniadb_databases); + if ((infile = fopen (infofile, "rt")) == NULL) + { + outfile = fopen (infofile, "w"); + if (outfile == NULL) + { + strcpy (_dbmt_error, infofile); + return ERR_FILE_OPEN_FAIL; + } + + snprintf (buf, sizeof (buf) - 1, "%% %s\n", dbname); + fputs (buf, outfile); + + if (!strcmp (target, "both")) + { + fprintf (outfile, "schema %s/%s%s\n", targetdir, dbname, + ARNIADB_UNLOAD_EXT_SCHEMA); + fprintf (outfile, "object %s/%s%s\n", targetdir, dbname, + ARNIADB_UNLOAD_EXT_OBJ); + } + else if (!strcmp (target, "schema")) + { + fprintf (outfile, "schema %s/%s%s\n", targetdir, dbname, + ARNIADB_UNLOAD_EXT_SCHEMA); + } + else if (!strcmp (target, "object")) + { + fprintf (outfile, "object %s/%s%s\n", targetdir, dbname, + ARNIADB_UNLOAD_EXT_OBJ); + } + + /* check index file and append if exist */ + snprintf (buf, sizeof (buf) - 1, "%s/%s%s", targetdir, dbname, + ARNIADB_UNLOAD_EXT_INDEX); + if (stat (buf, &statbuf) == 0) + { + fprintf (outfile, "index %s/%s%s\n", targetdir, dbname, + ARNIADB_UNLOAD_EXT_INDEX); + } + /* check trigger file and append if exist */ + snprintf (buf, sizeof (buf) - 1, "%s/%s%s", targetdir, dbname, + ARNIADB_UNLOAD_EXT_TRIGGER); + if (stat (buf, &statbuf) == 0) + { + fprintf (outfile, "trigger %s/%s%s\n", targetdir, dbname, + ARNIADB_UNLOAD_EXT_TRIGGER); + } + fclose (outfile); + } + else + { + snprintf (tmpfile, PATH_MAX - 1, "%s/DBMT_task_102.%d", + sco.dbmt_tmp_dir, (int) getpid ()); + outfile = fopen (tmpfile, "w"); + if (outfile == NULL) + { + fclose (infile); + strcpy (_dbmt_error, tmpfile); + return ERR_TMPFILE_OPEN_FAIL; + } + + while (fgets (buf, sizeof (buf), infile)) + { + if (sscanf (buf, "%255s %255s", n, v) != 2) + { + fputs (buf, outfile); + continue; + } + if (!strcmp (n, "%") && !strcmp (v, dbname)) + { + fputs (buf, outfile); + + if (!strcmp (target, "both")) + { + fprintf (outfile, "schema %s/%s%s\n", targetdir, dbname, + ARNIADB_UNLOAD_EXT_SCHEMA); + fprintf (outfile, "object %s/%s%s\n", targetdir, dbname, + ARNIADB_UNLOAD_EXT_OBJ); + } + else if (!strcmp (target, "schema")) + { + fprintf (outfile, "schema %s/%s%s\n", targetdir, dbname, + ARNIADB_UNLOAD_EXT_SCHEMA); + } + else if (!strcmp (target, "object")) + { + fprintf (outfile, "object %s/%s%s\n", targetdir, dbname, + ARNIADB_UNLOAD_EXT_OBJ); + } + + /* check index file and append if exist */ + snprintf (temp, PATH_MAX - 1, "%s/%s%s", targetdir, dbname, + ARNIADB_UNLOAD_EXT_INDEX); + if (stat (temp, &statbuf) == 0) + { + fprintf (outfile, "index %s/%s%s\n", targetdir, dbname, + ARNIADB_UNLOAD_EXT_INDEX); + index_exist = 1; + } + /* check trigger file and append if exist */ + snprintf (temp, PATH_MAX - 1, "%s/%s%s", targetdir, dbname, + ARNIADB_UNLOAD_EXT_TRIGGER); + if (stat (temp, &statbuf) == 0) + { + fprintf (outfile, "trigger %s/%s%s\n", targetdir, dbname, + ARNIADB_UNLOAD_EXT_TRIGGER); + trigger_exist = 1; + } + flag = 1; + continue; + } + if (!strcmp (target, "both") || !strcmp (target, "schema")) + { + snprintf (temp, PATH_MAX - 1, "%s/%s%s", targetdir, dbname, + ARNIADB_UNLOAD_EXT_SCHEMA); + if (!strcmp (n, "schema") && !strcmp (v, temp)) + { + continue; + } + } + if (!strcmp (target, "both") || !strcmp (target, "object")) + { + snprintf (temp, PATH_MAX - 1, "%s/%s%s", targetdir, dbname, + ARNIADB_UNLOAD_EXT_OBJ); + if (!strcmp (n, "object") && !strcmp (v, temp)) + { + continue; + } + } + if (index_exist) + { + snprintf (temp, PATH_MAX - 1, "%s/%s%s", targetdir, dbname, + ARNIADB_UNLOAD_EXT_INDEX); + if (!strcmp (n, "index") && !strcmp (v, temp)) + { + continue; + } + } + if (trigger_exist) + { + snprintf (temp, PATH_MAX - 1, "%s/%s%s", targetdir, dbname, + ARNIADB_UNLOAD_EXT_TRIGGER); + if (!strcmp (n, "trigger") && !strcmp (v, temp)) + { + continue; + } + } + fputs (buf, outfile); + } /* end of while(fgets()) */ + if (flag == 0) + { + fprintf (outfile, "%% %s\n", dbname); + if (!strcmp (target, "both")) + { + fprintf (outfile, "schema %s/%s%s\n", targetdir, dbname, + ARNIADB_UNLOAD_EXT_SCHEMA); + fprintf (outfile, "object %s/%s%s\n", targetdir, dbname, + ARNIADB_UNLOAD_EXT_OBJ); + } + else if (!strcmp (target, "schema")) + { + fprintf (outfile, "schema %s/%s%s\n", targetdir, dbname, + ARNIADB_UNLOAD_EXT_SCHEMA); + } + else if (!strcmp (target, "object")) + { + fprintf (outfile, "object %s/%s%s\n", targetdir, dbname, + ARNIADB_UNLOAD_EXT_OBJ); + } + /* check index file and append if exist */ + snprintf (temp, PATH_MAX - 1, "%s/%s%s", targetdir, dbname, + ARNIADB_UNLOAD_EXT_INDEX); + if (stat (temp, &statbuf) == 0) + { + fprintf (outfile, "index %s/%s%s\n", targetdir, dbname, + ARNIADB_UNLOAD_EXT_INDEX); + index_exist = 1; + } + /* check trigger file and append if exist */ + snprintf (temp, PATH_MAX - 1, "%s/%s%s", targetdir, dbname, + ARNIADB_UNLOAD_EXT_TRIGGER); + if (stat (temp, &statbuf) == 0) + { + fprintf (outfile, "trigger %s/%s%s\n", targetdir, dbname, + ARNIADB_UNLOAD_EXT_TRIGGER); + trigger_exist = 1; + } + } + fclose (infile); + fclose (outfile); + + /* copyback */ + infile = fopen (tmpfile, "rt"); + if (infile == NULL) + { + strcpy (_dbmt_error, tmpfile); + return ERR_TMPFILE_OPEN_FAIL; + } + + outfile = fopen (infofile, "w"); + if (outfile == NULL) + { + strcpy (_dbmt_error, infofile); + fclose (infile); + return ERR_FILE_OPEN_FAIL; + } + + while (fgets (buf, sizeof (buf), infile)) + { + fputs (buf, outfile); + } + fclose (infile); + fclose (outfile); + unlink (tmpfile); + } /* end of if */ + + return ERR_NO_ERROR; +} + +int +ts_loaddb (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char *dbname, *checkoption, *period, *user, *schema, *object, *index, + *error_control_file, *ignore_class_file, *estimated, *oiduse, *nolog, + *statisticsuse, tmpfile[PATH_MAX]; + + T_DB_SERVICE_MODE db_mode; + char *dbuser, *dbpasswd; + char arniadb_err_file[PATH_MAX]; + int retval; + char cmd_name[ARNIADB_CMD_NAME_LEN]; + const char *argv[32]; + int argc = 0; + + arniadb_err_file[0] = '\0'; + + if ((dbname = nv_get_val (req, "_DBNAME")) == NULL) + { + sprintf (_dbmt_error, "%s", "database name"); + return ERR_PARAM_MISSING; + } + + dbuser = nv_get_val (req, "_DBID"); + dbpasswd = nv_get_val (req, "_DBPASSWD"); + checkoption = nv_get_val (req, "checkoption"); + period = nv_get_val (req, "period"); + user = nv_get_val (req, "user"); + schema = nv_get_val (req, "schema"); + object = nv_get_val (req, "object"); + index = nv_get_val (req, "index"); + error_control_file = nv_get_val (req, "errorcontrolfile"); + ignore_class_file = nv_get_val (req, "ignoreclassfile"); +#if 0 /* will be added */ + trigger = nv_get_val (req, "trigger"); +#endif + estimated = nv_get_val (req, "estimated"); + oiduse = nv_get_val (req, "oiduse"); + nolog = nv_get_val (req, "nolog"); + statisticsuse = nv_get_val (req, "statisticsuse"); + + db_mode = uDatabaseMode (dbname, NULL); + if (db_mode == DB_SERVICE_MODE_SA) + { + sprintf (_dbmt_error, "%s", dbname); + return ERR_STANDALONE_MODE; + } + else if (db_mode == DB_SERVICE_MODE_CS) + { + sprintf (_dbmt_error, "%s", dbname); + return ERR_DB_ACTIVE; + } + + snprintf (tmpfile, PATH_MAX - 1, "%s/DBMT_task_%d.%d", sco.dbmt_tmp_dir, + TS_LOADDB, (int) getpid ()); + arniadb_cmd_name (cmd_name); + + argc = 0; + argv[argc++] = cmd_name; + argv[argc++] = UTIL_OPTION_LOADDB; + + if (checkoption != NULL) + { + if (strcmp (checkoption, "syntax") == 0) + { + argv[argc++] = "--" LOAD_CHECK_ONLY_L; + } + else if (strcmp (checkoption, "load") == 0) + { + argv[argc++] = "--" LOAD_LOAD_ONLY_L; + } + } + + if (dbuser) + { + argv[argc++] = "--" LOAD_USER_L; + argv[argc++] = dbuser; + if (dbpasswd) + { + argv[argc++] = "--" LOAD_PASSWORD_L; + argv[argc++] = dbpasswd; + } + } + + /* argv[argc++] = "-v"; */ + if (period != NULL && !uStringEqual (period, "none")) + { + argv[argc++] = "--" LOAD_PERIODIC_COMMIT_L; + argv[argc++] = period; + } + + if ((schema != NULL) && (strcmp (schema, "none") != 0)) + { + argv[argc++] = "--" LOAD_SCHEMA_FILE_L; + argv[argc++] = schema; + } + + if ((object != NULL) && (strcmp (object, "none") != 0)) + { + argv[argc++] = "--" LOAD_DATA_FILE_L; + argv[argc++] = object; + } + + if ((index != NULL) && (strcmp (index, "none") != 0)) + { + argv[argc++] = "--" LOAD_INDEX_FILE_L; + argv[argc++] = index; + } + +#if 0 /* will be added */ + if (trigger != NULL && !uStringEqual (trigger, "none")) + { + argv[argc++] = "-tf"; + argv[argc++] = trigger; + } +#endif + + if (estimated != NULL && !uStringEqual (estimated, "none")) + { + argv[argc++] = "--" LOAD_ESTIMATED_SIZE_L; + argv[argc++] = estimated; + } + + if (uStringEqual (oiduse, "no")) + { + argv[argc++] = "--" LOAD_NO_OID_L; + } + + if (uStringEqual (statisticsuse, "no")) + { + argv[argc++] = "--" LOAD_NO_STATISTICS_L; + } + + if (uStringEqual (nolog, "yes")) + { + argv[argc++] = "--" LOAD_IGNORE_LOGGING_L; + } + + if (error_control_file != NULL + && !uStringEqual (error_control_file, "none")) + { + argv[argc++] = "--" LOAD_ERROR_CONTROL_FILE_L; + argv[argc++] = error_control_file; + } + + if (ignore_class_file != NULL && !uStringEqual (ignore_class_file, "none")) + { + argv[argc++] = "--" LOAD_IGNORE_CLASS_L; + argv[argc++] = ignore_class_file; + } + argv[argc++] = dbname; + argv[argc++] = NULL; + + snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", + sco.dbmt_tmp_dir, "loaddb", getpid ()); + + retval = run_child (argv, 1, NULL, tmpfile, arniadb_err_file, NULL); /* loaddb */ + if (retval < 0) + { + if (access (arniadb_err_file, F_OK) == 0) + { + unlink (arniadb_err_file); + } + strcpy (_dbmt_error, argv[0]); + return ERR_SYSTEM_CALL; + } + + if (file_to_nvpairs (tmpfile, res) < 0) + { + if (access (arniadb_err_file, F_OK) == 0) + { + unlink (arniadb_err_file); + } + strcpy (_dbmt_error, tmpfile); + return ERR_TMPFILE_OPEN_FAIL; + } + unlink (tmpfile); + + /* the error file may not exist, don't check the error of it. */ + file_to_nvpairs (arniadb_err_file, res); + + if (access (arniadb_err_file, F_OK) == 0) + { + unlink (arniadb_err_file); + } + if (uStringEqualIgnoreCase (nv_get_val (req, "delete_orignal_files"), "y")) + { + if (schema) + { + unlink (schema); + } + if (object) + { + unlink (object); + } + if (index) + { + unlink (index); + } + } + + return ERR_NO_ERROR; +} + +int +ts_restoredb (nvplist *req, nvplist *res, char *_dbmt_error) +{ + int retval = ERR_NO_ERROR; + char *dbname, *date, *lv, *pathname, *partial, *recovery_path; + char cmd_name[ARNIADB_CMD_NAME_LEN]; + const char *argv[17]; + int argc = 0; + T_DB_SERVICE_MODE db_mode; + char arniadb_err_file[PATH_MAX]; + int status; + + arniadb_err_file[0] = '\0'; + + dbname = nv_get_val (req, "dbname"); + db_mode = uDatabaseMode (dbname, NULL); + if (db_mode == DB_SERVICE_MODE_SA) + { + sprintf (_dbmt_error, "%s", dbname); + return ERR_STANDALONE_MODE; + } + else if (db_mode == DB_SERVICE_MODE_CS) + { + sprintf (_dbmt_error, "%s", dbname); + return ERR_DB_ACTIVE; + } + + date = nv_get_val (req, "date"); + lv = nv_get_val (req, "level"); + pathname = nv_get_val (req, "pathname"); + partial = nv_get_val (req, "partial"); + recovery_path = nv_get_val (req, "recoverypath"); + + arniadb_cmd_name (cmd_name); + argv[argc++] = cmd_name; + argv[argc++] = UTIL_OPTION_RESTOREDB; + if ((date != NULL) && (strcmp (date, "none") != 0)) + { + argv[argc++] = "--" RESTORE_UP_TO_DATE_L; + argv[argc++] = date; + } + argv[argc++] = "--" RESTORE_LEVEL_L; + argv[argc++] = lv; + if (pathname != NULL && !uStringEqual (pathname, "none")) + { + argv[argc++] = "--" RESTORE_BACKUP_FILE_PATH_L; + argv[argc++] = pathname; + } + if (uStringEqual (partial, "y")) + { + argv[argc++] = "--" RESTORE_PARTIAL_RECOVERY_L; + } + + if (recovery_path != NULL && !uStringEqual (recovery_path, "") + && !uStringEqual (recovery_path, "none")) + { + /* use -u option to specify restore database path */ + argv[argc++] = "--" RESTORE_USE_DATABASE_LOCATION_PATH_L; + + if ((retval = + check_dbpath (recovery_path, _dbmt_error)) != ERR_NO_ERROR) + { + return retval; + } + if (access (recovery_path, F_OK) < 0) + { + retval = uCreateDir (recovery_path); + if (retval != ERR_NO_ERROR) + { + return retval; + } + } + + if ((retval = alter_dblocation (dbname, recovery_path)) != ERR_NO_ERROR) + { + return retval; + } + } + argv[argc++] = dbname; + argv[argc++] = NULL; + + snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", + sco.dbmt_tmp_dir, "restoredb", getpid ()); + + if (run_child (argv, 1, NULL, NULL, arniadb_err_file, &status) < 0) + { + strcpy_limit (_dbmt_error, argv[0], DBMT_ERROR_MSG_SIZE); + if (access (arniadb_err_file, F_OK) == 0) + { + unlink (arniadb_err_file); + } + return ERR_SYSTEM_CALL; + } + + if (status != 0 && read_error_file (arniadb_err_file, _dbmt_error, + DBMT_ERROR_MSG_SIZE) < 0) + { + if (access (arniadb_err_file, F_OK) == 0) + { + unlink (arniadb_err_file); + } + return ERR_WITH_MSG; + } + + if (access (arniadb_err_file, F_OK) == 0) + { + unlink (arniadb_err_file); + } + return ERR_NO_ERROR; +} + +int +ts_backup_vol_info (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char *dbname, *lv, *pathname, buf[1024], tmpfile[PATH_MAX]; + int ret; + FILE *infile; + char cmd_name[ARNIADB_CMD_NAME_LEN]; + const char *argv[10]; + int argc = 0; + + dbname = nv_get_val (req, "dbname"); + snprintf (tmpfile, PATH_MAX - 1, "%s/DBMT_task_%d.%d", sco.dbmt_tmp_dir, + TS_BACKUPVOLINFO, (int) getpid ()); + + if (uIsDatabaseActive (dbname)) + { + sprintf (_dbmt_error, "%s", dbname); + return ERR_DB_ACTIVE; + } + + if (uDatabaseMode (dbname, NULL) == DB_SERVICE_MODE_SA) + { + sprintf (_dbmt_error, "%s", dbname); + return ERR_STANDALONE_MODE; + } + + lv = nv_get_val (req, "level"); + pathname = nv_get_val (req, "pathname"); + + arniadb_cmd_name (cmd_name); + argv[argc++] = cmd_name; + argv[argc++] = UTIL_OPTION_RESTOREDB; + argv[argc++] = "--" RESTORE_LIST_L; + if (lv != NULL && + (uStringEqual (lv, "0") || uStringEqual (lv, "1") + || uStringEqual (lv, "2"))) + { + argv[argc++] = "--" RESTORE_LEVEL_L; + argv[argc++] = lv; + } + if (pathname != NULL && !uStringEqual (pathname, "none")) + { + argv[argc++] = "--" RESTORE_BACKUP_FILE_PATH_L; + argv[argc++] = pathname; + } + + argv[argc++] = dbname; + argv[argc++] = NULL; + +#if defined(WINDOWS) + ret = run_child (argv, 1, NULL, tmpfile, NULL, NULL); /* restoredb -t */ +#else + ret = run_child (argv, 1, "/dev/null", tmpfile, NULL, NULL); /* restoredb -t */ +#endif + if (ret < 0) + { + sprintf (_dbmt_error, "%s", argv[0]); + return ERR_SYSTEM_CALL; + } + + infile = fopen (tmpfile, "r"); + if (infile == NULL) + { + strcpy (_dbmt_error, tmpfile); + return ERR_TMPFILE_OPEN_FAIL; + } + + while (fgets (buf, sizeof (buf), infile)) + { + uRemoveCRLF (buf); + nv_add_nvp (res, "line", buf); + } + fclose (infile); + unlink (tmpfile); + + return ERR_NO_ERROR; +} + +int +ts_get_dbsize (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char *dbname; + char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; + int ha_mode = 0; + char strbuf[PATH_MAX], dbdir[PATH_MAX]; + int no_tpage = 0, log_size = 0, baselen; + struct stat statbuf; + GeneralSpacedbResult *cmd_res; + T_ARNIADB_MODE arniadb_mode; +#if defined(WINDOWS) + char find_file[PATH_MAX]; + WIN32_FIND_DATA data; + HANDLE handle; + int found; +#else + DIR *dirp; + struct dirent *dp; +#endif + char *cur_file; + + /* get dbname */ + if ((dbname = nv_get_val (req, "dbname")) == NULL) + { + sprintf (_dbmt_error, "%s", "database name"); + return ERR_PARAM_MISSING; + } + + if (uRetrieveDBDirectory (dbname, dbdir) != ERR_NO_ERROR) + { + strcpy (_dbmt_error, dbname); + return ERR_DBDIRNAME_NULL; + } + + arniadb_mode = + (uDatabaseMode (dbname, &ha_mode) == + DB_SERVICE_MODE_NONE) ? ARNIADB_MODE_SA : ARNIADB_MODE_CS; + + if (ha_mode != 0) + { + append_host_to_dbname (dbname_at_hostname, dbname, + sizeof (dbname_at_hostname)); + cmd_res = cmd_spacedb (dbname_at_hostname, arniadb_mode); + } + else + { + cmd_res = cmd_spacedb (dbname, arniadb_mode); + } + + if (cmd_res == NULL || cmd_res->has_error()) + { + sprintf (_dbmt_error, "spacedb %s", dbname); + delete cmd_res; + return ERR_SYSTEM_CALL; + } + + + /* get log volume info */ +#if defined(WINDOWS) + snprintf (find_file, PATH_MAX - 1, "%s/*", dbdir); + if ((handle = FindFirstFile (find_file, &data)) == INVALID_HANDLE_VALUE) +#else + if ((dirp = opendir (dbdir)) == NULL) +#endif + { + sprintf (_dbmt_error, "%s", dbdir); + return ERR_DIROPENFAIL; + } + + baselen = (int) strlen (dbname); +#if defined(WINDOWS) + for (found = 1; found; found = FindNextFile (handle, &data)) +#else + while ((dp = readdir (dirp)) != NULL) +#endif + { +#if defined(WINDOWS) + cur_file = data.cFileName; +#else + cur_file = dp->d_name; +#endif + if (!strncmp (cur_file + baselen, "_lginf", 6) + || !strcmp (cur_file + baselen, ARNIADB_ACT_LOG_EXT) + || !strncmp (cur_file + baselen, ARNIADB_ARC_LOG_EXT, ARNIADB_ARC_LOG_EXT_LEN)) + { + snprintf (strbuf, sizeof (strbuf) - 1, "%s/%s", dbdir, cur_file); + stat (strbuf, &statbuf); + log_size += statbuf.st_size; + } + } + +#if defined(WINDOWS) + FindClose (handle); +#else + closedir (dirp); +#endif + + snprintf (strbuf, sizeof (strbuf) - 1, "%d", + cmd_res->get_cnt_tpage() * cmd_res->get_page_size() + cmd_res->get_log_page_size()); + nv_add_nvp (res, "dbsize", strbuf); + + return ERR_NO_ERROR; +} + +int +tsGetEnvironment (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char tmpfile[PATH_MAX]; + char strbuf[1024]; + FILE *infile; + char cmd_name[ARNIADB_CMD_NAME_LEN]; + const char *argv[5]; + + nv_add_nvp (res, "ARNIADB", sco.szArniadb); + nv_add_nvp (res, "ARNIADB_DATABASES", sco.szArniadb_databases); + nv_add_nvp (res, "ARNIADB_DBMT", sco.szArniadb); + // nv_add_nvp (res, "ARNIADB_CHARSET", getenv ("ARNIADB_CHARSET")); + snprintf (tmpfile, PATH_MAX - 1, "%s/DBMT_task_015.%d", sco.dbmt_tmp_dir, + (int) getpid ()); + + cmd_name[0] = '\0'; + snprintf (cmd_name, sizeof (cmd_name) - 1, "%s/%s%s", sco.szArniadb, + ARNIADB_DIR_BIN, UTIL_ARNIADB_REL_NAME); + + argv[0] = cmd_name; + argv[1] = NULL; + + run_child (argv, 1, NULL, tmpfile, NULL, NULL); /* arniadb_rel */ + + if ((infile = fopen (tmpfile, "r")) != NULL) + { + fgets (strbuf, sizeof (strbuf), infile); + fgets (strbuf, sizeof (strbuf), infile); + uRemoveCRLF (strbuf); + fclose (infile); + unlink (tmpfile); + nv_add_nvp (res, "ARNIADBVER", strbuf); + } + else + { + nv_add_nvp (res, "ARNIADBVER", "version information not available"); + } + + snprintf (tmpfile, PATH_MAX - 1, "%s/DBMT_task_015.%d", sco.dbmt_tmp_dir, + (int) getpid ()); + snprintf (cmd_name, sizeof (cmd_name) - 1, "%s/bin/arniadb_broker%s", + sco.szArniadb, DBMT_EXE_EXT); + + argv[0] = cmd_name; + argv[1] = "--version"; + argv[2] = NULL; + + run_child (argv, 1, NULL, tmpfile, NULL, NULL); /* arniadb_broker --version */ + + if ((infile = fopen (tmpfile, "r")) != NULL) + { + fgets (strbuf, sizeof (strbuf), infile); + fclose (infile); + uRemoveCRLF (strbuf); + unlink (tmpfile); + nv_add_nvp (res, "BROKERVER", strbuf); + } + else + { + nv_add_nvp (res, "BROKERVER", "version information not available"); + } + + if (sco.hmtab1 == 1) + { + nv_add_nvp (res, "HOSTMONTAB0", "ON"); + } + else + { + nv_add_nvp (res, "HOSTMONTAB0", "OFF"); + } + if (sco.hmtab2 == 1) + { + nv_add_nvp (res, "HOSTMONTAB1", "ON"); + } + else + { + nv_add_nvp (res, "HOSTMONTAB1", "OFF"); + } + if (sco.hmtab3 == 1) + { + nv_add_nvp (res, "HOSTMONTAB2", "ON"); + } + else + { + nv_add_nvp (res, "HOSTMONTAB2", "OFF"); + } + if (sco.hmtab4 == 1) + { + nv_add_nvp (res, "HOSTMONTAB3", "ON"); + } + else + { + nv_add_nvp (res, "HOSTMONTAB3", "OFF"); + } + +#if defined(WINDOWS) + nv_add_nvp (res, "osinfo", "NT"); +#elif LINUX + nv_add_nvp (res, "osinfo", "LINUX"); +#elif AIX + nv_add_nvp (res, "osinfo", "AIX"); +#elif HPUX + nv_add_nvp (res, "osinfo", "HPUX"); +#elif UNIXWARE7 + nv_add_nvp (res, "osinfo", "UNIXWARE7"); +#elif SOLARIS + nv_add_nvp (res, "osinfo", "SOLARIS"); +#else + nv_add_nvp (res, "osinfo", "unknown"); +#endif + + return ERR_NO_ERROR; +} + +int +ts_startinfo (nvplist *req, nvplist *res, char *_dbmt_error) +{ + T_SERVER_STATUS_RESULT *cmd_res; + int retval; + + /* add dblist */ + retval = ut_get_dblist (res, 1); + if (retval != ERR_NO_ERROR) + { + return retval; + } + + nv_add_nvp (res, "open", "activelist"); + cmd_res = cmd_server_status (); + if (cmd_res != NULL) + { + T_SERVER_STATUS_INFO *info = (T_SERVER_STATUS_INFO *) cmd_res->result; + int i; + for (i = 0; i < cmd_res->num_result; i++) + { +#ifdef JSON_SUPPORT + nv_add_nvp (res, "open", "active"); +#endif + nv_add_nvp (res, "dbname", info[i].db_name); +#ifdef JSON_SUPPORT + nv_add_nvp (res, "close", "active"); +#endif + } + } + nv_add_nvp (res, "close", "activelist"); + + uWriteDBnfo2 (cmd_res); + cmd_servstat_result_free (cmd_res); + + return ERR_NO_ERROR; +} + +int +ts_kill_process (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char *pid_str; + int pid; + char *tgt_name; + + if ((pid_str = nv_get_val (req, "pid")) == NULL) + { + strcpy (_dbmt_error, "pid"); + return ERR_PARAM_MISSING; + } + tgt_name = nv_get_val (req, "name"); + + pid = atoi (pid_str); + if (pid > 0) + { + if (kill (pid, SIGTERM) < 0) + { + DBMT_ERR_MSG_SET (_dbmt_error, strerror (errno)); + return ERR_WITH_MSG; + } + } + + nv_add_nvp (res, "name", tgt_name); + uWriteDBnfo (); + return ERR_NO_ERROR; +} + +static int +ts_check_backup_id (const char *backupid) +{ + FILE *infile; + char strbuf[SIZE_BUFFER_MAX]; + char strbuf_tmp[SIZE_BUFFER_MAX]; + char *conf_item[AUTOBACKUP_CONF_ENTRY_NUM]; + + strbuf[0] = '\0'; + strbuf_tmp[0] = '\0'; + + infile = + fopen (conf_get_dbmt_file (FID_AUTO_BACKUPDB_CONF, strbuf_tmp), "r"); + if (infile == NULL) + { + return 0; + } + + while (fgets (strbuf, sizeof (strbuf), infile)) + { + ut_trim (strbuf); + if (strbuf[0] == '#') + { + continue; + } + if (string_tokenize (strbuf, conf_item, AUTOBACKUP_CONF_ENTRY_NUM) < 0) + { + continue; + } + if (strcmp (conf_item[1], backupid) == 0) + { + fclose (infile); + return 1; + } + } + fclose (infile); + + return 0; +} + +static int +_check_backup_info (const char *conf_item[], int check_backupid, + char *_dbmt_error) +{ + char time_item[5]; + char dbname[NAME_MAX]; + char path_item[PATH_MAX]; + char conf_value_item[NAME_MAX]; + + char *token = NULL; + + int i = 0; + int period_type_exist = 0; + int period_date_exist = 0; + int period_date = 0; + + time_item[0] = '\0'; + dbname[0] = '\0'; + path_item[0] = '\0'; + conf_value_item[0] = '\0'; + + /* check the validation of dbname */ + snprintf (dbname, NAME_MAX, "%s", conf_item[0]); + if (_isRegisteredDB (dbname) == 0) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", conf_item[0]); + return ERR_DB_NONEXISTANT; + } + /* check the validation of backupid */ + if (check_backupid == 1) + { + if (ts_check_backup_id (conf_item[1]) == 1) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, + "backupid(%s) already exist.", conf_item[1]); + return ERR_WITH_MSG; + } + } + /* check the validation of path */ + snprintf (path_item, PATH_MAX, "%s", conf_item[2]); + if (access (path_item, F_OK) < 0) + { + if (uCreateDir (path_item) == ERR_NO_ERROR) + { + uRemoveDir (path_item, REMOVE_DIR_FORCED); + } + else + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "Error : %s : %s", + conf_item[2], strerror (errno)); + return ERR_WITH_MSG; + } + } + else if (access (path_item, R_OK | W_OK) < 0) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "Error : %s : %s", + conf_item[2], strerror (errno)); + return ERR_WITH_MSG; + } + /* check the validation of period_type */ + for (i = 0; i < AUTOBACKUP_PERIOD_TYPE_NUM; i++) + { + if (strcmp (conf_item[3], autobackup_period_type[i]) == 0) + { + period_type_exist = 1; + break; + } + } + /* 0 is meaning period type is out of autobackup_period_type */ + if (period_type_exist == 0) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, + "(%s) is not allowed for parameter(%s).", conf_item[3], + autobackup_conf_entry[3]); + return ERR_WITH_MSG; + } + /* check the validation of period_date */ + /* period_date: Monthly */ + if ((strcmp (conf_item[3], AUTO_BACKUP_PERIOD_TYPE_MONTHLY) == 0)) + { + snprintf (conf_value_item, NAME_MAX, "%s", conf_item[4]); + token = strtok (conf_value_item, " ,"); + while (token != NULL) + { + period_date = atoi (token); + if ((period_date <= 0) || (period_date > 31)) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, + "(%s) is not allowed for parameter(%s).", token, + autobackup_conf_entry[4]); + return ERR_WITH_MSG; + } + + token = strtok (NULL, " ,"); + } + } + /* period_date: Weekly */ + else if (strcmp (conf_item[3], AUTO_BACKUP_PERIOD_TYPE_WEEKLY) == 0) + { + snprintf (conf_value_item, NAME_MAX, "%s", conf_item[4]); + token = strtok (conf_value_item, " ,"); + while (token != NULL) + { + for (i = 0; i < AUTOBACKUP_PERIOD_WEEK_NUM; i++) + { + if (strcmp (token, autobackup_period_week[i]) == 0) + { + period_date_exist = 1; + break; + } + } + /* 0 is meaning period type is out of autobackup_period_type */ + if (period_date_exist == 0) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, + "(%s) is not allowed for parameter(%s).", token, + autobackup_conf_entry[4]); + return ERR_WITH_MSG; + } + + period_date_exist = 0; + token = strtok (NULL, " ,"); + } + } + /* period_date: Daily */ + else if (strcmp (conf_item[3], AUTO_BACKUP_PERIOD_TYPE_DAILY) == 0) + { + /* do nothing */ + } + /* period_date: Hourly */ + else if (strcmp (conf_item[3], AUTO_BACKUP_PERIOD_TYPE_HOURLY) == 0) + { + period_date = atoi (conf_item[4]); + if ((period_date <= 0) || (period_date > 24)) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, + "(%s) is not allowed for parameter(%s).", conf_item[4], + autobackup_conf_entry[4]); + return ERR_WITH_MSG; + } + } + /* period_date: Special */ + else + { + snprintf (conf_value_item, NAME_MAX, "%s", conf_item[4]); + token = strtok (conf_value_item, " ,"); + while (token != NULL) + { + /* convert period_date from YYYY-MM-DD into YYYYMMDD */ + period_date = atoi (token) * 10000; /* convert year: YYYY0000 */ + period_date += atoi (token + 5) * 100; /* convert month: YYYYMM00 */ + period_date += atoi (token + 8); /* convert day: YYYYMMDD */ + + if (((period_date / 10000 - 1900) < 0) + || (((period_date % 10000) / 100) <= 0) + || (((period_date % 10000) / 100) > 12) + || ((period_date % 100) <= 0) || ((period_date % 100) > 31)) + { + /* tm_year : True year - 1900 */ + /* tm_mon : [0, 11] */ + /* tm_mday : [1, 31] */ + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, + "(%s) is not allowed for parameter(%s).", + conf_item[4], autobackup_conf_entry[4]); + return ERR_WITH_MSG; + } + token = strtok (NULL, " ,"); + } + } + /* check time */ + if (strlen (conf_item[5]) == 4) + { + snprintf (time_item, sizeof (time_item), "%s", conf_item[5]); + if ((time_item[0] < '0') || (time_item[0] >= '3')) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, + "(%s) is not valid time format for parameter(%s).", + conf_item[5], autobackup_conf_entry[5]); + return ERR_WITH_MSG; + } + if ((time_item[1] < '0') || (time_item[1] > '9')) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, + "(%s) is not valid time format for parameter(%s).", + conf_item[5], autobackup_conf_entry[5]); + return ERR_WITH_MSG; + } + if ((time_item[0] == '2') && (time_item[1] >= '4')) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, + "(%s) is not valid time format for parameter(%s).", + conf_item[5], autobackup_conf_entry[5]); + return ERR_WITH_MSG; + } + if ((time_item[2] < '0') || (time_item[2] >= '6')) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, + "(%s) is not valid time format for parameter(%s).", + conf_item[5], autobackup_conf_entry[5]); + return ERR_WITH_MSG; + } + if ((time_item[3] < '0') || (time_item[3] > '9')) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, + "(%s) is not valid time format for parameter(%s).", + conf_item[5], autobackup_conf_entry[5]); + return ERR_WITH_MSG; + } + } + else + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, + "(%s) is not valid time format for parameter(%s).", + conf_item[5], autobackup_conf_entry[5]); + return ERR_WITH_MSG; + } + /* check level: 0 (default ), 1, 2 */ + if ((conf_item[6][0] < '0') || (conf_item[6][0] >= '3')) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, + "(%c) is not allowed for parameter(%s).", conf_item[6][0], + autobackup_conf_entry[6]); + return ERR_WITH_MSG; + } + return ERR_NO_ERROR; +} + +int +ts_backupdb_info (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char db_dir[PATH_MAX], log_dir[PATH_MAX]; + char *tok[3], vinf[PATH_MAX], buf[LINE_MAX]; + char db_backup_dir[PATH_MAX]; + FILE *infile; + struct stat statbuf; + + char *dbname = NULL; + + db_dir[0] = '\0'; + log_dir[0] = '\0'; + vinf[0] = '\0'; + buf[0] = '\0'; + tok[0] = NULL; + db_backup_dir[0] = '\0'; /* Used for extension for backup path. */ + + dbname = nv_get_val (req, "dbname"); + if (dbname == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "dbname"); + return ERR_PARAM_MISSING; + } + + if (uDatabaseMode (dbname, NULL) == DB_SERVICE_MODE_SA) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", dbname); + return ERR_STANDALONE_MODE; + } + + if (uRetrieveDBDirectory (dbname, db_dir) != ERR_NO_ERROR) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", dbname); + return ERR_DBDIRNAME_NULL; + } + + if (uRetrieveDBLogDirectory (dbname, log_dir) != ERR_NO_ERROR) + { + strcpy (_dbmt_error, dbname); + return ERR_DBDIRNAME_NULL; + } + + snprintf (vinf, sizeof (vinf), "%s/%s%s", log_dir, dbname, + ARNIADB_BACKUP_INFO_EXT); + + if (access (vinf, F_OK) < 0) + { + goto exit_success; + } + + if ((infile = fopen (vinf, "rt")) != NULL) + { + while (fgets (buf, sizeof (buf), infile)) + { + ut_trim (buf); + if (string_tokenize (buf, tok, 3) < 0) + { + continue; + } + if (stat (tok[2], &statbuf) == 0) + { + snprintf (vinf, sizeof (vinf), "level%s", tok[0]); + nv_add_nvp (res, "open", vinf); + nv_add_nvp (res, "path", tok[2]); + nv_add_nvp_int (res, "size", statbuf.st_size); + ts_add_nvp_time (res, "data", statbuf.st_mtime, + "%04d.%02d.%02d.%02d.%02d", NV_ADD_DATE_TIME); + nv_add_nvp (res, "close", vinf); + } + } + fclose (infile); + } + else + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", vinf); + return ERR_PERMISSION; + } + +exit_success: + /* In ARNIADB Manager, $db_dir/backup is default path. */ + snprintf (db_backup_dir, sizeof (db_backup_dir), "%s/backup", db_dir); + nv_add_nvp (res, "dbdir", db_backup_dir); + + nv_add_nvp_int (res, "freespace", ut_disk_free_space (db_dir)); + + return ERR_NO_ERROR; +} + +int +ts_unloaddb_info (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char *n, *v, buf[1024]; + FILE *infile; + int flag = 0; + struct stat statbuf; + + snprintf (buf, sizeof (buf) - 1, "%s/unloaddb.info", + sco.szArniadb_databases); + if ((infile = fopen (buf, "rt")) == NULL) + { + return ERR_NO_ERROR; + } + + while (fgets (buf, sizeof (buf), infile)) + { + uRemoveCRLF (buf); + + if ((v = strchr (buf, ' ')) == NULL) + { + continue; + } + + *v = '\0'; + n = buf; + v++; + + while (*v == ' ') + { + v++; + } + + if (!strcmp (n, "%")) + { + if (flag == 1) + { + nv_add_nvp (res, "close", "database"); + } + else + { + flag = 1; + } + nv_add_nvp (res, "open", "database"); + nv_add_nvp (res, "dbname", v); + } + else + { + if (stat (v, &statbuf) == 0) + { + char timestr[64]; + char tmpbuf[1024]; + time_to_str (statbuf.st_mtime, "%04d.%02d.%02d %02d:%02d", + timestr, TIME_STR_FMT_DATE_TIME); + snprintf (tmpbuf, sizeof (tmpbuf) - 1, "%s;%s", v, timestr); + nv_add_nvp (res, n, tmpbuf); + } + } + } + if (flag == 1) + { + nv_add_nvp (res, "close", "database"); + } + fclose (infile); + + return ERR_NO_ERROR; +} + +/* backup automation */ + +int +ts_get_backup_info (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char *dbname; + FILE *infile; + char strbuf[1024]; + char *conf_item[AUTOBACKUP_CONF_ENTRY_NUM]; + int i; + + if ((dbname = nv_get_val (req, "_DBNAME")) == NULL) + { + strcpy (_dbmt_error, "database name"); + return ERR_PARAM_MISSING; + } + + nv_add_nvp (res, "dbname", dbname); + infile = fopen (conf_get_dbmt_file (FID_AUTO_BACKUPDB_CONF, strbuf), "r"); + if (infile == NULL) + { + return ERR_NO_ERROR; + } + + while (fgets (strbuf, sizeof (strbuf), infile)) + { + ut_trim (strbuf); + if (strbuf[0] == '#') + { + continue; + } + if (string_tokenize (strbuf, conf_item, AUTOBACKUP_CONF_ENTRY_NUM) < 0) + { + continue; + } + if (strcmp (conf_item[0], dbname) == 0) + { +#ifdef JSON_SUPPORT + nv_add_nvp (res, "open", dbname); +#endif + for (i = 0; i < AUTOBACKUP_CONF_ENTRY_NUM; i++) + { + nv_add_nvp (res, autobackup_conf_entry[i], conf_item[i]); + } +#ifdef JSON_SUPPORT + nv_add_nvp (res, "close", dbname); +#endif + } + } + fclose (infile); + + return ERR_NO_ERROR; +} + +int +ts_set_backup_info (nvplist *req, nvplist *res, char *_dbmt_error) +{ + FILE *infile, *outfile; + char line[LINE_MAX], tmpfile[PATH_MAX]; + char autofilepath[PATH_MAX]; + const char *conf_item[AUTOBACKUP_CONF_ENTRY_NUM]; + + int i = 0; + int retval = 0; + int no_auto_job = 1; /* 1 means there is no valid auto job */ + int backupid_exist = 0; + + autofilepath[0] = '\0'; + line[0] = '\0'; + tmpfile[0] = '\0'; + + for (i = 0; i < AUTOBACKUP_CONF_ENTRY_NUM - 1; i++) + { + conf_item[i] = nv_get_val (req, autobackup_conf_entry[i]); + if (conf_item[i] == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", + autobackup_conf_entry[i]); + return ERR_PARAM_MISSING; + } + } + + conf_item[AUTOBACKUP_CONF_ENTRY_NUM - 1] = + nv_get_val (req, autobackup_conf_entry[AUTOBACKUP_CONF_ENTRY_NUM - 1]); + if (conf_item[AUTOBACKUP_CONF_ENTRY_NUM - 1] == NULL) + { + conf_item[AUTOBACKUP_CONF_ENTRY_NUM - 1] = "1"; + } + + retval = _check_backup_info (conf_item, 0, _dbmt_error); + if (retval != ERR_NO_ERROR) + { + return retval; + } + + conf_get_dbmt_file (FID_AUTO_BACKUPDB_CONF, autofilepath); + if (access (autofilepath, F_OK) < 0) + { + outfile = fopen (autofilepath, "w"); + if (outfile == NULL) + { + strcpy (_dbmt_error, autofilepath); + return ERR_FILE_OPEN_FAIL; + } + for (i = 0; i < AUTOBACKUP_CONF_ENTRY_NUM; i++) + { + fprintf (outfile, "%s ", conf_item[i]); + } + fprintf (outfile, "\n"); + fclose (outfile); + return ERR_NO_ERROR; + } + + if ((infile = fopen (autofilepath, "r")) == NULL) + { + strcpy (_dbmt_error, autofilepath); + return ERR_FILE_OPEN_FAIL; + } + snprintf (tmpfile, PATH_MAX, "%s/DBMT_task_%d.%d", sco.dbmt_tmp_dir, + TS_SETBACKUPINFO, (int) getpid ()); + if ((outfile = fopen (tmpfile, "w")) == NULL) + { + fclose (infile); + return ERR_TMPFILE_OPEN_FAIL; + } + while (fgets (line, sizeof (line), infile)) + { + char conf_dbname[128], conf_backupid[128]; + + if (sscanf (line, "%127s %127s", conf_dbname, conf_backupid) < 2) + { + continue; + } + + no_auto_job = 0; /* 0 means there is some auto job in autobackupdb.conf */ + + if ((strcmp (conf_dbname, conf_item[0]) == 0) && + (strcmp (conf_backupid, conf_item[1]) == 0)) + { + for (i = 0; i < AUTOBACKUP_CONF_ENTRY_NUM; i++) + { + fprintf (outfile, "%s ", conf_item[i]); + } + fprintf (outfile, "\n"); + backupid_exist = 1; + } + else + { + fputs (line, outfile); + } + } + fclose (infile); + fclose (outfile); + + move_file (tmpfile, autofilepath); + /* if config file is valid but no auto job plan, create it. */ + if (no_auto_job == 1) + { + outfile = fopen (autofilepath, "w"); + if (outfile == NULL) + { + strcpy (_dbmt_error, autofilepath); + return ERR_FILE_OPEN_FAIL; + } + for (i = 0; i < AUTOBACKUP_CONF_ENTRY_NUM; i++) + { + fprintf (outfile, "%s ", conf_item[i]); + } + fprintf (outfile, "\n"); + fclose (outfile); + return ERR_NO_ERROR; + } + /* if config file is valid and there is some auto job plan, but no special backupid, throw exception */ + if (backupid_exist == 0) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, + "Backup plan does not exist. backupid is %s.", conf_item[1]); + return ERR_WITH_MSG; + } + return ERR_NO_ERROR; +} + +int +ts_add_backup_info (nvplist *req, nvplist *res, char *_dbmt_error) +{ + FILE *outfile; + char autofilepath[PATH_MAX]; + const char *conf_item[AUTOBACKUP_CONF_ENTRY_NUM]; + + int i = 0; + int retval = 0; + + autofilepath[0] = '\0'; + + for (i = 0; i < AUTOBACKUP_CONF_ENTRY_NUM - 1; i++) + { + conf_item[i] = nv_get_val (req, autobackup_conf_entry[i]); + if (conf_item[i] == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", + autobackup_conf_entry[i]); + return ERR_PARAM_MISSING; + } + } + + conf_item[AUTOBACKUP_CONF_ENTRY_NUM - 1] = + nv_get_val (req, autobackup_conf_entry[AUTOBACKUP_CONF_ENTRY_NUM - 1]); + if (conf_item[AUTOBACKUP_CONF_ENTRY_NUM - 1] == NULL) + { + conf_item[AUTOBACKUP_CONF_ENTRY_NUM - 1] = "1"; + } + + retval = _check_backup_info (conf_item, 1, _dbmt_error); + if (retval != ERR_NO_ERROR) + { + return retval; + } + + conf_get_dbmt_file (FID_AUTO_BACKUPDB_CONF, autofilepath); + if ((outfile = fopen (autofilepath, "a")) == NULL) + { + strcpy (_dbmt_error, autofilepath); + return ERR_FILE_OPEN_FAIL; + } + for (i = 0; i < AUTOBACKUP_CONF_ENTRY_NUM; i++) + { + fprintf (outfile, "%s ", conf_item[i]); + } + fprintf (outfile, "\n"); + + fclose (outfile); + + return ERR_NO_ERROR; +} + +int +ts_delete_backup_info (nvplist *req, nvplist *res, char *_dbmt_error) +{ + FILE *infile, *outfile; + char line[LINE_MAX], tmpfile[PATH_MAX]; + char autofilepath[PATH_MAX]; + + char *dbname = NULL; + char *backupid = NULL; + + line[0] = '\0'; + tmpfile[0] = '\0'; + autofilepath[0] = '\0'; + + dbname = nv_get_val (req, "dbname"); + if (dbname == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "dbname"); + return ERR_PARAM_MISSING; + } + + backupid = nv_get_val (req, "backupid"); + if (backupid == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "backupid"); + return ERR_PARAM_MISSING; + } + if (ts_check_backup_id (backupid) == 0) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, + "Backup plan does not exist. backupid is %s.", backupid); + return ERR_WITH_MSG; + } + + conf_get_dbmt_file (FID_AUTO_BACKUPDB_CONF, autofilepath); + if ((infile = fopen (autofilepath, "r")) == NULL) + { + strcpy (_dbmt_error, autofilepath); + return ERR_FILE_OPEN_FAIL; + } + snprintf (tmpfile, PATH_MAX - 1, "%s/DBMT_task_%d.%d", sco.dbmt_tmp_dir, + TS_DELETEBACKUPINFO, (int) getpid ()); + if ((outfile = fopen (tmpfile, "w")) == NULL) + { + fclose (infile); + return ERR_TMPFILE_OPEN_FAIL; + } + + while (fgets (line, sizeof (line), infile)) + { + char conf_dbname[128], conf_backupid[128]; + + if (sscanf (line, "%127s %127s", conf_dbname, conf_backupid) != 2) + { + continue; + } + if ((strcmp (conf_dbname, dbname) != 0) || + backupid == NULL || (strcmp (conf_backupid, backupid) != 0)) + { + fputs (line, outfile); + } + } + fclose (infile); + fclose (outfile); + move_file (tmpfile, autofilepath); + return ERR_NO_ERROR; +} + +int +ts_get_log_info (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char *dbname, log_dir[PATH_MAX], buf[PATH_MAX]; + char *error_log_param; + struct stat statbuf; + int fname_len = 0; +#if defined(WINDOWS) + WIN32_FIND_DATA data; + HANDLE handle; + int found; +#else + DIR *dirp = NULL; + struct dirent *dp = NULL; +#endif + char find_file[PATH_MAX]; + char *fname; + + dbname = nv_get_val (req, "_DBNAME"); + + if ((dbname == NULL) + || (uRetrieveDBDirectory (dbname, log_dir) != ERR_NO_ERROR)) + { + if (dbname != NULL) + { + strcpy (_dbmt_error, dbname); + } + return ERR_DBDIRNAME_NULL; + } + + nv_add_nvp (res, "dbname", dbname); + nv_add_nvp (res, "open", "loginfo"); + + if ((error_log_param = _ts_get_error_log_param (dbname)) == NULL) + { + snprintf (buf, sizeof (buf) - 1, "%s/%s.err", log_dir, dbname); + } + else if (error_log_param[0] == '/') + { + snprintf (buf, sizeof (buf) - 1, "%s", error_log_param); + } +#if defined(WINDOWS) + else if (error_log_param[2] == '/') + { + snprintf (buf, sizeof (buf) - 1, "%s", error_log_param); + } +#endif + else + { + snprintf (buf, sizeof (buf) - 1, "%s/%s", log_dir, error_log_param); + } + + if (stat (buf, &statbuf) == 0) + { + nv_add_nvp (res, "open", "log"); + nv_add_nvp (res, "path", buf); + nv_add_nvp (res, ENCRYPT_ARG ("owner"), + get_user_name (statbuf.st_uid, buf)); + nv_add_nvp_int (res, "size", statbuf.st_size); + ts_add_nvp_time (res, "lastupdate", statbuf.st_mtime, "%04d.%02d.%02d", + NV_ADD_DATE); + nv_add_nvp (res, "close", "log"); + } + FREE_MEM (error_log_param); + + snprintf (buf, sizeof (buf) - 1, "%s/arn_server.err", log_dir); + if (stat (buf, &statbuf) == 0) + { + nv_add_nvp (res, "open", "log"); + nv_add_nvp (res, "path", buf); + nv_add_nvp (res, ENCRYPT_ARG ("owner"), + get_user_name (statbuf.st_uid, buf)); + nv_add_nvp_int (res, "size", statbuf.st_size); + ts_add_nvp_time (res, "lastupdate", statbuf.st_mtime, "%04d.%02d.%02d", + NV_ADD_DATE); + nv_add_nvp (res, "close", "log"); + } + + snprintf (find_file, PATH_MAX - 1, "%s/%s", sco.szArniadb, + ARNIADB_ERROR_LOG_DIR); +#if defined(WINDOWS) + snprintf (&find_file[strlen (find_file)], PATH_MAX - strlen (find_file) - 1, + "/*"); + if ((handle = FindFirstFile (find_file, &data)) == INVALID_HANDLE_VALUE) +#else + if ((dirp = opendir (find_file)) == NULL) +#endif + { + nv_add_nvp (res, "close", "loginfo"); + return ERR_NO_ERROR; + } +#if defined(WINDOWS) + for (found = 1; found; found = FindNextFile (handle, &data)) +#else + while ((dp = readdir (dirp)) != NULL) +#endif + { +#if defined(WINDOWS) + fname = data.cFileName; +#else + fname = dp->d_name; +#endif + fname_len = (int) strlen (fname); + /* the "4" is the size of ".err" */ + if (fname_len < 4 || (strcmp (fname + fname_len - 4, ".err") != 0)) + { + continue; + } + if (memcmp (fname, dbname, strlen (dbname))) + { + continue; + } + if (isalnum (fname[strlen (dbname)])) + { + continue; + } + snprintf (buf, sizeof (buf) - 1, "%s/%s/%s", sco.szArniadb, + ARNIADB_ERROR_LOG_DIR, fname); + if (stat (buf, &statbuf) == 0) + { + nv_add_nvp (res, "open", "log"); + nv_add_nvp (res, "path", buf); + nv_add_nvp (res, ENCRYPT_ARG ("owner"), + get_user_name (statbuf.st_uid, buf)); + nv_add_nvp_int (res, "size", statbuf.st_size); + ts_add_nvp_time (res, "lastupdate", statbuf.st_mtime, + "%04d.%02d.%02d", NV_ADD_DATE); + nv_add_nvp (res, "close", "log"); + } + } +#if defined(WINDOWS) + FindClose (handle); +#else + closedir (dirp); +#endif + + nv_add_nvp (res, "close", "loginfo"); + return ERR_NO_ERROR; +} + +int +ts_view_log (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char *filepath, *startline, *endline, buf[1024]; + FILE *infile; + int no_line = 0, start, end; + + filepath = nv_get_val (req, "path"); + if (filepath == NULL) + { + strcpy (_dbmt_error, "filepath"); + return ERR_PARAM_MISSING; + } + + startline = nv_get_val (req, "start"); + endline = nv_get_val (req, "end"); + + start = (startline == NULL ? -1 : atoi (startline)); + end = (endline == NULL ? -1 : atoi (endline)); + + if ((infile = fopen (filepath, "rt")) == NULL) + { + sprintf (_dbmt_error, "%s", filepath); + return ERR_FILE_OPEN_FAIL; + } + + nv_add_nvp (res, "path", filepath); + nv_add_nvp (res, "open", "log"); + while (fgets (buf, sizeof (buf), infile)) + { + no_line++; + if (start != -1 && end != -1) + { + if (start > no_line || end < no_line) + { + continue; + } + } + + uRemoveCRLF (buf); + nv_add_nvp (res, "line", buf); + } + nv_add_nvp (res, "close", "log"); + fclose (infile); + + if (start != -1 && end != -1) + { + nv_add_nvp_int (res, "start", (start > no_line ? no_line : start)); + nv_add_nvp_int (res, "end", (end > no_line ? no_line : end)); + } + + nv_add_nvp_int (res, "total", no_line); + + return ERR_NO_ERROR; +} + +int +ts_reset_log (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char *path; + FILE *outfile; + + path = nv_get_val (req, "path"); + if (path == NULL) + { + strcpy (_dbmt_error, "filepath"); + return ERR_PARAM_MISSING; + } + + outfile = fopen (path, "w"); + if (outfile == NULL) + { + strcpy (_dbmt_error, path); + return ERR_FILE_OPEN_FAIL; + } + fclose (outfile); + + return ERR_NO_ERROR; +} + +int +ts_get_auto_add_vol (nvplist *req, nvplist *res, char *_dbmt_error) +{ + FILE *infile = NULL; + char *dbname; + char strbuf[1024], file[PATH_MAX]; + char *conf_item[AUTOADDVOL_CONF_ENTRY_NUM]; + int i; + + if ((dbname = nv_get_val (req, "_DBNAME")) == NULL) + { + sprintf (_dbmt_error, "%s", "database name"); + return ERR_PARAM_MISSING; + } + + nv_add_nvp (res, autoaddvol_conf_entry[1], "OFF"); + nv_add_nvp (res, autoaddvol_conf_entry[2], "0.0"); + nv_add_nvp (res, autoaddvol_conf_entry[3], "0"); + nv_add_nvp (res, autoaddvol_conf_entry[4], "OFF"); + nv_add_nvp (res, autoaddvol_conf_entry[5], "0.0"); + nv_add_nvp (res, autoaddvol_conf_entry[6], "0"); + + infile = fopen (conf_get_dbmt_file (FID_AUTO_ADDVOLDB_CONF, file), "r"); + if (infile == NULL) + { + return ERR_NO_ERROR; + } + + while (fgets (strbuf, sizeof (strbuf), infile)) + { + ut_trim (strbuf); + if (strbuf[0] == '#') + { + continue; + } + if (string_tokenize (strbuf, conf_item, AUTOADDVOL_CONF_ENTRY_NUM) < 0) + { + continue; + } + if (strcmp (conf_item[0], dbname) == 0) + { + for (i = 1; i < AUTOADDVOL_CONF_ENTRY_NUM; i++) + { + nv_update_val (res, autoaddvol_conf_entry[i], conf_item[i]); + } + break; + } + } + fclose (infile); + + return ERR_NO_ERROR; +} + +int +ts_set_auto_add_vol (nvplist *req, nvplist *res, char *_dbmt_error) +{ + FILE *infile, *outfile; + char line[1024], tmpfile[PATH_MAX]; + char auto_addvol_conf_file[PATH_MAX]; + char *conf_item[AUTOADDVOL_CONF_ENTRY_NUM]; + int i; + + if ((conf_item[0] = nv_get_val (req, "_DBNAME")) == NULL) + { + sprintf (_dbmt_error, "%s", "database name"); + return ERR_PARAM_MISSING; + } + + for (i = 1; i < AUTOADDVOL_CONF_ENTRY_NUM; i++) + { + conf_item[i] = nv_get_val (req, autoaddvol_conf_entry[i]); + if (conf_item[i] == NULL) + { + strcpy (_dbmt_error, autoaddvol_conf_entry[i]); + return ERR_PARAM_MISSING; + } + } + + conf_get_dbmt_file (FID_AUTO_ADDVOLDB_CONF, auto_addvol_conf_file); + if (access (auto_addvol_conf_file, F_OK) < 0) + { + outfile = fopen (auto_addvol_conf_file, "w"); + if (outfile == NULL) + { + strcpy (_dbmt_error, auto_addvol_conf_file); + return ERR_FILE_OPEN_FAIL; + } + for (i = 0; i < AUTOADDVOL_CONF_ENTRY_NUM; i++) + { + fprintf (outfile, "%s ", conf_item[i]); + } + fprintf (outfile, "\n"); + fclose (outfile); + return ERR_NO_ERROR; + } + + infile = fopen (auto_addvol_conf_file, "r"); + if (infile == NULL) + { + strcpy (_dbmt_error, auto_addvol_conf_file); + return ERR_FILE_OPEN_FAIL; + } + snprintf (tmpfile, PATH_MAX - 1, "%s/DBMT_task_045.%d", sco.dbmt_tmp_dir, + (int) getpid ()); + outfile = fopen (tmpfile, "w"); + if (outfile == NULL) + { + fclose (infile); + return ERR_TMPFILE_OPEN_FAIL; + } + + while (fgets (line, sizeof (line), infile)) + { + char conf_dbname[128]; + + if (sscanf (line, "%127s", conf_dbname) < 1) + { + continue; + } + + if (strcmp (conf_dbname, conf_item[0]) != 0) + { + fputs (line, outfile); + } + } + for (i = 0; i < AUTOADDVOL_CONF_ENTRY_NUM; i++) + { + fprintf (outfile, "%s ", conf_item[i]); + } + fprintf (outfile, "\n"); + fclose (infile); + fclose (outfile); + + move_file (tmpfile, auto_addvol_conf_file); + + return ERR_NO_ERROR; +} + +int +ts_get_addvol_status (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char *dbname = NULL; + char dbdir[PATH_MAX]; + + if ((dbname = nv_get_val (req, "_DBNAME")) == NULL) + { + sprintf (_dbmt_error, "%s", "database name"); + return ERR_PARAM_MISSING; + } + + if (uRetrieveDBDirectory (dbname, dbdir) != ERR_NO_ERROR) + { + strcpy (_dbmt_error, dbname); + return ERR_DBDIRNAME_NULL; + } + + nv_add_nvp_int (res, "freespace", ut_disk_free_space (dbdir)); + nv_add_nvp (res, "volpath", dbdir); + return ERR_NO_ERROR; +} + +int +ts_get_tran_info (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char *dbname = NULL; + char *dbpasswd = NULL; + char *user = NULL; + char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; + int ha_mode = 0; + char buf[1024]; + char tmpfile[PATH_MAX]; + char errfile[PATH_MAX]; + FILE *infile = NULL; + char *tok[9]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; + const char *argv[10]; + int argc = 0; + int retval = 0; + int tmp = 0; + T_DB_SERVICE_MODE db_mode; + char *sqltext; + + cmd_name[0] = '\0'; + buf[0] = '\0'; + tmpfile[0] = '\0'; + errfile[0] = '\0'; + dbname_at_hostname[0] = '\0'; + + if ((dbname = nv_get_val (req, "dbname")) == NULL) + { + strncpy (_dbmt_error, "dbname", DBMT_ERROR_MSG_SIZE); + return ERR_PARAM_MISSING; + } + + /* get database mode. */ + db_mode = uDatabaseMode (dbname, &ha_mode); + if (db_mode == DB_SERVICE_MODE_SA) + { + strncpy (_dbmt_error, dbname, DBMT_ERROR_MSG_SIZE); + return ERR_STANDALONE_MODE; + } + + snprintf (tmpfile, PATH_MAX - 1, "%s/DBMT_task_%d.%d", sco.dbmt_tmp_dir, + TS_GETTRANINFO, (int) getpid ()); + snprintf (errfile, PATH_MAX - 1, "%s/DBMT_task_%d.stderr.%d", + sco.dbmt_tmp_dir, TS_GETTRANINFO, (int) getpid ()); + + arniadb_cmd_name (cmd_name); + argv[argc++] = cmd_name; + argv[argc++] = UTIL_OPTION_TRANLIST; + + argv[argc++] = "-f"; + + if (ha_mode != 0) + { + append_host_to_dbname (dbname_at_hostname, dbname, + sizeof (dbname_at_hostname)); + argv[argc++] = dbname_at_hostname; + } + else + { + argv[argc++] = dbname; + } + + argv[argc++] = NULL; + + retval = run_child (argv, 1, NULL, tmpfile, errfile, NULL); /* tranlist */ + if (retval < 0) + { + strncpy (_dbmt_error, argv[0], DBMT_ERROR_MSG_SIZE); + return ERR_SYSTEM_CALL; + } + + if ((infile = fopen (errfile, "r")) == NULL) + { + return ERR_TMPFILE_OPEN_FAIL; + } + + retval = ERR_NO_ERROR; + tmp = 0; + while (fgets (buf, sizeof (buf), infile)) + { + ut_trim (buf); + strncpy (_dbmt_error + tmp, buf, DBMT_ERROR_MSG_SIZE - tmp); + tmp += (int) strlen (buf); + retval = ERR_WITH_MSG; + } + + if (retval != ERR_NO_ERROR) + { + fclose (infile); + unlink (tmpfile); + unlink (errfile); + return retval; + } + + fclose (infile); + + if ((infile = fopen (tmpfile, "rt")) == NULL) + { + return ERR_TMPFILE_OPEN_FAIL; + } + nv_add_nvp (res, "dbname", dbname); + nv_add_nvp (res, "open", "transactioninfo"); + while (fgets (buf, sizeof (buf), infile)) + { + if (buf[0] == '-') + { + break; + } + } + while (fgets (buf, sizeof (buf), infile)) + { + ut_trim (buf); + if (buf[0] == '-') + { + break; + } + if (string_tokenize (buf, tok, 9) < 0) + { + continue; + } + nv_add_nvp (res, "open", "transaction"); + nv_add_nvp (res, "tranindex", tok[0]); + nv_add_nvp (res, ENCRYPT_ARG ("user"), tok[1]); + nv_add_nvp (res, "host", tok[2]); + nv_add_nvp (res, "pid", tok[3]); + nv_add_nvp (res, "program", tok[4]); + nv_add_nvp (res, "query_time", tok[5]); + nv_add_nvp (res, "tran_time", tok[6]); + nv_add_nvp (res, "wait_for_lock_holder", tok[7]); + if (strncmp (tok[8], "***", 3) == 0) + { + nv_add_nvp (res, "SQL_ID", "empty"); + } + else + { + nv_add_nvp (res, "SQL_ID", tok[8]); + + sqltext = tok[8] + strlen (tok[8]) + 1; + while (sqltext && *sqltext) + { + if (*sqltext == ' ') + { + sqltext++; + } + else + { + break; + } + } + nv_add_nvp (res, "SQL_Text", sqltext); + } + nv_add_nvp (res, "close", "transaction"); + } + nv_add_nvp (res, "close", "transactioninfo"); + fclose (infile); + unlink (tmpfile); + unlink (errfile); + + return ERR_NO_ERROR; +} + +/* + * read stdout and stderr files as error message. + * + */ +static void +read_stdout_stderr_as_err (char *stdout_file, char *stderr_file, + char *_dbmt_error) +{ + FILE *fp; + int len = 0; + int len_tmp = 0; + char buf[1024]; + + if (access (stderr_file, F_OK) == 0) + { + fp = fopen (stderr_file, "r"); + if (fp != NULL) + { + while (fgets (buf, sizeof (buf), fp) != NULL) + { + ut_trim (buf); + len_tmp = (int) strlen (buf); + + if (len_tmp < DBMT_ERROR_MSG_SIZE - len - 1) + { + strcpy (_dbmt_error, buf); + _dbmt_error += len_tmp; + len += len_tmp; + } + else + { + strcpy_limit (_dbmt_error, buf, DBMT_ERROR_MSG_SIZE - len); + strcpy_limit (_dbmt_error + DBMT_ERROR_MSG_SIZE - len - 4, + "...", 4); + break; + } + } + } + fclose (fp); + } + + if (access (stdout_file, F_OK) == 0) + { + fp = fopen (stdout_file, "r"); + if (fp != NULL) + { + while (fgets (buf, sizeof (buf), fp) != NULL) + { + ut_trim (buf); + len_tmp = (int) strlen (buf); + + if (len_tmp < DBMT_ERROR_MSG_SIZE - len - 1) + { + strcpy (_dbmt_error, buf); + _dbmt_error += len_tmp; + len += len_tmp; + } + else + { + strcpy_limit (_dbmt_error, buf, DBMT_ERROR_MSG_SIZE - len); + strcpy_limit (_dbmt_error + DBMT_ERROR_MSG_SIZE - len - 4, + "...", 4); + break; + } + } + } + fclose (fp); + } +} + +int +ts_killtran (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char *dbname = NULL; + char *dbpasswd = NULL; + char *type = NULL; + char *param = NULL; + char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; + char task_name[TASKNAME_LEN]; + const char *argv[10]; + int ha_mode = 0; + int argc = 0; + int is_need_param = 1; + int retval = 0; + T_DB_SERVICE_MODE db_mode; + + task_name[0] = '\0'; + dbname_at_hostname[0] = '\0'; + cmd_name[0] = '\0'; + + if ((dbname = nv_get_val (req, "dbname")) == NULL) + { + strcpy (_dbmt_error, "dbname"); + return ERR_PARAM_MISSING; + } + + dbpasswd = nv_get_val (req, "_DBPASSWD"); + + if ((type = nv_get_val (req, "type")) == NULL) + { + strcpy (_dbmt_error, "type"); + return ERR_PARAM_MISSING; + } + + param = nv_get_val (req, "parameter"); + + db_mode = uDatabaseMode (dbname, &ha_mode); + if (db_mode == DB_SERVICE_MODE_SA) + { + sprintf (_dbmt_error, "%s", dbname); + return ERR_STANDALONE_MODE; + } + + arniadb_cmd_name (cmd_name); + argv[argc++] = cmd_name; + argv[argc++] = UTIL_OPTION_KILLTRAN; + if (dbpasswd != NULL) + { + if (strcmp (type, "i") == 0 || strcmp (type, "u") == 0 || strcmp (type, "h") == 0 || strcmp (type, "p") == 0 + || strcmp (type, "s") == 0) + { + argv[argc++] = "--" KILLTRAN_DBA_PASSWORD_L; + argv[argc++] = dbpasswd; + } + } + + if (strcmp (type, "i") == 0) + { + /* remove (+) from formated string such as "1(+) | 1(-)" */ + /*char *p = strstr (param, "("); + if (p != NULL) + *p = '\0'; */ + + argv[argc++] = "--" KILLTRAN_KILL_TRANSACTION_INDEX_L; + } + else if (strcmp (type, "u") == 0) + { + argv[argc++] = "--" KILLTRAN_KILL_USER_NAME_L; + } + else if (strcmp (type, "h") == 0) + { + argv[argc++] = "--" KILLTRAN_KILL_HOST_NAME_L; + } + else if (strcmp (type, "p") == 0) + { + argv[argc++] = "--" KILLTRAN_KILL_PROGRAM_NAME_L; + } + else if (strcmp (type, "s") == 0) + { + argv[argc++] = "--" KILLTRAN_KILL_SQL_ID_L; + } + else if (strcmp (type, "q") == 0) + { + argv[argc++] = "--" KILLTRAN_KILL_QUERY_INFO_L; + is_need_param = 0; + } + else if (strcmp (type, "d") == 0) + { + argv[argc++] = "--" KILLTRAN_DISPLAY_INFORMATION_L; + is_need_param = 0; + } + else + { + strcpy (_dbmt_error, "invalid value in type."); + return ERR_WITH_MSG; + } + + if (is_need_param) + { + if (param == NULL) + { + strcpy (_dbmt_error, "parameter"); + return ERR_PARAM_MISSING; + } + argv[argc++] = param; + argv[argc++] = "--" KILLTRAN_FORCE_L; + } + if (ha_mode != 0) + { + append_host_to_dbname (dbname_at_hostname, dbname, + sizeof (dbname_at_hostname)); + argv[argc++] = dbname_at_hostname; + } + else + { + argv[argc++] = dbname; + } + + argv[argc++] = NULL; + + strncpy (task_name, "killtran", TASKNAME_LEN); + retval = _run_child (argv, 1, task_name, NULL, _dbmt_error); + if (retval != ERR_NO_ERROR) + { + return retval; + } + + ts_get_tran_info (req, res, _dbmt_error); + return ERR_NO_ERROR; +} + +int +ts_lockdb (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char buf[1024], tmpfile[PATH_MAX], tmpfile2[PATH_MAX], s[32]; + char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; + char task_name[TASKNAME_LEN]; + + const char *argv[10]; + int argc = 0; + int ha_mode = 0; + int retval = 0; + + char *dbname = NULL; + + T_DB_SERVICE_MODE db_mode; + FILE *infile, *outfile; + + buf[0] = '\0'; + tmpfile[0] = '\0'; + tmpfile2[0] = '\0'; + s[0] = '\0'; + dbname_at_hostname[0] = '\0'; + cmd_name[0] = '\0'; + task_name[0] = '\0'; + + if ((dbname = nv_get_val (req, "dbname")) == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "dbname"); + return ERR_PARAM_MISSING; + } + db_mode = uDatabaseMode (dbname, &ha_mode); + if (db_mode == DB_SERVICE_MODE_SA) + { + sprintf (_dbmt_error, "%s", dbname); + return ERR_STANDALONE_MODE; + } + + snprintf (tmpfile, PATH_MAX, "%s/DBMT_task_%d_1.%d.tmp", sco.dbmt_tmp_dir, + TS_LOCKDB, (int) getpid ()); + + arniadb_cmd_name (cmd_name); + argv[argc++] = cmd_name; + argv[argc++] = UTIL_OPTION_LOCKDB; + argv[argc++] = "--" LOCK_OUTPUT_FILE_L; + argv[argc++] = tmpfile; + + if (ha_mode != 0) + { + append_host_to_dbname (dbname_at_hostname, dbname, + sizeof (dbname_at_hostname)); + argv[argc++] = dbname_at_hostname; + } + else + { + argv[argc++] = dbname; + } + + argv[argc++] = NULL; + + strncpy (task_name, "lockdb", TASKNAME_LEN); + + retval = _run_child (argv, 1, task_name, NULL, _dbmt_error); + if (retval != ERR_NO_ERROR) + { + return retval; + } + + infile = fopen (tmpfile, "rt"); + if (infile == NULL) + { + return ERR_TMPFILE_OPEN_FAIL; + } + + /* create file that remove line feed at existed outputfile */ + snprintf (tmpfile2, PATH_MAX, "%s/DBMT_task_%d_2.%d.tmp", sco.dbmt_tmp_dir, + TS_LOCKDB, (int) getpid ()); + + outfile = fopen (tmpfile2, "w"); + if (outfile == NULL) + { + fclose (infile); + return ERR_TMPFILE_OPEN_FAIL; + } + + while (fgets (buf, sizeof (buf), infile)) + { + if (sscanf (buf, "%31s", s) == 1) + { + fputs (buf, outfile); + } + } + fclose (infile); + fclose (outfile); + unlink (tmpfile); + if ((infile = fopen (tmpfile2, "rt")) == NULL) + { + return ERR_TMPFILE_OPEN_FAIL; + } + + if (_ts_lockdb_parse_us (res, infile) < 0) + { + /* parshing error */ + strcpy (_dbmt_error, + "Lockdb operation has been failed(Unexpected state)."); + fclose (infile); + unlink (tmpfile2); + return ERR_WITH_MSG; + } + + fclose (infile); + unlink (tmpfile2); + + return ERR_NO_ERROR; +} + +int +ts_get_backup_list (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char buf[1024], file[PATH_MAX], s1[256], s2[256], *dbname, log_dir[512]; + FILE *infile; + int lv = -1; + + dbname = nv_get_val (req, "dbname"); + if (dbname == NULL) + { + strcpy (_dbmt_error, "database name"); + return ERR_PARAM_MISSING; + } + + if (uRetrieveDBLogDirectory (dbname, log_dir) != ERR_NO_ERROR) + { + strcpy (_dbmt_error, dbname); + return ERR_DBDIRNAME_NULL; + } + + snprintf (file, PATH_MAX - 1, "%s/%s%s", log_dir, dbname, + ARNIADB_BACKUP_INFO_EXT); + if ((infile = fopen (file, "rt")) != NULL) + { + while (fgets (buf, sizeof (buf), infile)) + { + sscanf (buf, "%255s %*s %255s", s1, s2); + lv = atoi (s1); + snprintf (buf, sizeof (buf) - 1, "level%d", lv); + nv_add_nvp (res, buf, s2); + } + fclose (infile); + } + for (lv++; lv <= 2; lv++) + { + snprintf (buf, sizeof (buf) - 1, "level%d", lv); + nv_add_nvp (res, buf, "none"); + } + + return ERR_NO_ERROR; +} + +static char * +remove_special_characters (char *str) +{ + char ret_old[MAX_LINE]; + char ret_new[MAX_LINE]; + unsigned int i = 0; + unsigned int j = 0; + + ret_new[0] = '\0'; + snprintf (ret_old, sizeof (ret_old), "%s", str); + + for (i = 0; i < sizeof (ret_old); i ++) + { + if ((ret_old[i] == '[') || (ret_old[i] == ']')) + { + continue; + } + ret_new[j] = ret_old[i]; + j++; + } + + snprintf (str, sizeof (ret_old), "%s", ret_new); + + return str; +} + +#if defined(WINDOWS) +static int +_get_dir_list (list < string > &files_list, const char *roor_dir, string special_key) +{ + HANDLE handle; + WIN32_FIND_DATA ffd; + char find_path[PATH_MAX]; + string ams_log_name; + + snprintf (find_path, PATH_MAX, "%s/*", roor_dir); + + handle = FindFirstFile (find_path, &ffd); + if (handle == INVALID_HANDLE_VALUE) + { + return -1; + } + while (FindNextFile (handle, &ffd)) + { + if (ffd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN + || ffd.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) + { + continue; + } + else if (! (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) + { + ams_log_name = ffd.cFileName; + if (special_key.length() == 0) + { + files_list.push_back (ams_log_name); + } + else + { + if (ams_log_name.find (special_key) < ams_log_name.length()) + { + files_list.push_back (ams_log_name); + } + } + } + } + FindClose (handle); + + return 0; +} + +#else + +static int +_get_dir_list (list < string > &files_list, const char *roor_dir, string special_key) +{ + DIR *dirptr = NULL; + struct dirent *entry; + string ams_log_name; + + if ((dirptr = opendir (roor_dir)) == NULL) + { + return -1; + } + while ((entry = readdir (dirptr)) != NULL) + { + if (strcmp (entry->d_name, ".") == 0 || strcmp (entry->d_name, "..") == 0) + { + continue; + } + + ams_log_name = entry->d_name; + + if (special_key.length() == 0) + { + files_list.push_back (ams_log_name); + } + else + { + if (ams_log_name.find (special_key) < ams_log_name.length()) + { + files_list.push_back (ams_log_name); + } + } + } + + closedir (dirptr); + return 0; +} +#endif + +static list < string > +_get_filtered_files_list (list < string > &files_list, string file_exp) +{ + list < string >::iterator itor; + list < string > ret_files_list; + + ret_files_list.clear(); + + if (files_list.empty() == true) + { + return ret_files_list; + } + + for (itor = files_list.begin(); itor != files_list.end(); itor++) + { + if ((*itor).find (file_exp) < (*itor).length()) + { + ret_files_list.push_back (*itor); + } + } + return ret_files_list; +} + +int +ts_load_access_log (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char buf[MAX_LINE], time[256]; + char root_dir[PATH_MAX]; + char log_full_dir[PATH_MAX]; + char err_full_dir[PATH_MAX]; + FILE *infile; + char *tok[10]; + unsigned int message_line = 0; + string log_exp = ".log"; + string err_exp = ".err"; + string ams_process_name = AMS_NAME; + list < string > all_files_list; + list < string > err_files_list; + list < string > log_files_list; + list < string >::iterator itor; + + buf[0] = '\0'; + time[0] = '\0'; + root_dir[0] = '\0'; + log_full_dir[0] = '\0'; + err_full_dir[0] = '\0'; + + snprintf (root_dir, PATH_MAX, "%s/%s/", sco.szArniadb, DBMT_LOG_DIR); + + _get_dir_list (all_files_list, root_dir, ams_process_name); + + log_files_list = _get_filtered_files_list (all_files_list, log_exp); + +#ifndef JSON_SUPPORT + nv_add_nvp (res, "open", "accesslog"); +#endif + for (itor = log_files_list.begin(); itor != log_files_list.end(); itor++) + { + snprintf (log_full_dir, PATH_MAX, "%s%s", root_dir, (*itor).c_str()); + if ((infile = fopen (log_full_dir, "rt")) != NULL) + { + while (fgets (buf, sizeof (buf), infile) != NULL) + { + remove_special_characters (buf); + ut_trim (buf); + + if (string_tokenize (buf, tok, 9) < 0) + { + continue; + } + + if (strcmp (tok[5], ACCESS_LOG) != 0) + { + continue; + } + + if (message_line > MAX_MSG_LINE) + { + nv_add_nvp (res, "full_line", + "The message is too much, please go to the log path and get the left."); +#ifndef JSON_SUPPORT + nv_add_nvp (res, "close", "errorlog"); +#endif + fclose (infile); + return ERR_NO_ERROR; + } +#ifdef JSON_SUPPORT + nv_add_nvp (res, "open", "accesslog"); +#endif + nv_add_nvp (res, ENCRYPT_ARG ("user"), tok[6]); + nv_add_nvp (res, "taskname", tok[8]); + snprintf (time, sizeof (time) - 1, "%s %s", tok[0], tok[1]); + nv_add_nvp (res, "time", time); + +#ifdef JSON_SUPPORT + nv_add_nvp (res, "close", "accesslog"); +#endif + + message_line++; + } + fclose (infile); + } + } + +#ifndef JSON_SUPPORT + nv_add_nvp (res, "close", "accesslog"); +#endif + + err_files_list = _get_filtered_files_list (all_files_list, err_exp); +#ifndef JSON_SUPPORT + nv_add_nvp (res, "open", "errorlog"); +#endif + for (itor = err_files_list.begin(); itor != err_files_list.end(); itor++) + { + snprintf (err_full_dir, PATH_MAX, "%s%s", root_dir, (*itor).c_str()); + if ((infile = fopen (err_full_dir, "rt")) != NULL) + { + while (fgets (buf, sizeof (buf), infile) != NULL) + { + remove_special_characters (buf); + ut_trim (buf); + + if (string_tokenize (buf, tok, 9) < 0) + { + continue; + } + + if (strcmp (tok[5], ACCESS_ERR) != 0) + { + continue; + } + + if (message_line > MAX_MSG_LINE) + { + nv_add_nvp (res, "full_line", + "The message is too much, please go to the log path and get the left."); +#ifndef JSON_SUPPORT + nv_add_nvp (res, "close", "errorlog"); +#endif + fclose (infile); + return ERR_NO_ERROR; + } + +#ifdef JSON_SUPPORT + nv_add_nvp (res, "open", "errorlog"); +#endif + nv_add_nvp (res, ENCRYPT_ARG ("user"), tok[6]); + nv_add_nvp (res, "taskname", tok[8]); + snprintf (time, sizeof (time) - 1, "%s %s", tok[0], tok[1]); + nv_add_nvp (res, "time", time); + nv_add_nvp (res, "errornote", tok[8] + strlen (tok[8]) + 1); +#ifdef JSON_SUPPORT + nv_add_nvp (res, "close", "errorlog"); +#endif + + message_line++; + } + fclose (infile); + } + } +#ifndef JSON_SUPPORT + nv_add_nvp (res, "close", "errorlog"); +#endif + return ERR_NO_ERROR; +} + +static void +_get_error_access_log_files (nvplist *req, nvplist *res, bool is_access_log) +{ + char log_full_dir[PATH_MAX]; + char root_dir[PATH_MAX]; + list < string > log_files_list; + list < string > all_files_list; + list < string >::iterator itor; + + string ams_process_name = AMS_NAME; + string log_exp = ".log"; + if (is_access_log == false) + { + log_exp = ".err"; + } + + log_full_dir[0] = '\0'; + + snprintf (root_dir, PATH_MAX, "%s/%s/", sco.szArniadb, DBMT_LOG_DIR); + + _get_dir_list (all_files_list, root_dir, ams_process_name); + log_files_list = _get_filtered_files_list (all_files_list, log_exp); + + if (log_files_list.empty() == true) + { + nv_add_nvp (res, "open", "logfileslist"); + + snprintf (log_full_dir, PATH_MAX, "%s%s%s", root_dir, ams_process_name.c_str(), log_exp.c_str()); + nv_add_nvp (res, "logfile", log_full_dir); + + nv_add_nvp (res, "close", "logfileslist"); + } + + for (itor = log_files_list.begin(); itor != log_files_list.end(); itor++) + { + nv_add_nvp (res, "open", "logfileslist"); + + snprintf (log_full_dir, PATH_MAX, "%s%s", root_dir, (*itor).c_str()); + nv_add_nvp (res, "logfile", log_full_dir); + + nv_add_nvp (res, "close", "logfileslist"); + } +} + + +int +ts_get_access_log_files (nvplist *req, nvplist *res, char *_dbmt_error) +{ + _get_error_access_log_files (req, res, true); + + return ERR_NO_ERROR; +} + +int +ts_get_error_log_files (nvplist *req, nvplist *res, char *_dbmt_error) +{ + _get_error_access_log_files (req, res, false); + + return ERR_NO_ERROR; +} + +int +tsGetAutoaddvolLog (nvplist *req, nvplist *res, char *_dbmt_error) +{ + FILE *infile; + char strbuf[1024]; + char dbname[512]; + char volname[512]; + char purpose[512]; + char page[512]; + char time[512]; + char outcome[512]; + char file[PATH_MAX]; + char *start_time, *end_time; + + start_time = nv_get_val (req, "start_time"); + end_time = nv_get_val (req, "end_time"); + + infile = fopen (conf_get_dbmt_file (FID_AUTO_ADDVOLDB_LOG, file), "r"); + if (infile != NULL) + { + while (fgets (strbuf, sizeof (strbuf), infile)) + { + uRemoveCRLF (strbuf); + /*testdb testdb_x002 data 1024 2012-11-16,10:4:57 success */ + sscanf (strbuf, "%511s %511s %511s %511s %511s %511s", dbname, + volname, purpose, page, time, outcome); + if (start_time != NULL && strcmp (time, start_time) < 0) + { + continue; + } + if (end_time != NULL && strcmp (time, end_time) > 0) + { + continue; + } + nv_add_nvp (res, "open", "log"); + nv_add_nvp (res, "dbname", dbname); + nv_add_nvp (res, "volname", volname); + nv_add_nvp (res, "purpose", purpose); + nv_add_nvp (res, "page", page); + nv_add_nvp (res, "time", time); + nv_add_nvp (res, "outcome", outcome); + nv_add_nvp (res, "close", "log"); + } + fclose (infile); + } + return ERR_NO_ERROR; +} + +int +ts_check_dir (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char *n, *v; + int i; + for (i = 0; i < req->nvplist_leng; i++) + { + nv_lookup (req, i, &n, &v); + if ((n != NULL) && (strcmp (n, "dir") == 0)) + { + if ((v == NULL) || (access (v, F_OK) < 0)) + { + nv_add_nvp (res, "noexist", v); + } + } + } + + return ERR_NO_ERROR; +} + +int +ts_check_file (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char *n, *v; + int i; + for (i = 0; i < req->nvplist_leng; i++) + { + nv_lookup (req, i, &n, &v); + if ((n != NULL) && (strcmp (n, "file") == 0)) + { + if ((v != NULL) && (access (v, F_OK) == 0)) + { + nv_add_nvp (res, "existfile", v); + } + } + } + + return ERR_NO_ERROR; +} + +int +ts_get_autobackupdb_error_log (nvplist *req, nvplist *res, + char *_dbmt_error) +{ + char buf[1024], logfile[PATH_MAX], s1[256], s2[256], time[512], dbname[256], + backupid[256]; + char *start_time, *end_time; + FILE *infile; + + start_time = nv_get_val (req, "start_time"); + end_time = nv_get_val (req, "end_time"); + + snprintf (logfile, PATH_MAX - 1, "%s/log/manager/auto_backupdb.log", + sco.szArniadb); + if ((infile = fopen (logfile, "r")) == NULL) + { + return ERR_NO_ERROR; + } + + while (fgets (buf, sizeof (buf), infile)) + { + if (sscanf (buf, "%255s %255s", s1, s2) != 2) + { + continue; + } + if (!strncmp (s1, "DATE:", 5)) + { + snprintf (time, sizeof (time) - 1, "%s %s", s1 + 5, s2 + 5); + if (start_time != NULL && strcmp (time, start_time) < 0) + { + continue; + } + if (end_time != NULL && strcmp (time, end_time) > 0) + { + continue; + } + if (fgets (buf, sizeof (buf), infile) == NULL) + { + break; + } + sscanf (buf, "%255s %255s", s1, s2); + snprintf (dbname, sizeof (dbname) - 1, "%s", s1 + 7); + snprintf (backupid, sizeof (backupid) - 1, "%s", s2 + 9); + if (fgets (buf, sizeof (buf), infile) == NULL) + { + break; + } + uRemoveCRLF (buf); + nv_add_nvp (res, "open", "error"); + nv_add_nvp (res, "dbname", dbname); + nv_add_nvp (res, "backupid", backupid); + nv_add_nvp (res, "error_time", time); + nv_add_nvp (res, "error_desc", buf + 3); + nv_add_nvp (res, "close", "error"); + } + } + fclose (infile); + + return ERR_NO_ERROR; +} + +int +ts_get_autoexecquery_error_log (nvplist *req, nvplist *res, + char *_dbmt_error) +{ + char buf[1024], logfile[PATH_MAX], s1[256], s2[256], s3[256], s4[256], + time[512], dbname[256], username[256], query_id[256], error_code[256]; + char *start_time, *end_time; + FILE *infile; + + start_time = nv_get_val (req, "start_time"); + end_time = nv_get_val (req, "end_time"); + + snprintf (logfile, PATH_MAX - 1, "%s/log/manager/auto_execquery.log", + sco.szArniadb); + if ((infile = fopen (logfile, "r")) == NULL) + { + return ERR_NO_ERROR; + } + + while (fgets (buf, sizeof (buf), infile)) + { + if (sscanf (buf, "%255s %255s", s1, s2) != 2) + { + continue; + } + if (!strncmp (s1, "DATE:", 5)) + { + snprintf (time, sizeof (time) - 1, "%s %s", s1 + 5, s2 + 5); /* 5 = strlen("DATE:"); 5 = strlen("TIME:"); */ + if (start_time != NULL && strcmp (time, start_time) < 0) + { + continue; + } + if (end_time != NULL && strcmp (time, end_time) > 0) + { + continue; + } + if (fgets (buf, sizeof (buf), infile) == NULL) + { + break; + } + + s3[0] = 0; + sscanf (buf, "%255s %255s %255s %255s", s1, s2, s3, s4); + snprintf (dbname, sizeof (dbname) - 1, "%s", s1 + 7); /* 7 = strlen("DBNAME:") */ + snprintf (username, sizeof (username) - 1, "%s", s2 + 14); /* 14 = strlen("EMGR-USERNAME:") */ + snprintf (query_id, sizeof (query_id) - 1, "%s", s3 + 9); /* 9 = strlen("QUERY-ID:") */ + snprintf (error_code, sizeof (error_code) - 1, "%s", s4 + 11); /* 11 = strlen("ERROR-CODE:") */ + if (fgets (buf, sizeof (buf), infile) == NULL) + { + break; + } + + uRemoveCRLF (buf); + nv_add_nvp (res, "open", "error"); + nv_add_nvp (res, "dbname", dbname); + nv_add_nvp (res, ENCRYPT_ARG ("username"), username); + nv_add_nvp (res, "query_id", query_id); + nv_add_nvp (res, "error_time", time); + nv_add_nvp (res, "error_code", error_code); + nv_add_nvp (res, "error_desc", buf + 3); + nv_add_nvp (res, "close", "error"); + } + } + fclose (infile); + return ERR_NO_ERROR; +} + +int +ts_trigger_operation (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char *task, *dbname, *dbuser, *dbpasswd; + char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; + int ha_mode = 0; + char cmd_name[ARNIADB_CMD_NAME_LEN]; + const char *argv[11]; + char input_file[PATH_MAX]; + char arniadb_err_file[PATH_MAX]; + int retval, argc; + T_DB_SERVICE_MODE db_mode; + + input_file[0] = '\0'; + arniadb_err_file[0] = '\0'; + + task = nv_get_val (req, "task"); + if (task != NULL) + { + if (strcmp (task, "addtrigger") == 0) + { + snprintf (input_file, PATH_MAX - 1, "%s/dbmt_task_%d_%d", + sco.dbmt_tmp_dir, TS_ADDNEWTRIGGER, (int) getpid ()); + } + else if (strcmp (task, "droptrigger") == 0) + { + snprintf (input_file, PATH_MAX - 1, "%s/dbmt_task_%d_%d", + sco.dbmt_tmp_dir, TS_DROPTRIGGER, (int) getpid ()); + } + else if (strcmp (task, "altertrigger") == 0) + { + snprintf (input_file, PATH_MAX - 1, "%s/dbmt_task_%d_%d", + sco.dbmt_tmp_dir, TS_ALTERTRIGGER, (int) getpid ()); + } + } + + dbname = nv_get_val (req, "_DBNAME"); + dbuser = nv_get_val (req, "_DBID"); + dbpasswd = nv_get_val (req, "_DBPASSWD"); + + cmd_name[0] = '\0'; + snprintf (cmd_name, sizeof (cmd_name) - 1, "%s/%s%s", sco.szArniadb, + ARNIADB_DIR_BIN, UTIL_ASQL_NAME); + argc = 0; + argv[argc++] = cmd_name; + + db_mode = uDatabaseMode (dbname, &ha_mode); + if (ha_mode != 0) + { + append_host_to_dbname (dbname_at_hostname, dbname, + sizeof (dbname_at_hostname)); + argv[argc++] = dbname_at_hostname; + } + else + { + argv[argc++] = dbname; + } + + argv[argc++] = NULL; + argv[argc++] = "--" ASQL_INPUT_FILE_L; + argv[argc++] = input_file; + if (dbuser) + { + argv[argc++] = "--" ASQL_USER_L; + argv[argc++] = dbuser; + if (dbpasswd) + { + argv[argc++] = "--" ASQL_PASSWORD_L; + argv[argc++] = dbpasswd; + } + } + + argv[argc++] = "--" ASQL_NO_AUTO_COMMIT_L; + + for (; argc < 11; argc++) + { + argv[argc] = NULL; + } + + if (!_isRegisteredDB (dbname)) + { + return ERR_DB_NONEXISTANT; + } + + if (db_mode == DB_SERVICE_MODE_SA) + { + sprintf (_dbmt_error, "%s", dbname); + return ERR_STANDALONE_MODE; + } + + if (db_mode == DB_SERVICE_MODE_CS) + { + /* run asql command with -cs option */ + argv[2] = "--" ASQL_CS_MODE_L; + } + + if (db_mode == DB_SERVICE_MODE_NONE) + { + /* run asql command with -sa option */ + argv[2] = "--" ASQL_SA_MODE_L; + } + + /* asql -sa -i input_file dbname */ + if (task != NULL) + { + if (strcmp (task, "addtrigger") == 0) + { + if (op_make_triggerinput_file_add (req, input_file) == 0) + { + strcpy (_dbmt_error, argv[0]); + return ERR_TMPFILE_OPEN_FAIL; + } + } + else if (strcmp (task, "droptrigger") == 0) + { + if (op_make_triggerinput_file_drop (req, input_file) == 0) + { + strcpy (_dbmt_error, argv[0]); + return ERR_TMPFILE_OPEN_FAIL; + } + } + else if (strcmp (task, "altertrigger") == 0) + { + if (op_make_triggerinput_file_alter (req, input_file) == 0) + { + strcpy (_dbmt_error, argv[0]); + return ERR_TMPFILE_OPEN_FAIL; + } + } + } + + snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", + sco.dbmt_tmp_dir, "trigger_operation", getpid ()); + SET_TRANSACTION_NO_WAIT_MODE_ENV (); + + retval = run_child (argv, 1, NULL, NULL, arniadb_err_file, NULL); /* asql - trigger */ + if (strlen (input_file) > 0) + { + unlink (input_file); + } + + if (read_asql_error_file (arniadb_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) + { + if (access (arniadb_err_file, F_OK) == 0) + { + unlink (arniadb_err_file); + } + return ERR_WITH_MSG; + } + if (access (arniadb_err_file, F_OK) == 0) + { + unlink (arniadb_err_file); + } + if (retval < 0) + { + strcpy (_dbmt_error, argv[0]); + return ERR_SYSTEM_CALL; + } + + nv_add_nvp (res, "dbname", dbname); + + return ERR_NO_ERROR; +} + +int +ts_get_triggerinfo (nvplist *req, nvplist *res, char *_dbmt_error) +{ + return cm_ts_get_triggerinfo (req, res, _dbmt_error); +} + +int +ts_set_autoexec_query (nvplist *req, nvplist *res, char *_dbmt_error) +{ + FILE *conf_file, *temp_file; + char autoexecquery_conf_file[PATH_MAX]; + char tmpfile[PATH_MAX]; + char db_uid[64]; + char db_name[DB_NAME_LEN]; + char dbmt_uid[DBMT_USER_NAME_LEN]; + char enc_dbpasswd[PASSWD_ENC_LENGTH]; + nvplist *db_user_info; + char line_buf[MAX_JOB_CONFIG_FILE_LINE_LENGTH]; + char *conf_item[AUTOEXECQUERY_CONF_ENTRY_NUM]; + int i, nvlist_index, nvlist_section_len; + char *name, *value; + + if ((conf_item[0] = nv_get_val (req, "_DBNAME")) == NULL) + { + sprintf (_dbmt_error, "%s", "database name"); + return ERR_PARAM_MISSING; + } + + if ((conf_item[4] = nv_get_val (req, "_ID")) == NULL) + { + sprintf (_dbmt_error, "%s", "database user"); + return ERR_PARAM_MISSING; + } + + conf_get_dbmt_file (FID_AUTO_EXECQUERY_CONF, autoexecquery_conf_file); + if (access (autoexecquery_conf_file, F_OK) == 0) + { + conf_file = fopen (autoexecquery_conf_file, "r"); + } + else + { + conf_file = fopen (autoexecquery_conf_file, "w+"); + } + if (conf_file == NULL) + { + return ERR_FILE_OPEN_FAIL; + } + + snprintf (tmpfile, PATH_MAX - 1, "%s/DBMT_task_045.%d", sco.dbmt_tmp_dir, + (int) getpid ()); + if ((temp_file = fopen (tmpfile, "w")) == NULL) + { + fclose (conf_file); + return ERR_TMPFILE_OPEN_FAIL; + } + + db_user_info = nv_create (5, NULL, "\n", ":", "\n"); + while (fgets (line_buf, sizeof (line_buf), conf_file) != NULL) + { + if (obsolete_version_autoexecquery_conf (line_buf)) + { + if (sscanf (line_buf, "%64s %*s %64s", db_name, dbmt_uid) < 2) + { + continue; + } + + if ((strcmp (dbmt_uid, conf_item[4]) != 0) + || (strcmp (db_name, conf_item[0]) != 0)) + { + /* configure item not set by current dbmt_user, + * or it has no relation with current database */ + fputs (line_buf, temp_file); + } + } + else + { + if (sscanf + (line_buf, "%64s %*s %64s %80s %64s", db_name, db_uid, + enc_dbpasswd, dbmt_uid) < 4) + { + continue; + } + + if ((strcmp (dbmt_uid, conf_item[4]) != 0) + || (strcmp (db_name, conf_item[0]) != 0)) + { + fputs (line_buf, temp_file); + } + else + { + nv_add_nvp (db_user_info, db_uid, enc_dbpasswd); + } + } + } + fclose (conf_file); + + nv_locate (req, "planlist", &nvlist_index, &nvlist_section_len); + if (nvlist_section_len == 0) + { + fclose (temp_file); + move_file (tmpfile, autoexecquery_conf_file); + + return ERR_NO_ERROR; + } + + name = value = NULL; + for (i = nvlist_index + 1; i < nvlist_index + nvlist_section_len; i += 8) + { + /* open:queryplan */ + if (value != NULL && strcasecmp (value, "planlist") == 0) + { + fclose (temp_file); + return ERR_NO_ERROR; + } + + /* query_id */ + nv_lookup (req, i, &name, &value); + conf_item[1] = value; + + /* db_uid */ + nv_lookup (req, i + 1, &name, &value); + conf_item[2] = value; + + /* db_passwd */ + nv_lookup (req, i + 2, &name, &value); + if (strcmp (value, "unknown") == 0) + { + if ((conf_item[3] = + nv_get_val (db_user_info, conf_item[2])) == NULL) + { + uEncrypt (PASSWD_LENGTH, "", enc_dbpasswd); + conf_item[3] = enc_dbpasswd; + } + } + else if (strcmp (value, "none") == 0) + { + uEncrypt (PASSWD_LENGTH, "", enc_dbpasswd); + conf_item[3] = enc_dbpasswd; + } + else + { + uEncrypt (PASSWD_LENGTH, value, enc_dbpasswd); + conf_item[3] = enc_dbpasswd; + } + + /* period */ + nv_lookup (req, i + 3, &name, &value); + conf_item[5] = value; + + /* time detail */ + nv_lookup (req, i + 4, &name, &value); + conf_item[6] = value; + + /* query string */ + nv_lookup (req, i + 5, &name, &value); + if ((value != NULL) && (strlen (value) > MAX_AUTOQUERY_SCRIPT_SIZE)) + { + sprintf (_dbmt_error, + "Query script too long. MAX_AUTOQUERY_SCRIPT_SIZE:%d.", + MAX_AUTOQUERY_SCRIPT_SIZE); + fclose (temp_file); + return ERR_WITH_MSG; + } + else + { + conf_item[7] = value; + } + + fprintf (temp_file, "%s %s %s %s %s %s %s %s\n", conf_item[0], + conf_item[1], conf_item[2], conf_item[3], conf_item[4], + conf_item[5], conf_item[6], conf_item[7]); + /* close:queryplan */ + } + fclose (temp_file); + move_file (tmpfile, autoexecquery_conf_file); + + nv_destroy (db_user_info); + + return ERR_NO_ERROR; +} + +int +ts_get_autoexec_query (nvplist *req, nvplist *res, char *_dbmt_error) +{ + int retval = ERR_NO_ERROR; + FILE *conf_file; + char autoexecquery_conf_file[PATH_MAX]; + int conf_item_num; + char *dbname, *dbmt_uid; + char line_buf[MAX_JOB_CONFIG_FILE_LINE_LENGTH]; + char *conf_item[AUTOEXECQUERY_CONF_ENTRY_NUM]; + char exectime_detail[256]; + + conf_get_dbmt_file (FID_AUTO_EXECQUERY_CONF, autoexecquery_conf_file); + if (access (autoexecquery_conf_file, F_OK) == 0) + { + conf_file = fopen (autoexecquery_conf_file, "r"); + if (!conf_file) + { + return ERR_FILE_OPEN_FAIL; + } + } + else + { + nv_add_nvp (res, "open", "planlist"); + nv_add_nvp (res, "close", "planlist"); + return ERR_NO_ERROR; + } + + nv_add_nvp (res, "open", "planlist"); + dbname = nv_get_val (req, "_DBNAME"); + dbmt_uid = nv_get_val (req, "_ID"); + if (dbname == NULL || dbmt_uid == NULL) + { + goto err_ts_get_autoexec_query; + } + nv_add_nvp (res, "dbname", dbname); + + while (fgets (line_buf, sizeof (line_buf), conf_file) != NULL) + { + ut_trim (line_buf); + + if (obsolete_version_autoexecquery_conf (line_buf)) + { + conf_item_num = AUTOEXECQUERY_CONF_ENTRY_NUM - 2; + } + else + { + conf_item_num = AUTOEXECQUERY_CONF_ENTRY_NUM; + } + + if (string_tokenize_accept_laststring_space + (line_buf, conf_item, conf_item_num) < 0) + { + strcpy_limit (_dbmt_error, + "autoexecquery.conf contains syntax error.", + DBMT_ERROR_MSG_SIZE); + retval = ERR_WITH_MSG; + goto err_ts_get_autoexec_query; + } + + if (strcmp (dbname, conf_item[0]) != 0 + || strcmp (dbmt_uid, conf_item[conf_item_num - 5]) != 0) + { + continue; + } + + nv_add_nvp (res, "open", "queryplan"); + nv_add_nvp (res, "query_id", conf_item[1]); + + if (conf_item_num == AUTOEXECQUERY_CONF_ENTRY_NUM) + { + nv_add_nvp (res, ENCRYPT_ARG ("username"), conf_item[2]); + } + else + { + nv_add_nvp (res, ENCRYPT_ARG ("username"), NULL); + } + + nv_add_nvp (res, "period", conf_item[conf_item_num - 4]); + snprintf (exectime_detail, sizeof (exectime_detail) - 1, "%s %s", + conf_item[conf_item_num - 3], conf_item[conf_item_num - 2]); + nv_add_nvp (res, "detail", exectime_detail); + nv_add_nvp (res, "query_string", conf_item[conf_item_num - 1]); + nv_add_nvp (res, "close", "queryplan"); + } + +err_ts_get_autoexec_query: + nv_add_nvp (res, "close", "planlist"); + fclose (conf_file); + + return retval; +} + +int +ts_addstatustemplate (nvplist *cli_request, nvplist *cli_response, + char *diag_error) +{ + FILE *templatefile, *tempfile; + char templatefilepath[PATH_MAX], tempfilepath[PATH_MAX]; + char buf[1024]; + char *templatename, *desc, *sampling_term, *dbname; + int ret_val = ERR_NO_ERROR; + + templatename = nv_get_val (cli_request, "name"); + desc = nv_get_val (cli_request, "desc"); + sampling_term = nv_get_val (cli_request, "sampling_term"); + dbname = nv_get_val (cli_request, "db_name"); + + if (templatename == NULL) + { + snprintf (diag_error, DBMT_ERROR_MSG_SIZE, "%s", "name"); + return ERR_PARAM_MISSING; + } + + /* write related information to template config file */ + conf_get_dbmt_file (FID_DIAG_STATUS_TEMPLATE, templatefilepath); + if (access (templatefilepath, F_OK) < 0) + { + templatefile = fopen (templatefilepath, "w"); + if (templatefile == NULL) + { + if (diag_error) + { + strcpy (diag_error, templatefilepath); + } + return ERR_FILE_OPEN_FAIL; + } + fclose (templatefile); + } + + if ((templatefile = fopen (templatefilepath, "r")) == NULL) + { + if (diag_error) + { + strcpy (diag_error, templatefilepath); + } + return ERR_FILE_OPEN_FAIL; + } + + snprintf (tempfilepath, PATH_MAX - 1, "%s/statustemplate_add.tmp", + sco.dbmt_tmp_dir); + if ((tempfile = fopen (tempfilepath, "w+")) == NULL) + { + if (diag_error) + { + strcpy (diag_error, tempfilepath); + } + fclose (templatefile); + return ERR_FILE_OPEN_FAIL; + } + + while (fgets (buf, sizeof (buf), templatefile)) + { + if (strncmp (buf, "<<<", 3) == 0) + { + fprintf (tempfile, "%s", buf); + + /* template name */ + if (! (fgets (buf, sizeof (buf), templatefile))) + { + break; + } + buf[strlen (buf) - 1] = '\0'; + if (strcmp (buf, templatename) == 0) + { + strcpy (diag_error, templatename); + ret_val = ERR_TEMPLATE_ALREADY_EXIST; + break; + } + + fprintf (tempfile, "%s\n", buf); + + /* copy others */ + while (fgets (buf, sizeof (buf), templatefile)) + { + fprintf (tempfile, "%s", buf); + if (strncmp (buf, ">>>", 3) == 0) + { + break; + } + } + } + } + + if (ret_val == ERR_NO_ERROR) + { + int i, config_index, config_length; + char *target_name, *target_value; + + /* add new template config */ + fprintf (tempfile, "<<<\n"); + fprintf (tempfile, "%s\n", templatename); + if (desc) + { + fprintf (tempfile, "%s\n", desc); + } + else + { + fprintf (tempfile, " \n"); + } + + if (dbname) + { + fprintf (tempfile, "%s\n", dbname); + } + else + { + fprintf (tempfile, " \n"); + } + + fprintf (tempfile, "%s\n", sampling_term); + + if (nv_locate + (cli_request, "target_config", &config_index, &config_length) != 1) + { + ret_val = ERR_REQUEST_FORMAT; + } + else + { + for (i = config_index; i < config_index + config_length; i++) + { + if (nv_lookup (cli_request, i, &target_name, &target_value) == 1) + { + fprintf (tempfile, "%s %s\n", target_name, target_value); + } + else + { + ret_val = ERR_REQUEST_FORMAT; + break; + } + } + fprintf (tempfile, ">>>\n"); + } + } + + fclose (tempfile); + fclose (templatefile); + + if (ret_val == ERR_NO_ERROR) + { + unlink (templatefilepath); + rename (tempfilepath, templatefilepath); + } + else + { + unlink (tempfilepath); + } + + return ret_val; +} + +int +ts_removestatustemplate (nvplist *cli_request, nvplist *cli_response, + char *diag_error) +{ + FILE *templatefile, *tempfile; + char templatefilepath[PATH_MAX], tempfilepath[PATH_MAX]; + char buf[1024]; + char *templatename; + int ret_val = ERR_NO_ERROR; + + templatename = nv_get_val (cli_request, "name"); + + if (templatename == NULL) + { + snprintf (diag_error, DBMT_ERROR_MSG_SIZE, "%s", "name"); + return ERR_PARAM_MISSING; + } + + /* write related information to template config file */ + conf_get_dbmt_file (FID_DIAG_STATUS_TEMPLATE, templatefilepath); + if ((templatefile = fopen (templatefilepath, "r")) == NULL) + { + if (diag_error) + { + strcpy (diag_error, templatefilepath); + } + return ERR_FILE_OPEN_FAIL; + } + + snprintf (tempfilepath, PATH_MAX - 1, "%s/statustemplate_remove.tmp", + sco.dbmt_tmp_dir); + if ((tempfile = fopen (tempfilepath, "w+")) == NULL) + { + if (diag_error) + { + strcpy (diag_error, tempfilepath); + } + fclose (templatefile); + return ERR_FILE_OPEN_FAIL; + } + + while (fgets (buf, sizeof (buf), templatefile)) + { + if (strncmp (buf, "<<<", 3) == 0) + { + /* template name */ + if (! (fgets (buf, sizeof (buf), templatefile))) + { + break; + } + buf[strlen (buf) - 1] = '\0'; + if (strcmp (buf, templatename) == 0) + { + continue; + } + + fprintf (tempfile, "<<<\n"); + fprintf (tempfile, "%s\n", buf); + + /* copy others */ + while (fgets (buf, sizeof (buf), templatefile)) + { + fprintf (tempfile, "%s", buf); + if (strncmp (buf, ">>>", 3) == 0) + { + break; + } + } + } + } + + fclose (tempfile); + fclose (templatefile); + + if (ret_val == ERR_NO_ERROR) + { + unlink (templatefilepath); + rename (tempfilepath, templatefilepath); + } + else + { + unlink (tempfilepath); + } + + return ret_val; +} + +int +ts_updatestatustemplate (nvplist *cli_request, nvplist *cli_response, + char *diag_error) +{ + FILE *templatefile, *tempfile; + char templatefilepath[PATH_MAX], tempfilepath[PATH_MAX]; + char buf[1024]; + char *templatename, *desc, *sampling_term, *dbname; + int ret_val = ERR_NO_ERROR; + + templatename = nv_get_val (cli_request, "name"); + desc = nv_get_val (cli_request, "desc"); + sampling_term = nv_get_val (cli_request, "sampling_term"); + dbname = nv_get_val (cli_request, "db_name"); + + if (templatename == NULL) + { + snprintf (diag_error, DBMT_ERROR_MSG_SIZE, "%s", "name"); + return ERR_PARAM_MISSING; + } + + /* write related information to template config file */ + conf_get_dbmt_file (FID_DIAG_STATUS_TEMPLATE, templatefilepath); + if ((templatefile = fopen (templatefilepath, "r")) == NULL) + { + if (diag_error) + { + strcpy (diag_error, templatefilepath); + } + return ERR_FILE_OPEN_FAIL; + } + + snprintf (tempfilepath, PATH_MAX - 1, "%s/statustemplate_update_%d.tmp", + sco.dbmt_tmp_dir, getpid ()); + if ((tempfile = fopen (tempfilepath, "w+")) == NULL) + { + if (diag_error) + { + strcpy (diag_error, tempfilepath); + } + fclose (templatefile); + return ERR_FILE_OPEN_FAIL; + } + + while (fgets (buf, sizeof (buf), templatefile)) + { + if (strncmp (buf, "<<<", 3) == 0) + { + fprintf (tempfile, "%s", buf); + + /* template name */ + if (! (fgets (buf, sizeof (buf), templatefile))) + { + break; + } + buf[strlen (buf) - 1] = '\0'; + if (strcmp (buf, templatename) == 0) + { + int i, config_index, config_length; + char *target_name, *target_value; + + /* add new configuration */ + fprintf (tempfile, "%s\n", templatename); + if (desc) + { + fprintf (tempfile, "%s\n", desc); + } + else + { + fprintf (tempfile, " \n"); + } + + if (dbname) + { + fprintf (tempfile, "%s\n", dbname); + } + else + { + fprintf (tempfile, " \n"); + } + + fprintf (tempfile, "%s\n", sampling_term); + + if (nv_locate + (cli_request, "target_config", &config_index, + &config_length) != 1) + { + ret_val = ERR_REQUEST_FORMAT; + break; + } + else + { + for (i = config_index; i < config_index + config_length; i++) + { + if (nv_lookup + (cli_request, i, &target_name, &target_value) == 1) + { + fprintf (tempfile, "%s %s\n", target_name, target_value); + } + else + { + ret_val = ERR_REQUEST_FORMAT; + break; + } + } + if (ret_val != ERR_NO_ERROR) + { + break; + } + fprintf (tempfile, ">>>\n"); + } + + continue; + } + + fprintf (tempfile, "%s\n", buf); + + /* copy others */ + while (fgets (buf, sizeof (buf), templatefile)) + { + fprintf (tempfile, "%s", buf); + if (strncmp (buf, ">>>", 3) == 0) + { + break; + } + } + } + } + + fclose (tempfile); + fclose (templatefile); + + if (ret_val == ERR_NO_ERROR) + { + unlink (templatefilepath); + rename (tempfilepath, templatefilepath); + } + else + { + unlink (tempfilepath); + } + + return ret_val; +} + +int +ts_getstatustemplate (nvplist *cli_request, nvplist *cli_response, + char *diag_error) +{ + FILE *templatefile; + char templatefilepath[PATH_MAX]; + char buf[1024]; + char *templatename; + char targetname[100], targetcolor[8], targetmag[32]; + int ret_val = ERR_NO_ERROR; + + templatename = nv_get_val (cli_request, "name"); + + /* write related information to template config file */ + conf_get_dbmt_file (FID_DIAG_STATUS_TEMPLATE, templatefilepath); + if ((templatefile = fopen (templatefilepath, "r")) == NULL) + { + return ERR_NO_ERROR; + } +#ifdef JSON_SUPPORT + nv_add_nvp (cli_response, "open", "templatelist"); +#else + nv_add_nvp (cli_response, "start", "templatelist"); +#endif + while (fgets (buf, sizeof (buf), templatefile)) + { + if (strncmp (buf, "<<<", 3) == 0) + { + /* template name */ + if (! (fgets (buf, sizeof (buf), templatefile))) + { + break; + } + buf[strlen (buf) - 1] = '\0'; + if (templatename) + { + if (strcmp (buf, templatename) != 0) + { + continue; + } + } +#ifdef JSON_SUPPORT + nv_add_nvp (cli_response, "open", "template"); +#else + nv_add_nvp (cli_response, "start", "template"); +#endif + nv_add_nvp (cli_response, "name", buf); + if (!fgets (buf, sizeof (buf), templatefile)) + { + ret_val = ERR_WITH_MSG; + if (diag_error) + { + strcpy (diag_error, "Invalid file format\n"); + strcat (diag_error, templatefilepath); + } + + break; + } + buf[strlen (buf) - 1] = '\0'; + nv_add_nvp (cli_response, "desc", buf); + + if (!fgets (buf, sizeof (buf), templatefile)) + { + ret_val = ERR_WITH_MSG; + if (diag_error) + { + strcpy (diag_error, "Invalid file format\n"); + strcat (diag_error, templatefilepath); + } + + break; + } + buf[strlen (buf) - 1] = '\0'; + nv_add_nvp (cli_response, "db_name", buf); + + if (!fgets (buf, sizeof (buf), templatefile)) + { + ret_val = ERR_WITH_MSG; + if (diag_error) + { + strcpy (diag_error, "Invalid file format\n"); + strcat (diag_error, templatefilepath); + } + + break; + } + buf[strlen (buf) - 1] = '\0'; + nv_add_nvp (cli_response, "sampling_term", buf); +#ifdef JSON_SUPPORT + nv_add_nvp (cli_response, "close", "target_config"); +#else + nv_add_nvp (cli_response, "start", "target_config"); +#endif + while (fgets (buf, sizeof (buf), templatefile)) + { + int matched; + if (strncmp (buf, ">>>", 3) == 0) + { + break; + } + matched = + sscanf (buf, "%99s %7s %31s", targetname, targetcolor, + targetmag); + if (matched != 3) + { + continue; /* error file format */ + } + nv_add_nvp (cli_response, targetname, targetcolor); + nv_add_nvp (cli_response, targetname, targetmag); + } + +#ifdef JSON_SUPPORT + nv_add_nvp (cli_response, "close", "target_config"); + nv_add_nvp (cli_response, "close", "template"); +#else + nv_add_nvp (cli_response, "end", "target_config"); + nv_add_nvp (cli_response, "end", "template"); +#endif + + } + } +#ifdef JSON_SUPPORT + nv_add_nvp (cli_response, "close", "templatelist"); +#else + nv_add_nvp (cli_response, "end", "templatelist"); +#endif + + fclose (templatefile); + + return ret_val; +} + + +int +ts_analyzecaslog (nvplist *cli_request, nvplist *cli_response, + char *diag_error) +{ + int retval, i, arg_index; + int matched, sect, sect_len; + char tmpfileQ[PATH_MAX], tmpfileRes[PATH_MAX], tmpfileT[PATH_MAX], + tmpfileanalyzeresult[PATH_MAX]; + char *logfile, *option_t; + char cmd_name[ARNIADB_CMD_NAME_LEN]; + char diag_err_file[PATH_MAX]; + const char *argv[256]; + char buf[1024], logbuf[2048]; + char qnum[16], max[32], min[32], avg[32], cnt[16], err[16]; + FILE *fdRes, *fdQ, *fdT, *fdAnalyzeResult; +#if defined(WINDOWS) + DWORD th_id; +#else + T_THREAD th_id; +#endif + diag_err_file[0] = '\0'; + + logfile = nv_get_val (cli_request, "logfile"); + option_t = nv_get_val (cli_request, "option_t"); + + /* set prarameter with logfile and execute broker_log_top */ + /* execute at current directory and copy result to $ARNIADB/tmp directory */ + snprintf (cmd_name, sizeof (cmd_name) - 1, "%s/bin/broker_log_top%s", + sco.szArniadb, DBMT_EXE_EXT); + arg_index = 0; + argv[arg_index++] = cmd_name; + if (option_t &&!strcmp (option_t, "yes")) + { + argv[arg_index++] = "-t"; + } + nv_locate (cli_request, "logfilelist", §, §_len); + if (sect == -1) + { + snprintf (diag_error, DBMT_ERROR_MSG_SIZE, "%s", "logfilelist"); + return ERR_PARAM_MISSING; + } + for (i = 0; i < sect_len; i++) + { + nv_lookup (cli_request, sect + i, NULL, &logfile); + if (logfile) + { + argv[arg_index++] = logfile; + } + } + argv[arg_index++] = NULL; + snprintf (diag_err_file, PATH_MAX, "%s/%s.%u.err.tmp", + sco.dbmt_tmp_dir, "analyzecaslog", getpid ()); + + retval = run_child (argv, 1, NULL, NULL, diag_err_file, NULL); /* broker_log_top */ + if (read_error_file (diag_err_file, diag_error, DBMT_ERROR_MSG_SIZE) < 0) + { + if (access (diag_err_file, F_OK) == 0) + { + unlink (diag_err_file); + } + return ERR_WITH_MSG; + } + + if (access (diag_err_file, F_OK) == 0) + { + unlink (diag_err_file); + } + + if (retval < 0) + { + if (diag_error) + { + strcpy (diag_error, argv[0]); + } + return ERR_SYSTEM_CALL; + } + + snprintf (tmpfileanalyzeresult, PATH_MAX - 1, "%s/analyzelog_%d.res", + sco.dbmt_tmp_dir, (int) getpid ()); + fdAnalyzeResult = fopen (tmpfileanalyzeresult, "w+"); + if (fdAnalyzeResult == NULL) + { + if (diag_error) + { + strcpy (diag_error, "Tmpfile"); + } + return ERR_FILE_OPEN_FAIL; + } + + if ((option_t != NULL) && (strcmp (option_t, "yes") == 0)) + { + int log_init_flag, log_index; + + snprintf (tmpfileT, PATH_MAX - 1, "%s/log_top_%d.t", sco.dbmt_tmp_dir, + (int) getpid ()); + rename ("./log_top.t", tmpfileT); + + fdT = fopen (tmpfileT, "r"); + if (fdT == NULL) + { + if (diag_error) + { + strcpy (diag_error, "log_top.t"); + } + fclose (fdAnalyzeResult); + return ERR_FILE_OPEN_FAIL; + } + + log_index = 1; + log_init_flag = 1; +#ifdef JSON_SUPPORT + nv_add_nvp (cli_response, "open", "resultlist"); +#else + nv_add_nvp (cli_response, "resultlist", "start"); +#endif + while (fgets (buf, sizeof (buf), fdT)) + { + char *time_str = NULL; + const char *exec_time_tag = "*** elapsed time"; + + if (strlen (buf) == 1) + { + continue; + } + + if (log_init_flag == 1) + { +#ifdef JSON_SUPPORT + nv_add_nvp (cli_response, "open", "result"); +#else + nv_add_nvp (cli_response, "result", "start"); +#endif + snprintf (qnum, sizeof (qnum) - 1, "[Q%d]", log_index); + fprintf (fdAnalyzeResult, "%s\n", qnum); + nv_add_nvp (cli_response, "qindex", qnum); + log_index++; + log_init_flag = 0; + } + + if ((time_str = strstr (buf, exec_time_tag)) != NULL) + { + time_str += strlen (exec_time_tag); + ut_trim (time_str); + + nv_add_nvp (cli_response, "exec_time", time_str); +#ifdef JSON_SUPPORT + nv_add_nvp (cli_response, "close", "result"); +#else + nv_add_nvp (cli_response, "result", "end"); +#endif + log_init_flag = 1; + } + else + { + fprintf (fdAnalyzeResult, "%s", buf); + } + } +#ifdef JSON_SUPPORT + nv_add_nvp (cli_response, "close", "resultlist"); +#else + nv_add_nvp (cli_response, "resultlist", "end"); +#endif + + fclose (fdT); + unlink (tmpfileT); + } + else + { +#if defined(WINDOWS) + th_id = GetCurrentThreadId (); +#else + th_id = getpid (); +#endif + snprintf (tmpfileQ, PATH_MAX - 1, "%s/log_top_%lu.q", sco.dbmt_tmp_dir, + th_id); + snprintf (tmpfileRes, PATH_MAX - 1, "%s/log_top_%lu.res", + sco.dbmt_tmp_dir, th_id); + + rename ("./log_top.q", tmpfileQ); + rename ("./log_top.res", tmpfileRes); + + fdQ = fopen (tmpfileQ, "r"); + if (fdQ == NULL) + { + if (diag_error) + { + strcpy (diag_error, "log_top.q"); + } + fclose (fdAnalyzeResult); + return ERR_FILE_OPEN_FAIL; + } + + fdRes = fopen (tmpfileRes, "r"); + if (fdRes == NULL) + { + if (diag_error) + { + strcpy (diag_error, "log_top.res"); + } + fclose (fdAnalyzeResult); + fclose (fdQ); + return ERR_FILE_OPEN_FAIL; + } + + memset (buf, '\0', sizeof (buf)); + memset (logbuf, '\0', sizeof (logbuf)); +#ifdef JSON_SUPPORT + nv_add_nvp (cli_response, "open", "resultlist"); +#else + nv_add_nvp (cli_response, "resultlist", "start"); +#endif + /* read result, log file and create msg with them */ + while (fgets (buf, sizeof (buf), fdRes)) + { + if (strlen (buf) == 1) + { + continue; + } + + if (!strncmp (buf, "[Q", 2)) + { +#ifdef JSON_SUPPORT + nv_add_nvp (cli_response, "open", "result"); +#else + nv_add_nvp (cli_response, "result", "start"); +#endif + matched = + sscanf (buf, "%15s %31s %31s %31s %15s %15s", qnum, max, min, + avg, cnt, err); + if (matched != 6) + { + continue; + } + nv_add_nvp (cli_response, "qindex", qnum); + nv_add_nvp (cli_response, "max", max); + nv_add_nvp (cli_response, "min", min); + nv_add_nvp (cli_response, "avg", avg); + nv_add_nvp (cli_response, "cnt", cnt); + if (strlen (err)) + { + err[strlen (err) - 1] = '\0'; + } + nv_add_nvp (cli_response, "err", err + 1); + + fprintf (fdAnalyzeResult, "%s\n", qnum); + + while (strncmp (logbuf, qnum, 4) != 0) + { + if (fgets (logbuf, sizeof (logbuf), fdQ) == NULL) + { + if (diag_error) + { + strcpy (diag_error, + "log_top.q file format is not valid"); + } + fclose (fdRes); + fclose (fdQ); + fclose (fdAnalyzeResult); + return ERR_WITH_MSG; + } + } + + while (fgets (logbuf, sizeof (logbuf), fdQ)) + { + if (!strncmp (logbuf, "[Q", 2)) + { + break; + } + fprintf (fdAnalyzeResult, "%s", logbuf); + } +#ifdef JSON_SUPPORT + nv_add_nvp (cli_response, "close", "result"); +#else + nv_add_nvp (cli_response, "result", "end"); +#endif + } + } +#ifdef JSON_SUPPORT + nv_add_nvp (cli_response, "close", "resultlist"); +#else + nv_add_nvp (cli_response, "resultlist", "end"); +#endif + + fclose (fdRes); + fclose (fdQ); + + unlink (tmpfileQ); + unlink (tmpfileRes); + } + + fclose (fdAnalyzeResult); + nv_add_nvp (cli_response, "resultfile", tmpfileanalyzeresult); + + return ERR_NO_ERROR; +} + +int +ts_executecasrunner (nvplist *cli_request, nvplist *cli_response, + char *diag_error) +{ + int i, sect, sect_len; + char *log_string, *brokername, *username, *passwd; + char *num_thread, *repeat_count, *show_queryresult; + char *dbname, *casrunnerwithFile, *logfilename; + char *show_queryplan; + char bport[6], buf[1024]; + FILE *flogfile, *fresfile2; + char tmplogfilename[PATH_MAX], resfile[PATH_MAX], resfile2[PATH_MAX]; + char log_converter_res[PATH_MAX]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; + const char *argv[25]; + T_CM_BROKER_CONF uc_conf; + char out_msg_file_env[1024]; + T_CM_ERROR error; +#if defined(WINDOWS) + DWORD th_id; +#else + T_THREAD th_id; +#endif + char use_tmplogfile = FALSE; + + brokername = nv_get_val (cli_request, "brokername"); + dbname = nv_get_val (cli_request, "dbname"); + username = nv_get_val (cli_request, "username"); + passwd = nv_get_val (cli_request, "passwd"); + num_thread = nv_get_val (cli_request, "num_thread"); + repeat_count = nv_get_val (cli_request, "repeat_count"); + show_queryresult = nv_get_val (cli_request, "show_queryresult"); + show_queryplan = nv_get_val (cli_request, "show_queryplan"); + casrunnerwithFile = nv_get_val (cli_request, "executelogfile"); + logfilename = nv_get_val (cli_request, "logfile"); + + if (brokername == NULL) + { + snprintf (diag_error, DBMT_ERROR_MSG_SIZE, "%s", "brokername"); + return ERR_PARAM_MISSING; + } + + if (dbname == NULL) + { + snprintf (diag_error, DBMT_ERROR_MSG_SIZE, "%s", "dbname"); + return ERR_PARAM_MISSING; + } + + if (username == NULL) + { + snprintf (diag_error, DBMT_ERROR_MSG_SIZE, "%s", "username"); + return ERR_PARAM_MISSING; + } + +#if defined(WINDOWS) + th_id = GetCurrentThreadId (); +#else + th_id = getpid (); +#endif + + snprintf (resfile, PATH_MAX - 1, "%s/log_run_%lu.res", sco.dbmt_tmp_dir, + th_id); + snprintf (resfile2, PATH_MAX - 1, "%s/log_run_%lu.res2", sco.dbmt_tmp_dir, + th_id); + + /* get right port number with broker name */ + if (cm_get_broker_conf (&uc_conf, NULL, &error) < 0) + { + strcpy (diag_error, error.err_msg); + return ERR_WITH_MSG; + } + + memset (bport, 0x0, sizeof (bport)); + for (i = 0; i < uc_conf.num_broker; i++) + { + char *confvalue = cm_br_conf_get_value (& (uc_conf.br_conf[i]), "%"); + + if ((confvalue != NULL) && (strcmp (brokername, confvalue) == 0)) + { + confvalue = + cm_br_conf_get_value (& (uc_conf.br_conf[i]), "BROKER_PORT"); + if (confvalue != NULL) + { + snprintf (bport, sizeof (bport) - 1, "%s", confvalue); + } + break; + } + } + + cm_broker_conf_free (&uc_conf); + + if ((casrunnerwithFile != NULL) && (strcmp (casrunnerwithFile, "yes") == 0) + && (logfilename != NULL)) + { + snprintf (tmplogfilename, PATH_MAX - 1, "%s", logfilename); + } + else + { + use_tmplogfile = TRUE; + /* create logfile */ + snprintf (tmplogfilename, PATH_MAX - 1, "%s/cas_log_tmp_%lu.q", + sco.dbmt_tmp_dir, th_id); + + flogfile = fopen (tmplogfilename, "w+"); + if (!flogfile) + { + return ERR_FILE_OPEN_FAIL; + } + + nv_locate (cli_request, "logstring", §, §_len); + if (sect >= 0) + { + for (i = 0; i < sect_len; ++i) + { + nv_lookup (cli_request, sect + i, NULL, &log_string); + fprintf (flogfile, "%s\n", + (log_string == NULL) ? " " : log_string); + } + } + fclose (flogfile); + } + + /* execute broker_log_converter why logfile is created */ + snprintf (log_converter_res, PATH_MAX - 1, "%s/log_converted_%lu.q_res", + sco.dbmt_tmp_dir, th_id); + snprintf (cmd_name, sizeof (cmd_name) - 1, "%s/bin/broker_log_converter%s", + sco.szArniadb, DBMT_EXE_EXT); + + i = 0; + argv[i] = cmd_name; + argv[++i] = tmplogfilename; + argv[++i] = log_converter_res; + argv[++i] = NULL; + + if (run_child (argv, 1, NULL, NULL, NULL, NULL) < 0) + { + /* broker_log_converter */ + strcpy (diag_error, argv[0]); + return ERR_SYSTEM_CALL; + } + + /* execute broker_log_runner through logfile that converted */ + snprintf (cmd_name, sizeof (cmd_name) - 1, "%s/bin/broker_log_runner%s", + sco.szArniadb, DBMT_EXE_EXT); + i = 0; + argv[i] = cmd_name; + argv[++i] = "-I"; + argv[++i] = "localhost"; + argv[++i] = "-P"; + argv[++i] = bport; + argv[++i] = "-d"; + argv[++i] = dbname; + argv[++i] = "-u"; + argv[++i] = username; + if (passwd) + { + argv[++i] = "-p"; + argv[++i] = passwd; + } + argv[++i] = "-t"; + argv[++i] = num_thread; + argv[++i] = "-r"; + argv[++i] = repeat_count; + if (show_queryplan && !strcmp (show_queryplan, "yes")) + { + argv[++i] = "-Q"; + } + argv[++i] = "-o"; + argv[++i] = resfile; + argv[++i] = log_converter_res; + argv[++i] = NULL; + + snprintf (out_msg_file_env, sizeof (out_msg_file_env) - 1, + "ARNIADB_MANAGER_OUT_MSG_FILE=%s", resfile2); + putenv (out_msg_file_env); + + if (run_child (argv, 1, NULL, NULL, NULL, NULL) < 0) + { + /* broker_log_runner */ + return ERR_SYSTEM_CALL; + } + + /* create message with read file's content */ +#ifdef JSON_SUPPORT + nv_add_nvp (cli_response, "open", "result_list"); +#else + nv_add_nvp (cli_response, "result_list", "start"); +#endif + + fresfile2 = fopen (resfile2, "r"); + if (fresfile2) + { + while (fgets (buf, sizeof (buf), fresfile2)) + { + if (!strncmp (buf, "cas_ip", 6)) + { + continue; + } + if (!strncmp (buf, "cas_port", 8)) + { + continue; + } + if (!strncmp (buf, "num_thread", 10)) + { + continue; + } + if (!strncmp (buf, "repeat", 6)) + { + continue; + } + if (!strncmp (buf, "dbname", 6)) + { + continue; + } + if (!strncmp (buf, "dbuser", 6)) + { + continue; + } + if (!strncmp (buf, "dbpasswd", 6)) + { + continue; + } + if (!strncmp (buf, "result_file", 11)) + { + continue; + } + + buf[strlen (buf) - 1] = '\0'; /* remove new line ch */ + nv_add_nvp (cli_response, "result", buf); + } + fclose (fresfile2); + } +#ifdef JSON_SUPPORT + nv_add_nvp (cli_response, "close", "result_list"); +#else + nv_add_nvp (cli_response, "result_list", "end"); +#endif + nv_add_nvp (cli_response, "query_result_file", resfile); + nv_add_nvp (cli_response, "query_result_file_num", num_thread); + + if ((show_queryresult != NULL) && !strcmp (show_queryresult, "no")) + { + /* remove query result file - resfile */ + int i, n = 0; + char filename[PATH_MAX]; + if (num_thread != NULL) + { + n = atoi (num_thread); + } + + for (i = 0; i < n && i < MAX_SERVER_THREAD_COUNT; i++) + { + snprintf (filename, PATH_MAX - 1, "%s.%d", resfile, i); + unlink (filename); + } + } + + unlink (log_converter_res); /* broker_log_converter execute result */ + unlink (resfile2); /* cas log execute result */ + + if (use_tmplogfile == TRUE) + { + unlink (tmplogfilename); /* temp logfile */ + } + return ERR_NO_ERROR; +} + +int +ts_removecasrunnertmpfile (nvplist *cli_request, nvplist *cli_response, + char *diag_error) +{ + char command[PATH_MAX]; + char filename[PATH_MAX]; + char arniadb_tmp_path[PATH_MAX]; + char *fullpath_with_filename = NULL; + + const char *casrunnertmp_short[] = + { "log_converted", "cas_log_tmp", "log_run" }; + unsigned int casrunnertmp_short_num = + sizeof (casrunnertmp_short) / sizeof (casrunnertmp_short[0]); + unsigned int i = 0; + int valid_casrunnertmpfile = 0; + + command[0] = '\0'; + filename[0] = '\0'; + arniadb_tmp_path[0] = '\0'; + + fullpath_with_filename = nv_get_val (cli_request, "filename"); + if (fullpath_with_filename == NULL) + { + snprintf (diag_error, DBMT_ERROR_MSG_SIZE, "%s", "filename"); + return ERR_PARAM_MISSING; + } + + /* check permission : must under $ARNIADB/tmp/ */ +#if defined(WINDOWS) + snprintf (arniadb_tmp_path, PATH_MAX, "%s\\", sco.dbmt_tmp_dir); +#else + snprintf (arniadb_tmp_path, PATH_MAX, "%s/", sco.dbmt_tmp_dir); +#endif + + if (strstr (fullpath_with_filename, arniadb_tmp_path) == NULL) + { + snprintf (diag_error, DBMT_ERROR_MSG_SIZE, "%s", + fullpath_with_filename); + return ERR_PERMISSION; + } + + if (ut_get_filename (fullpath_with_filename, 1, filename) != 0) + { + snprintf (diag_error, DBMT_ERROR_MSG_SIZE, "%s", + fullpath_with_filename); + return ERR_PERMISSION; + } + + for (i = 0; i < casrunnertmp_short_num; i++) + { + if (strstr (filename, casrunnertmp_short[i]) != NULL) + { + valid_casrunnertmpfile = 1; + break; + } + } + + if (valid_casrunnertmpfile == 0) + { + snprintf (diag_error, DBMT_ERROR_MSG_SIZE, "%s", + fullpath_with_filename); + return ERR_PERMISSION; + } + +#if defined(WINDOWS) + snprintf (command, sizeof (command), "%s %s %s", DEL_FILE, + DEL_FILE_OPT, fullpath_with_filename); +#else + snprintf (command, sizeof (command), "%s %s %s", DEL_DIR, DEL_DIR_OPT, + fullpath_with_filename); +#endif + + if (system (command) == -1) + { + snprintf (diag_error, DBMT_ERROR_MSG_SIZE, "%s", + fullpath_with_filename); + return ERR_DIR_REMOVE_FAIL; + } + return ERR_NO_ERROR; +} + +int +ts_getcaslogtopresult (nvplist *cli_request, nvplist *cli_response, + char *diag_error) +{ + char *filename, *qindex; + FILE *fd; + char buf[1024]; + int find_flag; + + filename = nv_get_val (cli_request, "filename"); + if (filename == NULL) + { + snprintf (diag_error, DBMT_ERROR_MSG_SIZE, "%s", "filename"); + return ERR_PARAM_MISSING; + } + + qindex = nv_get_val (cli_request, "qindex"); + if (qindex == NULL) + { + snprintf (diag_error, DBMT_ERROR_MSG_SIZE, "%s", "qindex"); + return ERR_PARAM_MISSING; + } + + fd = fopen (filename, "r"); + if (!fd) + { + return ERR_FILE_OPEN_FAIL; + } + + find_flag = 0; +#ifndef JSON_SUPPORT + nv_add_nvp (cli_response, "logstringlist", "start"); +#endif + while (fgets (buf, sizeof (buf), fd)) + { + if (!strncmp (buf, "[Q", 2)) + { + if (find_flag == 1) + { + break; + } + if (!strncmp (buf, qindex, strlen (qindex))) + { + find_flag = 1; + continue; + } + } + + if (find_flag == 1) + { + buf[strlen (buf) - 1] = '\0'; +#ifdef JSON_SUPPORT + nv_add_nvp (cli_response, "open", "logstringlist"); +#endif + nv_add_nvp (cli_response, "logstring", buf); +#ifdef JSON_SUPPORT + nv_add_nvp (cli_response, "close", "logstringlist"); +#endif + } + } +#ifndef JSON_SUPPORT + nv_add_nvp (cli_response, "logstringlist", "end"); +#endif + fclose (fd); + return ERR_NO_ERROR; +} + +int +dbmt_user_is_dba (char *dbuser, const char *out_file) +{ + FILE *fp; + char buf[1024]; + int res_flag = 0; + int res = 0; + + buf[0] = '\0'; + + if (out_file == NULL || dbuser == NULL) + { + return 0; + } + + if (strcasecmp ("DBA", dbuser) == 0) + { + return 1; + } + + fp = fopen (out_file, "r"); + if (fp == NULL) + { + return 0; + } + + while (fgets (buf, sizeof (buf) - 1, fp)) + { + ut_trim (buf); + if (strncmp (buf, "=", 1) == 0) + { + continue; + } + + if (strstr (buf, "count(*)")) + { + res_flag = 1; + continue; + } + + if (res_flag) + { + if (strstr (buf, "0")) + { + res = 0; + break; + } + else + { + res = 1; + break; + } + } + } + fclose (fp); + + return res; +} + +int +cmd_dbmt_user_login (nvplist *in, nvplist *out, char *_dbmt_error) +{ + int errcode; + char *targetid, *dbname, *dbuser, *dbpasswd; + int isdba = 0; + char outfile[PATH_MAX]; + static int cmdid = 0; + const char *statement = + "SELECT COUNT( * ) FROM db_user d WHERE {'DBA'} SUBSETEQ (SELECT SET{CURRENT_USER}+COALESCE(SUM(SET{t.g.name}), SET{}) from db_user u, TABLE(groups) AS t( g ) WHERE u.name = d.name) AND d.name=CURRENT_USER;"; + + targetid = nv_get_val (in, "targetid"); + dbname = nv_get_val (in, "dbname"); + dbuser = nv_get_val (in, "dbuser"); + dbpasswd = nv_get_val (in, "dbpasswd"); + + if (dbname == NULL) + { + strcpy (_dbmt_error, "dbname"); + return ERR_PARAM_MISSING; + } + + if (dbuser == NULL) + { + strcpy (_dbmt_error, "dbuser"); + return ERR_PARAM_MISSING; + } + + nv_add_nvp (out, "targetid", targetid); + nv_add_nvp (out, "dbname", dbname); + + snprintf (outfile, sizeof (outfile) - 1, "%s/tmp/DBMT_user_login.%d", + sco.szArniadb, cmdid++); + errcode = + run_asql_statement (statement, dbname, dbuser, dbpasswd, outfile, _dbmt_error); + if (errcode != ERR_NO_ERROR) + { + return errcode; + } + + isdba = dbmt_user_is_dba (dbuser, outfile); + if (isdba) + { + nv_add_nvp (out, "authority", "isdba"); + } + else + { + nv_add_nvp (out, "authority", "isnotdba"); + } + _update_nvplist_name (out, "targetid", ENCRYPT_ARG ("targetid")); + unlink (outfile); + return ERR_NO_ERROR; +} + + + +int +tsDBMTUserLogin (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char hexacoded[PASSWD_ENC_LENGTH]; + int ret; + T_DBMT_CON_DBINFO con_dbinfo; + char *dbname, *dbpasswd, *dbuser; + char *ip, *port; + + ret = cmd_dbmt_user_login (req, res, _dbmt_error); + if (ret != ERR_NO_ERROR) + { + return ret; + } + + ip = nv_get_val (req, "_IP"); + port = nv_get_val (req, "_PORT"); + dbname = nv_get_val (req, "dbname"); + dbpasswd = nv_get_val (req, "dbpasswd"); + dbuser = nv_get_val (req, "dbuser"); + + if (dbpasswd != NULL && strlen (dbpasswd) > PASSWD_LENGTH) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, + "The input DB password is more than maximum password length %d.", + PASSWD_LENGTH); + return ERR_WITH_MSG; + } + + /* update dbinfo to conlist */ + uEncrypt (PASSWD_LENGTH, dbpasswd, hexacoded); + memset (&con_dbinfo, 0, sizeof (T_DBMT_CON_DBINFO)); + dbmt_con_set_dbinfo (&con_dbinfo, dbname, dbuser, hexacoded); + if (dbmt_con_write_dbinfo (&con_dbinfo, ip, port, dbname, 1, _dbmt_error) < 0) + { + return ERR_WITH_MSG; + } + + _update_nvplist_name (res, "targetid", ENCRYPT_ARG ("targetid")); + + return ERR_NO_ERROR; +} + + +int +ts_remove_log (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char *path = NULL; + FILE *output = NULL; + int i = 0; + int sect = -1; + int sect_len = 0; + int as_id = 0; + char broker_name[PATH_MAX]; + char command[PATH_MAX]; + char full_path_buf[PATH_MAX]; + char buf[PATH_MAX]; + T_CM_ERROR error = { 0, {0} }; + + broker_name[0] = '\0'; + command[0] = '\0'; + full_path_buf[0] = '\0'; + buf[0] = '\0'; + + nv_locate (req, "files", §, §_len); + if (sect < 0) + { + return ERR_REQUEST_FORMAT; + } + + for (i = 0; i < sect_len; ++i) + { + nv_lookup (req, sect + i, NULL, &path); +#if defined(WINDOWS) + path = nt_style_path (path, full_path_buf); +#endif + if (access (path, F_OK) != 0) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "No such file: %s", + path); + return ERR_WITH_MSG; + } + + snprintf (command, sizeof (command), "%s %s %s", DEL_FILE, + DEL_FILE_OPT, path); + + output = popen (command, "r"); + memset (buf, '\0', sizeof (buf)); + if (output != NULL) + { + if (fgets (buf, PATH_MAX, output) != NULL) + { +#if defined(WINDOWS) + pclose (output); + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "Cannot remove %s", + full_path_buf); + return ERR_WITH_MSG; +#endif + if (get_broker_info_from_filename (path, broker_name, &as_id) < 0 + || cm_del_cas_log (broker_name, as_id, &error) < 0) + { + pclose (output); + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", + error.err_msg); + return ERR_WITH_MSG; + } + } + } + pclose (output); + } /* end of for */ + + return ERR_NO_ERROR; +} + +int +ts_get_host_stat (nvplist *req, nvplist *res, char *_dbmt_error) +{ + int retval = ERR_NO_ERROR; + T_AMS_HOST_STAT stat; + + memset (&stat, 0, sizeof (T_AMS_HOST_STAT)); + + retval = ut_get_host_stat (&stat, _dbmt_error); + + nv_add_nvp_int64 (res, "cpu_user", stat.cpu_user); + nv_add_nvp_int64 (res, "cpu_kernel", stat.cpu_kernel); + nv_add_nvp_int64 (res, "cpu_idle", stat.cpu_idle); + nv_add_nvp_int64 (res, "cpu_iowait", stat.cpu_iowait); + nv_add_nvp_int64 (res, "mem_phy_total", stat.mem_physical_total); + nv_add_nvp_int64 (res, "mem_phy_free", stat.mem_physical_free); + nv_add_nvp_int64 (res, "mem_swap_total", stat.mem_swap_total); + nv_add_nvp_int64 (res, "mem_swap_free", stat.mem_swap_free); + + return retval; +} + +int +ts_get_dbproc_stat (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char *dbname = NULL; + T_CM_DB_PROC_STAT_ALL *db_stat_all = NULL; + T_CM_DB_PROC_STAT db_stat; + T_CM_ERROR error; + int retval; + int i = 0; + + memset (&db_stat, 0, sizeof (T_CM_DB_PROC_STAT)); + memset (&error, 0, sizeof (T_CM_ERROR)); + + if ((dbname = nv_get_val (req, "dbname")) == NULL) + { + if ((db_stat_all = cm_get_db_proc_stat_all (&error)) == NULL) + { + strcpy_limit (_dbmt_error, error.err_msg, DBMT_ERROR_MSG_SIZE); + retval = ERR_WITH_MSG; + goto error_return; + } + + for (i = 0; i < db_stat_all->num_stat; i++) + { + print_db_stat_to_res ((db_stat_all->db_stats + i), res); + } + + cm_db_proc_stat_all_free (db_stat_all); + retval = ERR_NO_ERROR; + } + else + { + if (cm_get_db_proc_stat (dbname, &db_stat, &error) < 0) + { + strcpy_limit (_dbmt_error, error.err_msg, DBMT_ERROR_MSG_SIZE); + retval = ERR_WITH_MSG; + goto error_return; + } + print_db_stat_to_res (&db_stat, res); + retval = ERR_NO_ERROR; + } + + return retval; + +error_return: + print_db_stat_to_res (&db_stat, res); + return retval; +} + +static int +analyze_heartbeat_cmd_outfile (FILE *infile, char *_dbmt_error) +{ + char buf[1024]; + const char *headtag = "++"; + const char *failtag = "not running"; + char *p; + + while (fgets (buf, sizeof (buf), infile)) + { + if (strncmp (buf, headtag, strlen (headtag)) == 0) + { + if (strstr (buf, failtag) != NULL) + { + p = strchr (buf, '\n'); + if (p) + { + *p = '\0'; + } + /* copy begins with the 3rd charactor, ignore the "++" tag. */ + strcpy_limit (_dbmt_error, &buf[2], DBMT_ERROR_MSG_SIZE); + return ERR_WITH_MSG; + } + } + } + + return ERR_NO_ERROR; +} + +static char * +arn_admin_cmd_name (char *cmd_name, int buf_len) +{ + cmd_name[0] = '\0'; +#if !defined (DO_NOT_USE_ARNIADBENV) + snprintf (cmd_name, buf_len, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, + UTIL_ADMIN_NAME); +#else + sprintf (cmd_name, buf_len, "%s/%s", ARNIADB_BINDIR, UTIL_ADMIN_NAME); +#endif + return cmd_name; +} + +static int +cmd_heartbeat_deact (char *_dbmt_error) +{ + int retval = ERR_NO_ERROR; + const char *argv[8]; + int argc = 0; + char cmd_name[ARNIADB_CMD_NAME_LEN]; + FILE *outputfile = NULL; + char outputfilepath[PATH_MAX]; + char arniadb_err_file[PATH_MAX]; + + arniadb_err_file[0] = '\0'; + outputfilepath[0] = '\0'; + + snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", + sco.dbmt_tmp_dir, "heartbeat_deact", getpid ()); + + arniadb_cmd_name (cmd_name); + argv[argc++] = cmd_name; + argv[argc++] = PRINT_CMD_HEARTBEAT; + argv[argc++] = PRINT_CMD_DEACT; + argv[argc++] = NULL; + + snprintf (outputfilepath, PATH_MAX - 1, "%s/DBMT_task_%d.%d", + sco.dbmt_tmp_dir, TS_HEARTBEAT_DEACT, (int) getpid ()); + + if (run_child (argv, 1, NULL, outputfilepath, arniadb_err_file, NULL) < 0) + { + /* heartbeat deact */ + strcpy (_dbmt_error, argv[0]); + retval = ERR_SYSTEM_CALL; + goto rm_outputfile; + } + + if (read_error_file (arniadb_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) + { + retval = ERR_WITH_MSG; + goto rm_outputfile; + } + + /* open tmp file. */ + outputfile = fopen (outputfilepath, "r"); + if (outputfile == NULL) + { + retval = ERR_TMPFILE_OPEN_FAIL; + goto rm_outputfile; + } + + if ((retval = + analyze_heartbeat_cmd_outfile (outputfile, _dbmt_error)) != ERR_NO_ERROR) + { + fclose (outputfile); + goto rm_outputfile; + } + + /* close tmp file. */ + fclose (outputfile); + +rm_outputfile: + unlink (outputfilepath); + if (access (arniadb_err_file, F_OK) == 0) + { + unlink (arniadb_err_file); + } + return retval; +} + +static int +cmd_heartbeat_act (char *_dbmt_error) +{ + int retval = ERR_NO_ERROR; + const char *argv[8]; + int argc = 0; + char cmd_name[ARNIADB_CMD_NAME_LEN]; + FILE *outputfile = NULL; + char outputfilepath[PATH_MAX]; + char arniadb_err_file[PATH_MAX]; + + outputfilepath[0] = '\0'; + arniadb_err_file[0] = '\0'; + + snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", + sco.dbmt_tmp_dir, "cmd_heartbeat_act", getpid ()); + + arniadb_cmd_name (cmd_name); + argv[argc++] = cmd_name; + argv[argc++] = PRINT_CMD_HEARTBEAT; + argv[argc++] = PRINT_CMD_ACT; + argv[argc++] = NULL; + + snprintf (outputfilepath, PATH_MAX - 1, "%s/DBMT_task_%d.%d", + sco.dbmt_tmp_dir, TS_HEARTBEAT_ACT, (int) getpid ()); + + if (run_child (argv, 1, NULL, outputfilepath, arniadb_err_file, NULL) < 0) + { + /* heartbeat act */ + strcpy (_dbmt_error, argv[0]); + retval = ERR_SYSTEM_CALL; + goto rm_outputfile; + } + + if (read_error_file (arniadb_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) + { + retval = ERR_WITH_MSG; + goto rm_outputfile; + } + + /* open tmp file. */ + outputfile = fopen (outputfilepath, "r"); + if (outputfile == NULL) + { + retval = ERR_TMPFILE_OPEN_FAIL; + goto rm_outputfile; + } + + if ((retval = + analyze_heartbeat_cmd_outfile (outputfile, _dbmt_error)) != ERR_NO_ERROR) + { + fclose (outputfile); + goto rm_outputfile; + } + + /* close tmp file. */ + fclose (outputfile); + +rm_outputfile: + unlink (outputfilepath); + if (access (arniadb_err_file, F_OK) == 0) + { + unlink (arniadb_err_file); + } + return retval; +} + +static int +run_asql_statement (const char *sql_stat, char *dbname, char *dbuser, + char *dbpasswd, char *outfilepath, char *_dbmt_error) +{ + char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; + char task_name[TASKNAME_LEN]; + const char *argv[15]; + + int argc = 0; + int retval = 0; + int ha_mode = 0; + + T_DB_SERVICE_MODE db_mode; + + task_name[0] = '\0'; + dbname_at_hostname[0] = '\0'; + cmd_name[0] = '\0'; + + snprintf (cmd_name, sizeof (cmd_name) - 1, "%s/%s%s", sco.szArniadb, + ARNIADB_DIR_BIN, UTIL_ASQL_NAME); + + if (!_isRegisteredDB (dbname)) + { + return ERR_DB_NONEXISTANT; + } + + db_mode = uDatabaseMode (dbname, &ha_mode); + + if (db_mode == DB_SERVICE_MODE_SA) + { + sprintf (_dbmt_error, "%s", dbname); + return ERR_STANDALONE_MODE; + } + + argv[argc++] = cmd_name; + + if (db_mode == DB_SERVICE_MODE_NONE) + { + argv[argc++] = "--" ASQL_SA_MODE_L; + } + else + { + argv[argc++] = "--" ASQL_CS_MODE_L; + } + + if (dbuser != NULL) + { + argv[argc++] = "--" ASQL_USER_L; + argv[argc++] = dbuser; + + argv[argc++] = "--" ASQL_PASSWORD_L; + if (dbpasswd != NULL) + { + argv[argc++] = dbpasswd; + } + else + { + argv[argc++] = ""; + } + } + else + { + strcpy (_dbmt_error, "dbuser"); + return ERR_PARAM_MISSING; + } + + argv[argc++] = "--" ASQL_COMMAND_L; + argv[argc++] = sql_stat; + + if (ha_mode != 0) + { + append_host_to_dbname (dbname_at_hostname, dbname, + sizeof (dbname_at_hostname)); + argv[argc++] = dbname_at_hostname; + } + else + { + argv[argc++] = dbname; + } + + argv[argc++] = NULL; + + SET_TRANSACTION_NO_WAIT_MODE_ENV (); + + strncpy (task_name, "asql", TASKNAME_LEN); + retval = _run_child (argv, 1, task_name, outfilepath, _dbmt_error); + + return retval; +} + +int +ts_user_verify (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char *dbname, *dbuser, *dbpasswd; + int retval = ERR_NO_ERROR; + + /* every user can access db_user table. */ + const char *sql_stat = "select 1 from db_root"; + + if ((dbname = nv_get_val (req, "dbname")) == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "dbname"); + return ERR_PARAM_MISSING; + } + + if ((dbuser = nv_get_val (req, "dbuser")) != NULL) + { + dbpasswd = nv_get_val (req, "dbpasswd"); + } + else + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "dbuser"); + return ERR_PARAM_MISSING; + } + + /* + * using asql to verify the user's password. + */ + retval = run_asql_statement (sql_stat, dbname, dbuser, dbpasswd, NULL, _dbmt_error); /* asql */ + + return retval; +} + +int +ts_get_standby_server_stat (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char *dbname, *dbuser, *dbpasswd; + char output_file[PATH_MAX] = { 0 }; + int retval; + T_STANDBY_SERVER_STAT stat; + FILE *outfile = NULL; + + /* + * get the record which contains the insert/delete/update/commit/fail counter, + * if there is more than one records, the one with largest last_access_time + * in db_ha_apply_info table is chosen. + */ + const char *sql_stat = + "select " + "insert_counter, update_counter, delete_counter, commit_counter, fail_counter, " + "(last_access_time - log_record_time) " + "from db_ha_apply_info " + "where (last_access_time IN (select max (last_access_time) from db_ha_apply_info))"; + + memset (&stat, 0, sizeof (stat)); + + snprintf (output_file, PATH_MAX - 1, "%s/dbmt_task_%d_%d", + sco.dbmt_tmp_dir, TS_GET_STANDBY_SERVER_STAT, (int) getpid ()); + + if ((dbname = nv_get_val (req, "dbname")) == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "dbname"); + retval = ERR_PARAM_MISSING; + goto func_return; + } + + nv_add_nvp (res, "dbname", dbname); + + if ((dbuser = nv_get_val (req, "dbid")) != NULL) + { + dbpasswd = nv_get_val (req, "dbpasswd"); + } + else + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "dbid"); + retval = ERR_PARAM_MISSING; + goto func_return; + } + + retval = run_asql_statement (sql_stat, dbname, dbuser, dbpasswd, output_file, _dbmt_error); /* asql */ + + if (retval != ERR_NO_ERROR) + { + goto func_return; + } + + if ((outfile = fopen (output_file, "r")) == NULL) + { + retval = ERR_TMPFILE_OPEN_FAIL; + goto func_return; + } + + if ((retval = + parse_standby_server_stat (&stat, outfile, _dbmt_error)) != ERR_NO_ERROR) + { + fclose (outfile); + goto func_return; + } + + fclose (outfile); + retval = ERR_NO_ERROR; + +func_return: + nv_add_nvp_int64 (res, "delay_time", stat.delay_time); + nv_add_nvp_int64 (res, "insert_counter", stat.insert_counter); + nv_add_nvp_int64 (res, "update_counter", stat.update_counter); + nv_add_nvp_int64 (res, "delete_counter", stat.delete_counter); + nv_add_nvp_int64 (res, "commit_counter", stat.commit_counter); + nv_add_nvp_int64 (res, "fail_counter", stat.fail_counter); + + unlink (output_file); + return retval; +} + +static int +parse_standby_server_stat (T_STANDBY_SERVER_STAT *stat, FILE *outfile, + char *_dbmt_error) +{ + char buf[1024]; + char prefix[64] = { 0 }; + long long delay_time = 0; + long long insert_counter = 0; + long long update_counter = 0; + long long delete_counter = 0; + long long commit_counter = 0; + long long fail_counter = 0; + + while (fgets (buf, sizeof (buf), outfile)) + { + sscanf (buf, "%63s", prefix); + + /* the first charactor is the num of insert_counter, it should be digit. */ + if (isdigit (prefix[0])) + { + /* break when found the result. */ + if (sscanf + (buf, "%lld %lld %lld %lld %lld %lld", + &insert_counter, &update_counter, &delete_counter, + &commit_counter, &fail_counter, &delay_time) == 6) + { + break; + } + } + } + + stat->delay_time = delay_time; + stat->insert_counter = insert_counter; + stat->update_counter = update_counter; + stat->delete_counter = delete_counter; + stat->commit_counter = commit_counter; + stat->fail_counter = fail_counter; + + return ERR_NO_ERROR; +} + +static char * +get_mode_from_output_file (char *mode, int buf_len, FILE *outputfile, + char *_dbmt_error) +{ + char buf[1024]; + char server_mode[64] = { 0 }; + int scan_matched = 0; + + while (fgets (buf, sizeof (buf), outputfile)) + { + if (strcmp (buf, "\n") == 0) + { + continue; + } + + scan_matched = + sscanf (buf, "%*s %*s %*s %*s %*s %*s %*s %*s %63s", server_mode); + + if (scan_matched != 1) + { + strcpy_limit (_dbmt_error, "error occur when parsing output file.", + DBMT_ERROR_MSG_SIZE); + return NULL; + } + + /* remove '.' */ + if (strlen (server_mode) != 0) + { + server_mode[strlen (server_mode) - 1] = '\0'; + } + break; + } + strcpy_limit (mode, server_mode, buf_len); + + return mode; +} + +static int +cmd_get_db_mode (T_DB_MODE_INFO *dbmodeinfo, char *dbname, char *_dbmt_error) +{ + int ha_mode = 0; + T_DB_SERVICE_MODE dbmode; + char server_mode[64] = ""; + char server_msg[1024] = "none"; + int retval; + + strcpy_limit (dbmodeinfo->dbname, dbname, sizeof (dbmodeinfo->dbname)); + + dbmode = uDatabaseMode (dbname, &ha_mode); + + if (ha_mode == 0) + { + /* To ARNIADB Client, the SA and NONE mode all means the database is stopped. */ + if (dbmode == DB_SERVICE_MODE_SA || dbmode == DB_SERVICE_MODE_NONE) + { + strcpy_limit (server_mode, "stopped", sizeof (server_mode)); + } + else + { + strcpy_limit (server_mode, "CS-mode", sizeof (server_mode)); + } + + retval = ERR_NO_ERROR; + } + else + { + /* + * The task is used for monitoring, the retval of changemode command is + * not checked. The error message will be appended to the server_msg. + */ + retval = + cmd_changemode (dbname, NULL, NULL, server_mode, sizeof (server_mode), + _dbmt_error); + /* changemode */ + } + + /* record the error message to server_msg */ + if (retval != ERR_NO_ERROR) + { + strcpy_limit (server_msg, _dbmt_error, sizeof (server_msg)); + } + + strcpy_limit (dbmodeinfo->server_msg, server_msg, + sizeof (dbmodeinfo->server_msg)); + strcpy_limit (dbmodeinfo->server_mode, server_mode, + sizeof (dbmodeinfo->server_mode)); + + return ERR_NO_ERROR; +} + +int +ts_get_db_mode (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char *dblist, *dbname; + char separator = ','; + T_DB_MODE_INFO dbmode; + + if ((dblist = nv_get_val (req, "dblist")) == NULL) + { + strcpy_limit (_dbmt_error, "dblist", DBMT_ERROR_MSG_SIZE); + return ERR_PARAM_MISSING; + } + + while (dblist != NULL) + { + dbname = dblist; + + if ((dblist = strchr (dblist, separator)) != NULL) + { + dblist[0] = '\0'; + dblist++; + } + + nv_add_nvp (res, "open", "dbserver"); + nv_add_nvp (res, "dbname", dbname); + + cmd_get_db_mode (&dbmode, dbname, _dbmt_error); + nv_add_nvp (res, "server_mode", (&dbmode)->server_mode); + nv_add_nvp (res, "server_msg", (&dbmode)->server_msg); + + nv_add_nvp (res, "close", "dbserver"); + } + + return ERR_NO_ERROR; +} + +int +ts_changemode (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char *dbname, *modify, *force; + char server_mode[64]; + int retval; + + if ((dbname = nv_get_val (req, "dbname")) == NULL) + { + strcpy_limit (_dbmt_error, "dbname", DBMT_ERROR_MSG_SIZE); + return ERR_PARAM_MISSING; + } + modify = nv_get_val (req, "modify"); + force = nv_get_val (req, "force"); + + /* changemode */ + retval = + cmd_changemode (dbname, modify, force, server_mode, sizeof (server_mode), + _dbmt_error); + + if (retval != ERR_NO_ERROR) + { + return retval; + } + + nv_add_nvp (res, "server_mode", server_mode); + + return ERR_NO_ERROR; +} + +static int +cmd_changemode (char *dbname, char *modify, char *force, + char *server_mode_out, int mode_len, char *_dbmt_error) +{ + char server_mode[64]; + const char *argv[10]; + int argc = 0; + int ha_mode = 0; + char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; + T_DB_SERVICE_MODE dbmode; + char arniadb_err_file[PATH_MAX]; + FILE *outputfile; + char tmpfilepath[PATH_MAX]; + int retval = ERR_NO_ERROR; + + arniadb_err_file[0] = '\0'; + + if (dbname == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "dbname"); + return ERR_PARAM_MISSING; + } + + dbmode = uDatabaseMode (dbname, &ha_mode); + if (dbmode == DB_SERVICE_MODE_SA) + { + strcpy_limit (_dbmt_error, dbname, DBMT_ERROR_MSG_SIZE); + return ERR_STANDALONE_MODE; + } + + snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", + sco.dbmt_tmp_dir, "changemode", getpid ()); + snprintf (tmpfilepath, PATH_MAX - 1, "%s/DBMT_task_%d.%d", + sco.dbmt_tmp_dir, TS_CHANGEMODE, (int) getpid ()); + + arniadb_cmd_name (cmd_name); + argv[argc++] = cmd_name; + argv[argc++] = UTIL_OPTION_CHANGEMODE; + + if (modify != NULL) + { + argv[argc++] = "--" CHANGEMODE_MODE_L; + argv[argc++] = modify; + + if (uStringEqual (force, "y")) + { + argv[argc++] = "--" CHANGEMODE_FORCE_L; + } + } + + if (ha_mode != 0) + { + append_host_to_dbname (dbname_at_hostname, dbname, + sizeof (dbname_at_hostname)); + argv[argc++] = dbname_at_hostname; + } + else + { + argv[argc++] = dbname; + } + + argv[argc++] = NULL; + + if (run_child (argv, 1, NULL, tmpfilepath, arniadb_err_file, NULL) < 0) /* changemode */ + { + strcpy_limit (_dbmt_error, argv[0], DBMT_ERROR_MSG_SIZE); + retval = ERR_SYSTEM_CALL; + goto error_return; + } + + if (read_error_file (arniadb_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) + { + retval = ERR_WITH_MSG; + goto error_return; + } + + if ((outputfile = fopen (tmpfilepath, "r")) == NULL) + { + retval = ERR_TMPFILE_OPEN_FAIL; + goto error_return; + } + + if ((get_mode_from_output_file + (server_mode, sizeof (server_mode), outputfile, _dbmt_error)) == NULL) + { + + fclose (outputfile); + strcpy_limit (server_mode_out, "", mode_len); + strcpy_limit (_dbmt_error, "unknown database mode.", + DBMT_ERROR_MSG_SIZE); + retval = ERR_WITH_MSG; + goto error_return; + } + + strcpy_limit (server_mode_out, server_mode, mode_len); + + fclose (outputfile); + unlink (tmpfilepath); + if (access (arniadb_err_file, F_OK) == 0) + { + unlink (arniadb_err_file); + } + return ERR_NO_ERROR; + +error_return: + unlink (tmpfilepath); + if (access (arniadb_err_file, F_OK) == 0) + { + unlink (arniadb_err_file); + } + return retval; +} + +int +ts_role_change (nvplist *req, nvplist *res, char *_dbmt_error) +{ + int i; + int retval = ERR_NO_ERROR; + char cmdfile[PATH_MAX]; + FILE *infile = NULL; + char *tok[8]; + const char *cmd_argv[8]; + char arn_admin_cmd[ARNIADB_CMD_NAME_LEN]; + char buf[2048] = { 0 }; + + const char *argv[] = + { + "/bin/ps", + "xo", + "cmd", + NULL, + }; + + snprintf (cmdfile, PATH_MAX - 1, "%s/DBMT_task_%d.%d", + sco.dbmt_tmp_dir, TS_ROLE_CHANGE, (int) getpid ()); + + /* save the process info before heartbeat deact operation. */ + if (run_child (argv, 1, NULL, cmdfile, NULL, NULL) < 0) + { + strcpy_limit (_dbmt_error, argv[0], DBMT_ERROR_MSG_SIZE); + return ERR_SYSTEM_CALL; + } + + /* + * use heartbeat deact command to deact the heartbeat in Master node, + * so that the slave node can change into a master node. + */ + if ((retval = cmd_heartbeat_deact (_dbmt_error)) != ERR_NO_ERROR) /* heartbeat deact */ + { + goto error_return; + } + + /* + * sleep 6s to wait for the slave node change into master node. + * the slave node needs about 4s to change itself into master node. + */ + SLEEP_SEC (6); + + /* restart the heartbeat after the slave node changed into master node. */ + if ((retval = cmd_heartbeat_act (_dbmt_error)) != ERR_NO_ERROR) /* heartbeat act */ + { + goto error_return; + } + + if ((infile = fopen (cmdfile, "r")) == NULL) + { + retval = ERR_TMPFILE_OPEN_FAIL; + goto error_return; + } + + /* restart the HA related processes recorded in cmdfile. */ + while (fgets (buf, sizeof (buf), infile)) + { + char buf_t[2048] = { 0 }; + + ut_trim (buf); + to_lower_str (buf, buf_t); + + for (i = 0; i < 8; i++) + { + tok[i] = NULL; + cmd_argv[i] = NULL; + } + + if ((strstr (buf_t, " copylogdb") != NULL) || + (strstr (buf_t, " applylogdb") != NULL)) + { + /* restart applylogdb & copylogdb processes. */ + string_tokenize2 (buf, tok, 8, ' '); + arn_admin_cmd_name (arn_admin_cmd, sizeof (arn_admin_cmd)); + + cmd_argv[0] = arn_admin_cmd; + + for (i = 1; tok[i] != NULL; i++) + { + cmd_argv[i] = tok[i]; + } + + if (run_child (cmd_argv, 0, NULL, NULL, NULL, NULL) < 0) + { + retval = ERR_SYSTEM_CALL; + goto error_return; + } + } + else if (strstr (buf, "arn_server") != NULL) + { + /* restart database server processes. */ + string_tokenize2 (buf, tok, 3, ' '); + + if (cmd_start_server (tok[1], _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) + { + retval = ERR_WITH_MSG; + goto error_return; + } + } + } + + retval = ERR_NO_ERROR; + +error_return: + if (infile) + { + fclose (infile); + } + unlink (cmdfile); + return retval; +} + +static void +print_db_stat_to_res (T_CM_DB_PROC_STAT *db_stat, nvplist *res) +{ + nv_add_nvp (res, "open", "dbstat"); + nv_add_nvp (res, "dbname", db_stat->name); + nv_add_nvp_int64 (res, "cpu_kernel", db_stat->stat.cpu_kernel); + nv_add_nvp_int64 (res, "cpu_user", db_stat->stat.cpu_user); + nv_add_nvp_int64 (res, "mem_physical", db_stat->stat.mem_physical); + nv_add_nvp_int64 (res, "mem_virtual", db_stat->stat.mem_virtual); + nv_add_nvp (res, "close", "dbstat"); +} + +int +ts_heartbeat_list (nvplist *req, nvplist *res, char *_dbmt_error) +{ + T_HA_SERVER_INFO_ALL *all_info = NULL; + char *dbmodeall = NULL; + char *dblist = NULL; + int get_all_dbmode = 0; + int retval = ERR_NO_ERROR; + + if ((dbmodeall = nv_get_val (req, "dbmodeall")) != NULL) + { + if (strcmp (dbmodeall, "y") == 0) + { + get_all_dbmode = 1; + } + else + { + get_all_dbmode = 0; + dblist = nv_get_val (req, "dblist"); + } + } + else + { + retval = ERR_PARAM_MISSING; + strcpy_limit (_dbmt_error, "dbmodeall", DBMT_ERROR_MSG_SIZE); + goto error_return; + } + + all_info = (T_HA_SERVER_INFO_ALL *) MALLOC (sizeof (T_HA_SERVER_INFO_ALL)); + if (all_info == NULL) + { + return ERR_MEM_ALLOC; + } + + memset (all_info, 0, sizeof (T_HA_SERVER_INFO_ALL)); + + if ((retval = + cmd_heartbeat_list (&all_info, get_all_dbmode, dblist, + _dbmt_error)) != ERR_NO_ERROR) + { + goto error_return; + } + + /* + * get dbmode for every dbserver in the dbinfo list, the allocated space will be + * freed in dbinfo_list_free function. + */ + if ((retval = + fill_dbmode_into_dbinfo_list (&all_info, _dbmt_error)) != ERR_NO_ERROR) + { + goto error_return; + } + + print_dbinfo_list_to_res (all_info, res); + +error_return: + dbinfo_list_free (all_info); + return retval; +} + +int +ts_get_envvar_by_name (nvplist *req, nvplist *res, char *_dbmt_error) +{ + int i; + char *n, *v; + + for (i = 0; i < req->nvplist_leng; i++) + { + nv_lookup (req, i, &n, &v); + if ((n != NULL) && (strcmp (n, "envvar") == 0)) + { + char *envvar_t = getenv (v); + + nv_add_nvp (res, v, (envvar_t == NULL ? "" : envvar_t)); + } + } + + return ERR_NO_ERROR; +} + +int +ts_copy_folder (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char *src_dir; + char *dest_dir; + + if ((src_dir = nv_get_val (req, "srcdir")) == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "srcdir"); + return ERR_PARAM_MISSING; + } + if ((dest_dir = nv_get_val (req, "destdir")) == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "destdir"); + return ERR_PARAM_MISSING; + } + + if (folder_copy (src_dir, dest_dir) < 0) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE - 1, + "Failed when copying %s to %s.", src_dir, dest_dir); + return ERR_WITH_MSG; + } + + return ERR_NO_ERROR; +} + +int +ts_delete_folder (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char *src_dir; + int force_flag; + + if ((src_dir = nv_get_val (req, "srcdir")) == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "srcdir"); + return ERR_PARAM_MISSING; + } + + force_flag = REMOVE_DIR_FORCED; + + if (uRemoveDir (src_dir, force_flag) != ERR_NO_ERROR) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE - 1, + "Can't' delete the folder: %s.", src_dir); + return ERR_WITH_MSG; + } + + return ERR_NO_ERROR; +} + +int +ts_write_and_save_conf (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char *conf_path; + char conf_backup_path[PATH_MAX]; + + if ((conf_path = nv_get_val (req, "confpath")) == NULL) + { + strcpy_limit (_dbmt_error, "confpath", DBMT_ERROR_MSG_SIZE); + return ERR_PARAM_MISSING; + } + + /* if conf_path exsit, backup it at the current path. */ + if (access (conf_path, F_OK) == 0) + { + snprintf (conf_backup_path, sizeof (conf_backup_path) - 1, + "%s.bak", conf_path); + + if (file_copy (conf_path, conf_backup_path) != 0) + { + strcpy_limit (_dbmt_error, "backup file error.", + DBMT_ERROR_MSG_SIZE); + return ERR_WITH_MSG; + } + } + + /* create a new conf file from request. */ + if (_write_conf_to_file (req, conf_path) < 0) + { + strcpy_limit (_dbmt_error, "write config file error.", + DBMT_ERROR_MSG_SIZE); + return ERR_WITH_MSG; + } + + return ERR_NO_ERROR; +} + +int +ts_run_sql_statement (nvplist *req, nvplist *res, char *_dbmt_error) +{ + T_ARNIADB_MODE mode; + T_ASQL_RESULT *asql_res = NULL; + int retval = ERR_NO_ERROR; + char *dbname, *uid, *passwd; + char *infile; + char *command; + char *error_continue; + + if ((dbname = nv_get_val (req, "dbname")) == NULL) + { + strcpy_limit (_dbmt_error, "dbname", DBMT_ERROR_MSG_SIZE); + return ERR_PARAM_MISSING; + } + + infile = nv_get_val (req, "infile"); + command = nv_get_val (req, "command"); + + uid = nv_get_val (req, "uid"); + passwd = nv_get_val (req, "passwd"); + error_continue = nv_get_val (req, "error_continue"); + + mode = + (uDatabaseMode (dbname, NULL) == + DB_SERVICE_MODE_NONE ? ARNIADB_MODE_SA : ARNIADB_MODE_CS); + + asql_res = cmd_asql (dbname, uid, passwd, mode, infile, command, error_continue); /* asql */ + + if (asql_res == NULL) + { + strcpy_limit (_dbmt_error, "Error occur when execurating asql.", + DBMT_ERROR_MSG_SIZE); + return ERR_WITH_MSG; + } + + if (strlen (asql_res->err_msg) != 0) + { + strcpy_limit (_dbmt_error, asql_res->err_msg, DBMT_ERROR_MSG_SIZE); + retval = ERR_WITH_MSG; + } + free (asql_res); + return retval; +} + +int +ts_get_folders_with_keyword (nvplist *req, nvplist *res, char *_dbmt_error) +{ + int retval; + char *search_folder; + char *keyword; + + if ((search_folder = nv_get_val (req, "search_folder")) == NULL) + { + strcpy_limit (_dbmt_error, "search_folder", DBMT_ERROR_MSG_SIZE); + return ERR_PARAM_MISSING; + } + + if ((keyword = nv_get_val (req, "keyword")) == NULL) + { + strcpy_limit (_dbmt_error, "keyword", DBMT_ERROR_MSG_SIZE); + return ERR_PARAM_MISSING; + } + + retval = + _get_folders_with_keyword (search_folder, keyword, res, _dbmt_error); + + return retval; +} + +int +ts_run_script (nvplist *req, nvplist *res, char *_dbmt_error) +{ + int argc = 0; + const char *argv[5]; + char *script_path; + char outfile[PATH_MAX]; + char errfile[PATH_MAX]; + char *n, *v; + int retval = ERR_NO_ERROR; + int i, pid; + + pid = (int) getpid (); + snprintf (outfile, sizeof (outfile) - 1, "%s/DBMT_task_%d_out.%d", + sco.dbmt_tmp_dir, TS_RUN_SCRIPT, pid); + snprintf (errfile, sizeof (errfile) - 1, "%s/DBMT_task_%d_err.%d", + sco.dbmt_tmp_dir, TS_RUN_SCRIPT, pid); + + /* set environment that the script need to run. */ + for (i = 0; i < req->nvplist_leng; i++) + { + nv_lookup (req, i, &n, &v); + if ((n != NULL) && (strcmp (n, "envvar") == 0)) + { + putenv (v); + } + } + + if ((script_path = nv_get_val (req, "script_path")) == NULL) + { + strcpy_limit (_dbmt_error, "script_path", DBMT_ERROR_MSG_SIZE); + return ERR_PARAM_MISSING; + } + + argv[argc++] = script_path; + argv[argc++] = NULL; + + /* run *.bat or *.sh. */ + if (run_child (argv, 1, NULL, outfile, errfile, NULL) < 0) + { + strcpy_limit (_dbmt_error, argv[0], DBMT_ERROR_MSG_SIZE); + retval = ERR_SYSTEM_CALL; + } + + unlink (outfile); + unlink (errfile); + + return retval; +} + +int +ts_get_file_total_line_num (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char *filepath; + FILE *fp = NULL; + char buf[LINE_MAX]; + int total_num = 0; + + if ((filepath = nv_get_val (req, "filepath")) == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "filepath"); + return ERR_PARAM_MISSING; + } + + if ((fp = fopen (filepath, "r")) == NULL) + { + return ERR_TMPFILE_OPEN_FAIL; + } + + while (fgets (buf, sizeof (buf), fp)) + { + total_num++; + } + fclose (fp); + + nv_add_nvp_int (res, "totalnum", total_num); + + return ERR_NO_ERROR; +} + +int +ts_error_trace (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char *err_log_path; + char *eid; + char *err_time; + FILE *fp; + char buf[10 * 1024]; + + if ((err_log_path = nv_get_val (req, "logpath")) == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "logpath"); + return ERR_PARAM_MISSING; + } + + if ((eid = nv_get_val (req, "eid")) == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "eid"); + return ERR_PARAM_MISSING; + } + + if ((err_time = nv_get_val (req, "errtime")) == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "errtime"); + return ERR_PARAM_MISSING; + } + + memset (buf, 0, sizeof (buf)); + + if ((fp = fopen (err_log_path, "r")) == NULL) + { + return ERR_FILE_OPEN_FAIL; + } + + nv_add_nvp (res, "open", "errbloc"); + + while (_get_block_from_log (fp, buf, sizeof (buf)) == 0) + { + char *line_start, *line_end; + char eid_tok[64]; + char err_time_tok[64]; + + snprintf (eid_tok, sizeof (eid_tok) - 1, "EID = %s", eid); + snprintf (err_time_tok, sizeof (err_time_tok) - 1, "%s (", err_time); + + line_start = buf; + if ((strstr (line_start, eid_tok) != NULL) + && (strstr (line_start, err_time_tok) != NULL)) + { + while ((line_end = strchr (line_start, '\n')) != NULL) + { + *line_end = '\0'; + nv_add_nvp (res, "line", line_start); + line_end++; + line_start = line_end; + } + } + } + + nv_add_nvp (res, "close", "errbloc"); + fclose (fp); + + return ERR_NO_ERROR; +} + +int +ts_remove_files (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char *path = NULL; + char fullpath[PATH_MAX]; + int i = 0; + int sect = -1; + int sect_len = -1; + int path_len = -1; + int found = -1; + + fullpath[0] = '\0'; + + nv_locate (req, "files", §, §_len); + if (sect >= 0) + { + for (i = 0; i < sect_len; ++i) + { + found = nv_lookup (req, sect + i, NULL, &path); + if (found == -1) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", + "The key [path] is missing or its value is not valid."); + return ERR_WITH_MSG; + } + if (path == NULL) + { + sprintf (_dbmt_error, + "Please inform file names to be deleted."); + return ERR_WITH_MSG; + } + path_len = (int) strlen (path); + if (path_len <= 2 || strstr (path, "..") || strstr (path, "/") + || strstr (path, "\\")) + { + sprintf (_dbmt_error, "Cannot be permitted to delete %s file", + path); + return ERR_WITH_MSG; + } + if (*path == '+' && * (path + 1) == 'T') // for ARNIADB/tmp + { + snprintf (fullpath, sizeof (fullpath) - 1, "%s/tmp/%s", + sco.szArniadb, (path + 2)); + } + else + { + sprintf (_dbmt_error, "Cannot be permitted to delete %s file", + path); + return ERR_WITH_MSG; + } + if ((unlink (fullpath) != 0) && (errno != ENOENT)) + { + sprintf (_dbmt_error, "Cannot remove file '%s' (%s)", path, + strerror (errno)); + return ERR_WITH_MSG; + } + } /* end of for */ + return ERR_NO_ERROR; + } + else + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", + "The key [files] is missing or its value is not valid."); + return ERR_WITH_MSG; + } +} + + +int +ts_login (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char *value = NULL; + int ret_val = ERR_NO_ERROR; + + if ((ret_val = ts_validate_user (req, res, _dbmt_error)) != ERR_NO_ERROR) + { + /* Authentication failed. Drop connection */ + /* because function ts_validate_user already add the err msg to res */ + return ret_val; + } + + if (ts_check_client_version (req, res) == 0) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "Version-mismatched"); + + /* because function ts_validate_user already add the err msg to res */ + return ERR_WITH_MSG; + } + + /* generate token and record new connection to file */ + value = nv_get_val (req, "id"); + /* set _ID token for ut_error_log & ut_access_log. */ + nv_add_nvp (req, "_ID", value); + + _accept_connection (req, res); + + ut_access_log (req, "connected"); + + return ERR_NO_ERROR; +} + +int +ts_logout (nvplist *req, nvplist *res, char *_dbmt_error) +{ + T_USER_TOKEN_INFO *removed_node = NULL; + + char *token = NULL; + + ut_access_log (req, "disconnected"); + + nv_update_val (res, "status", "success"); + nv_update_val (res, "note", ""); + + token = nv_get_val (req, "token"); + removed_node = dbmt_user_delete_token_info_by_token (token); + + if (removed_node == NULL) + { + return ERR_INVALID_TOKEN; + } + + FREE_MEM (removed_node); + + return ERR_NO_ERROR; +} + +int +ts_job_test (nvplist *req, nvplist *res, char *_dbmt_error) +{ + int i; + nvplist *cli_response; + const char *argvs[2]; + + cli_response = nv_create (5, NULL, "\n", ":", "\n"); + for (i = ERR_NO_ERROR; i <= ERR_WARNING; i++) + { + uGenerateStatus (req, cli_response, i, "test error"); + } + + nv_destroy (cli_response); + argvs[0] = "ping"; + argvs[1] = NULL; + + ut_run_child ("ping", argvs, 1, "infile.test", "outfile.test", + "errfile.test", &i); + unlink ("outfile.test"); + unlink ("errfile.test"); + return ERR_NO_ERROR; +} + +static const char * +get_processor_architecture () +{ +#ifdef WINDOWS + SYSTEM_INFO siSysInfo; + GetSystemInfo (&siSysInfo); + switch (siSysInfo.wProcessorArchitecture) + { + case PROCESSOR_ARCHITECTURE_AMD64: + case PROCESSOR_ARCHITECTURE_IA64: + return "x64"; + case PROCESSOR_ARCHITECTURE_INTEL: + return "x86"; + default: + break; + } + return "unknown"; +#else + struct utsname u_name; + if (uname (&u_name) < 0) + { + return "unknown"; + } + + if (!strcmp (u_name.machine, "x86_64")) + { + return "x64"; + } + else + { + return "x86"; + } +#endif +} + +int +ts_get_ams_env (nvplist *req, nvplist *res, char *_dbmt_error) +{ + int is_default_cert_file = 0; + + ts_get_server_version (req, res); + nv_add_nvp (res, "PLATFORM", get_processor_architecture ()); + nv_add_nvp (res, "AMS_VER", makestring (BUILD_NUMBER)); + + nv_add_nvp_int (res, "cm_port", sco.iAMS_port); + + is_default_cert_file = _is_default_cert (_dbmt_error); + if (is_default_cert_file < 0) + { + return ERR_WITH_MSG; + } + if (is_default_cert_file == 0) + { + nv_add_nvp (res, "is_default_cert", "no"); + } + else + { + nv_add_nvp (res, "is_default_cert", "yes"); + } + + return ERR_NO_ERROR; +} + +int +ts_keepalive (nvplist *req, nvplist *res, char *_dbmt_error) +{ + SLEEP_SEC (10); + nv_update_val (res, "status", "success"); + nv_update_val (res, "note", ""); + return ERR_NO_ERROR; +} + +static int +_get_block_from_log (FILE *fp, char *block_buf, int len) +{ + int retval = -1; + int space_left = len - 1; + char buf[2048]; + char *buf_t = block_buf; + + while (fgets (buf, sizeof (buf), fp)) + { + if (space_left <= 0) + { + return 0; + } + + if (strcmp (buf, "\n") == 0) + { + break; + } + + strcpy_limit (buf_t, buf, space_left); + space_left -= (int) strlen (buf); + buf_t += strlen (buf); + retval = 0; + } + + if (strlen (block_buf)) + { + block_buf[strlen (block_buf) - 1] = '\0'; + } + return retval; +} + +static int +cmd_heartbeat_list (T_HA_SERVER_INFO_ALL **all_info, int get_all_dbmode, + char *dblist, char *_dbmt_error) +{ + char cmd_name[ARNIADB_CMD_NAME_LEN]; + const char *argv[6]; + int argc = 0; + char arniadb_err_file[PATH_MAX]; + char outputfilepath[PATH_MAX]; + int retval = ERR_NO_ERROR; + FILE *tmpfile = NULL; + + arniadb_err_file[0] = '\0'; + + arniadb_cmd_name (cmd_name); + argv[argc++] = cmd_name; + argv[argc++] = PRINT_CMD_HEARTBEAT; + argv[argc++] = PRINT_CMD_LIST; + argv[argc++] = NULL; + + snprintf (arniadb_err_file, PATH_MAX, "%s/%s.%u.err.tmp", + sco.dbmt_tmp_dir, "heartbeat_list", getpid ()); + + snprintf (outputfilepath, PATH_MAX - 1, "%s/DBMT_task_%d.%d", + sco.dbmt_tmp_dir, TS_HEARTBEAT_LIST, (int) getpid ()); + + if (run_child (argv, 1, NULL, outputfilepath, arniadb_err_file, NULL) < 0) + { + /* heartbeat list */ + strcpy (_dbmt_error, argv[0]); + retval = ERR_SYSTEM_CALL; + goto rm_tmpfile; + } + + if (read_error_file (arniadb_err_file, _dbmt_error, DBMT_ERROR_MSG_SIZE) < 0) + { + retval = ERR_WITH_MSG; + goto rm_tmpfile; + } + + /* open tmp file. */ + tmpfile = fopen (outputfilepath, "r"); + if (tmpfile == NULL) + { + retval = ERR_TMPFILE_OPEN_FAIL; + goto rm_tmpfile; + } + + if ((retval = + record_ha_topology_to_struct (tmpfile, get_all_dbmode, dblist, + _dbmt_error, all_info)) != ERR_NO_ERROR) + { + fclose (tmpfile); + goto rm_tmpfile; + } + + /* close tmp file. */ + fclose (tmpfile); + +rm_tmpfile: + unlink (outputfilepath); + if (access (arniadb_err_file, F_OK) == 0) + { + unlink (arniadb_err_file); + } + return retval; +} + +static int +dbname_exist_in_dbinfo_list (int nitem, char *dbname, + T_HA_SERVER_INFO_ALL *all_info) +{ + int i; + T_HA_DBSERVER_INFO *db_info_t = NULL; + + for (i = 0; i < nitem; i++) + { + db_info_t = & (all_info->db_info[i]); + if (strcmp (dbname, db_info_t->dbname) == 0) + { + return i; + } + } + return -1; +} + +static void +print_ha_proc_info (T_HA_LOG_PROC_INFO *ha_log_proc, int elem_num, + int is_copylogdb, nvplist *res) +{ + int i; + + for (i = 0; i < elem_num; i++) + { + nv_add_nvp (res, "open", "element"); + nv_add_nvp (res, "hostname", ha_log_proc[i].hostname); + nv_add_nvp (res, "dbname", ha_log_proc[i].dbname); + nv_add_nvp (res, "state", ha_log_proc[i].state); + nv_add_nvp (res, "logpath", ha_log_proc[i].logpath); + nv_add_nvp_int (res, "pid", ha_log_proc[i].pid); + if (is_copylogdb != 0) + { + nv_add_nvp (res, "mode", ha_log_proc[i].mode); + } + nv_add_nvp (res, "close", "element"); + } +} + +static void +print_dbinfo_list_to_res (T_HA_SERVER_INFO_ALL *all_info, nvplist *res) +{ + int i; + T_DB_MODE_INFO *dbmode_info_t = NULL; + T_HA_DB_PROC_INFO *dbproc_info_t = NULL; + T_HA_LOG_PROC_INFO *applylogdb_info_t = NULL; + T_HA_LOG_PROC_INFO *copylogdb_info_t = NULL; + T_HA_NODE_INFO *node_info_t = NULL; + + nv_add_nvp (res, "currentnode", all_info->current_node); + nv_add_nvp (res, "currentnodestate", all_info->current_node_state); + + nv_add_nvp (res, "open", "hanodelist"); + + for (i = 0; i < all_info->num_nodeinfo; i++) + { + nv_add_nvp (res, "open", "node"); + if ((node_info_t = & (all_info->node_info[i])) != NULL) + { + nv_add_nvp (res, "hostname", node_info_t->hostname); + nv_add_nvp (res, "ip", node_info_t->ip); + nv_add_nvp_int (res, "priority", node_info_t->priority); + nv_add_nvp (res, "state", node_info_t->state); + } + nv_add_nvp (res, "close", "node"); + } + nv_add_nvp (res, "close", "hanodelist"); + + nv_add_nvp (res, "open", "hadbinfolist"); + + for (i = 0; i < all_info->num_dbinfo; i++) + { + nv_add_nvp (res, "open", "server"); + + /* add db mode info */ + nv_add_nvp (res, "open", "dbmode"); + if ((dbmode_info_t = all_info->db_info[i].dbmode_info) != NULL) + { + nv_add_nvp (res, "dbname", dbmode_info_t->dbname); + nv_add_nvp (res, "server_mode", dbmode_info_t->server_mode); + nv_add_nvp (res, "server_msg", dbmode_info_t->server_msg); + } + nv_add_nvp (res, "close", "dbmode"); + + nv_add_nvp (res, "open", "dbprocinfo"); + if ((dbproc_info_t = all_info->db_info[i].dbproc_info) != NULL) + { + nv_add_nvp (res, "dbname", dbproc_info_t->dbname); + nv_add_nvp_int (res, "pid", dbproc_info_t->pid); + nv_add_nvp (res, "state", dbproc_info_t->state); + } + nv_add_nvp (res, "close", "dbprocinfo"); + + nv_add_nvp (res, "open", "applylogdb"); + if ((applylogdb_info_t = all_info->db_info[i].applylogdb_info) != NULL) + { + print_ha_proc_info (applylogdb_info_t, all_info->db_info[i].num_ap, + 0, res); + } + nv_add_nvp (res, "close", "applylogdb"); + + nv_add_nvp (res, "open", "copylogdb"); + if ((copylogdb_info_t = all_info->db_info[i].copylogdb_info) != NULL) + { + print_ha_proc_info (copylogdb_info_t, all_info->db_info[i].num_cp, + 1, res); + } + nv_add_nvp (res, "close", "copylogdb"); + + nv_add_nvp (res, "close", "server"); + } + nv_add_nvp (res, "close", "hadbinfolist"); +} + +static void +dbinfo_list_free (T_HA_SERVER_INFO_ALL *all_info) +{ + int i; + + if (all_info == NULL) + { + return; + } + + for (i = 0; i < all_info->num_dbinfo; i++) + { + if (&all_info->db_info[i] == NULL) + { + continue; + } + + FREE_MEM ((&all_info->db_info[i])->dbmode_info); + FREE_MEM ((&all_info->db_info[i])->dbproc_info); + FREE_MEM ((&all_info->db_info[i])->applylogdb_info); + FREE_MEM ((&all_info->db_info[i])->copylogdb_info); + } + + FREE_MEM (all_info->db_info); + FREE_MEM (all_info->node_info); + FREE_MEM (all_info); +} + +static char * +get_ip_from_hostname (char *hostname, char *ipaddr, int ip_len) +{ + char *ip = NULL; + int i; + struct hostent *hostent_p = NULL; + + hostent_p = gethostbyname (hostname); + + if (hostent_p == NULL) + { + ipaddr = NULL; + } + else + { + for (i = 0; hostent_p->h_addr_list[i] != NULL; i++) + { + ip = inet_ntoa (* ((struct in_addr *) hostent_p->h_addr_list[i])); + + /* ignore the 127.0.0.1 */ + if (strcmp (ip, "127.0.0.1") == 0) + { + continue; + } + break; + } + if (ip) + { + strcpy_limit (ipaddr, ip, ip_len); + } + } + + return ipaddr; +} + +static int +is_name_in_list (char *name, char *list) +{ + int first_name_len = 0; + char *name_start_p = NULL; + char *name_end_p = NULL; + char name_t[1024] = { 0 }; + + name_start_p = list; + name_end_p = strchr (name_start_p, ','); + + while (name_end_p != NULL) + { + /* copy name from list and trim it. */ + first_name_len = (int) (name_end_p - name_start_p); + + if (first_name_len > (int) sizeof (name_t)) + { + return -1; + } + + strcpy_limit (name_t, name_start_p, first_name_len + 1); + + ut_trim (name_t); + + if (strcmp (name_t, name) == 0) + { + return 1; + } + + name_start_p = name_end_p + 1; + name_end_p = strchr (name_start_p, ','); + } + + /* + * when name_end_p is NULL, it indicates the end of list is met. + * check the last name in the list. + */ + + strcpy_limit (name_t, name_start_p, sizeof (name_t)); + ut_trim (name_t); + + if (strcmp (name_t, name) == 0) + { + return 1; + } + + return 0; +} + +static void +set_copylogdb_mode (T_HA_LOG_PROC_INFO *copylogdb) +{ + FILE *cmd_fp = NULL; + int cmd_len = 0; + char buf[2048] = { 0 }; + char cmd_file[PATH_MAX]; + char *buf_t = NULL; + + memset (buf, 0, sizeof (buf)); + + snprintf (cmd_file, PATH_MAX - 1, "/proc/%d/cmdline", copylogdb->pid); + cmd_fp = fopen (cmd_file, "r"); + + if (cmd_fp == NULL) + { + strcpy_limit (copylogdb->mode, "", sizeof (copylogdb->mode)); + return; + } + + cmd_len = (int) fread (buf, sizeof (char), sizeof (buf) - 1, cmd_fp); + buf_t = buf; + + while (buf_t[0] != 0 && ((int) (buf_t - buf)) < cmd_len) + { + int s_len = 0; + + s_len = (int) strlen (buf_t); + + if (uStringEqual (buf_t, "-m") || uStringEqual (buf_t, "--mode")) + { + /* if the arg is "-m" or "--mode", then the next arg is the mode. */ + buf_t = &buf_t[s_len + 1]; + break; + } + else if (strncmp (buf_t, "--mode=", strlen ("--mode=")) == 0) + { + /* if the arg is "--mode", the mode is right behind the '='. */ + buf_t += strlen ("--mode="); + break; + } + + buf_t = &buf_t[ (s_len + 1)]; + } + + /* if the "-m" & "--mode" args are not exist, the default "sync" mode is used. */ + if (buf_t[0] == 0) + { + strcpy_limit (copylogdb->mode, "sync", sizeof (copylogdb->mode)); + goto func_return; + } + else + { + if (uStringEqual (buf_t, "3") || uStringEqualIgnoreCase (buf_t, "sync")) + { + strcpy_limit (copylogdb->mode, "sync", sizeof (copylogdb->mode)); + } + else if (uStringEqual (buf_t, "2") || + uStringEqualIgnoreCase (buf_t, "semisync")) + { + strcpy_limit (copylogdb->mode, "semisync", + sizeof (copylogdb->mode)); + } + else if (uStringEqual (buf_t, "1") || + uStringEqualIgnoreCase (buf_t, "async")) + { + strcpy_limit (copylogdb->mode, "async", sizeof (copylogdb->mode)); + } + else + { + strcpy_limit (copylogdb->mode, "", + sizeof (copylogdb->mode)); + } + goto func_return; + } + +func_return: + fclose (cmd_fp); + return; +} + +static int +parse_ha_proc_msg_to_all_info_array (char *buf, char *_dbmt_error, + T_HA_SERVER_INFO_ALL **all_info, + int *nitem, int *nalloc, + int *nproc_alloc, int get_all_dbmode, + char *dblist) +{ + char tmpbuf[1280] = { 0 }; + char pid[32] = { 0 }; + char elem_name[64] = { 0 }; + char state[64] = { 0 }; + char dbname[DB_NAME_LEN] = { 0 }; + char logpath[PATH_MAX] = { 0 }; + char hostname[MAXHOSTNAMELEN] = { 0 }; + int dbinfo_index = 0; + int retval = ERR_NO_ERROR; + T_HA_LOG_PROC_INFO *applylogdb_info = NULL; + T_HA_LOG_PROC_INFO *copylogdb_info = NULL; + + if (sscanf (buf, "%63s %1279s %*s %31[^,] , %*s %63[^)]", + elem_name, tmpbuf, pid, state) != 4) + { + retval = ERR_NO_ERROR; + goto func_return; + } + else + { + T_HA_DBSERVER_INFO *db_info_t = NULL; + + if (strcmp (elem_name, "Server") == 0) + { + T_HA_DB_PROC_INFO *dbproc_info = NULL; + + if ((get_all_dbmode == 0) + && (is_name_in_list (tmpbuf, dblist) == 0)) + { + retval = ERR_NO_ERROR; + goto func_return; + } + + dbproc_info = + (T_HA_DB_PROC_INFO *) MALLOC (sizeof (T_HA_DB_PROC_INFO)); + + if (dbproc_info == NULL) + { + retval = ERR_MEM_ALLOC; + goto func_return; + } + + /* create a T_HA_DB_PROC_INFO element */ + strcpy_limit (dbproc_info->dbname, tmpbuf, + sizeof (dbproc_info->dbname)); + strcpy_limit (dbproc_info->state, state, + sizeof (dbproc_info->state)); + dbproc_info->pid = atoi (pid); + + /* + * if the dbname is already exist in dbinfo list, add the server proc + * info to the node with the dbname. + */ + if ((dbinfo_index = + dbname_exist_in_dbinfo_list ((*nitem), + dbproc_info->dbname, + *all_info)) >= 0) + { + (*all_info)->db_info[dbinfo_index].dbproc_info = dbproc_info; + } + else + { + /* + * Else add a new dbnode, and add the server proc info to the node. + */ + if ((*nitem) >= (*nalloc)) + { + (*nalloc) *= 2; + + (*all_info)->db_info = + (T_HA_DBSERVER_INFO *) realloc ((*all_info)->db_info, + (*nalloc) * sizeof (T_HA_DBSERVER_INFO)); + + if ((*all_info)->db_info == NULL) + { + retval = ERR_MEM_ALLOC; + goto func_return; + } + } + + /* create two node list for applylogdb and copylogdb process of the server. */ + copylogdb_info = + (T_HA_LOG_PROC_INFO *) MALLOC ((*nproc_alloc) * + sizeof (T_HA_LOG_PROC_INFO)); + applylogdb_info = + (T_HA_LOG_PROC_INFO *) MALLOC ((*nproc_alloc) * + sizeof (T_HA_LOG_PROC_INFO)); + + if (copylogdb_info == NULL || applylogdb_info == NULL) + { + FREE_MEM (copylogdb_info); + FREE_MEM (applylogdb_info); + retval = ERR_MEM_ALLOC; + goto func_return; + } + + db_info_t = & ((*all_info)->db_info[ (*nitem)]); + + strcpy_limit (db_info_t->dbname, + dbproc_info->dbname, sizeof (db_info_t->dbname)); + db_info_t->dbproc_info = dbproc_info; + db_info_t->applylogdb_info = applylogdb_info; + db_info_t->copylogdb_info = copylogdb_info; + db_info_t->num_ap = 0; + db_info_t->num_cp = 0; + (*nitem)++; + } + } + else + { + /* + * if the elem_name is 'Applylogdb' or 'Copylogdb'. + */ + + /* create a tmp T_HA_LOG_PROC_INFO element for later copy. */ + T_HA_DBSERVER_INFO *db_info_t = NULL; + T_HA_LOG_PROC_INFO p_proc_info; + memset (&p_proc_info, 0, sizeof (T_HA_LOG_PROC_INFO)); + if (sscanf (tmpbuf, "%63[^@] @ %128[^:] : %1023s", dbname, + hostname, logpath) != 3) + { + retval = ERR_NO_ERROR; + goto func_return; + } + + if ((get_all_dbmode == 0) + && (is_name_in_list (dbname, dblist) == 0)) + { + retval = ERR_NO_ERROR; + goto func_return; + } + + strcpy_limit (p_proc_info.dbname, dbname, + sizeof (p_proc_info.dbname)); + strcpy_limit (p_proc_info.hostname, hostname, + sizeof (p_proc_info.hostname)); + strcpy_limit (p_proc_info.logpath, logpath, + sizeof (p_proc_info.logpath)); + strcpy_limit (p_proc_info.state, state, sizeof (p_proc_info.state)); + p_proc_info.pid = atoi (pid); + + /* + * if the node already exist in the dbinfo list, then add + * the Applylogdb or Copylogdb proc info to the node with the + * dbname. + */ + if ((dbinfo_index = + dbname_exist_in_dbinfo_list ((*nitem), + p_proc_info.dbname, + *all_info)) >= 0) + { + db_info_t = & ((*all_info)->db_info[dbinfo_index]); + + if (db_info_t->num_ap >= (*nproc_alloc)) + { + (*nproc_alloc) *= 2; + db_info_t->applylogdb_info = + (T_HA_LOG_PROC_INFO *) realloc (db_info_t->applylogdb_info, + (*nproc_alloc) * sizeof (T_HA_LOG_PROC_INFO)); + db_info_t->copylogdb_info = + (T_HA_LOG_PROC_INFO *) realloc (db_info_t->copylogdb_info, + (*nproc_alloc) * sizeof (T_HA_LOG_PROC_INFO)); + + if ((db_info_t->applylogdb_info == NULL) || + (db_info_t->copylogdb_info == NULL)) + { + retval = ERR_MEM_ALLOC; + goto func_return; + } + } + + if (strcmp (elem_name, "Applylogdb") == 0) + { + memmove (& (db_info_t->applylogdb_info[db_info_t->num_ap]), + &p_proc_info, sizeof (T_HA_LOG_PROC_INFO)); + db_info_t->num_ap++; + } + else + { + /* set the copylogdb mode. */ + set_copylogdb_mode (&p_proc_info); + + memmove (& (db_info_t->copylogdb_info[db_info_t->num_cp]), + &p_proc_info, sizeof (T_HA_LOG_PROC_INFO)); + db_info_t->num_cp++; + } + } + else + { + /* + * if the node does not exist in the dbinfo list, + * add a new node with the dbname, and add Applylogdb and + * Copylogdb to the node. + */ + + if ((*nitem) >= (*nalloc)) + { + (*nalloc) *= 2; + + (*all_info)->db_info = + (T_HA_DBSERVER_INFO *) realloc ((*all_info)->db_info, + (*nalloc) * sizeof (T_HA_DBSERVER_INFO)); + if ((*all_info)->db_info == NULL) + { + retval = ERR_MEM_ALLOC; + goto func_return; + } + } + + /* create two node list for applylogdb and copylogdb process of the server. */ + copylogdb_info = + (T_HA_LOG_PROC_INFO *) MALLOC ((*nproc_alloc) * + sizeof (T_HA_LOG_PROC_INFO)); + applylogdb_info = + (T_HA_LOG_PROC_INFO *) MALLOC ((*nproc_alloc) * + sizeof (T_HA_LOG_PROC_INFO)); + + if (copylogdb_info == NULL || applylogdb_info == NULL) + { + FREE_MEM (copylogdb_info); + FREE_MEM (applylogdb_info); + retval = ERR_MEM_ALLOC; + goto func_return; + } + + db_info_t = & ((*all_info)->db_info[ (*nitem)]); + strcpy_limit (db_info_t->dbname, + p_proc_info.dbname, sizeof (db_info_t->dbname)); + db_info_t->dbproc_info = NULL; + db_info_t->copylogdb_info = copylogdb_info; + db_info_t->applylogdb_info = applylogdb_info; + db_info_t->num_ap = 0; + db_info_t->num_cp = 0; + + if (strcmp (elem_name, "Applylogdb") == 0) + { + memmove (& (db_info_t->applylogdb_info[db_info_t->num_ap]), + &p_proc_info, sizeof (T_HA_LOG_PROC_INFO)); + db_info_t->num_ap++; + } + if (strcmp (elem_name, "Copylogdb") == 0) + { + /* set the copylogdb mode. */ + set_copylogdb_mode (&p_proc_info); + + memmove (& (db_info_t->copylogdb_info[db_info_t->num_cp]), + &p_proc_info, sizeof (T_HA_LOG_PROC_INFO)); + db_info_t->num_cp++; + } + (*nitem)++; + } + } + } + +func_return: + return retval; +} + +static int +parse_ha_node_to_all_info_array (char *buf, T_HA_SERVER_INFO_ALL **all_info, + int *node_alloc, char *_dbmt_error) +{ + char tok[4][64] = { {0}, {0}, {0}, {0} }; + char ipaddr[64] = { 0 }; + T_HA_NODE_INFO *node_info_t = NULL; + + if (((*all_info)->num_nodeinfo) >= (*node_alloc)) + { + (*node_alloc) *= 2; + + (*all_info)->node_info = + (T_HA_NODE_INFO *) realloc ((*all_info)->node_info, + (*node_alloc) * sizeof (T_HA_NODE_INFO)); + + if ((*all_info)->node_info == NULL) + { + return ERR_MEM_ALLOC; + } + } + + node_info_t = & ((*all_info)->node_info[ (*all_info)->num_nodeinfo]); + + if (sscanf (buf, "%63s %63s %*s %63[^,] , %*s %63[^)]", + tok[0], tok[1], tok[2], tok[3]) != 4) + { + return ERR_NO_ERROR; + } + + strcpy_limit (node_info_t->hostname, tok[1], + sizeof (node_info_t->hostname)); + + get_ip_from_hostname (tok[1], ipaddr, sizeof (ipaddr)); + + if (ipaddr == NULL) + { + strcpy_limit (_dbmt_error, "can't get ip addr from hostname", + DBMT_ERROR_MSG_SIZE); + return ERR_WITH_MSG; + } + + strcpy_limit (node_info_t->ip, ipaddr, sizeof (node_info_t->ip)); + + node_info_t->priority = atoi (tok[2]); + + strcpy_limit (node_info_t->state, tok[3], sizeof (node_info_t->state)); + + (*all_info)->num_nodeinfo++; + return ERR_NO_ERROR; +} + +static int +record_ha_topology_to_struct (FILE *infile, int get_all_dbmode, char *dblist, + char *_dbmt_error, + T_HA_SERVER_INFO_ALL **all_info) +{ + char buf[2048] = { 0 }; + char ha_elem_name[64] = { 0 }; + T_HA_DBSERVER_INFO *dbserver_p = NULL; + T_HA_NODE_INFO *node_p = NULL; + + int nitem = 0; + int nalloc = 15; + int nproc_alloc = 20; + int node_alloc = 10; + int retval = ERR_NO_ERROR; + + /* Create a dbproc info list which contains all the info about the HA-Process. */ + dbserver_p = + (T_HA_DBSERVER_INFO *) MALLOC (nalloc * sizeof (T_HA_DBSERVER_INFO)); + node_p = (T_HA_NODE_INFO *) MALLOC (node_alloc * sizeof (T_HA_NODE_INFO)); + + if (dbserver_p == NULL || node_p == NULL) + { + FREE_MEM (dbserver_p); + FREE_MEM (node_p); + return ERR_MEM_ALLOC; + } + + (*all_info)->db_info = dbserver_p; + (*all_info)->node_info = node_p; + (*all_info)->num_dbinfo = 0; + (*all_info)->num_nodeinfo = 0; + + while (fgets (buf, sizeof (buf), infile)) + { + sscanf (buf, "%63s", ha_elem_name); + if (strcmp (ha_elem_name, "HA-Node") == 0) + { + char tok[4][64] = { {0}, {0}, {0}, {0} }; + + if (sscanf (buf, "%63s %63s %*s %63[^,] , %*s %63[^)]", + tok[0], tok[1], tok[2], tok[3]) != 4) + { + continue; + } + if (strcmp (tok[0], "HA-Node") == 0) + { + strcpy_limit ((*all_info)->current_node, tok[2], + sizeof ((*all_info)->current_node)); + strcpy_limit ((*all_info)->current_node_state, tok[3], + sizeof ((*all_info)->current_node_state)); + } + } + else if (strcmp (ha_elem_name, "Node") == 0) + { + parse_ha_node_to_all_info_array (buf, all_info, &node_alloc, + _dbmt_error); + } + else if (strcmp (ha_elem_name, "Applylogdb") == 0 || + strcmp (ha_elem_name, "Copylogdb") == 0 || + strcmp (ha_elem_name, "Server") == 0) + { + if (get_all_dbmode == 0 && dblist == NULL) + { + continue; + } + if ((retval = + parse_ha_proc_msg_to_all_info_array + (buf, _dbmt_error, all_info, &nitem, &nalloc, + &nproc_alloc, get_all_dbmode, dblist)) != ERR_NO_ERROR) + { + goto func_return; + } + } + else if ((strcmp (ha_elem_name, "++") == 0)) + { + /* delete the '\n' at the end of buf. */ + ut_trim (buf); + + /* ignore the "++" tag. */ + strcpy_limit (_dbmt_error, &buf[2], DBMT_ERROR_MSG_SIZE); + retval = ERR_WITH_MSG; + goto func_return; + } + } + + retval = ERR_NO_ERROR; + +func_return: + (*all_info)->num_dbinfo = nitem; + return retval; +} + +static int +fill_dbmode_into_dbinfo_list (T_HA_SERVER_INFO_ALL **all_info, + char *_dbmt_error) +{ + int i; + T_HA_DBSERVER_INFO *dbserver_info_t = NULL; + T_DB_MODE_INFO *dbmode_info_p = NULL; + + for (i = 0; i < (*all_info)->num_dbinfo; i++) + { + dbmode_info_p = (T_DB_MODE_INFO *) MALLOC (sizeof (T_DB_MODE_INFO)); + dbserver_info_t = & (*all_info)->db_info[i]; + + if (dbmode_info_p == NULL) + { + return ERR_MEM_ALLOC; + } + + cmd_get_db_mode (dbmode_info_p, dbserver_info_t->dbname, _dbmt_error); + dbserver_info_t->dbmode_info = dbmode_info_p; + } + + return ERR_NO_ERROR; +} + +/* + * get port info from brokers config, that located by + */ +static const char * +_op_get_port_from_config (T_CM_BROKER_CONF *uc_conf, char *broker_name) +{ + int pos; + char *name; + for (pos = 0; pos < uc_conf->num_broker; pos++) + { + name = cm_br_conf_get_value (& (uc_conf->br_conf[pos]), "%"); + if (name != NULL && strcasecmp (broker_name, name) == 0) + { + return cm_br_conf_get_value (& (uc_conf->br_conf[pos]), + "BROKER_PORT"); + } + } + + /* not found. in this case returns zero value, it is means unknown port. */ + return "0"; +} + +/* Read dbmt password file and append user information to nvplist */ +static void +_tsAppendDBMTUserList (nvplist *res, T_DBMT_USER *dbmt_user, + int return_dbmt_pwd, char *_dbmt_error) +{ + const char *unicas_auth, *dbcreate = NULL; + int i, j; + + nv_add_nvp (res, "open", "userlist"); + for (i = 0; i < dbmt_user->num_dbmt_user; i++) + { + if (dbmt_user->user_info[i].user_name[0] == '\0') + { + continue; + } + nv_add_nvp (res, "open", "user"); + nv_add_nvp (res, ENCRYPT_ARG ("id"), dbmt_user->user_info[i].user_name); + if (return_dbmt_pwd) + { + char decrypted[PASSWD_LENGTH + 1]; + + uDecrypt (PASSWD_LENGTH, dbmt_user->user_info[i].user_passwd, + decrypted); + nv_add_nvp (res, ENCRYPT_ARG ("passwd"), decrypted); + } + + nv_add_nvp (res, "open", "dbauth"); + unicas_auth = NULL; + /* add dbinfo */ + for (j = 0; j < dbmt_user->user_info[i].num_dbinfo; j++) + { + if (dbmt_user->user_info[i].dbinfo[j].dbname[0] == '\0') + { + continue; + } +#ifdef JSON_SUPPORT + nv_add_nvp (res, "open", "auth_info"); +#endif + nv_add_nvp (res, "dbname", + dbmt_user->user_info[i].dbinfo[j].dbname); + nv_add_nvp (res, ENCRYPT_ARG ("dbid"), + dbmt_user->user_info[i].dbinfo[j].uid); + nv_add_nvp (res, "dbbrokeraddress", + dbmt_user->user_info[i].dbinfo[j].broker_address); +#ifdef JSON_SUPPORT + nv_add_nvp (res, "close", "auth_info"); +#endif + } + nv_add_nvp (res, "close", "dbauth"); + + /* add auth info */ + for (j = 0; j < dbmt_user->user_info[i].num_authinfo; j++) + { + if (dbmt_user->user_info[i].authinfo[j].domain[0] == '\0') + { + continue; + } + if (strcmp (dbmt_user->user_info[i].authinfo[j].domain, "unicas") == 0) + { + unicas_auth = dbmt_user->user_info[i].authinfo[j].auth; + nv_add_nvp (res, "casauth", + dbmt_user->user_info[i].authinfo[j].auth); + continue; + } + else if (strcmp + (dbmt_user->user_info[i].authinfo[j].domain, "dbcreate") == 0) + { + dbcreate = dbmt_user->user_info[i].authinfo[j].auth; + nv_add_nvp (res, "dbcreate", + dbmt_user->user_info[i].authinfo[j].auth); + continue; + } + else if (strcmp (dbmt_user->user_info[i].authinfo[j].domain, + "statusmonitorauth") == 0) + { + nv_add_nvp (res, "statusmonitorauth", + dbmt_user->user_info[i].authinfo[j].auth); + continue; + } + } + if (unicas_auth == NULL) + { + nv_add_nvp (res, "casauth", "none"); + } + + if (dbcreate == NULL) + { + nv_add_nvp (res, "dbcreate", "none"); + } + nv_add_nvp (res, "close", "user"); + } + nv_add_nvp (res, "close", "userlist"); +} + +static char * +get_user_name (int uid, char *name_buf) +{ +#if defined(WINDOWS) + strcpy (name_buf, ""); +#else + struct passwd *pwd; + + pwd = getpwuid (uid); + if (pwd->pw_name) + { + strcpy (name_buf, pwd->pw_name); + } + else + { + name_buf[0] = '\0'; + } +#endif + + return name_buf; +} + +static int +uca_conf_write (T_CM_BROKER_CONF *uc_conf, char *del_broker, + char *_dbmt_error) +{ + char buf[512]; + FILE *fp; + int i, j; + struct stat statbuf; + + for (i = 0; i < uc_conf->num_header; i++) + { + if (uc_conf->header_conf[i].name == NULL || + uc_conf->header_conf[i].value == NULL) + { + return ERR_MEM_ALLOC; + } + } + for (i = 0; i < uc_conf->num_broker; i++) + { + for (j = 0; j < uc_conf->br_conf[i].num; j++) + { + if (uc_conf->br_conf[i].item[j].name == NULL || + uc_conf->br_conf[i].item[j].value == NULL) + { + return ERR_MEM_ALLOC; + } + } + } + + cm_get_broker_file (UC_FID_ARNIADB_BROKER_CONF, buf); + + if (stat (buf, &statbuf) < 0) + { + cm_get_broker_file (UC_FID_ARNIADB_CAS_CONF, buf); + if (stat (buf, &statbuf) < 0) + { + cm_get_broker_file (UC_FID_UNICAS_CONF, buf); + if (stat (buf, &statbuf) < 0) + { + cm_get_broker_file (UC_FID_ARNIADB_BROKER_CONF, buf); + } + } + } + + if ((fp = fopen (buf, "w")) == NULL) + { + strcpy (_dbmt_error, buf); + return ERR_FILE_OPEN_FAIL; + } + fprintf (fp, "[broker]\n"); + for (i = 0; i < uc_conf->num_header; i++) + { + fprintf (fp, "%-25s =%s\n", + uc_conf->header_conf[i].name, uc_conf->header_conf[i].value); + } + fprintf (fp, "\n"); + for (i = 0; i < uc_conf->num_broker; i++) + { + if ((del_broker != NULL) && + (strcmp (uc_conf->br_conf[i].item[0].value, del_broker) == 0)) + { + continue; + } + fprintf (fp, "[%s%s]\n", uc_conf->br_conf[i].item[0].name, + to_upper_str (uc_conf->br_conf[i].item[0].value, buf)); + for (j = 1; j < uc_conf->br_conf[i].num; j++) + { + if (uc_conf->br_conf[i].item[j].value[0] == '\0') + { + continue; + } + fprintf (fp, "%-25s =%s\n", uc_conf->br_conf[i].item[j].name, + uc_conf->br_conf[i].item[j].value); + } + fprintf (fp, "\n"); + } + fclose (fp); + return ERR_NO_ERROR; +} + +static int +_tsParseSpacedb (nvplist *req, nvplist *res, char *dbname, + char *_dbmt_error, GeneralSpacedbResult *cmd_res) +{ + int pagesize, logpagesize; + char dbdir[PATH_MAX]; +#if defined(WINDOWS) + WIN32_FIND_DATA data; + char find_file[PATH_MAX]; + HANDLE handle; + int found; +#else + DIR *dirp = NULL; + struct dirent *dp = NULL; +#endif + + cmd_res->create_result (res); + pagesize = cmd_res->get_page_size(); + logpagesize = cmd_res->get_log_page_size(); + + + if (uRetrieveDBLogDirectory (dbname, dbdir) != ERR_NO_ERROR) + { + strcpy (_dbmt_error, dbname); + return ERR_DBDIRNAME_NULL; + } + + /* read entries in the directory and generate result */ +#if defined(WINDOWS) + snprintf (find_file, PATH_MAX - 1, "%s/*", dbdir); + if ((handle = FindFirstFile (find_file, &data)) == INVALID_HANDLE_VALUE) +#else + if ((dirp = opendir (dbdir)) == NULL) +#endif + { + sprintf (_dbmt_error, "%s", dbdir); + return ERR_DIROPENFAIL; + } + +#if defined(WINDOWS) + for (found = 1; found; found = FindNextFile (handle, &data)) +#else + while ((dp = readdir (dirp)) != NULL) +#endif + { + int baselen; + char *fname; + +#if defined(WINDOWS) + fname = data.cFileName; +#else + fname = dp->d_name; +#endif + baselen = (int) strlen (dbname); + + if (strncmp (fname, dbname, baselen) == 0) + { + if (!strcmp (fname + baselen, ARNIADB_ACT_LOG_EXT)) + { + _ts_gen_spaceinfo (res, fname, dbdir, "Active_log", + logpagesize); + } + else if (!strncmp (fname + baselen, ARNIADB_ARC_LOG_EXT, + ARNIADB_ARC_LOG_EXT_LEN)) + { + _ts_gen_spaceinfo (res, fname, dbdir, "Archive_log", + logpagesize); + } +#if 0 + else if (strncmp (fname + baselen, "_lginf", 6) == 0) + { + _ts_gen_spaceinfo (res, fname, dbdir, "Generic_log", + logpagesize); + } +#endif + + } + } +#if defined(WINDOWS) + FindClose (handle); +#else + closedir (dirp); +#endif + + if (uRetrieveDBDirectory (dbname, dbdir) == ERR_NO_ERROR) + { + nv_add_nvp_int (res, "freespace", ut_disk_free_space (dbdir)); + } + else + { + nv_add_nvp_int (res, "freespace", -1); + } + + return ERR_NO_ERROR; +} + +static void +_ts_gen_spaceinfo (nvplist *res, const char *filename, + const char *dbinstalldir, const char *type, int pagesize) +{ + char volfile[PATH_MAX]; + struct stat statbuf; + + nv_add_nvp (res, "open", "spaceinfo"); + nv_add_nvp (res, "spacename", filename); + nv_add_nvp (res, "type", type); + nv_add_nvp (res, "location", dbinstalldir); + + snprintf (volfile, PATH_MAX - 1, "%s/%s", dbinstalldir, filename); + stat (volfile, &statbuf); + + nv_add_nvp_int (res, "totalpage", + pagesize ? statbuf.st_size / pagesize : 0); + nv_add_nvp (res, "freepage", " "); + + ts_add_nvp_time (res, "date", statbuf.st_mtime, "%04d%02d%02d", NV_ADD_DATE); + + nv_add_nvp (res, "close", "spaceinfo"); + return; +} + +static int +_ts_lockdb_parse_us (nvplist *res, FILE *infile) +{ + char buf[1024], s[256], s1[256], s2[256], s3[256], s4[256]; + char *temp, *temp2; + int scan_matched; + int flag = 0; + int flag_lot_tag = 0; + int has_index_name = 0; + + nv_add_nvp (res, "open", "lockinfo"); + while (fgets (buf, sizeof (buf), infile)) + { + sscanf (buf, "%255s", s); + + if (flag == 0 && !strcmp (s, "***")) + { + fgets (buf, sizeof (buf), infile); + scan_matched = + sscanf (buf, "%*s %*s %*s %*s %255s %*s %*s %*s %*s %255s", s1, s2); + + if (scan_matched != 2) + { + return -1; + } + if (strlen (s1) > 0) + { + s1[strlen (s1) - 1] = '\0'; + } + nv_add_nvp (res, "esc", s1); + nv_add_nvp (res, "dinterval", s2); + flag = 1; + } + else if (flag == 1) + { + if (strcmp (s, "Transaction") == 0) + { + scan_matched = + sscanf (buf, "%*s %*s %255s %255s %255s", s1, s2, s3); + + if (scan_matched != 3) + { + return -1; + } + + s1[strlen (s1) - 1] = '\0'; + s2[strlen (s2) - 1] = '\0'; + s3[strlen (s3) - 1] = '\0'; + + nv_add_nvp (res, "open", "transaction"); + nv_add_nvp (res, "index", s1); + nv_add_nvp (res, "pname", s2); + + temp = strchr (s3, '@'); + if (temp != NULL) + { + strncpy (buf, s3, (int) (temp - s3)); + buf[ (int) (temp - s3)] = '\0'; + nv_add_nvp (res, ENCRYPT_ARG ("uid"), buf); + } + + temp2 = strrchr (s3, '|'); + if (temp2 != NULL) + { + strncpy (buf, temp + 1, (int) (temp2 - temp - 1)); + buf[ (int) (temp2 - temp) - 1] = '\0'; + nv_add_nvp (res, "host", buf); + + nv_add_nvp (res, "pid", temp2 + 1); /* moved from below to avoid seg. fault */ + } + + fgets (buf, sizeof (buf), infile); + buf[strlen (buf) - 1] = '\0'; + nv_add_nvp (res, "isolevel", buf + strlen ("Isolation ")); + + fgets (buf, sizeof (buf), infile); + if (strncmp (buf, "State", strlen ("State")) == 0) + { + fgets (buf, sizeof (buf), infile); + } + + scan_matched = sscanf (buf, "%*s %255s", s1); + + if (scan_matched != 1) + { + return -1; + } + nv_add_nvp (res, "timeout", s1); + nv_add_nvp (res, "close", "transaction"); + } + else if (strcmp (s, "Object") == 0) + { + fgets (buf, sizeof (buf), infile); + scan_matched = + sscanf (buf, "%*s %*s %*s %*s %*s %*s %*s %*s %255s", s1); + if (scan_matched != 1) + { + return -1; + } + nv_add_nvp (res, "open", "lot"); + flag_lot_tag = 1; + nv_add_nvp (res, "numlocked", s1); + + fgets (buf, sizeof (buf), infile); + scan_matched = + sscanf (buf, "%*s %*s %*s %*s %*s %*s %*s %*s %*s %255s", s2); + if (scan_matched != 1) + { + return -1; + } + nv_add_nvp (res, "maxnumlock", s2); + flag = 2; + } + } /* end of if (flag == 1) */ + else if (flag == 2) + { + char value[1024]; + + while (!strcmp (s, "OID")) + { + int num_holders, num_b_holders, num_waiters, scan_matched; + + scan_matched = + sscanf (buf, "%*s %*s %[^|] %*[|] %[^|] %*[|] %255s", s1, s2, s3); + if (scan_matched != 3) + { + return -1; + } + + snprintf (value, sizeof (value) - 1, "%s|%s|%s", s1, s2, s3); + + nv_add_nvp (res, "open", "entry"); + nv_add_nvp (res, "oid", value); + + fgets (buf, sizeof (buf), infile); + sscanf (buf, "%*s %*s %255s", s); + + s1[0] = s2[0] = s3[0] = '\0'; + scan_matched = 0; + if ((strcmp (s, "Class") == 0) || (strcmp (s, "Instance") == 0) + || (strcmp (s, "Index") == 0)) + { + char *p; + p = strchr (buf, ':'); + if (strlen (buf) > 1) + { + buf[strlen (buf) - 1] = '\0'; + if (buf[strlen (buf) - 1] == '.') + { + buf[strlen (buf) - 1] = '\0'; + } + } + nv_add_nvp (res, "ob_type", p + 2); + if (strcmp (s, "Index") == 0) + { + has_index_name = 1; + } + fgets (buf, sizeof (buf), infile); + } + else if (strcmp (s, "Root") == 0) + { + nv_add_nvp (res, "ob_type", "Root class"); + fgets (buf, sizeof (buf), infile); + } + else + { + /* Current test is not 'OID = ...' and if 'Total mode of holders ...' then */ + if (has_index_name == 1) + { + fgets (buf, sizeof (buf), infile); + } + scan_matched = + sscanf (buf, + "%*s %*s %255s %*s %*s %255s %*s %*s %255s", s1, s2, s3); + if ((strncmp (s1, "of", 2) == 0) + && (strncmp (s3, "of", 2) == 0)) + { + nv_add_nvp (res, "ob_type", "None"); + } + else + { + return -1; + } + } + + if (has_index_name == 1) + { + fgets (buf, sizeof (buf), infile); + } + /* already get scan_matched value, don't sscanf */ + if (scan_matched == 0) + scan_matched = + sscanf (buf, "%*s %*s %255s %*s %*s %255s %*s %*s %255s", s1, s2, s3); + + if ((strncmp (s1, "of", 2) == 0) + && (strncmp (s3, "of", 2) == 0)) + { + /* ignore UnixWare's 'Total mode of ...' text */ + fgets (buf, sizeof (buf), infile); + scan_matched = + sscanf (buf, "%*s %*s %255s %*s %*s %255s %*s %*s %255s", s1, s2, s3); + } + + if (scan_matched != 3) + { + return -1; + } + s1[strlen (s1) - 1] = '\0'; + s2[strlen (s2) - 1] = '\0'; + + num_holders = atoi (s1); + num_b_holders = atoi (s2); + num_waiters = atoi (s3); + + if (num_waiters < 0 || num_waiters >= INT_MAX) + { + return -1; + } + + nv_add_nvp (res, "num_holders", s1); + nv_add_nvp (res, "num_b_holders", s2); + nv_add_nvp (res, "num_waiters", s3); + + while (fgets (buf, sizeof (buf), infile)) + { + sscanf (buf, "%255s", s); + if (strcmp (s, "NON_2PL_RELEASED:") == 0) + { + fgets (buf, sizeof (buf), infile); + while (sscanf (buf, "%255s", s)) + { + if (strcmp (s, "Tran_index") != 0) + { + break; + } + else + { + if (fgets (buf, sizeof (buf), infile) == NULL) + { + break; + } + } + } + break; + } /* ignore NON_2PL_RELEASED information */ + + sscanf (buf, "%*s %255s", s); + if (strcmp (s, "HOLDERS:") == 0) + { + int index; + + for (index = 0; index < num_holders; index++) + { + /* make lock holders information */ + + fgets (buf, sizeof (buf), infile); + scan_matched = + sscanf (buf, + "%*s %*s %255s %*s %*s %255s %*s %*s %255s %*s %*s %255s", + s1, s2, s3, s4); + + /* parshing error */ + if (scan_matched < 3) + { + return -1; + } + if (scan_matched == 4) + { + /* nsubgranules is existed */ + s3[strlen (s3) - 1] = '\0'; + } + + s1[strlen (s1) - 1] = '\0'; + s2[strlen (s2) - 1] = '\0'; + + nv_add_nvp (res, "open", "lock_holders"); + nv_add_nvp (res, "tran_index", s1); + nv_add_nvp (res, "granted_mode", s2); + nv_add_nvp (res, "count", s3); + if (scan_matched == 4) + { + nv_add_nvp (res, "nsubgranules", s4); + } + nv_add_nvp (res, "close", "lock_holders"); + } + + if ((num_b_holders == 0) && (num_waiters == 0)) + { + break; + } + } + else if (strcmp (s, "LOCK") == 0) + { + int index; + char *p; + + for (index = 0; index < num_b_holders; index++) + { + /* make blocked lock holders */ + int scan_matched; + fgets (buf, sizeof (buf), infile); + scan_matched = + sscanf (buf, + "%*s %*s %255s %*s %*s %255s %*s %*s %255s %*s %*s %255s", + s1, s2, s3, s4); + + /* parshing error */ + if (scan_matched < 3) + { + return -1; + } + if (scan_matched == 4) + { + /* nsubgranules is existed */ + s3[strlen (s3) - 1] = '\0'; + } + + s1[strlen (s1) - 1] = '\0'; + s2[strlen (s2) - 1] = '\0'; + + nv_add_nvp (res, "open", "b_holders"); + nv_add_nvp (res, "tran_index", s1); + nv_add_nvp (res, "granted_mode", s2); + nv_add_nvp (res, "count", s3); + + if (scan_matched == 4) + { + nv_add_nvp (res, "nsubgranules", s4); + } + fgets (buf, sizeof (buf), infile); + sscanf (buf, "%*s %*s %255s", s1); + nv_add_nvp (res, "b_mode", s1); + + fgets (buf, sizeof (buf), infile); + p = strchr (buf, '='); + buf[strlen (buf) - 1] = '\0'; + nv_add_nvp (res, "start_at", p + 2); + + fgets (buf, sizeof (buf), infile); + sscanf (buf, "%*s %*s %255s", s1); + nv_add_nvp (res, "waitfornsec", s1); + + nv_add_nvp (res, "close", "b_holders"); + } + + if (num_waiters == 0) + { + break; + } + } + else if (strcmp (s, "WAITERS:") == 0) + { + int index; + + for (index = 0; index < num_waiters; index++) + { + /* make lock waiters */ + char *p; + + fgets (buf, sizeof (buf), infile); + sscanf (buf, "%*s %*s %255s %*s %*s %255s", s1, s2); + s1[strlen (s1) - 1] = '\0'; + + nv_add_nvp (res, "open", "waiters"); + nv_add_nvp (res, "tran_index", s1); + nv_add_nvp (res, "b_mode", s2); + + fgets (buf, sizeof (buf), infile); + p = strchr (buf, '='); + buf[strlen (buf) - 1] = '\0'; + nv_add_nvp (res, "start_at", p + 2); + + fgets (buf, sizeof (buf), infile); + sscanf (buf, "%*s %*s %255s", s1); + nv_add_nvp (res, "waitfornsec", s1); + + nv_add_nvp (res, "close", "waiters"); + } + break; + } + } /* end of while - for just one object */ + nv_add_nvp (res, "close", "entry"); + } /* end of while(OID) */ + } + } + if (flag_lot_tag != 0) + { + nv_add_nvp (res, "close", "lot"); + } + nv_add_nvp (res, "close", "lockinfo"); + return 0; +} + +static char * +to_lower_str (char *str, char *buf) +{ + char *p; + + strcpy (buf, str); + for (p = buf; *p; p++) + { + if (*p >= 'A' && *p <= 'Z') + { + *p = *p - 'A' + 'a'; + } + } + return buf; +} + +static char * +to_upper_str (char *str, char *buf) +{ + char *p; + + strcpy (buf, str); + for (p = buf; *p; p++) + { + if (*p >= 'a' && *p <= 'z') + { + *p = *p - 'a' + 'A'; + } + } + return buf; +} + +static int +op_make_triggerinput_file_add (nvplist *req, char *input_filename) +{ + char *name, *status, *cond_source, *priority; + char *event_target, *event_type, *event_time, *actiontime, *action; + FILE *input_file; + + if (input_filename == NULL) + { + return 0; + } + + input_file = fopen (input_filename, "w+"); + if (input_file == NULL) + { + return 0; + } + + name = nv_get_val (req, "triggername"); + status = nv_get_val (req, "status"); + event_type = nv_get_val (req, "eventtype"); + event_target = nv_get_val (req, "eventtarget"); + event_time = nv_get_val (req, "conditiontime"); + cond_source = nv_get_val (req, "condition"); + actiontime = nv_get_val (req, "actiontime"); + action = nv_get_val (req, "action"); + priority = nv_get_val (req, "priority"); + /* fprintf(input_file, ";autocommit off\n"); */ + fprintf (input_file, "create trigger\t%s\n", name); + + if (status) + { + fprintf (input_file, "status\t%s\n", status); + } + if (priority) + { + fprintf (input_file, "priority\t%s\n", priority); + } + fprintf (input_file, "%s\t%s\t", event_time, event_type); + + if (event_target) + { + fprintf (input_file, "ON\t%s\n", event_target); + } + if (cond_source) + { + fprintf (input_file, "if\t%s\n", cond_source); + } + fprintf (input_file, "execute\t"); + + if (actiontime) + { + fprintf (input_file, "%s\t", actiontime); + } + fprintf (input_file, "%s\n", action); + fprintf (input_file, "\n\ncommit;\n\n"); + + fclose (input_file); + + return 1; +} + +static int +op_make_triggerinput_file_drop (nvplist *req, char *input_filename) +{ + char *trigger_name; + FILE *input_file; + + if (input_filename == NULL) + { + return 0; + } + + input_file = fopen (input_filename, "w+"); + if (input_file == NULL) + { + return 0; + } + + trigger_name = nv_get_val (req, "triggername"); + /* fprintf(input_file, ";autocommit off\n"); */ + fprintf (input_file, "drop trigger\t%s\n", trigger_name); + fprintf (input_file, "\n\n\ncommit;\n\n"); + + fclose (input_file); + + return 1; +} + +static int +op_make_triggerinput_file_alter (nvplist *req, char *input_filename) +{ + char *trigger_name, *status, *priority; + FILE *input_file; + + if (input_filename == NULL) + { + return 0; + } + + input_file = fopen (input_filename, "w+"); + if (input_file == NULL) + { + return 0; + } + + trigger_name = nv_get_val (req, "triggername"); + status = nv_get_val (req, "status"); + priority = nv_get_val (req, "priority"); + /* fprintf(input_file, ";autocommit off\n"); */ + if (status) + { + fprintf (input_file, "alter trigger\t%s\t", trigger_name); + fprintf (input_file, "status %s\t", status); + } + + if (priority) + { + fprintf (input_file, "alter trigger\t%s\t", trigger_name); + fprintf (input_file, "priority %s\t", priority); + } + + fprintf (input_file, "\n\n\ncommit;\n\n"); + fclose (input_file); + + return 1; +} + +static int +get_broker_info_from_filename (char *path, char *br_name, int *as_id) +{ +#if defined(WINDOWS) + const char *sql_log_ext = ".sql.log"; + int sql_log_ext_len = (int) strlen (sql_log_ext); + int path_len; + char *p; + + if (path == NULL) + { + return -1; + } + path_len = (int) strlen (path); + if (strncmp (path, sco.szArniadb, strlen (sco.szArniadb)) != 0 || + path_len <= sql_log_ext_len || + strcmp (path + (path_len - sql_log_ext_len), sql_log_ext) != 0) + { + return -1; + } + + for (p = path + path_len - 1; p >= path; p--) + { + if (*p == '/' || *p == '\\') + { + break; + } + } + path = p + 1; + path_len = (int) strlen (path); + + * (path + path_len - sql_log_ext_len) = '\0'; + p = strrchr (path, '_'); + + *as_id = atoi (p + 1); + if (*as_id <= 0) + { + return -1; + } + strncpy (br_name, path, p - path); + * (br_name + (p - path)) = '\0'; + + return 0; +#else + return -1; +#endif +} + +/* + * check if dir path contains white space character, + * and if path contains '\', substitute it with '/' + */ +static int +check_dbpath (char *dir, char *_dbmt_error) +{ + if (dir == NULL || *dir == '\0') + { + strcpy (_dbmt_error, "Path is NULL!"); + return ERR_WITH_MSG; + } + + while (*dir != '\0') + { + if (isspace (*dir)) + { + strcpy (_dbmt_error, "Path contains white space!"); + return ERR_WITH_MSG; + } + else if (*dir == '\\') + { + *dir = '/'; + } + dir++; + } + + return ERR_NO_ERROR; +} + +static int +get_dbitemdir (char *item_dir, size_t item_dir_size, char *dbname, + char *err_buf, int itemtype) +{ + FILE *databases_txt; + char *envpath; + char db_txt[PATH_MAX]; + char cbuf[2048]; + char itemname[1024]; + char scan_format[128]; + char pattern[64]; + const char *patternVol = "%%%lus %%%lus %%*s %%*s"; + const char *patternLog = "%%%lus %%*s %%*s %%%lus"; + + if (item_dir == NULL || dbname == NULL) + { + return -1; + } +#if !defined (DO_NOT_USE_ARNIADBENV) + envpath = sco.szArniadb_databases; +#else + envpath = ARNIADB_VARDIR; +#endif + if ((envpath == NULL) || (strlen (envpath) == 0)) + { + return -1; + } + snprintf (db_txt, sizeof (db_txt) - 1, "%s/%s", envpath, + ARNIADB_DATABASE_TXT); + databases_txt = fopen (db_txt, "r"); + + /*set the patten to get dir from databases.txt. */ + if (databases_txt == NULL) + { + return -1; + } + + if (itemtype == PATTERN_VOL) + { + strcpy_limit (pattern, patternVol, sizeof (pattern)); + } + else if (itemtype == PATTERN_LOG) + { + strcpy_limit (pattern, patternLog, sizeof (pattern)); + } + else + { + fclose (databases_txt); + return -1; + } + + snprintf (scan_format, sizeof (scan_format) - 1, pattern, + (unsigned long) sizeof (itemname) - 1, + (unsigned long) item_dir_size - 1); + + while (fgets (cbuf, sizeof (cbuf), databases_txt) != NULL) + { + if (sscanf (cbuf, scan_format, itemname, item_dir) < 2) + { + continue; + } + if (strcmp (itemname, dbname) == 0) + { + fclose (databases_txt); + return 1; + } + } + + fclose (databases_txt); + return 1; +} + +static int +get_dblogdir (char *log_dir, size_t log_dir_size, char *dbname, char *err_buf) +{ + int retVal = + get_dbitemdir (log_dir, log_dir_size, dbname, err_buf, PATTERN_LOG); + return retVal; +} + +static int +get_dbvoldir (char *vol_dir, size_t vol_dir_size, char *dbname, char *err_buf) +{ + int retVal = + get_dbitemdir (vol_dir, vol_dir_size, dbname, err_buf, PATTERN_VOL); + return retVal; +} + +static char * +cm_get_abs_file_path (const char *filename, char *buf) +{ + strcpy (buf, filename); + + if (buf[0] == '/') + { + return buf; + } +#if defined(WINDOWS) + if (buf[2] == '/' || buf[2] == '\\') + { + return buf; + } +#endif + sprintf (buf, "%s/%s", getenv ("ARNIADB"), filename); + return buf; +} + +static int +file_to_nvpairs (char *filepath, nvplist *res) +{ + FILE *infile; + char buf[1024]; + + /* return error if the input file is NULL. */ + if ((infile = fopen (filepath, "r")) == NULL) + { + return -1; + } + + /* get all file content into response. */ + while (fgets (buf, sizeof (buf), infile)) + { + uRemoveCRLF (buf); + nv_add_nvp (res, "line", buf); + } + + fclose (infile); + return 0; +} + +static int +file_to_nvp_by_separator (FILE *fp, nvplist *res, char separator) +{ + char buf[1024]; + char *p, *q, *next; + int clientexist = 0; + const char *comparestr = "System parameters"; + + while (fgets (buf, sizeof (buf), fp) != NULL) + { + if (strncmp (buf, comparestr, strlen (comparestr)) == 0) + { + /* check if the sentences contains "client" or "server" or "standalone". */ + if (strstr (buf, "client") != NULL) + { + clientexist = 1; + nv_add_nvp (res, "open", "client"); + } + else if (strstr (buf, "server") != NULL) + { + /* if it is "server" then check if there is need to close "client". */ + if (clientexist != 0) + { + nv_add_nvp (res, "close", "client"); + } + nv_add_nvp (res, "open", "server"); + } + else if (strstr (buf, "standalone") != NULL) + { + /* if it is "standalone" then there should return only server paramdump. */ + nv_add_nvp (res, "open", "server"); + } + else + { + return -1; + } + } + + /* + * ignore the lines that start with "#", empty lines, + * and lines with out separator. + */ + if ('#' == buf[0] || '\n' == buf[0] || strchr (buf, separator) == NULL) + { + continue; + } + p = buf; + next = strchr (p, '\n'); + if (next != NULL) + { + *next = '\0'; + } + q = strchr (p, '='); + if (q != NULL) + { + *q = '\0'; + q++; + } + nv_add_nvp (res, p, q); + } + nv_add_nvp (res, "close", "server"); + return 0; +} + +/* check if autoexecquery.conf version < 8.3.0 */ +static int +obsolete_version_autoexecquery_conf (const char *conf_line) +{ + char conf_item_buf[80]; + + if (conf_line == NULL) + { + return -1; + } + + sscanf (conf_line, "%*s %*s %*s %80s", conf_item_buf); + if (strcmp (conf_item_buf, "ONE") == 0 + || strcmp (conf_item_buf, "DAY") == 0 + || strcmp (conf_item_buf, "WEEK") == 0 + || strcmp (conf_item_buf, "MONTH") == 0) + { + return 1; + } + else + { + return 0; + } +} + +static int +alter_dblocation (const char *dbname, const char *new_dbpath) +{ + int retval = ERR_NO_ERROR; + FILE *dblocation_info, *tmpfile; + char dblocation_info_path[PATH_MAX]; + char tmpfile_path[PATH_MAX]; + char *strbuf; + int buf_len, get_len; + int db_existant = 0; + char *tok[4]; + + snprintf (dblocation_info_path, PATH_MAX - 1, "%s/%s", + sco.szArniadb_databases, ARNIADB_DATABASE_TXT); + snprintf (tmpfile_path, PATH_MAX - 1, "%s/DBMT_util_dblocation.%d", + sco.dbmt_tmp_dir, (int) getpid ()); + + dblocation_info = fopen (dblocation_info_path, "r"); + tmpfile = fopen (tmpfile_path, "w"); + if (dblocation_info == NULL || tmpfile == NULL) + { + if (dblocation_info != NULL) + { + fclose (dblocation_info); + } + if (tmpfile != NULL) + { + fclose (tmpfile); + } + retval = ERR_FILE_OPEN_FAIL; + } + else + { + strbuf = NULL; + buf_len = get_len = 0; + while ((get_len = + ut_getline (&strbuf, &buf_len, dblocation_info)) != -1) + { + ut_trim (strbuf); + if (strbuf[0] == '#') + { + fprintf (tmpfile, "%s\n", strbuf); + continue; + } + + string_tokenize (strbuf, tok, 4); + if (uStringEqual (dbname, tok[0])) + { + db_existant = 1; + fprintf (tmpfile, "%s\t\t%s\t%s\t%s\n", tok[0], new_dbpath, + tok[2], new_dbpath); + } + else + { + fprintf (tmpfile, "%s\t\t%s\t%s\t%s\n", tok[0], tok[1], + tok[2], tok[3]); + } + FREE_MEM (strbuf); + buf_len = 0; + } + + if (strbuf != NULL) + { + FREE_MEM (strbuf); + } + + fclose (dblocation_info); + fclose (tmpfile); + + move_file (tmpfile_path, dblocation_info_path); + } + + if (!db_existant) + { + retval = ERR_DB_NONEXISTANT; + } + + return retval; +} + +static int +_get_folders_with_keyword (char *search_folder_path, const char *keyword, + nvplist *res, char *_dbmt_error) +{ +#if defined(WINDOWS) + WIN32_FIND_DATA data; + char find_file[512]; + HANDLE handle; + int found; + + sprintf (find_file, "%s/%s", search_folder_path, keyword); + handle = FindFirstFile (find_file, &data); + if (handle == INVALID_HANDLE_VALUE) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE - 1, + "Folder with keyword: %s does not exist.", keyword); + return ERR_WITH_MSG; + } + + nv_add_nvp (res, "open", "folders"); + for (found = 1; found; found = FindNextFile (handle, &data)) + { + if (strcmp (data.cFileName, ".") == 0 + || strcmp (data.cFileName, "..") == 0) + { + continue; + } + + if (data.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY) + { + nv_add_nvp (res, "foldername", data.cFileName); + } + } /* end of while and for */ + nv_add_nvp (res, "close", "folders"); + + FindClose (handle); +#else + struct dirent *dirp; + struct stat statbuf; + DIR *dp; + + dp = opendir (search_folder_path); + if (dp == NULL) + { + strcpy_limit (_dbmt_error, "Could not open the search folder.", + DBMT_ERROR_MSG_SIZE); + return ERR_WITH_MSG; + } + + nv_add_nvp (res, "open", "folders"); + while ((dirp = readdir (dp)) != NULL) + { + char dir[PATH_MAX] = { 0 }; + + snprintf (dir, sizeof (dir) - 1, "%s/%s", search_folder_path, + dirp->d_name); + stat (dir, &statbuf); + + if (strcmp (dirp->d_name, ".") == 0 || strcmp (dirp->d_name, "..") == 0) + { + continue; + } + + if (S_ISDIR (statbuf.st_mode) && + (fnmatch (keyword, dirp->d_name, 0) == 0)) + { + nv_add_nvp (res, "foldername", dirp->d_name); + } + } /* end of while and for */ + nv_add_nvp (res, "close", "folders"); + + closedir (dp); +#endif + + return ERR_NO_ERROR; +} + +static int +_update_nvplist_name (nvplist *ref, const char *name, const char *value) +{ + int i; + char *name_buf; + nvpair *nvp; + + if ((ref == NULL) || (name == NULL) || (value == NULL)) + { + return -1; + } + + for (i = 0; i < ref->nvplist_leng; i++) + { + if ((nvp = ref->nvpairs[i]) == NULL) + { + return -1; + } + + name_buf = dst_buffer (nvp->name); + if (uStringEqual (name_buf, name)) + { + dst_reset (nvp->name); + dst_append (nvp->name, value, (int) strlen (value)); + } + } + + return 0; +} + +static int +read_shard_info_output (nvplist *res, char *stdout_file, char *stderr_file, + char *_dbmt_error) +{ + int num_shard = 0, rtn = ERR_NO_ERROR; + int len = 0; + char str_buf[512]; + char scan_buf[21][64]; + char *num[2] = { NULL, NULL }; + FILE *fp; + + if (access (stderr_file, F_OK) == 0) + { + fp = fopen (stderr_file, "r"); + if (fp != NULL) + { + while (fgets (str_buf, sizeof (str_buf), fp) != NULL) + { + ut_trim (str_buf); + if (strncmp (str_buf, "++", 2) == 0) + { + continue; + } + len += (int) strlen (str_buf); + if (len < (DBMT_ERROR_MSG_SIZE - 1)) + { + strcpy (_dbmt_error, str_buf); + _dbmt_error += len; + } + else + { + strcpy_limit (_dbmt_error, str_buf, DBMT_ERROR_MSG_SIZE); + strcpy_limit (_dbmt_error + DBMT_ERROR_MSG_SIZE - 4, "...", 4); + break; + } + } + fclose (fp); + if (len != 0) + { + return ERR_WITH_MSG; + } + } + } + + + fp = fopen (stdout_file, "r"); + if (fp == NULL) + { + strcpy (_dbmt_error, stdout_file); + return ERR_FILE_OPEN_FAIL; + } + + while (fgets (str_buf, sizeof (str_buf), fp)) + { + if (strstr (str_buf, "++") != NULL) + { + strcpy (_dbmt_error, str_buf); + rtn = ERR_WITH_MSG; + break; + } + + if (strstr (str_buf, "*") == NULL) + { + continue; + } + + /* * NAME PID PSIZE PORT Active-P Active-C REQ TPS QPS K-QPS (H-KEY H-ID H-ALL) NK-QPS LONG-T LONG-Q ERR-Q CANCELED ACCESS_MODE SQL_LOG */ + if (sscanf (str_buf, + "%63s %63s %63s %63s %63s %63s %63s %63s %63s %63s %63s %63s %63s %63s %63s %63s %63s %63s %63s %63s %63s ", + scan_buf[0], scan_buf[1], scan_buf[2], scan_buf[3], + scan_buf[4], scan_buf[5], scan_buf[6], scan_buf[7], + scan_buf[8], scan_buf[9], scan_buf[10], scan_buf[11], + scan_buf[12], scan_buf[13], scan_buf[14], scan_buf[15], + scan_buf[16], scan_buf[17], scan_buf[18], scan_buf[19], + scan_buf[20]) < 21) + { + continue; + } + + num_shard++; + nv_add_nvp (res, "open", "shard"); + nv_add_nvp (res, "name", scan_buf[1]); + nv_add_nvp (res, "pid", scan_buf[2]); + nv_add_nvp (res, "psize", scan_buf[3]); + nv_add_nvp (res, "port", scan_buf[4]); + nv_add_nvp (res, "active-p", scan_buf[5]); + nv_add_nvp (res, "active-c", scan_buf[6]); + nv_add_nvp (res, "req", scan_buf[7]); + + nv_add_nvp (res, "tps", scan_buf[8]); + nv_add_nvp (res, "qps", scan_buf[9]); + nv_add_nvp (res, "k-qps", scan_buf[10]); + nv_add_nvp (res, "h-key", scan_buf[11]); + nv_add_nvp (res, "h-id", scan_buf[12]); + nv_add_nvp (res, "h-all", scan_buf[13]); + nv_add_nvp (res, "nk-qps", scan_buf[14]); + + string_tokenize2 (scan_buf[15], num, 2, '/'); + nv_add_nvp (res, "long_tran", num[0]); + nv_add_nvp (res, "long_tran_time", num[1]); + + string_tokenize2 (scan_buf[16], num, 2, '/'); + nv_add_nvp (res, "long_query", num[0]); + nv_add_nvp (res, "long_query_time", num[1]); + + nv_add_nvp (res, "error_query", scan_buf[17]); + nv_add_nvp (res, "canceled", scan_buf[18]); + nv_add_nvp (res, "access_mode", scan_buf[19]); + nv_add_nvp (res, "sqll", scan_buf[20]); + nv_add_nvp (res, "state", "ON"); + nv_add_nvp (res, "close", "shard"); + } + fclose (fp); + return rtn; +} + +int +ts_get_shard_info (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char stdout_log_file[512]; + char stderr_log_file[512]; + int pid, argc = 0; + int ret_val; + char cmd_name[ARNIADB_CMD_NAME_LEN]; + const char *argv[6]; + static int reqid = 0; + + /* not thread safe :( */ + reqid++; + sprintf (stdout_log_file, "%s/amshardinfo.%d.err", sco.dbmt_tmp_dir, reqid); + sprintf (stderr_log_file, "%s/amshardinfo2.%d.err", sco.dbmt_tmp_dir, reqid); + + cmd_name[0] = '\0'; +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ARNIADB); +#else + sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_ARNIADB); +#endif + + argv[argc++] = cmd_name; + argv[argc++] = PRINT_CMD_SHARD; + argv[argc++] = PRINT_CMD_STATUS; + argv[argc++] = "-b"; + argv[argc++] = "-f"; + argv[argc++] = NULL; + + pid = run_child (argv, 1, NULL, stdout_log_file, stderr_log_file, NULL); /* start shard */ + + if (pid < 0) + { + if (_dbmt_error) + { + sprintf (_dbmt_error, "system error : %s shard status", cmd_name); + } + unlink (stdout_log_file); + unlink (stderr_log_file); + return ERR_WITH_MSG; + } + + ret_val = + read_shard_info_output (res, stdout_log_file, stderr_log_file, + _dbmt_error); + unlink (stdout_log_file); + unlink (stderr_log_file); + + return ret_val; +} + + +static int +read_shard_status_output (nvplist *res, char *stdout_file, char *stderr_file, + char *_dbmt_error) +{ + int rtn = ERR_NO_ERROR; + int len = 0; + char str_buf[512]; + char scan_buf[8][64]; + FILE *fp; + + if (access (stderr_file, F_OK) == 0) + { + fp = fopen (stderr_file, "r"); + if (fp != NULL) + { + while (fgets (str_buf, sizeof (str_buf), fp) != NULL) + { + ut_trim (str_buf); + if (strncmp (str_buf, "++", 2) == 0) + { + continue; + } + len += (int) strlen (str_buf); + if (len < (DBMT_ERROR_MSG_SIZE - 1)) + { + strcpy (_dbmt_error, str_buf); + _dbmt_error += len; + } + else + { + strcpy_limit (_dbmt_error, str_buf, DBMT_ERROR_MSG_SIZE); + strcpy_limit (_dbmt_error + DBMT_ERROR_MSG_SIZE - 4, "...", 4); + break; + } + } + fclose (fp); + if (len != 0) + { + return ERR_WITH_MSG; + } + } + } + + + fp = fopen (stdout_file, "r"); + if (fp == NULL) + { + strcpy (_dbmt_error, stdout_file); + return ERR_FILE_OPEN_FAIL; + } + + while (fgets (str_buf, sizeof (str_buf), fp)) + { + if (strstr (str_buf, "++") != NULL) + { + strcpy (_dbmt_error, str_buf); + rtn = ERR_WITH_MSG; + break; + } + + if (strstr (str_buf, "PROXY_ID") == NULL) + { + continue; + } + + /*ingore ------------ */ + fgets (str_buf, sizeof (str_buf), fp); + while (fgets (str_buf, sizeof (str_buf), fp)) + { + /* PROXY_ID SHARD_ID CAS_ID PID QPS LQS PSIZE STATUS */ + if (sscanf (str_buf, "%63s %63s %63s %63s %63s %63s %63s %63s", + scan_buf[0], scan_buf[1], scan_buf[2], scan_buf[3], + scan_buf[4], scan_buf[5], scan_buf[6], scan_buf[7]) < 8) + { + continue; + } + + nv_add_nvp (res, "open", "shard"); + nv_add_nvp (res, "proxy_id", scan_buf[0]); + nv_add_nvp (res, "shard_id", scan_buf[1]); + nv_add_nvp (res, "cas_id", scan_buf[2]); + nv_add_nvp (res, "pid", scan_buf[3]); + nv_add_nvp (res, "qps", scan_buf[4]); + nv_add_nvp (res, "lqs", scan_buf[5]); + nv_add_nvp (res, "psize", scan_buf[6]); + nv_add_nvp (res, "status", scan_buf[7]); + nv_add_nvp (res, "close", "shard"); + } + } + fclose (fp); + return rtn; +} + + +int +ts_get_shard_status (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char stdout_log_file[512]; + char stderr_log_file[512]; + int pid, argc = 0; + int ret_val; + char cmd_name[ARNIADB_CMD_NAME_LEN]; + const char *argv[6]; + char *sname; + static int reqid = 0; + + if ((sname = nv_get_val (req, "shardname")) == NULL) + { + strcpy (_dbmt_error, "shard name"); + return ERR_PARAM_MISSING; + } + /* not thread safe :( */ + reqid++; + sprintf (stdout_log_file, "%s/amshardstatus.%d.err", sco.dbmt_tmp_dir, reqid); + sprintf (stderr_log_file, "%s/amshardstatus2.%d.err", sco.dbmt_tmp_dir, reqid); + + cmd_name[0] = '\0'; +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ARNIADB); +#else + sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_ARNIADB); +#endif + + argv[argc++] = cmd_name; + argv[argc++] = PRINT_CMD_SHARD; + argv[argc++] = PRINT_CMD_STATUS; + argv[argc++] = sname; + argv[argc++] = NULL; + + pid = run_child (argv, 1, NULL, stdout_log_file, stderr_log_file, NULL); /* start shard */ + + if (pid < 0) + { + if (_dbmt_error) + { + sprintf (_dbmt_error, "system error : %s shard status %s", cmd_name, sname); + } + unlink (stdout_log_file); + unlink (stderr_log_file); + return ERR_WITH_MSG; + } + + nv_add_nvp (res, "name", sname); + ret_val = + read_shard_status_output (res, stdout_log_file, stderr_log_file, _dbmt_error); + unlink (stdout_log_file); + unlink (stderr_log_file); + + return ret_val; +} + + +static int +read_start_shard_output (char *stdout_file, char *stderr_file, + char *_dbmt_error) +{ + FILE *fp, *fp2; + char buf[1024]; + char *strp; + int retval = 0; + + if (access (stdout_file, F_OK) == 0) + { + fp = fopen (stdout_file, "r"); + if (fp != NULL) + { + while (fgets (buf, sizeof (buf), fp) != NULL) + { + ut_trim (buf); + if (strncmp (buf, "@", 1) == 0) + { + continue; + } + if (strncmp (buf, "++", 2) == 0) + { + if ((strp = strchr (buf, ':')) && strstr (strp, "fail")) + { + retval = -1; + break; + } + } + strcpy (_dbmt_error, buf); + if (strstr (buf, "Cannot")) + { + retval = -1; + break; + } + } + fclose (fp); + } + } + + if (access (stderr_file, F_OK) == 0) + { + fp2 = fopen (stderr_file, "r"); + if (fp2 != NULL) + { + int len = 0; + while (fgets (buf, sizeof (buf), fp2) != NULL) + { + ut_trim (buf); + if (strncmp (buf, "++", 2) == 0 || strncmp (buf, "@", 1) == 0) + { + continue; + } + len += (int) strlen (buf); + if (len < (DBMT_ERROR_MSG_SIZE - 1)) + { + strcpy (_dbmt_error, buf); + _dbmt_error += len; + } + else + { + strcpy_limit (_dbmt_error, buf, DBMT_ERROR_MSG_SIZE); + strcpy_limit (_dbmt_error + DBMT_ERROR_MSG_SIZE - 4, "...", 4); + break; + } + } + + if (len != 0 && retval != -1) + { + retval = 1; + } + fclose (fp2); + } + } + + return retval; +} + + +int +ts_shard_start (nvplist *req, nvplist *res, char *err_buf) +{ + char stdout_log_file[512]; + char stderr_log_file[512]; + int pid, argc = 0; + int ret_val; + char cmd_name[ARNIADB_CMD_NAME_LEN]; + const char *argv[5]; + char *sname = NULL; + + sname = nv_get_val (req, "shardname"); + + sprintf (stdout_log_file, "%s/amshardstart.%d.err", sco.dbmt_tmp_dir, + (int) getpid ()); + sprintf (stderr_log_file, "%s/amshardstart2.%d.err", sco.dbmt_tmp_dir, + (int) getpid ()); + + cmd_name[0] = '\0'; +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ARNIADB); +#else + sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_ARNIADB); +#endif + + argv[argc++] = cmd_name; + argv[argc++] = PRINT_CMD_SHARD; + if (sname == NULL) + { + argv[argc++] = PRINT_CMD_START; + } + else + { + argv[argc++] = PRINT_CMD_ON; + argv[argc++] = sname; + } + + argv[argc++] = NULL; + + pid = run_child (argv, 1, NULL, stdout_log_file, stderr_log_file, NULL); /* start shard */ + + if (pid < 0) + { + if (err_buf) + { + sprintf (err_buf, "system error : %s start shard", cmd_name); + } + unlink (stdout_log_file); + unlink (stderr_log_file); + return ERR_WITH_MSG; + } + + ret_val = + read_start_shard_output (stdout_log_file, stderr_log_file, err_buf); + unlink (stdout_log_file); + unlink (stderr_log_file); + + if (ret_val != 0) + { + return ERR_WITH_MSG; + } + + return ERR_NO_ERROR; +} + + +int +ts_shard_stop (nvplist *req, nvplist *res, char *err_buf) +{ + char stdout_log_file[512]; + char stderr_log_file[512]; + int pid, argc = 0; + int ret_val; + char cmd_name[ARNIADB_CMD_NAME_LEN]; + const char *argv[5]; + char *sname = NULL; + + sname = nv_get_val (req, "shardname"); + + sprintf (stdout_log_file, "%s/amshardstop.%d.err", sco.dbmt_tmp_dir, + (int) getpid ()); + sprintf (stderr_log_file, "%s/amshardstop2.%d.err", sco.dbmt_tmp_dir, + (int) getpid ()); + + cmd_name[0] = '\0'; +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ARNIADB); +#else + sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_ARNIADB); +#endif + + argv[argc++] = cmd_name; + argv[argc++] = PRINT_CMD_SHARD; + if (sname == NULL) + { + argv[argc++] = PRINT_CMD_STOP; + } + else + { + argv[argc++] = PRINT_CMD_OFF; + argv[argc++] = sname; + } + + argv[argc++] = NULL; + + pid = run_child (argv, 1, NULL, stdout_log_file, stderr_log_file, NULL); /* start shard */ + + if (pid < 0) + { + if (err_buf) + { + sprintf (err_buf, "system error : %s stop shard", cmd_name); + } + unlink (stdout_log_file); + unlink (stderr_log_file); + return -1; + } + + ret_val = + read_start_shard_output (stdout_log_file, stderr_log_file, err_buf); + unlink (stdout_log_file); + unlink (stderr_log_file); + if (ret_val != 0) + { + return ERR_WITH_MSG; + } + + return ERR_NO_ERROR; +} + +static int +read_broker_changer_output (char *stdout_file, char *stderr_file, + char *_dbmt_error) +{ + FILE *fp; + char buf[1024]; + int len = 0; + + strcpy (buf, ""); + + if (access (stdout_file, F_OK) == 0) + { + fp = fopen (stdout_file, "r"); + if (fp != NULL) + { + while (fgets (buf, sizeof (buf), fp) != NULL) + { + if (strncmp (buf, "OK", 2) == 0) + { + fclose (fp); + return ERR_NO_ERROR; + } + ut_trim (buf); + len += (int) strlen (buf); + if (len < DBMT_ERROR_MSG_SIZE - len - 1) + { + strcpy (_dbmt_error, buf); + _dbmt_error += len; + } + else + { + strcpy_limit (_dbmt_error, buf, DBMT_ERROR_MSG_SIZE - len); + strcpy_limit (_dbmt_error + DBMT_ERROR_MSG_SIZE - len - 4, + "...", 4); + break; + } + } + fclose (fp); + } + } + + if (access (stderr_file, F_OK) == 0) + { + fp = fopen (stderr_file, "r"); + if (fp != NULL) + { + while (fgets (buf, sizeof (buf), fp) != NULL) + { + ut_trim (buf); + len += (int) strlen (buf); + if (len < DBMT_ERROR_MSG_SIZE - len - 1) + { + strcpy (_dbmt_error, buf); + _dbmt_error += len; + } + else + { + strcpy_limit (_dbmt_error, buf, DBMT_ERROR_MSG_SIZE - len); + strcpy_limit (_dbmt_error + DBMT_ERROR_MSG_SIZE - len - 4, + "...", 4); + break; + } + } + + fclose (fp); + } + } + + return ERR_SYSTEM_CALL; +} + +int +ts_broker_changer (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char stdout_log_file[512]; + char stderr_log_file[512]; + + char cmd_name[ARNIADB_CMD_NAME_LEN]; + const char *argv[6]; + + char *bname = NULL; + char *casnum = NULL; + char *confname = NULL; + char *confvalue = NULL; + + int argc = 0; + int pid; + int ret_val; + + if ((bname = nv_get_val (req, "bname")) == NULL) + { + sprintf (_dbmt_error, "bname"); + return ERR_PARAM_MISSING; + } + + // casnum is optional. + casnum = nv_get_val (req, "casnum"); + + if ((confname = nv_get_val (req, "confname")) == NULL) + { + sprintf (_dbmt_error, "confname"); + return ERR_PARAM_MISSING; + } + + if ((confvalue = nv_get_val (req, "confvalue")) == NULL) + { + sprintf (_dbmt_error, "confvalue"); + return ERR_PARAM_MISSING; + } + + sprintf (stdout_log_file, "%s/cmbrokerchanger.%d.out", sco.dbmt_tmp_dir, + (int) getpid ()); + sprintf (stderr_log_file, "%s/cmbrokerchanger.%d.err", sco.dbmt_tmp_dir, + (int) getpid ()); + + cmd_name[0] = '\0'; +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, + UTIL_BROKER_CHANGER); +#else + sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_BROKER_CHANGER); +#endif + + argv[argc++] = cmd_name; + argv[argc++] = bname; + + // casnum is optional. + if (casnum != NULL) + { + argv[argc++] = casnum; + } + argv[argc++] = confname; + argv[argc++] = confvalue; + argv[argc] = NULL; + + // run "broker_changer" + pid = run_child (argv, 1, NULL, stdout_log_file, stderr_log_file, NULL); + + if (pid < 0) + { + if (_dbmt_error) + { + sprintf (_dbmt_error, "%s : system error, fork failed!", cmd_name); + } + unlink (stdout_log_file); + unlink (stderr_log_file); + return ERR_SYSTEM_CALL; + } + + ret_val = + read_broker_changer_output (stdout_log_file, stderr_log_file, + _dbmt_error); + + unlink (stdout_log_file); + unlink (stderr_log_file); + + return ret_val; + +} + +static int +read_ha_cmd_output (char *stdout_file, char *stderr_file, char *_dbmt_error) +{ + FILE *fp; + char buf[1024]; + int len = 0; + int len_tmp = 0; + int ret_val = ERR_NO_ERROR; + + if (access (stderr_file, F_OK) == 0) + { + fp = fopen (stderr_file, "r"); + if (fp != NULL) + { + while (fgets (buf, sizeof (buf), fp) != NULL) + { + ut_trim (buf); + len_tmp = (int) strlen (buf); + + if (len_tmp < DBMT_ERROR_MSG_SIZE - len - 1) + { + strcpy (_dbmt_error, buf); + _dbmt_error += len_tmp; + len += len_tmp; + } + else + { + strcpy_limit (_dbmt_error, buf, DBMT_ERROR_MSG_SIZE - len); + strcpy_limit (_dbmt_error + DBMT_ERROR_MSG_SIZE - len - 4, + "...", 4); + } + + ret_val = ERR_SYSTEM_CALL; + } + } + fclose (fp); + } + + if (access (stdout_file, F_OK) == 0 && ret_val == ERR_NO_ERROR) + { + fp = fopen (stdout_file, "r"); + if (fp != NULL) + { + while (fgets (buf, sizeof (buf), fp) != NULL) + { + ut_trim (buf); + len_tmp = (int) strlen (buf); + + if (len_tmp < DBMT_ERROR_MSG_SIZE - len - 1) + { + strcpy (_dbmt_error, buf); + _dbmt_error += len_tmp; + len += len_tmp; + } + else + { + strcpy_limit (_dbmt_error, buf, DBMT_ERROR_MSG_SIZE - len); + strcpy_limit (_dbmt_error + DBMT_ERROR_MSG_SIZE - len - 4, + "...", 4); + } + } + } + fclose (fp); + } + + return ret_val; +} + +static int +handle_ha_status_output (nvplist *res, char *_dbmt_error) +{ + char *iter1 = NULL; + char *iter2 = NULL; + char *applydb_pos = NULL; + char *copydb_pos = NULL; + char *db_names[1000]; + char value[1024]; + int len_tmp; + int num_dbs = 0; + int i; + + // "current_node" + iter1 = strstr (_dbmt_error, "current"); + if (iter1 == NULL) + { + return ERR_WITH_MSG; + } + + iter2 = strstr (iter1, "state"); + if (iter2 == NULL) + { + return ERR_WITH_MSG; + } + + len_tmp = (int) (iter2 - iter1 - 10); + + strncpy (value, iter1 + 8, len_tmp); + value[len_tmp] = '\0'; + nv_add_nvp (res, "current_node", value); + + // "current_node_state" + iter1 = strstr (iter2, ")"); + if (iter1 == NULL) + { + return ERR_WITH_MSG; + } + + len_tmp = (int) (iter1 - iter2 - 6); + strncpy (value, iter2 + 6, len_tmp); + value[len_tmp] = '\0'; + nv_add_nvp (res, "current_node_state", value); + + // "nodeA" + iter1 = strstr (iter1, "Node"); + if (iter1 == NULL) + { + return ERR_WITH_MSG; + } + + iter2 = strstr (iter1, "("); + if (iter2 == NULL) + { + return ERR_WITH_MSG; + } + + len_tmp = (int) (iter2 - iter1 - 6); + strncpy (value, iter1 + 5, len_tmp); + value[len_tmp] = '\0'; + nv_add_nvp (res, "nodeA", value); + + // "nodeA_state" + iter1 = strstr (iter2, "state"); + if (iter1 == NULL) + { + return ERR_WITH_MSG; + } + + iter2 = strstr (iter1, ")"); + if (iter2 == NULL) + { + return ERR_WITH_MSG; + } + + len_tmp = (int) (iter2 - iter1 - 6); + strncpy (value, iter1 + 6, len_tmp); + value[len_tmp] = '\0'; + nv_add_nvp (res, "nodeA_state", value); + + // "nodeB" + iter1 = strstr (iter2, "Node"); + if (iter1 == NULL) + { + return ERR_WITH_MSG; + } + + iter2 = strstr (iter1, "("); + if (iter2 == NULL) + { + return ERR_WITH_MSG; + } + + len_tmp = (int) (iter2 - iter1 - 6); + strncpy (value, iter1 + 5, len_tmp); + value[len_tmp] = '\0'; + nv_add_nvp (res, "nodeB", value); + + // "nodeB_state" + iter1 = strstr (iter2, "state"); + if (iter1 == NULL) + { + return ERR_WITH_MSG; + } + + iter2 = strstr (iter1, ")"); + if (iter2 == NULL) + { + return ERR_WITH_MSG; + } + + len_tmp = (int) (iter2 - iter1 - 6); + strncpy (value, iter1 + 6, len_tmp); + value[len_tmp] = '\0'; + nv_add_nvp (res, "nodeB_state", value); + + // count dbs + + iter1 = strstr (iter2, "Applylogdb"); + if (iter1 == NULL) + { + return ERR_WITH_MSG; + } + + while (iter1 != NULL) + { + char *iter3 = NULL; + + iter3 = strstr (iter1, "@"); + if (iter3 == NULL) + { + return ERR_WITH_MSG; + } + + strncpy (value, iter1 + 11, iter3 - iter1 - 11); + value[iter3 - iter1 - 11] = '\0'; + + db_names[num_dbs] = (char *) malloc (iter3 - iter1 - 10); + strcpy (db_names[num_dbs], value); + num_dbs++; + + iter1 = strstr (iter3, "Applylogdb"); + } + + applydb_pos = strstr (iter2, "Applylogdb"); + if (applydb_pos == NULL) + { + return ERR_WITH_MSG; + } + + copydb_pos = strstr (iter2, "Copylogdb"); + if (copydb_pos == NULL) + { + return ERR_WITH_MSG; + } + + i = 0; + while (i < num_dbs) + { + // for each db, create an array to store "applylogdb" and "copylogdb" + nv_add_nvp (res, "open", "ha_info"); + + nv_add_nvp (res, "dbname", db_names[i]); + + if (applydb_pos != NULL) + { + // "applylogdb" + iter1 = applydb_pos; + iter2 = strstr (iter1, "("); + if (iter2 == NULL) + { + return ERR_WITH_MSG; + } + + len_tmp = (int) (iter2 - iter1 - 12); + strncpy (value, iter1 + 11, len_tmp); + value[len_tmp] = '\0'; + nv_add_nvp (res, "applylogdb", value); + + // "applylogdb_pid" + iter1 = strstr (iter2, "pid"); + if (iter1 == NULL) + { + return ERR_WITH_MSG; + } + + iter2 = strstr (iter1, "state"); + if (iter2 == NULL) + { + return ERR_WITH_MSG; + } + + len_tmp = (int) (iter2 - iter1 - 6); + strncpy (value, iter1 + 4, len_tmp); + value[len_tmp] = '\0'; + nv_add_nvp (res, "applylogdb_pid", value); + + // "applylogdb_state" + iter1 = strstr (iter2, ")"); + if (iter1 == NULL) + { + return ERR_WITH_MSG; + } + + len_tmp = (int) (iter1 - iter2 - 6); + strncpy (value, iter2 + 6, len_tmp); + value[len_tmp] = '\0'; + nv_add_nvp (res, "applylogdb_state", value); + + // for next loop + applydb_pos = strstr (iter1, "Applylogdb"); + } + + if (copydb_pos != NULL) + { + // "copylogdb" + iter1 = copydb_pos; + iter2 = strstr (iter1, "("); + if (iter2 == NULL) + { + return ERR_WITH_MSG; + } + + len_tmp = (int) (iter2 - iter1 - 11); + strncpy (value, iter1 + 10, len_tmp); + value[len_tmp] = '\0'; + nv_add_nvp (res, "copylogdb", value); + + // "copylogdb_pid" + iter1 = strstr (iter2, "pid"); + if (iter1 == NULL) + { + return ERR_WITH_MSG; + } + + iter2 = strstr (iter1, "state"); + if (iter2 == NULL) + { + return ERR_WITH_MSG; + } + + len_tmp = (int) (iter2 - iter1 - 6); + strncpy (value, iter1 + 4, len_tmp); + value[len_tmp] = '\0'; + nv_add_nvp (res, "copylogdb_pid", value); + + // "copylogdb_state" + iter1 = strstr (iter2, ")"); + if (iter1 == NULL) + { + return ERR_WITH_MSG; + } + + len_tmp = (int) (iter1 - iter2 - 6); + strncpy (value, iter2 + 6, len_tmp); + value[len_tmp] = '\0'; + nv_add_nvp (res, "copylogdb_state", value); + + // for next loop + copydb_pos = strstr (iter1, "Copylogdb"); + } + + // finish filling array + nv_add_nvp (res, "close", "ha_info"); + + // release the string after storing it to nvplist + free (db_names[i]); + + i++; + } + + return ERR_NO_ERROR; +} + +int +ts_ha_start (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char stdout_log_file[512]; + char stderr_log_file[512]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; + const char *argv[6]; + char *dbname = NULL; + + int argc = 0; + int pid; + int ret_val; + + // dbname is optional. + dbname = nv_get_val (req, "dbname"); + + sprintf (stdout_log_file, "%s/cmhastart.%d.out", sco.dbmt_tmp_dir, + (int) getpid ()); + sprintf (stderr_log_file, "%s/cmhastart.%d.err", sco.dbmt_tmp_dir, + (int) getpid ()); + + cmd_name[0] = '\0'; +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ARNIADB); +#else + sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_ARNIADB); +#endif + + argv[argc++] = cmd_name; + argv[argc++] = PRINT_CMD_HEARTBEAT; + argv[argc++] = PRINT_CMD_START; + + // casnum is optional. + if (dbname != NULL) + { + argv[argc++] = dbname; + } + argv[argc] = NULL; + + // run "arniadb heartbeat start [dbname]" + pid = run_child (argv, 1, NULL, stdout_log_file, stderr_log_file, NULL); + + if (pid < 0) + { + if (_dbmt_error) + { + sprintf (_dbmt_error, "%s : system error, fork failed!", cmd_name); + } + unlink (stdout_log_file); + unlink (stderr_log_file); + return ERR_SYSTEM_CALL; + } + + ret_val = + read_ha_cmd_output (stdout_log_file, stderr_log_file, _dbmt_error); + + unlink (stdout_log_file); + unlink (stderr_log_file); + + return ret_val; +} + +int +ts_ha_stop (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char stdout_log_file[512]; + char stderr_log_file[512]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; + const char *argv[6]; + char *dbname = NULL; + + int argc = 0; + int pid; + int ret_val; + + + // dbname is optional. + dbname = nv_get_val (req, "dbname"); + + sprintf (stdout_log_file, "%s/cmhastop.%d.out", sco.dbmt_tmp_dir, + (int) getpid ()); + sprintf (stderr_log_file, "%s/cmhastop.%d.err", sco.dbmt_tmp_dir, + (int) getpid ()); + + cmd_name[0] = '\0'; +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ARNIADB); +#else + sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_ARNIADB); +#endif + + argv[argc++] = cmd_name; + argv[argc++] = PRINT_CMD_HEARTBEAT; + argv[argc++] = PRINT_CMD_STOP; + + // dbname is optional. + if (dbname != NULL) + { + argv[argc++] = dbname; + } + argv[argc] = NULL; + + // run "arniadb heartbeat stop [dbname]" + pid = run_child (argv, 1, NULL, stdout_log_file, stderr_log_file, NULL); + + if (pid < 0) + { + if (_dbmt_error) + { + sprintf (_dbmt_error, "%s : system error, fork failed!", cmd_name); + } + unlink (stdout_log_file); + unlink (stderr_log_file); + return ERR_SYSTEM_CALL; + } + + ret_val = + read_ha_cmd_output (stdout_log_file, stderr_log_file, _dbmt_error); + + unlink (stdout_log_file); + unlink (stderr_log_file); + + return ret_val; +} + +int +ts_ha_status (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char stdout_log_file[512]; + char stderr_log_file[512]; + char cmd_name[ARNIADB_CMD_NAME_LEN]; + const char *argv[6]; + int argc = 0; + int pid; + int ret_val; + + + sprintf (stdout_log_file, "%s/cmhastatus.%d.out", sco.dbmt_tmp_dir, + (int) getpid ()); + sprintf (stderr_log_file, "%s/cmhastatus.%d.err", sco.dbmt_tmp_dir, + (int) getpid ()); + + cmd_name[0] = '\0'; +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ARNIADB); +#else + sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_ARNIADB); +#endif + + argv[argc++] = cmd_name; + argv[argc++] = PRINT_CMD_HEARTBEAT; + argv[argc++] = PRINT_CMD_STATUS; + argv[argc] = NULL; + + // run "arniadb heartbeat status" + pid = run_child (argv, 1, NULL, stdout_log_file, stderr_log_file, NULL); + + if (pid < 0) + { + if (_dbmt_error) + { + sprintf (_dbmt_error, "%s : system error, fork failed!", cmd_name); + } + unlink (stdout_log_file); + unlink (stderr_log_file); + return ERR_SYSTEM_CALL; + } + + if ((ret_val = + read_ha_cmd_output (stdout_log_file, stderr_log_file, + _dbmt_error)) != ERR_NO_ERROR) + { + + unlink (stdout_log_file); + unlink (stderr_log_file); + + return ret_val; + } + + unlink (stdout_log_file); + unlink (stderr_log_file); + + // handle the response + if ((ret_val = handle_ha_status_output (res, _dbmt_error)) != ERR_NO_ERROR) + { + return ret_val; + } + + return ret_val; +} + +int +ts_ha_reload (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char stdout_log_file[512]; + char stderr_log_file[512]; + + char cmd_name[ARNIADB_CMD_NAME_LEN]; + const char *argv[6]; + + int argc = 0; + int pid; + int ret_val; + + + sprintf (stdout_log_file, "%s/cmhareload.%d.out", sco.dbmt_tmp_dir, + (int) getpid ()); + sprintf (stderr_log_file, "%s/cmhareload.%d.err", sco.dbmt_tmp_dir, + (int) getpid ()); + + cmd_name[0] = '\0'; +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ARNIADB); +#else + sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_ARNIADB); +#endif + + argv[argc++] = cmd_name; + argv[argc++] = PRINT_CMD_HEARTBEAT; + argv[argc++] = PRINT_CMD_RELOAD; + argv[argc] = NULL; + + // run "arniadb heartbeat reload" + pid = run_child (argv, 1, NULL, stdout_log_file, stderr_log_file, NULL); + + if (pid < 0) + { + if (_dbmt_error) + { + sprintf (_dbmt_error, "%s : system error, fork failed!", cmd_name); + } + unlink (stdout_log_file); + unlink (stderr_log_file); + return ERR_SYSTEM_CALL; + } + + ret_val = + read_ha_cmd_output (stdout_log_file, stderr_log_file, _dbmt_error); + + unlink (stdout_log_file); + unlink (stderr_log_file); + + return ret_val; + +} + +int +ts_ha_copylogdb (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char stdout_log_file[512]; + char stderr_log_file[512]; + + char cmd_name[ARNIADB_CMD_NAME_LEN]; + const char *argv[7]; + + char *dbname = NULL; + char *on_off = NULL; + char *peer_node = NULL; + + int argc = 0; + int pid = -1; + int ret_val = 0; + + + if ((dbname = nv_get_val (req, "dbname")) == NULL) + { + sprintf (_dbmt_error, "dbname"); + return ERR_PARAM_MISSING; + } + + // on_off should be "start" or "stop". + if ((on_off = nv_get_val (req, "on_off")) == NULL) + { + sprintf (_dbmt_error, "on_off"); + return ERR_PARAM_MISSING; + } + else if (strcmp (on_off, "start") && strcmp (on_off, "stop")) + { + return ERR_REQUEST_FORMAT; + } + + if ((peer_node = nv_get_val (req, "peer_node")) == NULL) + { + sprintf (_dbmt_error, "peer_node"); + return ERR_PARAM_MISSING; + } + + sprintf (stdout_log_file, "%s/cmhacopylogdb.%d.out", sco.dbmt_tmp_dir, + (int) getpid ()); + sprintf (stderr_log_file, "%s/cmhacopylogdb.%d.err", sco.dbmt_tmp_dir, + (int) getpid ()); + + cmd_name[0] = '\0'; +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ARNIADB); +#else + sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_ARNIADB); +#endif + + argv[argc++] = cmd_name; + argv[argc++] = PRINT_CMD_HEARTBEAT; + argv[argc++] = UTIL_OPTION_COPYLOGDB; + argv[argc++] = on_off; + argv[argc++] = dbname; + argv[argc++] = peer_node; + argv[argc] = NULL; + + // run "arniadb heartbeat copylogdb dbname peer_node" + pid = run_child (argv, 1, NULL, stdout_log_file, stderr_log_file, NULL); + + if (pid < 0) + { + if (_dbmt_error) + { + sprintf (_dbmt_error, "%s : system error, fork failed!", cmd_name); + } + unlink (stdout_log_file); + unlink (stderr_log_file); + return ERR_SYSTEM_CALL; + } + + //ret_val = read_broker_changer_output(stdout_log_file, stderr_log_file, _dbmt_error); + + unlink (stdout_log_file); + unlink (stderr_log_file); + + return ret_val; + +} + +int +ts_ha_applylogdb (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char stdout_log_file[512]; + char stderr_log_file[512]; + + char cmd_name[ARNIADB_CMD_NAME_LEN]; + const char *argv[7]; + + char *dbname = NULL; + char *on_off = NULL; + char *peer_node = NULL; + + int argc = 0; + int pid = -1; + int ret_val = 0; + + + if ((dbname = nv_get_val (req, "dbname")) == NULL) + { + sprintf (_dbmt_error, "dbname"); + return ERR_PARAM_MISSING; + } + + // on_off should be "start" or "stop". + if ((on_off = nv_get_val (req, "on_off")) == NULL) + { + sprintf (_dbmt_error, "on_off"); + return ERR_PARAM_MISSING; + } + else if (strcmp (on_off, "start") && strcmp (on_off, "stop")) + { + return ERR_REQUEST_FORMAT; + } + + if ((peer_node = nv_get_val (req, "peer_node")) == NULL) + { + sprintf (_dbmt_error, "peer_node"); + return ERR_PARAM_MISSING; + } + + sprintf (stdout_log_file, "%s/cmhacopylogdb.%d.out", sco.dbmt_tmp_dir, + (int) getpid ()); + sprintf (stderr_log_file, "%s/cmhacopylogdb.%d.err", sco.dbmt_tmp_dir, + (int) getpid ()); + + cmd_name[0] = '\0'; +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (cmd_name, "%s/%s%s", sco.szArniadb, ARNIADB_DIR_BIN, UTIL_ARNIADB); +#else + sprintf (cmd_name, "%s/%s", ARNIADB_BINDIR, UTIL_ARNIADB); +#endif + + argv[argc++] = cmd_name; + argv[argc++] = PRINT_CMD_HEARTBEAT; + argv[argc++] = UTIL_OPTION_APPLYLOGDB; + argv[argc++] = on_off; + argv[argc++] = dbname; + argv[argc++] = peer_node; + argv[argc] = NULL; + + // run "arniadb heartbeat applylogdb dbname peer_node" + pid = run_child (argv, 1, NULL, stdout_log_file, stderr_log_file, NULL); + + if (pid < 0) + { + if (_dbmt_error) + { + sprintf (_dbmt_error, "%s : system error, fork failed!", cmd_name); + } + unlink (stdout_log_file); + unlink (stderr_log_file); + return ERR_SYSTEM_CALL; + } + + //ret_val = read_broker_changer_output(stdout_log_file, stderr_log_file, _dbmt_error); + + unlink (stdout_log_file); + unlink (stderr_log_file); + + return ret_val; + +} + +/*static int _get_update_url(char *url) +{ + char cm_conf_file[PATH_MAX]; + char line_buf[MAX_JOB_CONFIG_FILE_LINE_LENGTH]; + + char *iter = NULL; + + FILE *fin; + +#if !defined (DO_NOT_USE_ARNIADBENV) + snprintf (cm_conf_file, PATH_MAX - 1, "%s/conf/%s", sco.szArniadb, ARNIADB_DBMT_CONF); +#else + snprintf (cm_conf_file, PATH_MAX - 1, "%s/%s", ARNIADB_CONFDIR, ARNIADB_DBMT_CONF); +#endif + + fin = fopen(cm_conf_file, "r"); + if (fin == NULL) + { + return ERR_FILE_OPEN_FAIL; + } + + while (fgets(&line_buf, MAX_JOB_CONFIG_FILE_LINE_LENGTH, fin) != NULL) + { + iter = strstr(line_buf, "patch_url"); + if( iter == NULL) + { + continue; + } + + iter = strstr(line_buf, "="); + strcpy (url, iter+2); + + break; + } + + fclose(fin); + + return ERR_NO_ERROR; +}*/ + +static char * +_get_format_time () +{ + char *buff = (char *) malloc (sizeof (char) * LINE_MAX); +#ifdef WINDOWS + +#else + time_t lt; + + time (<); + struct tm *t = localtime (<); + + if (t) + { + strftime (buff, LINE_MAX, "%Y%m%d %H:%M:%S", t); + } + +#endif + return buff; +} + +static void +_write_auto_update_log (char *line_buf, int is_success) +{ + char *log_time; + + char log_path[PATH_MAX]; + + FILE *fin = NULL; + + sprintf (log_path, "%s/log/manager/ams.update.log", sco.szArniadb); + + fin = fopen (log_path, "a"); + + log_time = _get_format_time (); + if (is_success) + { + fprintf (fin, "[%s] %s, update to %s.\n", log_time, line_buf, + sco.szAMSVersion); + } + else + { + fprintf (fin, "[%s] AMS update error: %s\n", log_time, line_buf); + } + + free (log_time); + fclose (fin); + +} + +int +ts_is_update_success (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char err_log[PATH_MAX]; + char output_log[PATH_MAX]; + char line_buf[LINE_MAX]; + + FILE *fin = NULL; + + sprintf (err_log, "%s/ams_auto_update.err", sco.dbmt_tmp_dir); + sprintf (output_log, "%s/ams_auto_update.log", sco.dbmt_tmp_dir); + + fin = fopen (output_log, "r"); + if (fin == NULL) + { + sprintf (_dbmt_error, "%s", output_log); + return ERR_FILE_OPEN_FAIL; + } + + while (fgets (line_buf, LINE_MAX, fin) != NULL) + { + if (strstr (line_buf, "ARNIADB Manager Server is updated.") != NULL) + { + nv_add_nvp (res, "autoupdate_success", "success"); + + _write_auto_update_log (line_buf, TRUE); + fclose (fin); + return ERR_NO_ERROR; + } + + } + fclose (fin); + + nv_add_nvp (res, "autoupdate_result", "failure"); + + fin = fopen (err_log, "r"); + if (fin == NULL) + { + sprintf (_dbmt_error, "%s", err_log); + return ERR_FILE_OPEN_FAIL; + } + + while (fgets (line_buf, LINE_MAX, fin) != NULL) + { + _write_auto_update_log (line_buf, FALSE); + } + fclose (fin); + + + return ERR_NO_ERROR; +} + +int +ts_auto_update (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char *patch_name = NULL; + + char path[PATH_MAX]; + char shell_name[PATH_MAX]; + char err_log[PATH_MAX]; + char output_log[PATH_MAX]; +#ifndef WINDOWS + char cmd[PATH_MAX]; +#endif + char *argv[2]; + + int ret_val = 0; + +#ifndef WINDOWS + pid_t pid = 0; +#endif + + patch_name = nv_get_val (req, "patch_name"); + if (patch_name == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "patch_name"); + return ERR_PARAM_MISSING; + } +#ifdef WINDOWS + sprintf (path, "%s\\", sco.dbmt_tmp_dir); +#else + sprintf (path, "%s/", sco.dbmt_tmp_dir); +#endif + + if ((ret_val = + generate_update_script (patch_name, sco.szAutoUpdateURL, path, + _dbmt_error)) != ERR_NO_ERROR) + { + return ret_val; + } + + sprintf (shell_name, "%s" SHELL_NAME, path); + + argv[0] = shell_name; + argv[1] = NULL; + + sprintf (err_log, "%sams.autoupdate.err", path); + sprintf (output_log, "%sams.autoupdate.log", path); + +#ifdef WINDOWS + ret_val = run_child (argv, 0, NULL, output_log, err_log, NULL); + +#else + sprintf (cmd, "%s >%s 2>%s", shell_name, output_log, err_log); + + // As "system" fucntion will wait for the command return in parent process, fork a new procee to execute it in order to avoid blocking. + if ((pid = fork ()) > 0) + { + return ERR_NO_ERROR; + } + else if (pid == 0) + { + system (cmd); + exit (0); + } + else + { + sprintf (_dbmt_error, "fork()"); + return ERR_SYSTEM_CALL; + } + +#endif + + return ERR_NO_ERROR; +} + +int +ts_list_dir (nvplist *req, nvplist *res, char *_dbmt_error) +{ + char *nvp_path = NULL; + char path[PATH_MAX]; + char full_path[PATH_MAX]; + + path[0] = 0; + full_path[0] = 0; + + if (NULL == (nvp_path = nv_get_val (req, "path"))) + { + strcpy (_dbmt_error, "missing path parameter"); + return ERR_PARAM_MISSING; + } + + if (0 == strncmp (nvp_path, "../", strlen ("../"))) + { + strcpy (_dbmt_error, "path parameter includes invalid dirctories!"); + return ERR_WITH_MSG; + } + if (NULL != strstr (nvp_path, "../")) + { + strcpy (_dbmt_error, "path parameter includes invalid dirctories!"); + return ERR_WITH_MSG; + } + if ('/' == nvp_path[strlen (nvp_path) - 3] + && '.' == nvp_path[strlen (nvp_path) - 2] + && '.' == nvp_path[strlen (nvp_path) - 1]) + { + strcpy (_dbmt_error, "path parameter includes invalid dirctories!"); + return ERR_WITH_MSG; + } + + snprintf (path, sizeof (path), "%s", nvp_path); + if (path[strlen (path) - 1] != '/') + { + snprintf (path, sizeof (path), "%s/", nvp_path); + } + nv_add_nvp (res, "path", path); + +#if !defined (DO_NOT_USE_ARNIADBENV) + snprintf (full_path, PATH_MAX, "%s/%s/", sco.szArniadb, path); +#else + sprintf (full_path, "%s/%s/", ARNIADB, path); +#endif + +#if defined(WINDOWS) + { + HANDLE handle; + WIN32_FIND_DATA ffd; + char find_path[PATH_MAX]; + snprintf (find_path, PATH_MAX - 1, "%s/*", full_path); + + nv_add_nvp (res, "open", "dir"); + handle = FindFirstFile (find_path, &ffd); + if (handle == INVALID_HANDLE_VALUE) + { + sprintf (_dbmt_error, "open directory %s failed!", path); + return ERR_WITH_MSG; + } + while (FindNextFile (handle, &ffd)) + { + if (ffd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN + || ffd.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) + { + continue; + } + else if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) + { + if (0 != strcmp (ffd.cFileName, ".") + && 0 != strcmp (ffd.cFileName, "..")) + { + nv_add_nvp (res, "group", ffd.cFileName); + } + } + } + FindClose (handle); + nv_add_nvp (res, "close", "dir"); + + nv_add_nvp (res, "open", "file"); + handle = FindFirstFile (find_path, &ffd); + if (handle == INVALID_HANDLE_VALUE) + { + sprintf (_dbmt_error, "open directory %s failed!", path); + return ERR_WITH_MSG; + } + while (FindNextFile (handle, &ffd)) + { + if (ffd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN + || ffd.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) + { + continue; + } + else if (! (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) + { + if (0 == strcmp (ffd.cFileName, "cm.pass") + || 0 == strcmp (ffd.cFileName, "cmdb.pass")) + { + continue; + } + nv_add_nvp (res, "group", ffd.cFileName); + } + } + FindClose (handle); + nv_add_nvp (res, "close", "file"); + } + +#else + { + char name_temp[1024]; + DIR *dirptr = NULL; + struct dirent *entry; + + nv_add_nvp (res, "open", "dir"); + if ((dirptr = opendir (full_path)) == NULL) + { + sprintf (_dbmt_error, "open directory %s failed!", path); + return ERR_WITH_MSG; + } + else + { + while ((entry = readdir (dirptr)) != NULL) + { + struct stat stat_file; + if (entry->d_name[0] == '.') + { + continue; + } + strcpy (name_temp, full_path); + strcat (name_temp, entry->d_name); + + stat (name_temp, &stat_file); + if (S_ISDIR (stat_file.st_mode)) + { + nv_add_nvp (res, "group", entry->d_name); + } + } + } + closedir (dirptr); + nv_add_nvp (res, "close", "dir"); + + nv_add_nvp (res, "open", "file"); + if ((dirptr = opendir (full_path)) == NULL) + { + sprintf (_dbmt_error, "open directory %s failed!", path); + return ERR_WITH_MSG; + } + else + { + while ((entry = readdir (dirptr)) != NULL) + { + struct stat stat_file; + if (entry->d_name[0] == '.') + { + continue; + } + strcpy (name_temp, full_path); + strcat (name_temp, entry->d_name); + + stat (name_temp, &stat_file); + if (! (S_ISDIR (stat_file.st_mode))) + { + if (0 == strcmp (entry->d_name, "cm.pass") + || 0 == strcmp (entry->d_name, "cmdb.pass")) + { + continue; + } + nv_add_nvp (res, "group", entry->d_name); + } + } + } + closedir (dirptr); + nv_add_nvp (res, "close", "file"); + } +#endif + + return ERR_NO_ERROR; +} + +int +ts_monitor_process (nvplist *req, nvplist *res, char *_dbmt_error) +{ + // processes need monitoring + const char process_name[][PATH_MAX] = {"arn_master", 0}; + char exist[15]; + int i = 0; + +#ifdef WINDOWS + + PROCESSENTRY32 pe32; + HANDLE process_snap = 0; + pe32.dwSize = sizeof (pe32); + + process_snap = CreateToolhelp32Snapshot (TH32CS_SNAPPROCESS, 0); + if (process_snap == INVALID_HANDLE_VALUE) + { + strcpy (_dbmt_error, "create process snapshot failed!"); + return ERR_SYSTEM_CALL; + } + + i = 0; + while (process_name[i][0] != 0) + { + strcpy (exist, "don't exist"); + if (!Process32First (process_snap, &pe32)) + { + strcpy (_dbmt_error, "get process info failed!"); + return ERR_SYSTEM_CALL; + } + + do + { + if (!strncmp + (process_name[i], pe32.szExeFile, strlen (process_name[i]))) + { + strcpy (exist, "exist"); + break; + } + + } + while (Process32Next (process_snap, &pe32)); + + nv_add_nvp (res, process_name[i], exist); + i++; + } + +#else + char pid_file[PATH_MAX]; + char cmd_name[PATH_MAX]; + + FILE *fin; + int ch; + + sprintf (pid_file, "%s/monitor_process.%u.tmp", sco.dbmt_tmp_dir, + getpid ()); + fin = fopen (pid_file, "w+"); + + i = 0; + while (process_name[i][0] != 0) + { + sprintf (cmd_name, "pgrep -u $(whoami) %s > %s", process_name[i], + pid_file); + system (cmd_name); + + if ((ch = fgetc (fin)) == EOF) + { + strcpy (exist, "don't exist"); + } + else if (ch > '1' && ch < '9') + { + strcpy (exist, "exist"); + } + + nv_add_nvp (res, process_name[i], exist); + i++; + } + + fclose (fin); + unlink (pid_file); +#endif + + return ERR_NO_ERROR; +} + +static int +_make_cert (nvplist *req, X509 **x509p, EVP_PKEY **pkeyp, int bits, + char *_dbmt_error) +{ + char user_info[PATH_MAX]; + char nid_basic_constraints[PATH_MAX]; + char nid_key_usage[PATH_MAX]; + char nid_subject_key_identifier[PATH_MAX]; + char nid_netscape_cert_type[PATH_MAX]; + char nid_netscape_comment[PATH_MAX]; + + X509 *x509_local = NULL; + EVP_PKEY *pub_key = NULL; + RSA *rsa = NULL; + X509_NAME *name = NULL; + BIGNUM *bignum = NULL; + + char *country_name = NULL; + char *state_name = NULL; + char *locality_name = NULL; + char *organization_name = NULL; + char *organizational_unit_name = NULL; + char *common_name = NULL; + char *email_addr = NULL; + char *days = NULL; + + int day = 0; + + user_info[0] = '\0'; + nid_basic_constraints[0] = '\0'; + nid_key_usage[0] = '\0'; + nid_subject_key_identifier[0] = '\0'; + nid_netscape_cert_type[0] = '\0'; + nid_netscape_comment[0] = '\0'; + + country_name = nv_get_val (req, "cname"); + state_name = nv_get_val (req, "stname"); + locality_name = nv_get_val (req, "loname"); + organization_name = nv_get_val (req, "orgname"); + organizational_unit_name = nv_get_val (req, "orgutname"); + common_name = nv_get_val (req, "comname"); + email_addr = nv_get_val (req, "email"); + days = nv_get_val (req, "days"); + + if (days == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "days"); + return ERR_PARAM_MISSING; + } + + if ((pkeyp == NULL) || (*pkeyp == NULL)) + { + if ((pub_key = EVP_PKEY_new ()) == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, + "Cannot make a new private key."); + return ERR_WITH_MSG; + } + } + else + { + pub_key = *pkeyp; + } + + if ((x509p == NULL) || (*x509p == NULL)) + { + if ((x509_local = X509_new ()) == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, + "Cannot make a new certification file."); + return ERR_WITH_MSG; + } + } + else + { + x509_local = *x509p; + } + + /* Generate RSA key using RSA_generate_key_ex to replace RSA_generate_key + * + */ + if ((bignum = BN_new ()) == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, + "Cannot make a new SSL private key file - create bignum failed."); + return ERR_WITH_MSG; + } + if (BN_set_word (bignum, RSA_F4) == 0) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, + "Cannot make a new SSL private key file - set bignum failed."); + return ERR_WITH_MSG; + } + if ((rsa = RSA_new ()) == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, + "Cannot make a new SSL private key file - create RSA failed."); + return ERR_WITH_MSG; + } + if (RSA_generate_key_ex (rsa, bits, bignum, NULL) == 0) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, + "Cannot make a new SSL private key file."); + return ERR_WITH_MSG; + } + if (EVP_PKEY_assign_RSA (pub_key, rsa) == 0) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, + "Failed to generate public key."); + return ERR_WITH_MSG; + } + rsa = NULL; + + X509_set_version (x509_local, 2); + ASN1_INTEGER_set (X509_get_serialNumber (x509_local), 0); + X509_gmtime_adj (X509_get_notBefore (x509_local), 0); + + day = atoi (days); + if (day <= 0) + { + day = 365; + } + X509_gmtime_adj (X509_get_notAfter (x509_local), (long) 60 * 60 * 24 * day); + X509_set_pubkey (x509_local, pub_key); + + name = X509_get_subject_name (x509_local); + + /* This function creates and adds the entry, working out the + * correct string type and performing checks on its length. + * Normally we'd check the return value for errors... + */ + if (country_name != NULL) + { + _add_issuer_info (name, "C", country_name); + } + if (state_name != NULL) + { + _add_issuer_info (name, "ST", state_name); + } + if (locality_name != NULL) + { + _add_issuer_info (name, "L", locality_name); + } + if (organization_name != NULL) + { + _add_issuer_info (name, "O", organization_name); + } + if (organizational_unit_name != NULL) + { + _add_issuer_info (name, "OU", organizational_unit_name); + } + if ((common_name != NULL) && (email_addr != NULL)) + { + snprintf (user_info, PATH_MAX, "%s/%s", common_name, email_addr); + _add_issuer_info (name, "CN", user_info); + } + else if ((common_name != NULL) && (email_addr == NULL)) + { + snprintf (user_info, PATH_MAX, "%s", common_name); + _add_issuer_info (name, "CN", user_info); + } + else if ((common_name == NULL) && (email_addr != NULL)) + { + snprintf (user_info, PATH_MAX, "%s", email_addr); + _add_issuer_info (name, "CN", user_info); + } + + /* Issuer should not be null for all items, + * We have to set at least one issue as default, + * We decide to set organizational_unit_name as the last one. + */ + if ((country_name == NULL) && (state_name == NULL) + && (locality_name == NULL) && (organization_name == NULL) + && (organizational_unit_name == NULL) && (common_name == NULL) + && (email_addr == NULL)) + { + snprintf (user_info, PATH_MAX, "ARNIADB Manger Server Group."); + _add_issuer_info (name, "OU", user_info); + } + /* Its self signed so set the issuer name to be the same as the + * subject. + */ + X509_set_issuer_name (x509_local, name); + + /* Add various extensions: standard extensions */ + snprintf (nid_basic_constraints, PATH_MAX, "critical,CA:TRUE"); + _add_extensions (x509_local, NID_basic_constraints, nid_basic_constraints); + + snprintf (nid_key_usage, PATH_MAX, "critical,keyCertSign,cRLSign"); + _add_extensions (x509_local, NID_key_usage, nid_key_usage); + + snprintf (nid_subject_key_identifier, PATH_MAX, "hash"); + _add_extensions (x509_local, NID_subject_key_identifier, + nid_subject_key_identifier); + + /* Some Netscape specific extensions */ + snprintf (nid_netscape_cert_type, PATH_MAX, "sslCA"); + _add_extensions (x509_local, NID_netscape_cert_type, + nid_netscape_cert_type); + + snprintf (nid_netscape_comment, PATH_MAX, + "ARNIADB Manager server comment extension"); + _add_extensions (x509_local, NID_netscape_comment, nid_netscape_comment); + + if (X509_sign (x509_local, pub_key, EVP_md5 ()) == 0) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, + "Cannot sign with public key."); + return ERR_WITH_MSG; + } + + *x509p = x509_local; + *pkeyp = pub_key; + return ERR_NO_ERROR; +} + +static void +_add_issuer_info (X509_NAME *name, const char *item_name, char *item_value) +{ + X509_NAME_add_entry_by_txt (name, item_name, MBSTRING_ASC, + (const unsigned char *) item_value, -1, -1, 0); +} + +static int +_add_extensions (X509 *cert, int nid, char *value) +{ + X509_EXTENSION *extension; + X509V3_CTX ctx; + /* This sets the 'context' of the extensions. */ + /* No configuration database */ + X509V3_set_ctx_nodb (&ctx); + /* Issuer and subject certs: both the target since it is self signed, + * no request and no CRL + */ + X509V3_set_ctx (&ctx, cert, cert, NULL, NULL, 0); + extension = X509V3_EXT_conf_nid (NULL, &ctx, nid, value); + if (extension == 0) + { + return 1; + } + + X509_add_ext (cert, extension, -1); + X509_EXTENSION_free (extension); + return 0; +} + +static int +_backup_cert (char *_dbmt_error) +{ + char default_backup_cert_path[PATH_MAX]; + char default_cert_path[PATH_MAX]; + + default_backup_cert_path[0] = '\0'; + default_cert_path[0] = '\0'; + + snprintf (default_backup_cert_path, PATH_MAX, "%s.bak", + sco.szSSLCertificate); + if (access (default_backup_cert_path, F_OK) == 0) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, + "Cannot backup SSL certification file: %s.", + sco.szSSLCertificate); + return 1; + } + + snprintf (default_cert_path, PATH_MAX, "%s", sco.szSSLCertificate); + if (access (default_cert_path, F_OK) != 0) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, + "Cannot find SSL certification file: %s.", + sco.szSSLCertificate); + return 1; + } + /*No need to backup custom certification file */ + if (_is_default_cert (_dbmt_error) == 0) + { + return 1; + } + + if (file_copy (default_cert_path, default_backup_cert_path) != 0) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, + "Failed to backup SSL certification file: %s.", + sco.szSSLCertificate); + return 1; + } + return 0; +} + +static int +_recover_cert (char *_dbmt_error) +{ + char default_cert_path[PATH_MAX]; + char default_backup_cert_path[PATH_MAX]; + + default_cert_path[0] = '\0'; + default_backup_cert_path[0] = '\0'; + + /*Check the validation of backup certification file */ + if (_is_exist_default_backup_cert (_dbmt_error) != 1) + { + return 1; + } + + snprintf (default_cert_path, PATH_MAX, "%s", sco.szSSLCertificate); + if (access (default_cert_path, F_OK) == 0) + { + if (uRemoveDir (default_cert_path, REMOVE_DIR_FORCED) != ERR_NO_ERROR) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, + "Cannot delete SSL certification file: %s.", + sco.szSSLCertificate); + return 1; + } + } + + snprintf (default_backup_cert_path, PATH_MAX, "%s.bak", + sco.szSSLCertificate); + if (file_copy (default_backup_cert_path, default_cert_path) != 0) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, + "Failed to recover SSL certification file: %s.", + sco.szSSLCertificate); + return 1; + } + return 0; +} + +int +ts_generate_cert (nvplist *req, nvplist *res, char *_dbmt_error) +{ + BIO *bio_err = NULL; + X509 *x509 = NULL; + EVP_PKEY *pub_key = NULL; + FILE *keyfile = NULL; + FILE *crtfile = NULL; + char keyfilepath[PATH_MAX], crtfilepath[PATH_MAX]; + int ret_val = ERR_NO_ERROR; + + keyfilepath[0] = '\0'; + crtfilepath[0] = '\0'; + + CRYPTO_mem_ctrl (CRYPTO_MEM_CHECK_ON); + + bio_err = BIO_new_fp (stderr, BIO_NOCLOSE); + + /*Backup default certification file. */ + + if (_is_exist_default_backup_cert (_dbmt_error) != 1) + { + if (_backup_cert (_dbmt_error) != 0) + { + ret_val = ERR_WITH_MSG; + goto release_src; + } + } + + ret_val = _make_cert (req, &x509, &pub_key, RSA_KEY_SIZE, _dbmt_error); + if (ret_val != ERR_NO_ERROR) + { + goto release_src; + } + + snprintf (keyfilepath, PATH_MAX, "%s", sco.szSSLKey); + if ((keyfile = fopen (keyfilepath, "w")) == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", sco.szSSLKey); + ret_val = ERR_FILE_OPEN_FAIL; + goto release_src; + } + PEM_write_PrivateKey (keyfile, pub_key, NULL, NULL, 0, NULL, NULL); + fclose (keyfile); + + snprintf (crtfilepath, PATH_MAX, "%s", sco.szSSLCertificate); + if ((crtfile = fopen (crtfilepath, "w")) == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", sco.szSSLCertificate); + ret_val = ERR_FILE_OPEN_FAIL; + goto release_src; + } + if (PEM_write_X509 (crtfile, x509) != 1) + { + _recover_cert (_dbmt_error); + ret_val = ERR_WITH_MSG; + goto release_src; + } + +release_src: + if (crtfile != NULL) + { + fclose (crtfile); + } + if (x509 != NULL) + { + X509_free (x509); + } + if (pub_key != NULL) + { + EVP_PKEY_free (pub_key); + } + +#ifndef OPENSSL_NO_ENGINE + ENGINE_cleanup (); +#endif + CRYPTO_cleanup_all_ex_data (); + if (pub_key != NULL) + { + BIO_free (bio_err); + } + return ret_val; +} + +int +ts_start_statdump (nvplist *req, nvplist *res, char *_dbmt_error) +{ + int ret_val = ERR_NO_ERROR; + char *db_name, *interval_str; + int interval = 0; + char *argv [10]; + char path [512]; + int argc = 0; + char note [20]; + int slot = -1; + db_name = nv_get_val (req, "_DBNAME"); + interval_str = nv_get_val (req, "interval"); + if (!interval_str || !db_name) + { + nv_update_val (res, "note", "no sufficient arguments"); + LOG_ERROR ("start_statdump: dbname or interval was not specified"); + return -1; + } + + if (find_statdumpd_info (db_name) >= 0) + { + nv_update_val (res, "note", "already running"); + return -1; + } + + slot = find_new_statdumpd_info (); + if (slot < 0) + { + nv_update_val (res, "note", "memory allocation error"); + return -1; + } + strcpy (statdump_daemon[slot].dbname, db_name); + interval = atoi (interval_str); + arniadb_cmd_name (path); + + argv[argc++] = path; + argv[argc++] = "statdump"; + argv[argc++] = "-i"; + argv[argc++] = interval_str; + argv[argc++] = db_name; + argv[argc++] = NULL; + +#if defined (WINDOWS) + ret_val = run_child (argv, 0, NULL, NULL, NULL, NULL); +#else + ret_val = run_child (argv, 0, NULL, "/dev/null", "/dev/null", NULL); +#endif + + if (ret_val < 0) + { + nv_update_val (res, "note", "could not execute statdump"); + return -1; + } + + statdump_daemon[slot].status = STATD_RUNNING; + statdump_daemon[slot].pid = ret_val; + nv_update_val (res, "note", db_name); + nv_update_val (res, "status", "success"); + nv_add_nvp_int (res, "pid", ret_val); + + return 0; +} + +extern int errno; + +int +ts_stop_statdump (nvplist *req, nvplist *res, char *_dbmt_error) +{ + int ret_val = ERR_NO_ERROR; + char *db_name; + int slot; + char cmd [1024]; + int ret; + + db_name = nv_get_val (req, "_DBNAME"); + if (!db_name || (slot = find_statdumpd_info (db_name)) < 0) + { + nv_update_val (res, "note", "no statdump running"); + nv_update_val (res, "status", "failed"); + return -1; + } + + nv_update_val (res, "note", db_name); + +#if defined (WINDOWS) + sprintf (cmd, "taskkill /T /F /PID %d", statdump_daemon[slot].pid); +#else + sprintf (cmd, "/bin/ps -o pid --ppid %d | grep -v PID | xargs kill", statdump_daemon[slot].pid); +#endif + + ret_val = system (cmd); + +#if !defined (WINDOWS) + /* + * Double check if the process is still running. + */ + if (ret_val < 0) + { + sprintf (cmd, "/bin/ps -p %d", statdump_daemon[slot].pid); + ret = system (cmd); + if (ret < 0) + { + ret_val = 0; + } + else + { + nv_add_nvp (res, "Linux_error", strerror (errno)); + } + } +#endif + + if (ret_val < 0) + { + nv_add_nvp_int (res, "pid", statdump_daemon[slot].pid); + nv_update_val (res, "status", "failed"); + return ret_val; + } + + statdump_daemon[slot].status = STATD_IDLE; + nv_update_val (res, "status", "success"); + return ret_val; +} + +int +find_new_statdumpd_info () +{ + int i; + if (statdump_daemon == NULL) + { + statdump_daemon = (T_STATDUMP_STAT *) calloc (sizeof(T_STATDUMP_STAT), MAX_STATDUMP_PROC); + if (statdump_daemon == NULL) + { + return -1; + } + else + { + return 0; + } + } + for (i = 0; i < MAX_STATDUMP_PROC; i++) + { + if (statdump_daemon[i].status == STATD_IDLE) + { + return i; + } + } + return -3; +} + +int +find_statdumpd_info (char *dbname) +{ + int i; + + if (statdump_daemon == NULL) + { + return -1; + } + for (i = 0; i < MAX_STATDUMP_PROC; i++) + { + if (statdump_daemon[i].status == STATD_RUNNING && strcmp (statdump_daemon[i].dbname, dbname) == 0) + { + return i; + } + } + return -1; +} + + +static int +_hash_cert (char *hash_value, char *file_path) +{ + MD5_CTX mdContext; + unsigned char data[RSA_KEY_SIZE]; + unsigned char md5_final[MD5_DIGEST_LENGTH]; + char md5_final_hex[MD5_DIGEST_LENGTH]; + int bytes = 0; + int i = 0; + FILE *inFile = NULL; + + if ((inFile = fopen (file_path, "rb")) == NULL) + { + return 1; + } + + MD5_Init (&mdContext); + + while ((bytes = (int) fread (data, 1, RSA_KEY_SIZE, inFile)) != 0) + { + MD5_Update (&mdContext, data, bytes); + } + MD5_Final (md5_final, &mdContext); + fclose (inFile); + + for (i = 0; i < MD5_DIGEST_LENGTH; i++) + { + snprintf (md5_final_hex, 3, "%x", md5_final[i]); + strncat (hash_value, md5_final_hex, 3); + } + return 0; +} + +static int +_is_default_cert (char *_dbmt_error) +{ + char new_hash_value[33]; + char default_cert_path[PATH_MAX]; + const char *default_hash_file = "df6a39a5565f858e40b6a7a3b0dee779"; + int compare_ret = 0; + + new_hash_value[0] = '\0'; + default_cert_path[0] = '\0'; + + snprintf (default_cert_path, PATH_MAX, "%s", sco.szSSLCertificate); + + if (_hash_cert (new_hash_value, default_cert_path) != 0) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, + "Fail to get the value of SSL certification file."); + return -1; + } + + compare_ret = + strncmp (default_hash_file, new_hash_value, strlen (new_hash_value)); + + if (compare_ret == 0) + { + return 1; + } + return 0; +} + +static int +_is_exist_default_backup_cert (char *_dbmt_error) +{ + char new_hash_value[33]; + char default_backup_cert_path[PATH_MAX]; + const char *default_hash_file = "df6a39a5565f858e40b6a7a3b0dee779"; + int compare_ret = 0; + + new_hash_value[0] = '\0'; + default_backup_cert_path[0] = '\0'; + + snprintf (default_backup_cert_path, PATH_MAX, "%s.bak", + sco.szSSLCertificate); + + if (access (default_backup_cert_path, F_OK) != 0) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, + "Cannot find the backup SSL certification file: %s.", + default_backup_cert_path); + return -1; + } + + if (_hash_cert (new_hash_value, default_backup_cert_path) != 0) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, + "Fail to get the value of backup SSL certification file."); + return -1; + } + + compare_ret = + strncmp (default_hash_file, new_hash_value, strlen (new_hash_value)); + + if (compare_ret == 0) + { + return 1; + } + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, + "(%s) is not default backup SSL certification file.", + default_backup_cert_path); + return 0; +} diff --git a/server/src/am_job_task.h b/server/src/am_job_task.h new file mode 100644 index 0000000..544a909 --- /dev/null +++ b/server/src/am_job_task.h @@ -0,0 +1,439 @@ +/* + * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. + * + * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + + +/* + * cm_job_task.h - + */ + +#ifndef _CM_JOB_TASK_H_ +#define _CM_JOB_TASK_H_ + +#if defined(WINDOWS) +#include +#endif + +#include "cm_dep.h" + +#define DBMT_ERROR_MSG_SIZE 5000 + +#ifndef TASKNAME_LEN +#define TASKNAME_LEN 50 +#endif + +#ifndef SIZE_BUFFER_MAX +#define SIZE_BUFFER_MAX 1024 +#endif + +#define SET_TRANSACTION_NO_WAIT_MODE_ENV() \ + do { \ + putenv((char *) "ARNIADB_LOCK_TIMEOUT_IN_SECS=1"); \ + putenv((char *) "ARNIADB_ISOLATION_LEVEL=TRAN_READ_COMMITTED"); \ + } while (0) + +typedef enum +{ + TS_UNDEFINED, + TS_STARTINFO, + TS_USERINFO, + TS_CREATEUSER, + TS_DELETEUSER, + TS_CREATEDB, + TS_DELETEDB, + TS_RENAMEDB, + TS_STARTDB, + TS_STOPDB, + TS_UPDATEUSER, + TS_DBSPACEINFO, + TS_CLASSINFO, + TS_CLASS, + TS_RENAMECLASS, + TS_DROPCLASS, + TS_SETSYSPARAM, + TS_GETALLSYSPARAM, + TS_ADDVOLDB, + TS_CREATECLASS, + TS_CREATEVCLASS, + TS_GETLOGINFO, + TS_VIEWLOG, + TS_RESETLOG, + TS_ADDATTRIBUTE, + TS_DROPATTRIBUTE, + TS_UPDATEATTRIBUTE, + TS_ADDCONSTRAINT, + TS_DROPCONSTRAINT, + TS_ADDSUPER, + TS_DROPSUPER, + TS_GETSUPERCLASSESINFO, + TS_ADDRESOLUTION, + TS_DROPRESOLUTION, + TS_ADDMETHOD, + TS_DROPMETHOD, + TS_UPDATEMETHOD, + TS_ADDMETHODFILE, + TS_DROPMETHODFILE, + TS_ADDQUERYSPEC, + TS_DROPQUERYSPEC, + TS_CHANGEQUERYSPEC, + TS_VALIDATEQUERYSPEC, + TS_VALIDATEVCLASS, + TS_COPYDB, + TS_OPTIMIZEDB, + TS_STATDUMP, + TS_CHECKDB, + TS_COMPACTDB, + TS_BACKUPDBINFO, + TS_BACKUPDB, + TS_UNLOADDB, + TS_UNLOADDBINFO, + TS_LOADDB, + TS_GETTRANINFO, + TS_KILLTRAN, + TS_LOCKDB, + TS_GETBACKUPLIST, + TS_RESTOREDB, + TS_BACKUPVOLINFO, + TS_GETDBSIZE, + TS_GETDBMTUSERINFO, + TS_DELETEDBMTUSER, + TS_UPDATEDBMTUSER, + TS_SETDBMTPASSWD, + TS_ADDDBMTUSER, + TS_GETBACKUPINFO, + TS_ADDBACKUPINFO, + TS_DELETEBACKUPINFO, + TS_SETBACKUPINFO, + TS_GETDBERROR, + TS_GETAUTOADDVOL, + TS_SETAUTOADDVOL, + TS_GENERALDBINFO, + TS_LOADACCESSLOG, + TS_GETACCESSLOGFILES, + TS_GETERRORLOGFILES, + TS_CHECKDIR, + TS_AUTOBACKUPDBERRLOG, + TS_AUTOEXECQUERYERRLOG, + TS_KILL_PROCESS, + TS_GETENV, + TS_GETACCESSRIGHT, + TS_GETADDVOLSTATUS, + TS_GETHISTORY, + TS_SETHISTORY, + TS_GETHISTORYFILELIST, + TS_READHISTORYFILE, + TS_CHECKAUTHORITY, + TS_GETAUTOADDVOLLOG, + TS2_GETINITUNICASINFO, + TS2_GETUNICASINFO, + TS2_STARTUNICAS, + TS2_STOPUNICAS, + TS2_GETADMINLOGINFO, + TS2_GETLOGFILEINFO, + TS2_ADDBROKER, + TS2_GETADDBROKERINFO, + TS2_DELETEBROKER, + TS2_RENAMEBROKER, + TS2_GETBROKERSTATUS, + TS2_GETBROKERCONF, + TS2_GETBROKERONCONF, + TS2_SETBROKERCONF, + TS2_SETBROKERONCONF, + TS2_STARTBROKER, + TS2_STOPBROKER, + TS2_SUSPENDBROKER, + TS2_RESUMEBROKER, + TS2_BROKERJOBFIRST, + TS2_BROKERJOBINFO, + TS2_ADDBROKERAS, + TS2_DROPBROKERAS, + TS2_RESTARTBROKERAS, + TS2_GETBROKERSTATUSLOG, + TS2_GETBROKERMCONF, + TS2_SETBROKERMCONF, + TS2_GETBROKERASLIMIT, + TS2_GETBROKERENVINFO, + TS2_SETBROKERENVINFO, + TS2_ACCESSLISTADDIP, + TS2_ACCESSLISTDELETEIP, + TS2_ACCESSLISTINFO, + TS_CHECKFILE, + TS_REGISTERLOCALDB, + TS_REMOVELOCALDB, + TS_ADDNEWTRIGGER, + TS_ALTERTRIGGER, + TS_DROPTRIGGER, + TS_GETTRIGGERINFO, + TS_GETFILE, + TS_GETAUTOEXECQUERY, + TS_SETAUTOEXECQUERY, + TS_GETDIAGINFO, + TS_GET_DIAGDATA, + TS_GET_BROKER_DIAGDATA, + TS_ADDSTATUSTEMPLATE, + TS_REMOVESTATUSTEMPLATE, + TS_UPDATESTATUSTEMPLATE, + TS_GETSTATUSTEMPLATE, + TS_GETCASLOGFILELIST, + TS_ANALYZECASLOG, + TS_EXECUTECASRUNNER, + TS_REMOVECASRUNNERTMPFILE, + TS_GETCASLOGTOPRESULT, + TS_DBMTUSERLOGIN, + TS_CHANGEOWNER, + TS_REMOVE_LOG, + TS_PARAMDUMP, + TS_PLANDUMP, + TS_GETHOSTSTAT, + TS_GETDBPROCSTAT, + TS_CHANGEMODE, + TS_HEARTBEAT_LIST, + TS_HEARTBEAT_DEACT, + TS_HEARTBEAT_ACT, + TS_GET_STANDBY_SERVER_STAT, + TS_GETDBMODE, + TS_ROLE_CHANGE, + TS_USER_VERIFY, + TS_RUN_SCRIPT, + TS_GET_FOLDERS_WITH_KEYWORD, + TS_WRITE_AND_SAVE_CONF, + TS_RUN_SQL_STATEMENT, + TS_COPY_FOLDER, + TS_DELETE_FOLDER, + TS_GET_FILE_TOTAL_LINE_NUM, + TS_GET_ENVVAR_BY_NAME, + TS_ERROR_TRACE, + TS_LOGIN, + TS_LOGOUT, + TS_GET_AMS_ENV, + TS_KEEPALIVE, + TS_REMOVE_FILES, + TS_JOB_TEST, + TS_DB_SPACE_INFO, + TS_SHARD_START, + TS_SHARD_STOP, + TS_GET_SHARD_INFO, + TS_GET_SHARD_STATUS, + TS_BROKER_CHANGER, + TS_HA_START, + TS_HA_STOP, + TS_HA_STATUS, + TS_HA_APPLYLOGDB, + TS_HA_COPYLOGDB, + TS_HA_RELOAD, + TS_LIST_DIR, + TS_AUTO_UPDATE, + TS_IS_UPDATE_SUCCESS, + TS_MONITOR_PROCESS, + TS_GENERATE_CERT, + TS_START_STATDUMP, + TS_STOP_STATDUMP +} T_TASK_CODE; + +typedef enum +{ + FSVR_NONE, + FSVR_SA, + FSVR_CS, + FSVR_SA_CS, + FSVR_UC, + FSVR_SA_UC +} T_FSVR_TYPE; + +typedef int (*T_TASK_FUNC) (nvplist *req, nvplist *res, char *_dbmt_error); + +typedef unsigned int T_USER_AUTH; + +enum +{ + AU_DBC = 1, + AU_DBO = 2, + AU_BRK = 4, + AU_MON = 8, + AU_JOB = 16, + AU_VAR = 32, + AU_ADMIN = (1u << (sizeof (unsigned) * 8 - 1)) +}; + +#define ALL_AUTHORITY (AU_DBC | AU_DBO | AU_MON | AU_JOB | AU_BRK | AU_VAR) + +typedef struct +{ + const char *task_str; + int task_code; + char access_log_flag; + T_TASK_FUNC task_func; + T_FSVR_TYPE fsvr_type; + T_USER_AUTH user_auth; + +} T_FSERVER_TASK_INFO; + +int ts_userinfo (nvplist *in, nvplist *out, char *_dbmt_error); +int ts_create_user (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_delete_user (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_update_user (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_class_info (nvplist *in, nvplist *out, char *_dbmt_error); +int ts_class (nvplist *in, nvplist *out, char *_dbmt_error); +int ts_update_attribute (nvplist *in, nvplist *out, char *_dbmt_error); +int ts2_get_unicas_info (nvplist *in, nvplist *out, char *_dbmt_error); +int ts2_start_unicas (nvplist *in, nvplist *out, char *_dbmt_error); +int ts2_stop_unicas (nvplist *in, nvplist *out, char *_dbmt_error); +int ts2_get_admin_log_info (nvplist *in, nvplist *out, char *_dbmt_error); +int ts2_get_logfile_info (nvplist *in, nvplist *out, char *_dbmt_error); +int ts2_get_add_broker_info (nvplist *in, nvplist *out, char *_dbmt_error); +int ts2_delete_broker (nvplist *in, nvplist *out, char *_dbmt_error); +int ts2_get_broker_status (nvplist *in, nvplist *out, char *_dbmt_error); +int ts2_set_broker_conf (nvplist *in, nvplist *out, char *_dbmt_error); +int ts2_start_broker (nvplist *in, nvplist *out, char *_dbmt_error); +int ts2_stop_broker (nvplist *in, nvplist *out, char *_dbmt_error); +int ts2_restart_broker_as (nvplist *in, nvplist *out, char *_dbmt_error); +int ts_set_sysparam (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_get_all_sysparam (nvplist *req, nvplist *res, char *_dbmt_error); +int tsCreateDBMTUser (nvplist *req, nvplist *res, char *_dbmt_error); +int tsDeleteDBMTUser (nvplist *req, nvplist *res, char *_dbmt_error); +int tsUpdateDBMTUser (nvplist *req, nvplist *res, char *_dbmt_error); +int tsChangeDBMTUserPasswd (nvplist *req, nvplist *res, char *_dbmt_error); +int tsGetDBMTUserInfo (nvplist *req, nvplist *res, char *_dbmt_error); +int tsCreateDB (nvplist *req, nvplist *res, char *_dbmt_error); +int tsDeleteDB (nvplist *req, nvplist *res, char *_dbmt_error); +int tsRenameDB (nvplist *req, nvplist *res, char *_dbmt_error); +int tsStartDB (nvplist *req, nvplist *res, char *_dbmt_error); +int tsStopDB (nvplist *req, nvplist *res, char *_dbmt_error); +int tsDbspaceInfo (nvplist *req, nvplist *res, char *_dbmt_error); +int tsRunAddvoldb (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_copydb (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_optimizedb (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_plandump (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_paramdump (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_statdump (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_checkdb (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_compactdb (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_backupdb (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_unloaddb (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_loaddb (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_restoredb (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_backup_vol_info (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_get_dbsize (nvplist *req, nvplist *res, char *_dbmt_error); +int tsGetEnvironment (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_startinfo (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_kill_process (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_backupdb_info (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_unloaddb_info (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_get_backup_info (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_set_backup_info (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_add_backup_info (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_delete_backup_info (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_get_log_info (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_view_log (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_reset_log (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_get_autostart_db (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_set_autostart_db (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_get_auto_add_vol (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_set_auto_add_vol (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_get_addvol_status (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_get_tran_info (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_killtran (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_lockdb (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_get_backup_list (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_load_access_log (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_get_access_log_files (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_get_error_log_files (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_check_dir (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_get_autobackupdb_error_log (nvplist *req, nvplist *res, + char *_dbmt_error); +int ts_get_autoexecquery_error_log (nvplist *req, nvplist *res, + char *_dbmt_error); +int tsGetAutoaddvolLog (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_check_file (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_trigger_operation (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_get_triggerinfo (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_set_autoexec_query (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_get_autoexec_query (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_get_diagdata (nvplist *req, nvplist *res, char *diag_error); +int ts_get_broker_diagdata (nvplist *req, nvplist *res, char *diag_error); +int ts_addstatustemplate (nvplist *req, nvplist *res, char *diag_error); +int ts_removestatustemplate (nvplist *req, nvplist *res, char *diag_error); +int ts_updatestatustemplate (nvplist *req, nvplist *res, char *diag_error); +int ts_getstatustemplate (nvplist *req, nvplist *res, char *diag_error); +#if 0 /* ACTIVITY_PROFILE */ +int ts_addactivitytemplate (nvplist *req, nvplist *res, char *diag_error); +int ts_removeactivitytemplate (nvplist *req, nvplist *res, + char *diag_error); +int ts_updateactivitytemplate (nvplist *req, nvplist *res, + char *diag_error); +int ts_getactivitytemplate (nvplist *req, nvplist *res, char *diag_error); +#endif +int ts_analyzecaslog (nvplist *req, nvplist *res, char *diag_error); +int ts_executecasrunner (nvplist *req, nvplist *res, char *diag_error); +int ts_removecasrunnertmpfile (nvplist *req, nvplist *res, + char *diag_error); +int ts_getcaslogtopresult (nvplist *cli_request, nvplist *cli_response, + char *diag_error); +int ts_get_ldb_class_att (nvplist *req, nvplist *res, char *_dbmt_error); +int tsDBMTUserLogin (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_remove_log (nvplist *in, nvplist *out, char *_dbmt_error); +int ts_get_host_stat (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_get_dbproc_stat (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_changemode (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_heartbeat_list (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_get_standby_server_stat (nvplist *req, nvplist *res, + char *_dbmt_error); +int ts_get_db_mode (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_role_change (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_user_verify (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_write_and_save_conf (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_run_sql_statement (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_get_folders_with_keyword (nvplist *req, nvplist *res, + char *_dbmt_error); +int ts_run_script (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_copy_folder (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_delete_folder (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_get_file_total_line_num (nvplist *req, nvplist *res, + char *_dbmt_error); +int ts_get_envvar_by_name (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_error_trace (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_login (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_logout (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_get_ams_env (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_keepalive (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_remove_files (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_job_test (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_dbs_spaceInfo (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_shard_start (nvplist *req, nvplist *res, char *err_buf); +int ts_shard_stop (nvplist *req, nvplist *res, char *err_buf); +int ts_get_shard_info (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_get_shard_status (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_broker_changer (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_ha_start (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_ha_stop (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_ha_status (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_ha_reload (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_ha_applylogdb (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_ha_copylogdb (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_list_dir (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_auto_update (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_is_update_success (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_monitor_process (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_generate_cert (nvplist *req, nvplist *res, char *_dbmt_error); +int +ts_add_nvp_time (nvplist *ref, const char *name, time_t t, const char *fmt, + int type); +int ts_start_statdump (nvplist *req, nvplist *res, char *_dbmt_error); +int ts_stop_statdump (nvplist *req, nvplist *res, char *_dbmt_error); + +#endif /* _CM_JOB_TASK_H_ */ diff --git a/server/src/am_log.h b/server/src/am_log.h new file mode 100644 index 0000000..15922e0 --- /dev/null +++ b/server/src/am_log.h @@ -0,0 +1,515 @@ +/* + * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. + * + * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + + +#ifndef __CM_LOG__H__ +#define __CM_LOG__H__ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(WINDOWS) +#include +#include +#else +#include +#include +#include +#include +#include +#include /* opendir() ... */ +#endif + +#include "cm_config.h" + +using namespace std; + +#define DEFAULT_LOG_LEVEL xINFO + +#ifdef WINDOWS +#define mutex_t CRITICAL_SECTION +#define mutex_init(mutex) InitializeCriticalSection(&mutex) +#define mutex_lock(mutex) EnterCriticalSection(&mutex) +#define mutex_unlock(mutex) LeaveCriticalSection(&mutex) +#define mutex_destory(mutex) DeleteCriticalSection(&mutex) +#else +#define mutex_t pthread_mutex_t +#define mutex_init(mutex) pthread_mutex_init(&mutex, NULL) +#define mutex_lock(mutex) pthread_mutex_lock(&mutex) +#define mutex_unlock(mutex) pthread_mutex_unlock(&mutex) +#define mutex_destory(mutex) pthread_mutex_destroy(&mutex) +#endif + +#define MAX_DATE_TIME_LENGTH 128 + +class CLog +{ + public: + enum LOGLEVEL + { + xFATAL = 0, + xERROR = 1, + xWARN = 2, + xINFO = 3, + xDEBUG = 4, + }; + + protected: + CLog () + { + sLogLevel = CLog::xINFO; + m_lTruncate = sco.iMaxLogFileSize; + m_pLogFile = fopen (sco.szAccessLog, "a"); + m_pErrFile = fopen (sco.szErrorLog, "a"); + mutex_init (m_cs); + }; + + CLog (bool bappend, LOGLEVEL loglevel = + CLog::DEFAULT_LOG_LEVEL, long maxloglen = sco.iMaxLogFileSize) + { + sLogLevel = loglevel; + m_lTruncate = maxloglen; + + m_pLogFile = fopen (sco.szAccessLog, bappend ? "a" : "w"); + m_pErrFile = fopen (sco.szErrorLog, bappend ? "a" : "w"); + + mutex_init (m_cs); + } + + public: + ~CLog () + { + if (m_pLogFile) + { + fclose (m_pLogFile); + m_pLogFile = NULL; + } + + if (m_pErrFile) + { + fclose (m_pErrFile); + m_pErrFile = NULL; + } + + mutex_destory (m_cs); + } + + private: + LOGLEVEL _logLevel () + { + return sLogLevel; + } + + string _get_format_time () + { + char buff[MAX_DATE_TIME_LENGTH] = "unkonwn"; + time_t lt; + time (<); + tm *t = localtime (<); + if (t) + { + strftime (buff, MAX_DATE_TIME_LENGTH, "%Y%m%d %H:%M:%S", t); + } + return string (buff); + } + + void + _init_file_hander (void) + { + if (m_pLogFile != NULL) + { + fclose (m_pLogFile); + m_pLogFile = NULL; + } + if (m_pErrFile != NULL) + { + fclose (m_pErrFile); + m_pErrFile = NULL; + } + } + + void + _get_current_time_year_mon_day_hour_minute_second (char *current_time) + { + time_t cur_time; + + time (&cur_time); + strftime (current_time, MAX_DATE_TIME_LENGTH, "%Y%m%d%H%M%S", localtime (&cur_time)); + } + +#if defined(WINDOWS) + unsigned int + _get_files_count (list < string > &files_list, const char *roor_dir, string special_key = "") + { + HANDLE handle; + WIN32_FIND_DATA ffd; + char find_path[PATH_MAX]; + string ams_log_name; + + snprintf (find_path, PATH_MAX, "%s/*", roor_dir); + + handle = FindFirstFile (find_path, &ffd); + if (handle == INVALID_HANDLE_VALUE) + { + return 0; + } + while (FindNextFile (handle, &ffd)) + { + if (ffd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN + || ffd.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) + { + continue; + } + else if (! (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) + { + ams_log_name = ffd.cFileName; + if (special_key.length() == 0) + { + files_list.push_back (ams_log_name); + } + else + { + if (ams_log_name.find (special_key) < ams_log_name.length()) + { + files_list.push_back (ams_log_name); + } + } + } + } + FindClose (handle); + + return (unsigned int) files_list.size(); + } + +#else + + unsigned int + _get_files_count (list < string > &files_list, const char *roor_dir, string special_key = "") + { + DIR *dirptr = NULL; + struct dirent *entry; + string ams_log_name; + + if ((dirptr = opendir (roor_dir)) == NULL) + { + return 0; + } + while ((entry = readdir (dirptr)) != NULL) + { + if (strcmp (entry->d_name, ".") == 0 || strcmp (entry->d_name, "..") == 0) + { + continue; + } + + ams_log_name = entry->d_name; + + if (special_key.length() == 0) + { + files_list.push_back (ams_log_name); + } + else + { + if (ams_log_name.find (special_key) < ams_log_name.length()) + { + + files_list.push_back (ams_log_name); + } + } + } + + closedir (dirptr); + return files_list.size(); + } +#endif + + void + _remove_oldest_file (list < string > &files_list) + { + list < string >::iterator itor; + list < string > files_mtime_list; + char log_full_path[PATH_MAX]; + char oldest_file[PATH_MAX]; + struct stat st; + long oldest_time = LONG_MAX; + + char log_path[PATH_MAX]; + snprintf (log_path, PATH_MAX, "%s/%s", sco.szArniadb, DBMT_LOG_DIR); + + if (files_list.empty() == true) + { + return; + } + + for (itor = files_list.begin(); itor != files_list.end(); itor++) + { + snprintf (log_full_path, PATH_MAX, "%s/%s", log_path, (*itor).c_str()); + stat (log_full_path, &st); + if ((long) st.st_mtime < oldest_time) + { + oldest_time = (long) st.st_mtime; + snprintf (oldest_file, PATH_MAX, "%s", log_full_path); + } + } + + unlink (oldest_file); + } + + bool + _backup_log_files (char *base_log_path, string error_log_name, string log_name) + { + int ret_backup_log = -1; + int ret_backup_err = -1; + char backup_log_name[PATH_MAX]; + char backup_err_name[PATH_MAX]; + char cur_time[MAX_DATE_TIME_LENGTH]; + + backup_log_name[0] = '\0'; + backup_err_name[0] = '\0'; + cur_time[0] = '\0'; + + _get_current_time_year_mon_day_hour_minute_second (cur_time); + snprintf (backup_err_name, PATH_MAX, "%s/%s.%s", base_log_path, error_log_name.c_str(), cur_time); + snprintf (backup_log_name, PATH_MAX, "%s/%s.%s", base_log_path, log_name.c_str(), cur_time); + + ret_backup_log = rename (sco.szAccessLog, backup_log_name); + ret_backup_err = rename (sco.szErrorLog, backup_err_name); + + if ((ret_backup_log == -1) || (ret_backup_err == -1)) + { + return false; + } + return true; + } + + + public: + + static CLog *GetInstance (unsigned int logLevel) + { + static CLog *instance_log = NULL; + static CLog *instance_err = NULL; + + if ((logLevel <= CLog::xWARN) && (logLevel >= CLog::xFATAL)) + { + // write log into error log file + + if ((instance_err == NULL) || (access (sco.szErrorLog, F_OK) < 0)) + { + instance_err = new CLog (TRUE); + } + return instance_err; + } + else + { + // write log into normal log file + if ((instance_log == NULL) || (access (sco.szAccessLog, F_OK) < 0)) + { + instance_log = new CLog (TRUE); + } + return instance_log; + } + } + + void setLogLevel (const unsigned int level) + { + sLogLevel = (LOGLEVEL) level; + } + + void formatLog (const int iPriority, const char *fmt, ...) + { + char log_path[PATH_MAX]; + list < string > log_files_list; + + string error_log_name = "arn_manager.err"; + string log_name = "arn_manager.log"; + + log_path[0] = '\0'; + snprintf (log_path, PATH_MAX, "%s/%s", sco.szArniadb, DBMT_LOG_DIR); + + //check log level + if (iPriority > _logLevel ()) + { + return; + } + + //format log message + const char *strLevel; + bool isErrorLog = false; + switch (iPriority) + { + case CLog::xFATAL: + strLevel = "FATAL"; + isErrorLog = true; + break; + case CLog::xERROR: + strLevel = "ERROR"; + isErrorLog = true; + break; + case CLog::xWARN: + strLevel = " WARN"; + isErrorLog = true; + break; + case CLog::xINFO: + strLevel = " INFO"; + break; + case CLog::xDEBUG: + default: + strLevel = "DEBUG"; + break; + } + + if (isErrorLog == true) + { + if (m_pErrFile == NULL) + { + return; + } + } + else + { + if (m_pLogFile == NULL) + { + return; + } + } + + //format log data + size_t size = 1024; + char *buffer = new char[size]; + memset (buffer, 0, size); + + while (1) + { + va_list args; + va_start (args, fmt); +#ifdef _WIN32 + int n = _vsnprintf (buffer, size, fmt, args); +#else + int n = vsnprintf (buffer, size, fmt, args); +#endif + va_end (args); + if ((n > -1) && (static_cast < size_t > (n) < size)) + { + break; + } + + size = (n > -1) ? n + 1 : size * 2; + delete[]buffer; + buffer = new char[size]; + memset (buffer, 0, size); + } + + bool shouldBackupFiles = false; + + if (isErrorLog == true) + { + mutex_lock (m_cs); + + fprintf (m_pErrFile, "[%s] [%s] [%6d] %s\n", + _get_format_time ().c_str (), strLevel, getpid (), buffer); + fflush (m_pErrFile); + + if (ftell (m_pErrFile) > m_lTruncate) + { + shouldBackupFiles = true; + } + mutex_unlock (m_cs); + } + else + { + mutex_lock (m_cs); + + fprintf (m_pLogFile, "[%s] [%s] [%6d] %s\n", + _get_format_time ().c_str (), strLevel, getpid (), buffer); + + fflush (m_pLogFile); + + if (ftell (m_pLogFile) > m_lTruncate) + { + shouldBackupFiles = true; + } + mutex_unlock (m_cs); + } + + // backup log when the file grow too large + if (shouldBackupFiles == true) + { + mutex_lock (m_cs); + + // init open file - close them firstly + _init_file_hander (); + + // then move the arn_manager.log into new name log file. + _backup_log_files (log_path, error_log_name, log_name); + + // remove the oldest file + if (_get_files_count (log_files_list, log_path, error_log_name) > (unsigned int) sco.iMaxLogFiles) + { + _remove_oldest_file (log_files_list); + } + + log_files_list.clear(); + // remove the oldest file + if (_get_files_count (log_files_list, log_path, log_name) > (unsigned int) sco.iMaxLogFiles) + { + _remove_oldest_file (log_files_list); + } + mutex_unlock (m_cs); + } + delete[]buffer; + } + + private: + LOGLEVEL sLogLevel; + mutex_t m_cs; + FILE *m_pLogFile; + FILE *m_pErrFile; + long m_lTruncate; + +}; + +#define STRINGIZE2(s) #s +#define STRINGIZE(s) STRINGIZE2(s) + +#ifndef LogPrefix +#define LogPrefix(fmt) std::string("[").append(__FUNCTION__).append(":").append(STRINGIZE(__LINE__)).append("] ").append(fmt).c_str() +#endif + +#define LOG_DEBUG(fmt, ...) \ + CLog::GetInstance(CLog::xDEBUG)->formatLog(CLog::xDEBUG, LogPrefix(fmt), ##__VA_ARGS__) + +#define LOG_INFO(fmt, ...) \ + CLog::GetInstance(CLog::xINFO)->formatLog(CLog::xINFO, LogPrefix(fmt), ##__VA_ARGS__) + +#define LOG_WARN(fmt, ...) \ + CLog::GetInstance(CLog::xWARN)->formatLog(CLog::xWARN, LogPrefix(fmt), ##__VA_ARGS__) + +#define LOG_ERROR(fmt, ...) \ + CLog::GetInstance(CLog::xERROR)->formatLog(CLog::xERROR, LogPrefix(fmt), ##__VA_ARGS__) + +#define LOG_FATAL(fmt, ...) \ + CLog::GetInstance(CLog::xFATAL)->formatLog(CLog::xFATAL, LogPrefix(fmt), ##__VA_ARGS__) + +#endif diff --git a/server/src/am_mailer.h b/server/src/am_mailer.h new file mode 100644 index 0000000..e0af839 --- /dev/null +++ b/server/src/am_mailer.h @@ -0,0 +1,1913 @@ +// Note that the only valid version of the GPL as far as jwSMTP +// is concerned is v2 of the license (ie v2, not v2.2 or v3.x or whatever), +// unless explicitly otherwise stated. +// +// This file is part of the jwSMTP library. +// +// jwSMTP library 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; version 2 of the License. +// +// jwSMTP library 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 jwSMTP library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA +// +// jwSMTP library +// http://johnwiggins.net +// smtplib@johnwiggins.net +// +#ifndef __CM_MAILER_H__ +#define __CM_MAILER_H__ +#ifdef WIN32 +// std::vector This gives this warning in VC.. +// bloody annoying, there is a way round it according to MS. +// The debugger basically cannot browse anything with a name +// longer than 256 characters, "get with the template program MS". +#pragma warning( disable : 4786 ) +// tell the linker which libraries to find functions in +#include +#else +#include +#include +#include +#include +#include +typedef int SOCKET; // get round windows definitions. +#endif +#include +#include // ostrstream +#include // for localtime +#include +#include +#include + +namespace jwsmtp { + +// added the B64 to all members of the enum for SunOS (thanks Ken Weinert) +enum BASE64 +{ + B64_A, B64_B, B64_C, B64_D, B64_E, B64_F, B64_G, B64_H, B64_I, B64_J, B64_K, B64_L, B64_M, B64_N, B64_O, B64_P, B64_Q, B64_R, B64_S, B64_T, B64_U, B64_V, B64_W, B64_X, B64_Y, B64_Z, + B64_a, B64_b, B64_c, B64_d, B64_e, B64_f, B64_g, B64_h, B64_i, B64_j, B64_k, B64_l, B64_m, B64_n, B64_o, B64_p, B64_q, B64_r, B64_s, B64_t, B64_u, B64_v, B64_w, B64_x, B64_y, B64_z, + B64_0, B64_1, B64_2, B64_3, B64_4, B64_5, B64_6, B64_7, B64_8, B64_9, plus, slash, padding +}; + +char getbase64character(const char& in) +{ + switch(in) { + case B64_A: + return 'A'; + case B64_B: + return 'B'; + case B64_C: + return 'C'; + case B64_D: + return 'D'; + case B64_E: + return 'E'; + case B64_F: + return 'F'; + case B64_G: + return 'G'; + case B64_H: + return 'H'; + case B64_I: + return 'I'; + case B64_J: + return 'J'; + case B64_K: + return 'K'; + case B64_L: + return 'L'; + case B64_M: + return 'M'; + case B64_N: + return 'N'; + case B64_O: + return 'O'; + case B64_P: + return 'P'; + case B64_Q: + return 'Q'; + case B64_R: + return 'R'; + case B64_S: + return 'S'; + case B64_T: + return 'T'; + case B64_U: + return 'U'; + case B64_V: + return 'V'; + case B64_W: + return 'W'; + case B64_X: + return 'X'; + case B64_Y: + return 'Y'; + case B64_Z: + return 'Z'; + case B64_a: + return 'a'; + case B64_b: + return 'b'; + case B64_c: + return 'c'; + case B64_d: + return 'd'; + case B64_e: + return 'e'; + case B64_f: + return 'f'; + case B64_g: + return 'g'; + case B64_h: + return 'h'; + case B64_i: + return 'i'; + case B64_j: + return 'j'; + case B64_k: + return 'k'; + case B64_l: + return 'l'; + case B64_m: + return 'm'; + case B64_n: + return 'n'; + case B64_o: + return 'o'; + case B64_p: + return 'p'; + case B64_q: + return 'q'; + case B64_r: + return 'r'; + case B64_s: + return 's'; + case B64_t: + return 't'; + case B64_u: + return 'u'; + case B64_v: + return 'v'; + case B64_w: + return 'w'; + case B64_x: + return 'x'; + case B64_y: + return 'y'; + case B64_z: + return 'z'; + case B64_0: + return '0'; + case B64_1: + return '1'; + case B64_2: + return '2'; + case B64_3: + return '3'; + case B64_4: + return '4'; + case B64_5: + return '5'; + case B64_6: + return '6'; + case B64_7: + return '7'; + case B64_8: + return '8'; + case B64_9: + return '9'; + case plus: + return '+'; + case slash: + return '/'; + case padding: + return '='; + } + return '\0'; // ?????? yikes +} + +std::vector base64encode(const std::vector& input, const bool returns = true) { + std::vector output; + + // add a newline (SMTP demands less than 1000 characters in a message line). + long count = 0; + for(std::vector::size_type p = 0; p < input.size(); p+=3) { + output.push_back(getbase64character((input[p] & 0xFC) >> 2)); + ++count; + + if(p+1 < input.size()) { + output.push_back(getbase64character(((input[p] & 0x03) <<4) | ((input[p+1] & 0xF0) >> 4))); + ++count; + } + if(p+2 < input.size()) { + output.push_back(getbase64character(((input[p+1] & 0x0F) <<2) | ((input[p+2] & 0xC0) >>6))); + output.push_back(getbase64character((input[p+2] & 0x3F))); + ++count; + } + + if(p+1 == input.size()) { + output.push_back(getbase64character(((input[p] & 0x03) <<4))); + } + else if(p+2 == input.size()) { + output.push_back(getbase64character(((input[p+1] & 0x0F) <<2))); + } + + if(returns) { + // 79 characters on a line. + if(count > 75) { + output.push_back('\r'); + output.push_back('\n'); + count = 0; + } + } + } + + int pad(input.size() % 3); + if(pad) { + if(pad == 1) + pad = 2; + else + pad = 1; + } + for(int i = 0; i < pad; ++i) + output.push_back('='); + + return output; +} + +std::string base64encode(const std::string& input, const bool returns = true) { + std::vector in, out; + for(std::string::const_iterator it = input.begin(); it != input.end(); ++it) { + in.push_back(*it); + } + out = base64encode(in, returns); + std::string ret; + for(std::vector::const_iterator it1 = out.begin(); it1 != out.end(); ++it1) { + ret += *it1; + } + return ret; +} + +struct SOCKADDR_IN { + sockaddr_in ADDR; // we are wrapping this structure. + + // this is bad as we just assume that the address "addr" is valid here. + // need a real check and set ok appropriately +// SOCKADDR_IN(sockaddr_in addr):ADDR(addr), ok(true) {} + + SOCKADDR_IN(const std::string& address, unsigned short port, short family = AF_INET) { + ADDR.sin_port = port; + ADDR.sin_family = family; +#ifdef WIN32 + ADDR.sin_addr.S_un.S_addr = inet_addr(address.c_str()); + ok = (ADDR.sin_addr.S_un.S_addr != INADDR_NONE); +#else + ok = (inet_aton(address.c_str(), &ADDR.sin_addr)); +#endif + } + + SOCKADDR_IN(const SOCKADDR_IN& addr) { + ADDR = addr.ADDR; + ok = addr.ok; + } + SOCKADDR_IN operator = (const SOCKADDR_IN& addr) { + ADDR = addr.ADDR; + ok = addr.ok; + return *this; + } + + operator bool() const {return ok;} + + operator const sockaddr_in () const { + return ADDR; + } + operator const sockaddr () const { + sockaddr addr; + std::copy((char*)&ADDR, (char*)&ADDR + sizeof(ADDR), (char*)&addr); + return addr; + } + + size_t get_size() const {return sizeof(ADDR);} + char* get_sin_addr() { + return (char*)&ADDR.sin_addr; + } + void set_port(unsigned short newport) {ADDR.sin_port = newport;} + void set_ip(const std::string& newip) { +#ifdef WIN32 + ADDR.sin_addr.S_un.S_addr = inet_addr(newip.c_str()); + ok = (ADDR.sin_addr.S_un.S_addr != INADDR_NONE); +#else + ok = (inet_aton(newip.c_str(), &ADDR.sin_addr)); +#endif + } + void zeroaddress() { +#ifdef WIN32 + ADDR.sin_addr.S_un.S_addr = 0; +#else + ADDR.sin_addr.s_addr = 0; +#endif + } + +private: + bool ok; +}; + + +bool Connect(SOCKET sockfd, const SOCKADDR_IN& addr) { +#ifdef WIN32 + return bool(connect(sockfd, (sockaddr*)&addr, (int) addr.get_size()) != SOCKET_ERROR); +#else + return bool(connect(sockfd, (sockaddr*)&addr, addr.get_size()) == 0); +#endif +} + +bool Socket(SOCKET& s, int domain, int type, int protocol) { + s = socket(AF_INET, type, protocol); +#ifdef WIN32 + return bool(s != INVALID_SOCKET); +#else + return bool(s != -1); +#endif +} + +bool Send(int &CharsSent, SOCKET s, const char *msg, size_t len, int flags) { + CharsSent = send(s, msg, (int) len, flags); +#ifdef WIN32 + return bool((CharsSent != SOCKET_ERROR)); +#else + return bool((CharsSent != -1)); +#endif +} + +bool Recv(int &CharsRecv, SOCKET s, char *buf, size_t len, int flags) { + CharsRecv = recv(s, buf, (int) len, flags); +#ifdef WIN32 + return bool((CharsRecv != SOCKET_ERROR)); +#else + return bool((CharsRecv != -1)); +#endif +} + +// just wrap the call to shutdown the connection on a socket +// this way I don't have to call it this way everywhere. +void Closesocket(const SOCKET& s) { +#ifdef WIN32 + closesocket(s); +#else + close(s); +#endif +} + +// This does nothing on unix. +// for windoze only, to initialise networking, snore +void initNetworking() { +#ifdef WIN32 + class socks + { + public: + bool init() { + + WORD wVersionRequested; + WSADATA wsaData; + + wVersionRequested = MAKEWORD( 2, 0 ); + int ret = WSAStartup( wVersionRequested, &wsaData); + if(ret) + return false; + initialised = true; + return true; + } + bool IsInitialised() const {return initialised;} + socks():initialised(false){init();} + ~socks() + { + if(initialised) + shutdown(); + } + private: + void shutdown(){WSACleanup();} + bool initialised; + }; + static socks s; +#endif +} + + + + +class mailer +{ +public: + // if MXLookup is true: + // 'server' is a nameserver to lookup an MX record by. + // if MXLookup is false. + // 'server' is an SMTP server which will be attempted directly for mailing + // if an IP address is not found, either MX record or direct to SMTP server, + // an attempt will be made to send mail directly to the server in the mail address. + // e.g. mail to fred@somewhere.com will have a connection attempt made directly to: + // somewhere.com (which is probably wrong and therefore will still fail) + mailer(const char* TOaddress, const char* FROMaddress, + const char* Subject, const std::vector& Message, + const char* server = "127.0.0.1"/*default to localhost*/, + unsigned short Port = SMTP_PORT, // default SMTP port + bool MXLookup = true) : type(LOGIN), + subject(Subject), + server(getserveraddress(TOaddress)), + nameserver(server), + port(htons(Port)), // make the 'port' network byte order. + lookupMXRecord(MXLookup), + auth(false) { + // Parse the email addresses into an Address structure. + setsender(FROMaddress); + addrecipient(TOaddress); + setmessage(Message); + + initNetworking(); // in win32 init networking, else just does nothin' +}; + + mailer(const char* TOaddress, const char* FROMaddress, + const char* Subject, const char* Message, + const char* server = "127.0.0.1"/*default to localhost*/, + unsigned short Port = SMTP_PORT, // default SMTP port + bool MXLookup = true) : type(LOGIN), + subject(Subject), + server(getserveraddress(TOaddress)), + nameserver(server), + port(htons(Port)), // make the 'port' network byte order. + lookupMXRecord(MXLookup), + auth(false) { + // Parse the email addresses into an Address structure. + setsender(FROMaddress); + addrecipient(TOaddress); + setmessage(Message); + + initNetworking(); // in win32 init networking, else just does nothin' +}; + + // defaults to SMTP_PORT & no MX lookup. + // now we can do: + // mailer m; // mail an smtp server direct. + // mailer m2(true); // use MX lookup. + // mailer m2(false, weirdportnumber); // SMTP to a non standard port. + mailer(bool MXLookup = false, unsigned short Port = SMTP_PORT): + type(LOGIN), + port(htons(Port)), + lookupMXRecord(MXLookup), + auth(false) { + initNetworking(); // in win32 init networking, else just does nothin' +}; + + ~mailer() {}; + + // call this operator to have the mail mailed. + // This is to facilitate using multiple threads + // i.e. using boost::thread. (see http://www.boost.org) + // + // e.g. + // mailer mail(args...); + // boost::thread thrd(mail); // operator()() implicitly called. + // thrd.join(); // if needed. + // + // or: + // mailer mail(args...); + // mail.operator()(); + void operator()() { + returnstring = ""; // clear out any errors from previous use + + if(!recipients.size()) { + returnstring = "451 Requested action aborted: local error who am I mailing"; + return; + } + if(!fromAddress.address.length()) { + returnstring = "451 Requested action aborted: local error who am I"; + return; + } + if(!nameserver.length()) { + returnstring = "451 Requested action aborted: local error no SMTP/name server/smtp server"; + return; + } + + std::vector adds; + if(lookupMXRecord) { + if(!gethostaddresses(adds)) { + // error!! we are dead. + returnstring = "451 Requested action aborted: No MX records ascertained"; + return; + } + } + else { // connect directly to an SMTP server. + SOCKADDR_IN addr(nameserver, port, AF_INET); + hostent* host = 0; + if(addr) { + host = gethostbyaddr(addr.get_sin_addr(), sizeof(addr.ADDR.sin_addr), AF_INET); + } + else + host = gethostbyname(nameserver.c_str()); + if(!host) { + returnstring = "451 Requested action aborted: local error in processing"; + return; // error!!! + } + //memcpy(addr.get_sin_addr(), host->h_addr, host->h_length); + std::copy(host->h_addr_list[0], host->h_addr_list[0] + host->h_length, addr.get_sin_addr()); + adds.push_back(addr); + } + + SOCKET s; + if(!Socket(s, AF_INET, SOCK_STREAM, 0)) { + returnstring = "451 Requested action aborted: socket function error"; + return; + } + + if(!adds.size()) { // oops + returnstring = "451 Requested action aborted: No MX records ascertained"; + } + + const std::string OK("250"); + const std::vector smtpheader(makesmtpmessage()); + const int buffsize(1024); + char buff[buffsize] = ""; + + for(std::vector::const_iterator address = adds.begin(); + address < adds.end(); ++address) { + if(!Connect(s, *address)) { + returnstring = "554 Transaction failed: server connect error."; + continue; + } + + // 220 the server line returned here + int len1; + if(!Recv(len1, s, buff, buffsize -1, 0)) { + returnstring = "554 Transaction failed: server connect response error."; + continue; + } + + // get our hostname to pass to the smtp server + char hn[buffsize] = ""; + if(gethostname(hn, buffsize)) { + // no local hostname!!! make one up + strcpy(hn, "flibbletoot"); + } + std::string commandline(std::string("EHLO ") + hn + std::string("\r\n")); + // say hello to the server + + if(!Send(len1, s, commandline.c_str(), commandline.length(), 0)) { + returnstring = "554 Transaction failed: EHLO send"; + continue; + } + if(!Recv(len1, s, buff, buffsize -1, 0)) { + returnstring = "554 Transaction failed: EHLO receipt"; + continue; + } + + buff[len1] = '\0'; + std::string greeting = returnstring = buff; + if(returnstring.substr(0,3) != OK) { + if(auth) { + // oops no ESMTP but using authentication no go bail out! + returnstring = "554 possibly trying to use AUTH without ESMTP server, ERROR!"; + continue; + } + // maybe we only do non extended smtp + // send HELO instead. + commandline[0] = 'H'; + commandline[1] = 'E'; + if(!Send(len1, s, commandline.c_str(), commandline.length(), 0)) { + returnstring = "554 Transaction failed: HELO send"; + continue; + } + if(!Recv(len1, s, buff, buffsize -1, 0)) { + returnstring = "554 Transaction failed: HELO receipt"; + continue; + } + buff[len1] = '\0'; + + returnstring = buff; + if(returnstring.substr(0,3) != OK) { + // we must issue a quit even on an error. + // in keeping with the rfc's + if(Send(len1, s, "QUIT\r\n", 6, 0)) { + char dummy[buffsize]; + Recv(len1, s, dummy, buffsize -1, 0); + } + Closesocket(s); + // don't know what went wrong here if we are connected!! + // we continue because maybe we have more than 1 server to connect to. + continue; + } + } + + if(auth) + if(!authenticate(greeting, s)) + continue; // try the next server, you never know!! + + // MAIL + // S: MAIL FROM: + // R: 250 OK + // e.g. "MAIL FROM:\r\n" + // or "MAIL FROM: John Wiggins " + commandline = "MAIL FROM:<" + fromAddress.address + ">\r\n"; + if(!Send(len1, s, commandline.c_str(), commandline.length(), 0)) { + returnstring = "554 MAIL FROM sending error"; + continue; + } + + if(!Recv(len1, s, buff, buffsize -1, 0)) { + returnstring = "554 MAIL FROM receipt error"; + continue; + } + + buff[len1] = '\0'; + returnstring = buff; + if(returnstring.substr(0,3) != OK) { + // we must issue a quit even on an error. + // in keeping with the rfc's + if(Send(len1, s, "QUIT\r\n", 6, 0)) { + char dummy[buffsize]; + Recv(len1, s, dummy, buffsize -1, 0); + } + Closesocket(s); + // don't know what went wrong here if we are connected!! + // we continue because maybe we have more than 1 server to connect to. + continue; + } + + for(recipient_const_iter recip = recipients.begin(); recip < recipients.end(); ++recip) { + // RCPT + + // S: RCPT TO: + // R: 250 OK + commandline = "RCPT TO: <" + (*recip).first.address + ">\r\n"; + // S: RCPT TO: + // R: 550 No such user here + // + // S: RCPT TO: + // R: 250 OK + if(!Send(len1, s, commandline.c_str(), commandline.length(), 0)) { + returnstring = "554 Transaction failed"; + continue; + } + if(!Recv(len1, s, buff, buffsize -1, 0)) { + returnstring = buff; + continue; + } + buff[len1] = '\0'; + returnstring = buff; + if(returnstring.substr(0,3) != OK) { + // This particular recipient does not exist! + // not strictly an error as we may have more than one recipient + // we should have an error vector e.g. + // vector > errs; + // errs.push_back(make_pair(recip->first, returnstring)); + // + // we then need a function to return this vector. + // e.g. const vector >& getrecipienterrors(); + continue; + } + } + + // DATA + + // S: DATA + // R: 354 Start mail input; end with . + // S: Blah blah blah... + // S: ...etc. etc. etc. + + // S: . + // R: 250 OK + if(!Send(len1, s, "DATA\r\n", 6, 0)) { + returnstring = "554 DATA send error"; + continue; + } + if(!Recv(len1, s, buff, buffsize -1, 0)) { + returnstring = "554 DATA, server response error"; + continue; + } + buff[len1] = '\0'; + returnstring = buff; + if(returnstring.substr(0,3) != "354") { + // we must issue a quit even on an error. + // in keeping with the rfc's + + if(Send(len1, s, "QUIT\r\n", 6, 0)) { + char dummy[buffsize]; + Recv(len1, s, dummy, buffsize -1, 0); + } + Closesocket(s); + continue; + } + // Sending the email + /*if(!Send(len1, s, smtpheader.c_str(), smtpheader.length(), 0)) {*/ + if(!Send(len1, s, &smtpheader[0], smtpheader.size(), 0)) { + returnstring = "554 DATA, server response error (actual send)"; + continue; + } + if(!Recv(len1, s, buff, buffsize -1, 0)) { + returnstring = "554 DATA, server response error (actual send)"; + continue; + } + + // The server should give us a 250 reply if the mail was delivered okay + buff[len1] = '\0'; + returnstring = buff; + if(returnstring.substr(0,3) != OK) { + // we must issue a quit even on an error. + // in keeping with the rfc's + if(Send(len1, s, "QUIT\r\n", 6, 0)) { + char dummy[buffsize]; + Recv(len1, s, dummy, buffsize -1, 0); + } + Closesocket(s); + continue; + } + // hang up the connection + if(Send(len1, s, "QUIT\r\n", 6, 0)) { + char dummy[buffsize]; + Recv(len1, s, dummy, buffsize -1, 0); + } + + // Let the server give us our 250 reply. + //buff[len1] = '\0'; + //returnstring = buff; + + // for future reference the server is meant to give a 221 response to a quit. + if(returnstring.substr(0,3) != "221") { + // maybe will use this later + } + Closesocket(s); // disconnect + + // Let the server give us our 250 reply. + // don't continue as we have delivered the mail + // at this point just leave. all done + //returnstring = "250 Requested mail action okay, completed"; + break; + } +}; + void send() { + operator()(); +}; + + // attach a file to the mail. (MIME 1.0) + // returns false if !filename.length() or + // the file could not be opened for reading...etc. + bool attach(const std::string& filename) { + if(!filename.length()) // do silly checks. + return false; + + std::ifstream file(filename.c_str(), std::ios::binary | std::ios::in); + if(!file) + return false; + + std::vector filedata; + char c = file.get(); + for(; file.good(); c = file.get()) { + if(file.bad()) + break; + filedata.push_back(c); + } + + filedata = base64encode(filedata); + + std::string fn(filename); + std::string::size_type p = fn.find_last_of('/'); + if(p == std::string::npos) + p = fn.find_last_of('\\'); + if(p != std::string::npos) { + p +=1; // get past folder delimeter + fn = fn.substr(p, fn.length() - p); + } + + attachments.push_back(std::make_pair(filedata, fn)); + + return true; +}; + + // remove an attachment from the list of attachments. + // returns false if !filename.length() or + // the file is not attached or there are no attachments. + bool removeattachment(const std::string& filename) { + if(!filename.length()) // do silly checks. + return false; + + if(!attachments.size()) + return false; + + std::string fn(filename); + std::string::size_type p = fn.find_last_of('/'); + if(p == std::string::npos) + p = fn.find_last_of('\\'); + if(p != std::string::npos) { + p +=1; // get past folder delimeter + fn = fn.substr(p, fn.length() - p); + } + // fn is now what is stored in the attachments pair as the second parameter + // i.e. it->second == fn + std::vector, std::string> >::iterator it; + for(it = attachments.begin(); it < attachments.end(); ++it) { + if((*it).second == fn) { + attachments.erase(it); + return true; + } + } + return false; +}; + + // Set a new message (replacing the old) + // will return false and not change the message if newmessage is empty. + bool setmessage(const std::string& newmessage) { + if(!newmessage.length()) + return false; + + message.clear(); // erase the old message + for (std::string::size_type i = 0; i < newmessage.length(); ++i) + message.push_back(newmessage[i]); + + checkRFCcompat(); + + return true; +}; + bool setmessage(const std::vector& newmessage) { + if(!newmessage.size()) + return false; + + message = newmessage; + + checkRFCcompat(); + + return true; +}; + + // Set a new HTML message (replacing the old) + // will return false and not change the message if newmessage is empty. + bool setmessageHTML(const std::string& newmessage) { + if(!newmessage.length()) + return false; + + messageHTML.clear(); // erase the old message + for (std::string::size_type i = 0; i < newmessage.length(); ++i) + messageHTML.push_back(newmessage[i]); + messageHTML = base64encode(messageHTML); + + return true; +}; + bool setmessageHTML(const std::vector& newmessage) { + if(!newmessage.size()) + return false; + + messageHTML = base64encode(newmessage); + + return true; +}; + // use a file for the data + bool setmessageHTMLfile(const std::string& filename) { + if(!filename.length()) + return false; + + std::ifstream file(filename.c_str(), std::ios::binary | std::ios::in); + if(!file) + return false; + std::vector filedata; + char c = file.get(); + for(; file.good(); c = file.get()) { + if(file.bad()) + break; + filedata.push_back(c); + } + + messageHTML = base64encode(filedata); + + return true; +}; + + // Set a new Subject for the mail (replacing the old) + // will return false if newSubject is empty. + bool setsubject(const std::string& newSubject) { + if(!newSubject.length()) + return false; + + subject = newSubject; + return true; +}; + + // sets the nameserver or smtp server to connect to + // dependant on the constructor call, i.e. whether + // 'lookupMXRecord' was set to false or true. + // (see constructor comment for details) + bool setserver(const std::string& nameserver_or_smtpserver) { + if(!nameserver_or_smtpserver.length()) + return false; + + nameserver = nameserver_or_smtpserver; + return true; +}; + + // sets the senders address (fromAddress variable) + bool setsender(const std::string& newsender) { + if(!newsender.length()) + return false; + + Address newaddress(parseaddress(newsender)); + + fromAddress = newaddress; + return true; +}; + + // add a recipient to the recipient list. (maximum allowed recipients 100). + // returns true if the address could be added to the + // recipient list, otherwise false. + // recipient_type must be in the range mailer::TO -> mailer::BCC if + // not recipient_type defaults to BCC (blind copy), see const enum below. + bool addrecipient(const std::string& newrecipient, short recipient_type = TO /*CC, BCC*/) { + // SMTP only allows 100 recipients max at a time. + // rfc821 + if(recipients.size() >= 100) // == would be fine, but let's be stupid safe + return false; + + if(newrecipient.length()) { + // If there are no recipients yet + // set the server address for MX queries + if(!recipients.size()) { + server = getserveraddress(newrecipient); + } + + Address newaddress = parseaddress(newrecipient); + + if(recipient_type > Bcc || recipient_type < TO) + recipient_type = Bcc; // default to blind copy on error(hidden is better) + + recipients.push_back(std::make_pair(newaddress, recipient_type)); + return true; + } + return false; +}; + + // remove a recipient from the recipient list. + // returns true if the address could be removed from the + // recipient list, otherwise false. + bool removerecipient(const std::string& recipient) { + if(recipient.length()) { // there is something to remove + std::vector >::iterator it(recipients.begin()); + for(; it < recipients.end(); ++it) { + if((*it).first.address == recipient) { + recipients.erase(it); + return true; + } + } + // fall through as we did not find this recipient + } + return false; +}; + + // clear all recipients from the recipient list. + void clearrecipients() { + recipients.clear(); +}; + + // clear all attachments from the mail. + void clearattachments() { + attachments.clear(); +}; + + // clear all recipients, message, attachments, errors. + // does not reset the name/smtp server (use setserver for this) + // does not set the senders address (use setsender for this) + void reset() { + recipients.clear(); + attachments.clear(); + // fromAddress = ""; // assume the same sender. + // if this is to be changed use the setserver function to change it. + // nameserver = ""; // we don't do this as the same server is probably used!! + // leave auth type alone. + // leave username password pair alone. + server = ""; + message.clear(); + messageHTML.clear(); + returnstring = ""; // clear out any errors from previous use +}; + + // returns the return code sent by the smtp server or a local error. + // this is the only way to find if there is an error in processing. + // if the mail is sent correctly this string will begin with 250 + // see smtp RFC 821 section 4.2.2 for response codes. + const std::string& response() const { + return returnstring; +}; + + // Constants + // in unix we have to have a named object. + const static enum {TO, Cc, Bcc, SMTP_PORT = 25, DNS_PORT = 53} consts; + + // what type of authentication are we using. + // (if using authentication that is). + enum authtype {LOGIN = 1, PLAIN} type; + + // set the authentication type + // currently LOGIN or PLAIN only. + // The default login type is LOGIN, set in the constructor + void authtype(const enum authtype Type) { + assert(Type == LOGIN || Type == PLAIN); + type = Type; +}; + + // set the username for authentication. + // If this function is called with a non empty string + // jwSMTP will try to use authentication. + // To not use authentication after this, call again + // with the empty string e.g. + // mailerobject.username(""); + void username(const std::string& User) { + auth = (User.length() != 0); + user = User; +}; + // set the password for authentication + void password(const std::string& Pass) { + pass = Pass; +}; + +private: + // create a header with current message and attachments. + std::vector makesmtpmessage() const { + std::string sender(fromAddress.address); + if(sender.length()) { + std::string::size_type pos(sender.find("@")); + if(pos != std::string::npos) { //found the server beginning + sender = sender.substr(0, pos); + } + } + + std::vector ret; + std::string headerline; + if(fromAddress.name.length()) { + headerline = "From: " + fromAddress.address + " (" + fromAddress.name + ") \r\n" + "Reply-To: " + fromAddress.address + "\r\n"; + ret.insert(ret.end(), headerline.begin(), headerline.end()); + } + else { + headerline = "From: " + fromAddress.address + "\r\n" + "Reply-To: " + fromAddress.address + "\r\n"; + ret.insert(ret.end(), headerline.begin(), headerline.end()); + } + headerline.clear(); // clearout our temp variable + + // add the recipients to the header + std::vector to, cc, bcc; + for(recipient_const_iter recip = recipients.begin(); recip < recipients.end(); ++recip) { + if(recip->second == TO) { + to.push_back(recip->first.address); + } + else if(recip->second == Cc) { + cc.push_back(recip->first.address); + } + else if(recip->second == Bcc) { + bcc.push_back(recip->first.address); + } + } + vec_str_const_iter it; // instead of making three on the stack, just one (stops VC whining too) + // next section adds To: Cc: Bcc: lines to the header + int count = (int) to.size(); + if(count) + headerline += "To: "; + for(it = to.begin(); it < to.end(); ++it) { + headerline += *it; + if(count > 1 && ((it + 1) < to.end()) ) + headerline += ",\r\n "; // must add a space after the comma + else + headerline += "\r\n"; + } + count = (int) cc.size(); + if(count) + headerline += "Cc: "; + for(it = cc.begin(); it < cc.end(); ++it) { + headerline += *it; + if(count > 1 && ((it + 1) < cc.end()) ) + headerline += ",\r\n "; // must add a space after the comma + else + headerline += "\r\n"; + } + + // Remove insertion of the Bcc line into the header, I should never have done this, oopsy + // + //count = bcc.size(); + //if(count) + // headerline += "Bcc: "; + //for(it = bcc.begin(); it < bcc.end(); ++it) { + // headerline += *it; + // if(count > 1 && ((it + 1) < bcc.end()) ) + // headerline += ",\r\n "; // must add a space after the comma + // else + // headerline += "\r\n"; + //} + ret.insert(ret.end(), headerline.begin(), headerline.end()); + // end adding To: Cc: Bcc: lines to the header + + const std::string boundary("bounds=_NextP_0056wi_0_8_ty789432_tp"); + bool MIME(false); + if(attachments.size() || messageHTML.size()) + MIME = true; + + if(MIME) { // we have attachments + // use MIME 1.0 + headerline = "MIME-Version: 1.0\r\n" + "Content-Type: multipart/mixed;\r\n" + "\tboundary=\"" + boundary + "\"\r\n"; + ret.insert(ret.end(), headerline.begin(), headerline.end()); + headerline.clear(); + } + + /////////////////////////////////////////////////////////////////////////// + // add the current time. + // format is + // Date: 05 Jan 93 21:22:07 + // Date: 05 Jan 93 21:22:07 -0500 + // Date: 27 Oct 81 15:01:01 PST (RFC 821 example) + time_t t; + time(&t); + char timestring[128] = ""; + const char * timeformat = "Date: %d %b %y %H:%M:%S %Z"; + if(strftime(timestring, 127, timeformat, localtime(&t))) { // got the date + headerline = timestring; + headerline += "\r\n"; + ret.insert(ret.end(), headerline.begin(), headerline.end()); + } + /////////////////////////////////////////////////////////////////////////// + // add the subject + headerline = "Subject: " + subject + "\r\n\r\n"; + ret.insert(ret.end(), headerline.begin(), headerline.end()); + + /////////////////////////////////////////////////////////////////////////// + // + // everything else added is the body of the email message. + // + /////////////////////////////////////////////////////////////////////////// + + if(MIME) { + headerline = "This is a MIME encapsulated message\r\n\r\n"; + headerline += "--" + boundary + "\r\n"; + if(!messageHTML.size()) { + // plain text message first. + headerline += "Content-type: text/plain; charset=iso-8859-1\r\n" + "Content-transfer-encoding: 7BIT\r\n\r\n"; + + ret.insert(ret.end(), headerline.begin(), headerline.end()); + ret.insert(ret.end(), message.begin(), message.end()); + headerline = "\r\n\r\n--" + boundary + "\r\n"; + } + else { // make it multipart/alternative as we have html + const std::string innerboundary("inner_jfd_0078hj_0_8_part_tp"); + headerline += "Content-Type: multipart/alternative;\r\n" + "\tboundary=\"" + innerboundary + "\"\r\n"; + + // need the inner boundary starter. + headerline += "\r\n\r\n--" + innerboundary + "\r\n"; + + // plain text message first. + headerline += "Content-type: text/plain; charset=iso-8859-1\r\n" + "Content-transfer-encoding: 7BIT\r\n\r\n"; + ret.insert(ret.end(), headerline.begin(), headerline.end()); + ret.insert(ret.end(), message.begin(), message.end()); + headerline = "\r\n\r\n--" + innerboundary + "\r\n"; + /////////////////////////////////// + // Add html message here! + headerline += "Content-type: text/html; charset=iso-8859-1\r\n" + "Content-Transfer-Encoding: base64\r\n\r\n"; + + ret.insert(ret.end(), headerline.begin(), headerline.end()); + ret.insert(ret.end(), messageHTML.begin(), messageHTML.end()); + headerline = "\r\n\r\n--" + innerboundary + "--\r\n"; + + // end the boundaries if there are no attachments + if(!attachments.size()) + headerline += "\r\n--" + boundary + "--\r\n"; + else + headerline += "\r\n--" + boundary + "\r\n"; + /////////////////////////////////// + } + ret.insert(ret.end(), headerline.begin(), headerline.end()); + headerline.clear(); + + // now add each attachment. + for(vec_pair_char_str_const_iter it1 = attachments.begin(); + it1 != attachments.end(); ++ it1) { + if(it1->second.length() > 3) { // long enough for an extension + std::string typ(it1->second.substr(it1->second.length()-4, 4)); + if(typ == ".gif") { // gif format presumably + headerline += "Content-Type: image/gif;\r\n"; + } + else if(typ == ".jpg" || typ == "jpeg") { // j-peg format presumably + headerline += "Content-Type: image/jpg;\r\n"; + } + else if(typ == ".txt") { // text format presumably + headerline += "Content-Type: plain/txt;\r\n"; + } + else if(typ == ".bmp") { // windows bitmap format presumably + headerline += "Content-Type: image/bmp;\r\n"; + } + else if(typ == ".htm" || typ == "html") { // hypertext format presumably + headerline += "Content-Type: plain/htm;\r\n"; + } + else if(typ == ".png") { // portable network graphic format presumably + headerline += "Content-Type: image/png;\r\n"; + } + else if(typ == ".exe") { // application + headerline += "Content-Type: application/X-exectype-1;\r\n"; + } + else { // add other types + // everything else + headerline += "Content-Type: application/X-other-1;\r\n"; + } + } + else { + // default to don't know + headerline += "Content-Type: application/X-other-1;\r\n"; + } + + headerline += "\tname=\"" + it1->second + "\"\r\n"; + headerline += "Content-Transfer-Encoding: base64\r\n"; + headerline += "Content-Disposition: attachment; filename=\"" + it1->second + "\"\r\n\r\n"; + ret.insert(ret.end(), headerline.begin(), headerline.end()); + headerline.clear(); + + ret.insert(ret.end(), it1->first.begin(), it1->first.end()); + + // terminate the message with the boundary + "--" + if((it1 + 1) == attachments.end()) + headerline += "\r\n\r\n--" + boundary + "--\r\n"; + else + headerline += "\r\n\r\n--" + boundary + "\r\n"; + ret.insert(ret.end(), headerline.begin(), headerline.end()); + headerline.clear(); + } + } + else // just a plain text message only + ret.insert(ret.end(), message.begin(), message.end()); + + // end the data in the message. + headerline = "\r\n.\r\n"; + ret.insert(ret.end(), headerline.begin(), headerline.end()); + + return ret; +}; + + // this breaks a message line up to be less than 1000 chars per line. + // keeps words intact also --- rfc821 + // Check line returns are in the form "\r\n" + // (qmail balks otherwise, i.e. LAME server) + // also if a period is on a line by itself add a period + // stops prematurely ending the mail before whole message is sent. + void checkRFCcompat(){ + // Check the line breaks. + std::vector::iterator it; + for(it = message.begin(); it != message.end(); ++it) { + // look for \n add \r before if not there. Pretty lame but still. + // haven't thought of a better way yet. + if(*it == '\n') { + if(it == message.begin()) { + it = message.insert(it, '\r'); + ++it; // step past newline + continue; + } + if((*(it -1) != '\r') ) { + // add a return before '\n' + it = message.insert(it, '\r'); + ++it; // step past newline + } + } + } + + // if we get a period on a line by itself + // add another period to stop the server ending the mail prematurely. + // ( suggested by david Irwin ) + if(message.size() == 1) { + if(*(message.begin()) == '.') + message.push_back('.'); + } + else if(message.size() == 2) { + if(*(message.begin()) == '.') { + it = message.begin(); + it = message.insert(it, '.'); + } + } + else { + if(*(message.begin()) == '.') { + it = message.begin(); + it = message.insert(it, '.'); + } + for(it = message.begin()+2; it != message.end(); ++it) { + // follow the rfc. Add '.' if the first character on a line is '.' + if(*it == '\n') { + if( ((it + 1) != message.end()) && (*(it +1) == '.') ) { + it = message.insert(it + 1, '.'); + ++it; // step past + } + } + } + } + + // don't do anything if we are not longer than a 1000 characters + if(message.size() < 1000) + return; + + // now we have checked line breaks + // check line lengths. + int count(1); + for(it = message.begin(); it < message.end(); ++it, ++count) { + if(*it == '\r') { + count = 0; // reset for a new line. + ++it; // get past newline + continue; + } + else if(count >= 998) { + ++it; + if(*it != ' ') { // we are not in a word!! + // it should never get to message.begin() because we + // start at least 998 chars into the message! + // Also, assume a word isn't bigger than 997 chars! (seems reasonable) + std::vector::iterator pos = it; + for(int j = 0; j < 997; ++j, --pos) { + if(*pos == ' ') { + it = ++pos; // get past the space. + break; + } + } + } + if(it < message.end()) + it = message.insert(it, '\r'); + ++it; + if(it < message.end()) + it = message.insert(it, '\n'); + count = 0; // reset for a new line. + } + } + count=1; // reset the count + if(messageHTML.size()) { + for(it = messageHTML.begin(); it < messageHTML.end(); ++it, ++count) { + if(*it == '\r') { + count = 0; // reset for a new line. + ++it; // get past newline + continue; + } + else if(count >= 998) { + ++it; + if(*it != ' ') { // we are in a word!! + // it should never get to message.begin() because we + // start at least 998 chars into the message! + // Also, assume a word isn't bigger than 997 chars! (seems reasonable) + std::vector::iterator pos = it; + for(int j = 0; j < 997; ++j, --pos) { + if(*pos == ' ') { + it = ++pos; // get past the space. + break; + } + } + } + if(it < messageHTML.end()) + it = messageHTML.insert(it, '\r'); + ++it; + if(it < messageHTML.end()) + it = messageHTML.insert(it, '\n'); + count = 0; // reset for a new line. + } + } + } +}; + + // helper function. + // returns the part of the string toaddress after the @ symbol. + // i.e. the 'toaddress' is an email address eg. someone@somewhere.com + // this function returns 'somewhere.com' + std::string getserveraddress(const std::string& toaddress) const { + if(toaddress.length()) { + std::string::size_type pos(toaddress.find("@")); + if(pos != std::string::npos) { //found the server beginning + if(++pos < toaddress.length()) + return toaddress.substr(pos, toaddress.length()- pos); + } + } + return ""; +}; + + // Does the work of getting MX records for the server returned by 'getserveraddress' + // will use the dns server passed to this's constructor in 'nameserver' + // or if MXlookup is false in the constuctor, will return an address + // for the server that 'getserveraddress' returns. + // returns false on failure, true on success + bool gethostaddresses(std::vector& adds) { + adds.clear(); // be safe in case of my utter stupidity + + SOCKADDR_IN addr(nameserver, htons(DNS_PORT), AF_INET); + + hostent* host = 0; + if(addr) + host = gethostbyaddr(addr.get_sin_addr(), sizeof(addr.ADDR.sin_addr), AF_INET); + else + host = gethostbyname(nameserver.c_str()); + + if(!host) { // couldn't get to dns, try to connect directly to 'server' instead. + //////////////////////////////////////////////////////////////////////////////// + // just try to deliver mail directly to "server" + // as we didn't get an MX record. + // addr.sin_family = AF_INET; + addr = SOCKADDR_IN(server, port); + addr.ADDR.sin_port = port; // smtp port!! 25 + if(addr) { + host = gethostbyaddr(addr.get_sin_addr(), sizeof(addr.ADDR.sin_addr), AF_INET); + } + else + host = gethostbyname(server.c_str()); + + if(!host) { + returnstring = "550 Requested action not taken: mailbox unavailable"; + return false; // error!!! + } + + //memcpy((char*)&addr.sin_addr, host->h_addr, host->h_length); + std::copy(host->h_addr_list[0], host->h_addr_list[0] + host->h_length, addr.get_sin_addr()); + adds.push_back(addr); + + return true; + } + else + //memcpy((char*)&addr.sin_addr, host->h_addr, host->h_length); + std::copy(host->h_addr_list[0], host->h_addr_list[0] + host->h_length, addr.get_sin_addr()); + + SOCKET s; + if(!Socket(s, AF_INET, SOCK_DGRAM, 0)) { + returnstring = "451 Requested action aborted: socket function error"; + return false; + } + + if(!Connect(s, addr)) { + returnstring = "451 Requested action aborted: dns server unavailable"; + return false; // dns connection unavailable + } + + // dnsheader info id flags num queries + unsigned char dns[512] = {1,1, 1,0, 0,1, 0,0, 0,0, 0,0}; + int dnspos = 12; // end of dns header + std::string::size_type stringpos(0); + std::string::size_type next(server.find(".")); + if(next != std::string::npos) { // multipart name e.g. "aserver.somewhere.net" + while(stringpos < server.length()) { + std::string part(server.substr(stringpos, next-stringpos)); + dns[dnspos] = (unsigned char) part.length(); + ++dnspos; + for(std::string::size_type i = 0; i < part.length(); ++i, ++dnspos) { + dns[dnspos] = part[i]; + } + + stringpos = ++next; + next = server.find(".", stringpos); + if(next == std::string::npos) { + part = server.substr(stringpos, server.length() - stringpos); + dns[dnspos] = (unsigned char) part.length(); + ++dnspos; + for(std::string::size_type i = 0; i < part.length(); ++i, ++dnspos) { + dns[dnspos] = part[i]; + } + break; + } + } + } + else { // just a single part name. e.g. "aserver" + dns[dnspos] = (unsigned char) server.length(); + ++dnspos; + + for(std::string::size_type i = 0; i < server.length(); ++i, ++dnspos) { + dns[dnspos] = server[i]; + } + } + // in case the server string has a "." on the end + if(server[server.length()-1] == '.') + dns[dnspos] = 0; + else + dns[dnspos++] = 0; + + // add the class & type + dns[dnspos++] = 0; + dns[dnspos++] = 15; // MX record. + + dns[dnspos++] = 0; + dns[dnspos++] = 1; + + // used to have MSG_DONTROUTE this breaks obviously if you are not + // running a local nameserver and using it (as I used to do so I didn't + // notice until now, oops) + int ret; + if(!Send(ret, s, (char*)dns, dnspos, 0)) { + returnstring = "451 Requested action aborted: server seems to have disconnected."; + Closesocket(s); // clean up + return false; + } + if(Recv(ret, s, (char*)dns, 512, 0)) { + Closesocket(s); + // now parse the data sent back from the dns for MX records + if(dnspos > 12) { // we got more than a dns header back + unsigned short numsitenames = ((unsigned short)dns[4]<<8) | dns[5]; + unsigned short numanswerRR = ((unsigned short)dns[6]<<8) | dns[7]; + unsigned short numauthorityRR = ((unsigned short)dns[8]<<8) | dns[9]; + unsigned short numadditionalRR = ((unsigned short)dns[10]<<8) | dns[11]; + + if(!(dns[3] & 0x0F)) { // check for an error + // int auth((dns[2] & 0x04)); // AA bit. the nameserver has given authoritive answer. + int pos = 12; // start after the header. + + std::string questionname; + if(numsitenames) { + parsename(pos, dns, questionname); + pos += 4; // move to the next RR + } + + // This gives this warning in VC. + // bloody annoying, there is a way round it according to microsoft. + // The debugger basically cannot browse anything with a name + // longer than 256 characters, "get with the template program MS". + // #pragma warning( disable : 4786 ) + // #pragma warning( default : 4786 ) + std::vector names; + in_addr address; + std::string name; + // VC++ incompatability scoping + // num should be able to be declared in every for loop here + // not in VC + int num = 0; + for(; num < numanswerRR; ++num) { + name = ""; + parseRR(pos, dns, name, address); + if(name.length()) + names.push_back(name); + } + for(num = 0; num < numauthorityRR; ++num) { + name = ""; + parseRR(pos, dns, name, address); + if(name.length()) + names.push_back(name); + } + for(num = 0; num < numadditionalRR; ++num) { + name = ""; + parseRR(pos, dns, name, address); + if(name.length()) + names.push_back(name); + } + + // now get all the MX records IP addresess + addr.ADDR.sin_family = AF_INET; + addr.ADDR.sin_port = port; // smtp port!! 25 + hostent* host = 0; + for(vec_str_const_iter it = names.begin(); it < names.end(); ++it) { + host = gethostbyname(it->c_str()); + if(!host) { + addr.zeroaddress(); + continue; // just skip it!!! + } + std::copy(host->h_addr_list[0], host->h_addr_list[0] + host->h_length, addr.get_sin_addr()); + adds.push_back(addr); + } + // got the addresses + return true; + } + } + } + else + Closesocket(s); + // what are we doing here!! + return false; +}; + + // Parses a dns Resource Record (see TCP/IP illustrated, STEVENS, page 194) + bool parseRR(int& pos, const unsigned char dns[], std::string& name, in_addr& address) { + if(pos < 12) // didn,t get more than a header. + return false; + if(pos > 512) // oops. + return false; + + int len = dns[pos]; + if(len >= 192) { // pointer + int pos1 = dns[++pos]; + len = dns[pos1]; + } + else { // not a pointer. + parsename(pos, dns, name); + } + // If I do not seperate getting the short values to different + // lines of code, the optimizer in VC++ only increments pos once!!! + unsigned short a = ((unsigned short)dns[++pos]<<8); + unsigned short b = dns[++pos]; + unsigned short Type = a | b; + a = ((unsigned short)dns[++pos]<<8); + b = dns[++pos]; + // unsigned short Class = a | b; + pos += 4; // ttl + a = ((unsigned short)dns[++pos]<<8); + b = dns[++pos]; + unsigned short Datalen = a | b; + if(Type == 15) { // MX record + // first two bytes the precedence of the MX server + a = ((unsigned short)dns[++pos]<<8); + b = dns[++pos]; + // unsigned short order = a | b; // we don't use this here + len = dns[++pos]; + if(len >= 192) { + int pos1 = dns[++pos]; + parsename(pos1, dns, name); + } + else + parsename(pos, dns, name); + } + else if(Type == 12) { // pointer record + pos += Datalen+1; + } + else if(Type == 2) { // nameserver + pos += Datalen+1; + } + else if(Type == 1) { // IP address, Datalen should be 4. + pos += Datalen+1; + } + else { + pos += Datalen+1; + } + return true; +}; + + // Parses a dns name returned in a dns query (see TCP/IP illustrated, STEVENS, page 192) + void parsename(int& pos, const unsigned char dns[], std::string& name) { + int len = dns[pos]; + if(len >= 192) { + int pos1 = ++pos; + ++pos; + parsename(pos1, dns, name); + } + else { + for(int i = 0; i < len; ++i) + name += dns[++pos]; + len = dns[++pos]; + if(len != 0) + name += "."; + if(len >= 192) { + int pos1 = dns[++pos]; + ++pos; + parsename(pos1, dns, name); + } + else if(len > 0) { + parsename(pos, dns, name); + } + else if(len == 0) + ++pos; + } +}; + + // email address wrapper struct + struct Address { + std::string name; // e.g. freddy foobar + std::string address; // e.g. someone@mail.com + }; + + // authenticate against a server. + bool authenticate(const std::string& servergreeting, const SOCKET& s) { + assert(auth && user.length()); // shouldn't be calling this function if this is not set! + int len(0); + if(!user.length()) { // obvioulsy a big whoops + Send(len, s, "QUIT\r\n", 6, 0); + return false; + } + + // now parse the servergreeting looking for the auth type 'type' + // if 'type' is not present exit with error (return false) + std::string at; + if(type == LOGIN) + at = "LOGIN"; + else if(type == PLAIN) + at = "PLAIN"; + else { // oopsy no other auth types yet!! MUST BE A BUG + assert(false); + returnstring = "554 jwSMTP only handles LOGIN or PLAIN authentication at present!"; + Send(len, s, "QUIT\r\n", 6, 0); + return false; + } + + // uppercase servergreeting first. + std::string greeting(servergreeting); + //char ch; + for(std::string::size_type pos = 0; pos < greeting.length(); ++pos) { + //ch = greeting[pos]; + greeting[pos] = toupper(greeting[pos] /*ch*/); + } + if(greeting.find(at) == std::string::npos) { + returnstring = "554 jwSMTP only handles LOGIN or PLAIN authentication at present!"; + Send(len, s, "QUIT\r\n", 6, 0); + return false; // didn't find that type of login! + } + + // ok try and authenticate to the server. + const int buffsize(1024); + char buff[buffsize]; + if(type == LOGIN) { + greeting = "auth " + at + "\r\n"; + if(!Send(len, s, greeting.c_str(), greeting.length(), 0)) { + returnstring = "554 send failure: \"auth " + at + "\""; + return false; + } + if(!Recv(len, s, buff, buffsize, 0)) { + returnstring = "554 receive failure: waiting on username question!"; + return false; + } + buff[len] = '\0'; + returnstring = buff; + + // The server should give us a "334 VXNlcm5hbWU6" base64 username + if(returnstring.substr(0,16) != "334 VXNlcm5hbWU6") { + // returnstring = "554 Server did not return correct response to \'auth login\' command"; + Send(len, s, "QUIT\r\n", 6, 0); + return false; + } + greeting = base64encode(user, false) + "\r\n"; + if(!Send(len, s, greeting.c_str(), greeting.length(), 0)) { + returnstring = "554 send failure: sending username"; + return false; + } + // now get the password question + if(!Recv(len, s, buff, buffsize, 0)) { + returnstring = "554 receive failure: waiting on password question!"; + return false; + } + buff[len] = '\0'; + returnstring = buff; + // The server should give us a "334 UGFzc3dvcmQ6" base64 password + if(returnstring.substr(0,16) != "334 UGFzc3dvcmQ6") { + // returnstring = "554 Server did not return correct password question"; + Send(len, s, "QUIT\r\n", 6, 0); + return false; + } + greeting = base64encode(pass, false) + "\r\n"; + if(!Send(len, s, greeting.c_str(), greeting.length(), 0)) { + returnstring = "554 send failure: sending password"; + return false; + } + // now see if we are authenticated. + if(!Recv(len, s, buff, buffsize, 0)) { + returnstring = "554 receive failure: waiting on auth login response!"; + return false; + } + buff[len] = '\0'; + returnstring = buff; + if(returnstring.substr(0,3) == "235") + return true; + } + // PLAIN authetication + else if(type == PLAIN) { // else if not needed, being anal + // now create the authentication response and send it. + // username\0username\0password\r\n + // i.e. \0fred\0secret\r\n (blank identity) + std::vector enc; + std::string::size_type pos = 0; + for(; pos < user.length(); ++pos) + enc.push_back(user[pos]); + enc.push_back('\0'); + for(pos = 0; pos < user.length(); ++pos) + enc.push_back(user[pos]); + enc.push_back('\0'); + for(pos = 0; pos < pass.length(); ++pos) + enc.push_back(pass[pos]); + + enc = base64encode(enc, false); + greeting = "auth plain "; + for(std::vector::const_iterator it1 = enc.begin(); it1 < enc.end(); ++it1) + greeting += *it1; + greeting += "\r\n"; + + if(!Send(len, s, greeting.c_str(), greeting.length(), 0)) { + returnstring = "554 send failure: sending login:plain authenication info"; + return false; + } + if(!Recv(len, s, buff, buffsize, 0)) { + returnstring = "554 receive failure: waiting on auth plain autheticated response!"; + return false; + } + buff[len] = '\0'; + returnstring = buff; + if(returnstring.substr(0,3) == "235") + return true; + } + + // fall through return an error. + Send(len, s, "QUIT\r\n", 6, 0); + return false; +}; + + // less typing later, these are definately abominations! + typedef std::vector, std::string> >::const_iterator vec_pair_char_str_const_iter; + typedef std::vector >::const_iterator recipient_const_iter; + typedef std::vector >::iterator recipient_iter; + typedef std::vector::const_iterator vec_str_const_iter; + + // split an address into its relevant parts i.e. + // name and actual address and return it in Address. + // this may be usefull out of the class maybe + // it should be a static function or a global? thinking about it. + Address parseaddress(const std::string& addresstoparse) { + Address newaddress; // return value + + // do some silly checks + if(!addresstoparse.length()) + return newaddress; // its empty, oops (this should fail at the server.) + + if(!addresstoparse.find("@") == std::string::npos) { + // no '@' symbol (could be a local address, e.g. root) + // so just assume this. The SMTP server should just deny delivery if its messed up! + newaddress.address = addresstoparse; + return newaddress; + } + // we have one angle bracket but not the other + // (this isn't strictly needed, just thought i'd throw it in) + if(((addresstoparse.find('<') != std::string::npos) && + (addresstoparse.find('>') == std::string::npos)) || + ((addresstoparse.find('>') != std::string::npos) && + (addresstoparse.find('<') == std::string::npos))) { + return newaddress; // its empty, oops (this should fail at the server.) + } + + // we have angle bracketed delimitered address + // like this maybe: + // "foo@bar.com" + // or "foo bar " + // or " foo bar" + if((addresstoparse.find('<') != std::string::npos) && + (addresstoparse.find('>') != std::string::npos)) { + std::string::size_type sta = addresstoparse.find('<'); + std::string::size_type end = addresstoparse.find('>'); + + newaddress.address = addresstoparse.substr(sta + 1, end - sta - 1); + + if(sta > 0) { // name at the beginning + // we are cutting off the last character if the bracket address + // continues without a space into the bracketed address + // e.g. "hoopla girl" + // name becomes 'hoopla gir' + // Fix by David Irwin + // old code: + // end = sta -1; + // newaddress.name = addresstoparse.substr(0, end); + newaddress.name = addresstoparse.substr(0, sta); + return newaddress; + } + else { // name at the end + // no name to get + if(end >= addresstoparse.length()-1) + return newaddress; + + end += 2; + if(end >= addresstoparse.length()) + return newaddress; + + newaddress.name = addresstoparse.substr(end, addresstoparse.length()- end); + // remove whitespace from end if need be + if(newaddress.name[newaddress.name.length()-1] == ' ') + newaddress.name = newaddress.name.substr(0, newaddress.name.length()-1); + return newaddress; + } + } + // if we get here assume an address of the form: foo@bar.com + // and just save it. + newaddress.address = addresstoparse; + + return newaddress; +}; + + // The addresses to send the mail to + std::vector > recipients; + // The address the mail is from. + Address fromAddress; + // Subject of the mail + std::string subject; + // The contents of the mail message + std::vector message; + // The contents of the mail message in html format. + std::vector messageHTML; + // attachments: the file as a stream of char's and the name of the file. + std::vector, std::string> > attachments; + // This will be filled in from the toAddress by getserveraddress + std::string server; + // Name of a nameserver to query + std::string nameserver; + // The port to mail to on the smtp server. + const unsigned short port; + // use dns to query for MX records + const bool lookupMXRecord; + // using authentication + bool auth; + // username for authenticated smtp + std::string user; + // password for authenticated smtp + std::string pass; + // filled in with server return strings + std::string returnstring; +}; + +} // end namespace jwsmtp + +#endif // !ifndef __CM_MAILER_H__ diff --git a/server/src/am_mon_stat.cpp b/server/src/am_mon_stat.cpp new file mode 100644 index 0000000..42504ab --- /dev/null +++ b/server/src/am_mon_stat.cpp @@ -0,0 +1,1943 @@ +/* + * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. + * + * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#include + +#include "cm_log.h" +#include "json/json.h" +#include "cm_config.h" +#include "cm_job_task.h" +#include "cm_server_interface.h" +#include "cm_mon_stat.h" +#include "cm_server_extend_interface.h" + +#include +#include +#include + +using namespace std; + +#define DEFAULT_MON_STAT_INTERVAL 60 + +#define MON_DATA_BLOCK ((24 * 60 * 60) / _meta[K_INTERVAL].asInt() + 30 * 24 + 365) +/* MB_SIZE = 1024 * 1024 */ +#define MB_SIZE (1048576) + +// Initial metric value +#define INIT_METRIC_VALUE -1 + +/* monitoring data file names */ +#define META_NAME "meta.json" +#define BROKER_MON "broker_mon" +#define DB_MON "db_mon" +#define VOL_MON "vol_mon" +#define HA_MON "ha_mon" +#define OS_MON "os_mon" +/* end of monitoring data file names */ + +typedef struct +{ + const char *metric; + int pfactor; + bool ddiff; +} T_METRIC; + +/* broker metrics */ +/* two unused metrics*/ +#define BROKER_METRICS_LEN 10 + +#define BROKER_TPS "broker_tps" +#define BROKER_QPS "broker_qps" +#define BROKER_LONG_T "broker_long_t" +#define BROKER_LONG_Q "broker_long_q" +#define BROKER_REQ "broker_req" +#define BROKER_ERR_Q "broker_err_q" +#define BROKER_JQ "broker_jq" + +const T_METRIC BROKER_METRICS[BROKER_METRICS_LEN] = +{ + {BROKER_TPS, 1, true}, + {BROKER_QPS, 1, true}, + {BROKER_LONG_T, 1, true}, + {BROKER_LONG_Q, 1, true}, + {BROKER_REQ, 1, true}, + {BROKER_ERR_Q, 1, true}, + {BROKER_JQ, 1, false}, + {"none1", 1, false}, + {"none2", 1, false}, + {"uptime", 1, false} // uptime must be the last one +}; + +/* DB metrics */ +/* two unused metrics */ +#define DB_METRICS_LEN 19 + +#define DB_CPU_KERNEL "db_cpu_kernel" +#define DB_CPU_USER "db_cpu_user" +#define DB_MEM_PHY "db_mem_phy" +#define DB_MEM_VIR "db_mem_vir" +#define DB_QPS "db_qps" +#define DB_TPS "db_tps" +#define DB_HIT_RATIO "db_hit_ratio" +#define DB_FETCH_PAGES "db_fetch_pages" +#define DB_DIRTY_PAGES "db_dirty_pages" +#define DB_IO_READ "db_io_read" +#define DB_IO_WRITE "db_io_write" +/* HA metrics for DB */ +#define DB_HA_COPY_DELAY_PAGE "db_ha_copy_delay_page" +#define DB_HA_COPY_DELAY_ESTIMATED "db_ha_copy_delay_estimated" +#define DB_HA_APPLY_DELAY_PAGE "db_ha_apply_delay_page" +#define DB_HA_APPLY_DELAY_ESTIMATED "db_ha_apply_delay_estimated" + +#define DB_FREESPACE "db_freespace" + +const T_METRIC DB_METRICS[DB_METRICS_LEN] = +{ + {DB_CPU_KERNEL, 1, true}, + {DB_CPU_USER, 1, true}, + {DB_MEM_PHY, 100, false}, + {DB_MEM_VIR, 100, false}, + {DB_QPS, 1, true}, + {DB_TPS, 1, true}, + {DB_HIT_RATIO, 1, false}, + {DB_FETCH_PAGES, 1, true}, + {DB_DIRTY_PAGES, 1, true}, + {DB_IO_READ, 1, true}, + {DB_IO_WRITE, 1, true}, + {DB_HA_COPY_DELAY_PAGE, 1, true}, + {DB_HA_COPY_DELAY_ESTIMATED, 1, false}, + {DB_HA_APPLY_DELAY_PAGE, 1, true}, + {DB_HA_APPLY_DELAY_ESTIMATED, 1, false}, + {DB_FREESPACE, 100, false}, + {"none1", 1, false}, + {"none2", 1, false}, + {"uptime", 1, false} // uptime must be the last one +}; + +// volume free sapce is a special metrics for DB +#define VOL_FREESPACE "vol_freespace" +#define VOL_METRICS_LEN 2 + +/* OS metrics */ +/* two unused metrics */ +#define OS_METRICS_LEN 10 + +#define OS_CPU_IDLE "os_cpu_idle" +#define OS_CPU_IOWAIT "os_cpu_iowait" +#define OS_CPU_KERNEL "os_cpu_kernel" +#define OS_CPU_USER "os_cpu_user" +#define OS_MEM_PHY_FREE "os_mem_phy_free" +#define OS_MEM_SWAP_FREE "os_mem_swap_free" +#define OS_DISK_FREE "os_disk_free" + +const T_METRIC OS_METRICS[OS_METRICS_LEN] = +{ + {OS_CPU_IDLE, 1, true}, + {OS_CPU_IOWAIT, 1, true}, + {OS_CPU_KERNEL, 1, true}, + {OS_CPU_USER, 1, true}, + {OS_MEM_PHY_FREE, 100, false}, + {OS_MEM_SWAP_FREE, 100, false}, + {OS_DISK_FREE, 100, false}, + {"none1", 1, false}, + {"none2", 1, false}, + {"uptime", 1, false} // uptime must be the last one +}; + +/* end metrics define */ + +/* meta key word */ +#define K_INTERVAL "k_interval" +#define K_TOTAL_VOL_NUM "k_total_vol_num" + +#define K_BROKER_METRICS "k_broker_metrics" +#define K_BROKER_NUM "k_broker_num" +#define K_BROKER_RRD "k_broker_rrd" + +#define K_DB_METRICS "k_db_metrics" +#define K_DB_NUM "k_db_num" +#define K_DB_RRD "k_db_rrd" + +#define K_OS_METRICS "k_os_metrics" +#define K_OS_RRD "k_os_rrd" + +#define K_BROKER_HOUR_AGG_TIME "k_broker_hour_agg_time" +#define K_DB_HOUR_AGG_TIME "k_db_hour_agg_time" +#define K_OS_HOUR_AGG_TIME "k_os_hour_agg_time" + +#define K_BROKER_DAILY_AGG_TIME "k_broker_daily_agg_time" +#define K_DB_DAILY_AGG_TIME "k_db_daily_agg_time" +#define K_OS_DAILY_AGG_TIME "k_os_daily_agg_time" +/* end meta key word */ + +#define JSON_ATOI(x) (atoi((x).asString().c_str())) +#if defined(WINDOWS) +#define JSON_ATOL(x) (_atoi64((x).asString().c_str())) +#define CPU_BASE_FEQ_WIN 1000000 +#else +#define JSON_ATOL(x) (atoll((x).asString().c_str())) +#endif + +static bool init_rrdfile (string filename, int rrdsize, int metrics_len); +static bool get_rrdfile (string filename, int rrdpos, int *buf, int bufsize, int metrics_len); +static bool append_rrdfile (string filename, int rrdsize, int metrics_len); +static bool update_rrdfile (string filename, int rrdpos, int *buf, int bufsize, int mlen); +static bool call_task (Json::Value &req, Json::Value &res, T_TASK_FUNC func, string &errmsg); +static bool get_dbs_list (Json::Value &db_list); +static bool get_active_dbs_list (Json::Value &db_list); +static bool get_brokers_list (Json::Value &brokers_list); +static bool get_volume_list (string dbname, Json::Value &vol_list); +static void mon_last (int *buf, int bufsize, int *agg_data, int idx, int mlen, int pfactor = 1); +static void mon_avg (int *buf, int bufsize, int *agg_data, int idx, int mlen, int pfactor = 1); +static void mon_diff_avg (int *buf, int bufsize, int *agg_data, int idx, int mlen, int interval, int pfactor = 1); +static bool call_task_ext (Json::Value &req, Json::Value &res, T_EXT_TASK_FUNC func); +static bool mdtype_from_str (const string &dtype, MDTYPE &mdtype); + +class scope_lock +{ + public: + scope_lock (MUTEX_T &mutex):_mutex (mutex) + { + MUTEX_LOCK (_mutex); + } + ~scope_lock() + { + MUTEX_UNLOCK (_mutex); + } + private: + MUTEX_T _mutex; +}; + +cm_mon_stat *cm_mon_stat::_instance = NULL; + +cm_mon_stat::cm_mon_stat (string data_path): + _data_path (data_path + "/"), + _meta_file (_data_path + META_NAME) +{ + _daily_idx = -1; + _monthly_idx = -1; + _yearly_idx = -1; + _prev_gather = 0; + _init = false; + MUTEX_INIT (_data_mutex); +} + +cm_mon_stat *cm_mon_stat::get_instance() +{ + if (NULL == _instance) + { + _instance = new cm_mon_stat (sco.sMonStatDataPath); + } + return _instance; +} + +bool cm_mon_stat::get_mon_interval (time_t &interval) const +{ + if (true == _init) + { + interval = _meta[K_INTERVAL].asInt(); + return true; + } + else + { + return false; + } +} + +bool cm_mon_stat::set_mon_interval (time_t interval) +{ + if (false == _init) + { + return false; + } + if (_meta[K_INTERVAL].asInt() == interval) + { + return true; + } + try + { + return reset_meta ((int) interval); + } + catch (exception &) + { + return false; + } +} + +bool cm_mon_stat::initial() +{ + try + { + if (access (_meta_file.c_str(), F_OK) < 0) /* file not exist */ + { + _init = init_meta (DEFAULT_MON_STAT_INTERVAL); + } + else + { + _init = load_meta_file(); + } + } + catch (exception &) + { + _init = false; + } + return _init; +} + +void cm_mon_stat::gather_mon_data (void) +{ + + time_t gather_time = time (NULL); + //try { + if ((0 != _prev_gather) + && (gather_time - _prev_gather < _meta[K_INTERVAL].asInt())) + { + return; + } + if (false == _init) + { + LOG_WARN ("monitoring statistic module is not initialized"); + return; + } + scope_lock slocker (_data_mutex); + + if (false == get_dbs_list (_dbs)) + { + LOG_WARN ("get dbs list failed, time=[%d]", gather_time); + return; + } + + if (false == get_brokers_list (_brokers)) + { + LOG_WARN ("get brokers list failed, time=[%d]", gather_time); + return; + } + + + gather_daily_brokers_mon (gather_time); + gather_daily_dbs_mon (gather_time); + gather_daily_os_mon (gather_time); + _daily_idx = (gather_time % (60 * 60 * 24)) / _meta[K_INTERVAL].asInt(); + + aggregate_2_hour (gather_time); + _monthly_idx = (gather_time % ( 30 * 60 * 60 * 24)) / 3600; + + aggregate_2_day (gather_time); + _yearly_idx = (gather_time % ( 365 * 60 * 60 * 24)) / (3600 * 24); + + _prev_gather = gather_time; + //} + //catch (...) { + // LOG_WARN("gather_mon_data end with exception, time=[%d]", gather_time); + //} +} + +void cm_mon_stat::aggregate_2_hour (time_t gather_time) +{ + int monthly_idx = (gather_time % ( 30 * 60 * 60 * 24)) / 3600; + int buf_base = 3600/_meta[K_INTERVAL].asInt(); + int read_offset = 0; + + if (0 == _daily_idx) + { + read_offset += (23 * 3600) / _meta[K_INTERVAL].asInt(); + } + else + { + read_offset += _daily_idx - (3600 / _meta[K_INTERVAL].asInt()); + } + + int write_offset = 24 * 3600 / _meta[K_INTERVAL].asInt() + monthly_idx; + + aggregate_brokers (read_offset, buf_base, write_offset, HOUR, gather_time); + aggregate_dbs (read_offset, buf_base, write_offset, HOUR, gather_time); + aggregate_os (read_offset, buf_base, write_offset, HOUR, gather_time); +} + +void cm_mon_stat::aggregate_2_day (time_t gather_time) +{ + int yearly_idx = (gather_time % ( 365 * 60 * 60 * 24)) / (3600 * 24); + int buf_base = 24; + int read_offset = 24 * 3600 /_meta[K_INTERVAL].asInt(); + + if (0 == _monthly_idx) + { + read_offset += 29 * 24; + } + else + { + read_offset += _monthly_idx - 24; + } + + int write_offset = 24 * 3600 / _meta[K_INTERVAL].asInt() + 30 * 24 + yearly_idx; + + aggregate_brokers (read_offset, buf_base, write_offset, DAY, gather_time); + aggregate_dbs (read_offset, buf_base, write_offset, DAY, gather_time); + aggregate_os (read_offset, buf_base, write_offset, DAY, gather_time); +} + +void cm_mon_stat::aggregate_os (int read_offset, + int buf_base, + int write_offset, + AGG_TYPE atype, + time_t gather_time) +{ + string key; + int mod = 0; + if (HOUR == atype) + { + key = K_OS_HOUR_AGG_TIME; + mod = 3600; + } + else + { + key = K_OS_DAILY_AGG_TIME; + mod = 3600 * 24; + } + + if (Json::Value::null != _meta[key]) + { + time_t last_time = _meta[key].asInt(); + if (last_time / mod >= gather_time / mod) + { + return; + } + } + int bufsize = buf_base * OS_METRICS_LEN; + int *buf = new (int[bufsize]); + if (false == get_rrdfile (_data_path + OS_MON, read_offset, buf, bufsize, OS_METRICS_LEN)) + { + LOG_WARN ("read os rrd file failed"); + delete [] buf; + return; + } + + int agg_data[OS_METRICS_LEN]; + memset (agg_data, 0, OS_METRICS_LEN * sizeof (int)); + for (int i = 0; i < 4; i++) + { + if (HOUR == atype) + { + mon_diff_avg (buf, bufsize, agg_data, i, OS_METRICS_LEN, _meta[K_INTERVAL].asInt()); + } + else + { + mon_avg (buf, bufsize, agg_data, i, OS_METRICS_LEN); + } + } + mon_avg (buf, bufsize, agg_data, 4, OS_METRICS_LEN, 100); + mon_avg (buf, bufsize, agg_data, 5, OS_METRICS_LEN, 100); + mon_last (buf, bufsize, agg_data, 6, OS_METRICS_LEN, 100); + agg_data[7] = 0; + agg_data[8] = 0; + agg_data[9] = int (gather_time); + + update_rrdfile (_data_path + OS_MON, write_offset, agg_data, OS_METRICS_LEN, OS_METRICS_LEN); + _meta[key] = int (gather_time); + flush_meta_file(); + delete [] buf; +} + +void cm_mon_stat::aggregate_dbs (int read_offset, + int buf_base, + int write_offset, + AGG_TYPE atype, + time_t gather_time) +{ + string key; + int mod = 0; + if (HOUR == atype) + { + key = K_DB_HOUR_AGG_TIME; + mod = 3600; + } + else + { + key = K_DB_DAILY_AGG_TIME; + mod = 3600 * 24; + } + if (Json::Value::null != _meta[key]) + { + time_t last_time = _meta[key].asInt(); + if (last_time / mod >= gather_time / mod) + { + return; + } + } + + // Fix for CUBRIDSUS-11976 + Json::Value active_dbs; + if (false == get_active_dbs_list (active_dbs)) + { + LOG_WARN ("get active dbs list failed, time=[%d]", gather_time); + return; + } + + for (unsigned int i = 0; i < active_dbs.size(); i++) + { + string dbname = active_dbs[i].asString(); + if (false == _meta[K_DB_RRD].isMember (dbname + "_idx")) + { + LOG_WARN ("can't find db [%s] index in meta file", dbname.c_str()); + continue; + } + int db_idx = _meta[K_DB_RRD][dbname + "_idx"].asInt(); + int read_idx = db_idx * MON_DATA_BLOCK + read_offset; + + int bufsize = buf_base * DB_METRICS_LEN; + int *buf = new (int[bufsize]); + + if (false == get_rrdfile (_data_path + DB_MON, read_idx, buf, bufsize, DB_METRICS_LEN)) + { + LOG_WARN ("read db rrd file failed"); + delete [] buf; + return; + } + + int agg_data[DB_METRICS_LEN]; + memset (agg_data, 0, DB_METRICS_LEN * sizeof (int)); + + if (HOUR == atype) + { + mon_diff_avg (buf, bufsize, agg_data, 0, DB_METRICS_LEN, _meta[K_INTERVAL].asInt()); + agg_data[0] = agg_data[0] / _meta[K_INTERVAL].asInt(); + mon_diff_avg (buf, bufsize, agg_data, 1, DB_METRICS_LEN, _meta[K_INTERVAL].asInt()); + agg_data[1] = agg_data[1] / _meta[K_INTERVAL].asInt(); + } + else + { + mon_avg (buf, bufsize, agg_data, 0, DB_METRICS_LEN); + mon_avg (buf, bufsize, agg_data, 1, DB_METRICS_LEN); + } + mon_avg (buf,bufsize, agg_data, 2, DB_METRICS_LEN, 100); + mon_avg (buf,bufsize, agg_data, 3, DB_METRICS_LEN, 100); + if (HOUR == atype) + { + mon_diff_avg (buf, bufsize, agg_data, 4, DB_METRICS_LEN, _meta[K_INTERVAL].asInt()); + agg_data[4] = agg_data[4] / _meta[K_INTERVAL].asInt(); + mon_diff_avg (buf, bufsize, agg_data, 5, DB_METRICS_LEN, _meta[K_INTERVAL].asInt()); + agg_data[5] = agg_data[5] / _meta[K_INTERVAL].asInt(); + } + else + { + mon_avg (buf, bufsize, agg_data, 4, DB_METRICS_LEN); + mon_avg (buf, bufsize, agg_data, 5, DB_METRICS_LEN); + } + mon_avg (buf,bufsize, agg_data, 6, DB_METRICS_LEN); + for (unsigned int i = 7; i < 11; i++) + { + if (HOUR == atype) + { + mon_diff_avg (buf,bufsize, agg_data, i, DB_METRICS_LEN, _meta[K_INTERVAL].asInt()); + agg_data[i] /= _meta[K_INTERVAL].asInt(); + } + else + { + mon_avg (buf,bufsize, agg_data, i, DB_METRICS_LEN); + } + } + // HA metrics + if (HOUR == atype) + { + mon_diff_avg (buf,bufsize, agg_data, 11, DB_METRICS_LEN, _meta[K_INTERVAL].asInt()); + agg_data[11] /= _meta[K_INTERVAL].asInt(); + } + else + { + mon_avg (buf,bufsize, agg_data, 11, DB_METRICS_LEN); + } + mon_avg (buf,bufsize, agg_data, 12, DB_METRICS_LEN); + if (HOUR == atype) + { + mon_diff_avg (buf,bufsize, agg_data, 13, DB_METRICS_LEN, _meta[K_INTERVAL].asInt()); + agg_data[13] /= _meta[K_INTERVAL].asInt(); + } + else + { + mon_avg (buf,bufsize, agg_data, 13, DB_METRICS_LEN); + } + mon_avg (buf,bufsize, agg_data, 14, DB_METRICS_LEN); + mon_last (buf,bufsize, agg_data, 15, DB_METRICS_LEN, 100); + agg_data[16] = 0; + agg_data[17] = 0; + agg_data[18] = int (gather_time); + + int rrdpos = db_idx * MON_DATA_BLOCK + write_offset; + update_rrdfile (_data_path + DB_MON, rrdpos, agg_data, DB_METRICS_LEN, DB_METRICS_LEN); + + // volume + Json::Value vols; + if (false == get_volume_list (dbname, vols)) + { + continue; + } + + for (unsigned int i = 0; i < vols.size(); i++) + { + string vol_name = vols[i].asString(); + if (false == _meta[K_DB_RRD][dbname + "_vol"].isMember (vol_name)) + { + LOG_WARN ("can't find db [%s] vol[%s] index in meta file", dbname.c_str(), vol_name.c_str()); + continue; + } + int vol_idx = _meta[K_DB_RRD][dbname + "_vol"][vol_name].asInt(); + int read_idx = vol_idx * MON_DATA_BLOCK + read_offset; + int bufsize_vol = buf_base * VOL_METRICS_LEN; + int *buf_vol = new (int[bufsize_vol]); + if (false == get_rrdfile (_data_path + VOL_MON, read_idx, buf_vol, bufsize_vol, VOL_METRICS_LEN)) + { + LOG_WARN ("read volume rrd file failed"); + delete [] buf; + delete [] buf_vol; + return; + } + int agg_data[VOL_METRICS_LEN]; + memset (agg_data, 0, VOL_METRICS_LEN * sizeof (int)); + mon_last (buf_vol,bufsize_vol,agg_data,0,VOL_METRICS_LEN, 100); + agg_data[1] = int (gather_time); + + int rrdpos = vol_idx * MON_DATA_BLOCK + write_offset; + update_rrdfile (_data_path + VOL_MON, rrdpos, agg_data, VOL_METRICS_LEN, VOL_METRICS_LEN); + delete [] buf_vol; + } + delete [] buf; + } + _meta[key] = int (gather_time); + flush_meta_file(); +} + +static bool mdtype_from_str (const string &dtype, MDTYPE &mdtype) +{ + if ("daily" == dtype) + { + mdtype = DAILY; + } + else if ("weekly" == dtype) + { + mdtype = WEEKLY; + } + else if ("monthly" == dtype) + { + mdtype = MONTHLY; + } + else if ("yearly" == dtype) + { + mdtype = YEARLY; + } + else + { + return false; + } + return true; +} + +bool cm_mon_stat::get_mon_statistic (const Json::Value req, Json::Value &res, string &errmsg) const +{ + if (false == _init) + { + errmsg = "monitoring staticstic module is not initialized"; + LOG_WARN (errmsg.c_str()); + return false; + } + string metric = req["metric"].asString(); + if (OS_CPU_IDLE == metric + || OS_CPU_IOWAIT == metric + || OS_CPU_KERNEL == metric + || OS_CPU_USER == metric + || DB_CPU_KERNEL == metric + || DB_CPU_USER == metric) + { + if (false == m_get_mon_statistic (req, res, errmsg)) + { + return false; + } + + Json::Value os_idle_req, os_idle_res; + os_idle_req = req; + os_idle_req["metric"] = OS_CPU_IDLE; + if (false == m_get_mon_statistic (os_idle_req, os_idle_res, errmsg)) + { + res.removeMember ("data"); + return false; + } + + Json::Value os_iowait_req, os_iowait_res; + os_iowait_req = req; + os_iowait_req["metric"] = OS_CPU_IOWAIT; + if (false == m_get_mon_statistic (os_iowait_req, os_iowait_res, errmsg)) + { + res.removeMember ("data"); + return false; + } + + Json::Value os_kernel_req, os_kernel_res; + os_kernel_req = req; + os_kernel_req["metric"] = OS_CPU_KERNEL; + if (false == m_get_mon_statistic (os_kernel_req, os_kernel_res, errmsg)) + { + res.removeMember ("data"); + return false; + } + + Json::Value os_user_req, os_user_res; + os_user_req = req; + os_user_req["metric"] = OS_CPU_USER; + if (false == m_get_mon_statistic (os_user_req, os_user_res, errmsg)) + { + res.removeMember ("data"); + return false; + } + + for (unsigned int i = 0; i < res["data"].size(); i++) + { + if (res["data"][i].asInt() == INIT_METRIC_VALUE) + { + continue; + } + else if (os_idle_res["data"][i].asInt() != INIT_METRIC_VALUE + && os_iowait_req["data"][i].asInt() != INIT_METRIC_VALUE + && os_kernel_res["data"][i].asInt() != INIT_METRIC_VALUE + && os_user_res["data"][i].asInt() != INIT_METRIC_VALUE) + { + int total = os_idle_res["data"][i].asInt() + os_iowait_req["data"][i].asInt() + + os_kernel_res["data"][i].asInt() + os_user_res["data"][i].asInt(); + if (total <= 0) + { + res["data"][i] = 0; + } + else + { + // Because of percentage and accurating to the second decimal places, + // so it should be multiply by 10000. + res["data"][i] = int (float (res["data"][i].asInt()) * 10000 / total); + } + } + else + { + res["data"][i] = INIT_METRIC_VALUE; + } + } + return true; + } + else + { + return m_get_mon_statistic (req, res, errmsg); + } +} + +// the data maybe wrong for the begin of the return data array +bool cm_mon_stat::m_get_mon_statistic (const Json::Value req, Json::Value &res, string &errmsg) const +{ + res["metric"] = req["metric"]; + res["dtype"] = req["dtype"]; + + string metric = req["metric"].asString(); + + MDTYPE mdtype = DAILY; + if (false == mdtype_from_str (req["dtype"].asString(), mdtype)) + { + errmsg = string ("Error format of dtype [") + req["dtype"].asString() + "] in request"; + LOG_WARN (errmsg.c_str()); + return false; + } + + int m_idx = 0; + int i = 0; + int pfactor = 1; + bool d_diff = false; + + if (0 == strncmp ("db_", metric.c_str(), strlen ("db_"))) + { + string dbname = req["dbname"].asString(); + res["dbname"] = dbname; + if (false == _meta[K_DB_RRD].isMember (dbname + "_idx")) + { + errmsg = string ("Can't find dbname[") + dbname + "] in meta[k_db_rrd]"; + LOG_WARN (errmsg.c_str()); + return false; + } + int db_idx = _meta[K_DB_RRD][dbname + "_idx"].asInt(); + for (i = 0; i < DB_METRICS_LEN; i++) + { + if (DB_METRICS[i].metric == metric) + { + m_idx = i; + pfactor = DB_METRICS[i].pfactor; + d_diff = DB_METRICS[i].ddiff; + break; + } + } + if (i == DB_METRICS_LEN) + { + errmsg = string ("Can't find DB metric[") + metric + "] from request"; + LOG_WARN (errmsg.c_str()); + return false; + } + string data_path = _data_path + DB_MON; + return get_rrd_data (mdtype, data_path, db_idx, m_idx, pfactor, d_diff, DB_METRICS_LEN, res, errmsg); + } + + if (0 == strncmp ("vol_", metric.c_str(), strlen ("vol_"))) + { + string dbname = req["dbname"].asString(); + string volname = req["volname"].asString(); + res["dbname"] = dbname; + res["volname"] = volname; + if (false == _meta[K_DB_RRD].isMember (dbname + "_vol")) + { + errmsg = string ("Can't find dbname_vol[") + dbname + "] in meta[k_db_rrd]"; + LOG_WARN (errmsg.c_str()); + return false; + } + if (false == _meta[K_DB_RRD][dbname + "_vol"].isMember (volname)) + { + errmsg = string ("Can't find volname[") + volname + "] in DB [" + dbname + "] meta[k_db_rrd]"; + LOG_WARN (errmsg.c_str()); + return false; + } + int vol_idx = _meta[K_DB_RRD][dbname + "_vol"][volname].asInt(); + if (VOL_FREESPACE != metric) + { + errmsg = string ("Can't find volume metric[") + metric + "] from request"; + LOG_WARN (errmsg.c_str()); + return false; + } + string data_path = _data_path + VOL_MON; + return get_rrd_data (mdtype, data_path, vol_idx, m_idx, 100, d_diff, VOL_METRICS_LEN, res, errmsg); + } + + if (0 == strncmp ("broker_", metric.c_str(), strlen ("broker_"))) + { + string bname = req["bname"].asString(); + res["bname"] = bname; + if (false == _meta[K_BROKER_RRD].isMember (bname + "_idx")) + { + errmsg = string ("Can't find broker [") + bname + "] in meta[k_db_rrd]"; + LOG_WARN (errmsg.c_str()); + return false; + } + int b_idx = _meta[K_BROKER_RRD][bname + "_idx"].asInt(); + for (i = 0; i < BROKER_METRICS_LEN; i++) + { + if (BROKER_METRICS[i].metric == metric) + { + m_idx = i; + pfactor = BROKER_METRICS[i].pfactor; + d_diff = BROKER_METRICS[i].ddiff; + break; + } + } + if (i == BROKER_METRICS_LEN) + { + errmsg = string ("Can't find broker metric[") + metric + "] from request"; + LOG_WARN (errmsg.c_str()); + return false; + } + string data_path = _data_path + BROKER_MON; + return get_rrd_data (mdtype, data_path, b_idx, m_idx, pfactor, d_diff, BROKER_METRICS_LEN, res, errmsg); + } + + if (0 == strncmp ("os_", metric.c_str(), strlen ("os_"))) + { + for (i = 0; i < OS_METRICS_LEN; i++) + { + if (OS_METRICS[i].metric == metric) + { + m_idx = i; + pfactor = OS_METRICS[i].pfactor; + d_diff = OS_METRICS[i].ddiff; + break; + } + } + if (i == OS_METRICS_LEN) + { + errmsg = string ("Can't find os metric[") + metric + "] from request"; + LOG_WARN (errmsg.c_str()); + return false; + } + string data_path = _data_path + OS_MON; + return get_rrd_data (mdtype, data_path, 0, m_idx, pfactor, d_diff, OS_METRICS_LEN, res, errmsg); + } + + return false; +} + +bool cm_mon_stat::get_rrd_data (MDTYPE mdtype, string dpath, int didx, + int midx, int pfactor, bool ddiff, int mlen, + Json::Value &res, string &errmsg) const +{ + int read_rrd_idx = didx * MON_DATA_BLOCK; + int bufsize = 0; + switch (mdtype) + { + case DAILY: + bufsize = mlen * (24 * 60 * 60 / _meta[K_INTERVAL].asInt()); + break; + case WEEKLY: + case MONTHLY: + bufsize = mlen * 30 * 24; + read_rrd_idx += 24 * 60 * 60 / _meta[K_INTERVAL].asInt(); + break; + case YEARLY: + bufsize = mlen * 365; + read_rrd_idx += 24 * 60 * 60 / _meta[K_INTERVAL].asInt() + 24 * 30; + break; + } + int *buf = new (int[bufsize]); + if (false == get_rrdfile (dpath, read_rrd_idx, buf, bufsize, mlen)) + { + errmsg = string ("read rrd file failed [") + dpath + "]"; + LOG_WARN (errmsg.c_str()); + delete [] buf; + return false; + } + + time_t cur_time = time (NULL); + int read_buf_idx = 0; + int daily_mod = (3600 * 24) / _meta[K_INTERVAL].asInt(); + switch (mdtype) + { + case DAILY: + read_buf_idx = _daily_idx < 0 ? + (cur_time % (60 * 60 * 24)) / _meta[K_INTERVAL].asInt():_daily_idx + 1; + if (true == ddiff) + { + // Smoothing data functionality is added + int value = INIT_METRIC_VALUE; + int start = 0; // for count the num if the it's not updated from the beginning + for (int i = 1; i < daily_mod; i++) + { + int cur = buf[ ((read_buf_idx + i) % daily_mod) * mlen + midx]; + int cur_up = buf[ ((read_buf_idx + i) % daily_mod) * mlen + mlen - 1]; + int pre = buf[ ((read_buf_idx + i - 1) % daily_mod) * mlen + midx]; + int pre_up = buf[ ((read_buf_idx + i - 1) % daily_mod) * mlen + mlen - 1]; + if ((cur_up < pre_up) || (cur_up - pre_up > 2 * _meta[K_INTERVAL].asInt())) + { + if (-1 != start) + { + start++; + } + else + { + res["data"].append (value); // using last value + } + } + else + { + if (cur == INIT_METRIC_VALUE) + { + value = INIT_METRIC_VALUE; + } + else if (pre == INIT_METRIC_VALUE) + { + value = int ((float (cur) * (100/pfactor)) / _meta[K_INTERVAL].asInt()); + } + else + { + value = int ((float (cur >= pre ? cur - pre: cur) * (100/pfactor)) / _meta[K_INTERVAL].asInt()); + } + res["data"].append (value); + if (-1 != start) // If from the start, add extra value + { + while (start >= 0) + { + res["data"].append (value); + start--; + } + } + } + } + if (Json::Value::null == res["data"]) + { + for (int i = 0; i < daily_mod; i++) + { + res["data"].append (0); + } + } + } + else + { + for (int i = read_buf_idx; i < read_buf_idx + daily_mod; i++) + { + res["data"].append (buf[ (i % daily_mod) * mlen + midx] * (100/pfactor)); + } + } + break; + case WEEKLY: + read_buf_idx = _monthly_idx < 0 ? (cur_time % (30 * 60 * 60 * 24)) / 3600 :_monthly_idx + 1; + read_buf_idx += 30 * 24; + for (int i = read_buf_idx - 24*7; i < read_buf_idx; i++) + { + res["data"].append (buf[ (i% (30*24)) * mlen + midx]); + } + break; + case MONTHLY: + read_buf_idx = _monthly_idx < 0 ? (cur_time % (30 * 60 * 60 * 24)) / 3600 :_monthly_idx + 1; + for (int i = read_buf_idx; i < 30 * 24 + read_buf_idx; i++) + { + res["data"].append (buf[ (i% (30*24)) * mlen + midx]); + } + break; + case YEARLY: + read_buf_idx = _yearly_idx < 0 ? (cur_time % (365 * 3600 * 24)) / (3600*24) :_yearly_idx + 1; + for (int i = read_buf_idx; i < 365; i++) + { + res["data"].append (buf[i * mlen + midx]); + } + for (int i = 0; i < read_buf_idx; i++) + { + res["data"].append (buf[i * mlen + midx]); + } + break; + } + delete [] buf; + return true; +} + +static bool get_volume_list (string dbname, Json::Value &vol_list) +{ + Json::Value req, res; + req["dbname"] = dbname; + req["_DBNAME"] = dbname; + string errmsg; + if (false == call_task (req, res, tsDbspaceInfo, errmsg)) + { + LOG_WARN ("call getdbspaceinfo failed, error code[%d], error message [%s]", + res["retval"].asInt(), errmsg.c_str()); + return false; + } + for (unsigned int i = 0; i < res["spaceinfo"].size(); i++) + { + vol_list.append (res["spaceinfo"][i]["spacename"].asString()); + } + return true; +} + +void cm_mon_stat::aggregate_brokers (int read_offset, + int buf_base, + int write_offset, + AGG_TYPE atype, + time_t gather_time) +{ + string key; + int mod = 0; + if (HOUR == atype) + { + key = K_BROKER_HOUR_AGG_TIME; + mod = 3600; + } + else + { + key = K_BROKER_DAILY_AGG_TIME; + mod = 3600 * 24; + } + if (Json::Value::null != _meta[key]) + { + time_t last_time = _meta[key].asInt(); + if (last_time / mod >= gather_time / mod) + { + return; + } + } + + for (unsigned int i = 0; i < _brokers.size(); i++) + { + string bname = _brokers[i].asString(); + if (false == _meta[K_BROKER_RRD].isMember (bname + "_idx")) + { + LOG_WARN ("can't find broker [%s] index in meta file", bname.c_str()); + continue; + } + int broker_idx = _meta[K_BROKER_RRD][bname + "_idx"].asInt(); + + int read_idx = broker_idx * MON_DATA_BLOCK + read_offset; + + int bufsize = buf_base * BROKER_METRICS_LEN; + int *buf = new (int[bufsize]); + + if (false == get_rrdfile (_data_path + BROKER_MON, read_idx, buf, bufsize, BROKER_METRICS_LEN)) + { + LOG_WARN ("read broker rrd file failed"); + delete [] buf; + return; + } + + int agg_data[BROKER_METRICS_LEN]; + memset (agg_data, 0, BROKER_METRICS_LEN * sizeof (int)); + for (int i = 0; i < 6; i ++) + { + if (HOUR == atype) + { + mon_diff_avg (buf, bufsize, agg_data, i, BROKER_METRICS_LEN, _meta[K_INTERVAL].asInt()); + agg_data[i] = agg_data[i] / _meta[K_INTERVAL].asInt(); + } + else + { + mon_avg (buf, bufsize, agg_data, i, BROKER_METRICS_LEN); + } + } + mon_avg (buf, bufsize, agg_data, 6, BROKER_METRICS_LEN); + agg_data[7] = 0; + agg_data[8] = 0; + agg_data[9] = int (gather_time); + + int rrdpos = broker_idx * MON_DATA_BLOCK + write_offset; + update_rrdfile (_data_path + BROKER_MON, rrdpos, agg_data, BROKER_METRICS_LEN, BROKER_METRICS_LEN); + delete [] buf; + } + _meta[key] = int (gather_time); + flush_meta_file(); +} + +static void mon_last (int *buf, int bufsize, int *agg_data, int idx, int mlen, int pfactor) +{ + if (buf[bufsize - mlen + idx] != INIT_METRIC_VALUE) + { + agg_data[idx] = buf[bufsize - mlen + idx] * (100 / pfactor); + } + else + { + agg_data[idx] = 0; + } +} + +// pfactor is used to control the precision, the default is accurating to 2 decimal places + +static void mon_avg (int *buf, int bufsize, int *agg_data, int idx, int mlen, int pfactor) +{ + int count = 0; + for (int i = 0; i < bufsize/mlen; i++) + { + if (buf[i * mlen + idx] != INIT_METRIC_VALUE) + { + agg_data[idx] += buf[i * mlen + idx]; + count++; + } + } + if (count != 0) + { + agg_data[idx] = agg_data[idx] * (100/pfactor) / count; + } + else + { + agg_data[idx] = 0; + } +} + +// pfactor is used to control the precision, the default is accurating to 2 decimal places + +static void mon_diff_avg (int *buf, int bufsize, int *agg_data, int idx, int mlen, int interval, int pfactor) +{ + int count = 0; + for (int i = 0; i < bufsize/mlen - 1; i++) + { + int pre = buf[i * mlen + idx]; + int pre_up = buf[i * mlen + mlen - 1]; + int next = buf[ (i + 1) * mlen + idx]; + int next_up = buf[ (i + 1) * mlen + mlen - 1]; + if (next == INIT_METRIC_VALUE) + { + continue; + } + if (pre == INIT_METRIC_VALUE) + { + agg_data[idx] += next; + count++; + continue; + } + if ((pre <= next) && (next_up > pre_up) && (next_up - pre_up < 2*interval)) + { + agg_data[idx] += (next - pre); + count++; + } + } + if (0 != count) + { + agg_data[idx] = agg_data[idx] * (100/pfactor) / count; + } + else + { + agg_data[idx] = 0; + } +} + +void cm_mon_stat::gather_daily_brokers_mon (time_t gather_time) +{ + int broker_data[BROKER_METRICS_LEN]; + memset (broker_data, 0, BROKER_METRICS_LEN * sizeof (int)); + + int daily_idx = (gather_time % (60 * 60 * 24)) / _meta[K_INTERVAL].asInt(); + + Json::Value req, brokers_info; + string errmsg; + if (false == call_task (req, brokers_info, ts2_get_unicas_info, errmsg)) + { + LOG_ERROR ("failed to get brokers infomation, time=[%d], error code[%d], error message [%s]", + gather_time, brokers_info["retval"].asInt(), errmsg.c_str()); + return; + } + if (brokers_info.isMember ("brokersinfo")) + { + for (unsigned int i = 0; i < brokers_info["brokersinfo"][0u]["broker"].size(); i++) + { + Json::Value &bdata = brokers_info["brokersinfo"][0u]["broker"][i]; + string bname = bdata["name"].asString(); + + // resize broker rrdfile + if (false == _meta[K_BROKER_RRD].isMember (bname + "_idx")) + { + if (false == append_rrdfile (_data_path + BROKER_MON, MON_DATA_BLOCK, BROKER_METRICS_LEN)) + { + continue; + } + _meta[K_BROKER_RRD][bname + "_idx"] = _meta[K_BROKER_NUM].asInt(); + _meta[K_BROKER_NUM] = _meta[K_BROKER_NUM].asInt() + 1; + if (false == flush_meta_file()) + { + continue; + } + } + + broker_data[0] = JSON_ATOI (bdata["tran"]); + broker_data[1] = JSON_ATOI (bdata["query"]); + broker_data[2] = JSON_ATOI (bdata["long_tran"]); + broker_data[3] = JSON_ATOI (bdata["long_query"]); + broker_data[4] = JSON_ATOI (bdata["req"]); + broker_data[5] = JSON_ATOI (bdata["error_query"]); + broker_data[6] = JSON_ATOI (bdata["jq"]); + broker_data[7] = 0; + broker_data[8] = 0; + broker_data[9] = int (gather_time); + + int broker_idx = _meta[K_BROKER_RRD][bname+"_idx"].asInt(); + int rrdpos = broker_idx * MON_DATA_BLOCK + daily_idx; + update_rrdfile (_data_path + BROKER_MON, rrdpos, broker_data, BROKER_METRICS_LEN, BROKER_METRICS_LEN); + } + } + else + { + LOG_ERROR ("error format of brokers infomation, time=[%d]", gather_time); + } +} + +bool cm_mon_stat::gather_dbs_tran_query (time_t gather_time, Json::Value &db_tq) +{ + string bstr = _brokers[0u].asString(); + + for (unsigned int i = 1; i < _brokers.size(); i ++) + { + bstr += "," + _brokers[i].asString(); + } + + Json::Value as_req, as_res; + as_req["bname"] = bstr; + string errmsg; + if (false != call_task (as_req, as_res, ts2_get_broker_status, errmsg)) + { + Json::Value b_as; + // more than one broker + if (as_res.isMember ("broker")) + { + b_as = as_res["broker"]; + } + else if (as_res.isMember ("asinfo")) // one broker + { + b_as.append (as_res); + } + else + { + LOG_WARN ("get broker status failed, time=[%d]", gather_time); + return false; + } + + for (unsigned int i = 0; i < b_as.size(); i++) + { + for (unsigned int j = 0; j < b_as[i]["asinfo"].size(); j++) + { + string dbname = b_as[i]["asinfo"][j]["as_dbname"].asString(); + if (0 != dbname.length()) + { + if (db_tq.isMember (dbname)) + { + db_tq[dbname]["query"] = db_tq[dbname]["query"].asInt() + JSON_ATOI (b_as[i]["asinfo"][j]["as_num_query"]); + db_tq[dbname]["tran"] = db_tq[dbname]["tran"].asInt() + JSON_ATOI (b_as[i]["asinfo"][j]["as_num_tran"]); + } + else + { + db_tq[dbname]["query"] = JSON_ATOI (b_as[i]["asinfo"][j]["as_num_query"]); + db_tq[dbname]["tran"] = JSON_ATOI (b_as[i]["asinfo"][j]["as_num_tran"]); + } + } + } + } + } + else + { + LOG_WARN ("get brokers status failed, time=[%d], error code [%d], error message [%s]", + gather_time, as_res["retval"].asInt(), errmsg.c_str()); + return false; + } + return true; +} + +void cm_mon_stat::gather_daily_dbs_mon (time_t gather_time) +{ + int db_data[DB_METRICS_LEN]; + Json::Value db_tq; + if (false == gather_dbs_tran_query (gather_time, db_tq)) + { + return; + } + + int daily_idx = (gather_time % (60 * 60 * 24)) / _meta[K_INTERVAL].asInt(); + + Json::Value active_dbs; + if (false == get_active_dbs_list (active_dbs)) + { + LOG_WARN ("get active dbs list failed, time=[%d]", gather_time); + return; + } + + Json::Value ha_req, ha_res; + ha_req["task"] = "ha_status"; + bool has_ha_info = false; + string errmsg; + string ha_rmt_hostname; + if (true == call_task (ha_req, ha_res, ts_ha_status, errmsg)) + { + has_ha_info = true; + if ("master" == ha_res["current_node_state"].asString()) + { + ha_rmt_hostname = ha_res["nodeA"].asString(); + } + else + { + ha_rmt_hostname = ha_res["nodeB"].asString(); + } + } + else if (ERR_SYSTEM_CALL != ha_res["retval"].asInt()) + { + LOG_WARN ("Get HA status failed, time=[%d], error code [%d], error message [%s]", + gather_time, ha_res["retval"].asInt(), errmsg.c_str()); + } + + for (unsigned int i = 0; i < active_dbs.size(); i++) + { + memset (db_data, 0, DB_METRICS_LEN * sizeof (int)); + string dbname = active_dbs[i].asString(); + // resize db rrdfile + if (false == _meta[K_DB_RRD].isMember (dbname + "_idx")) + { + if (false == append_rrdfile (_data_path + DB_MON, MON_DATA_BLOCK, DB_METRICS_LEN)) + { + LOG_WARN ("append rrd file for new db failed, time=[%d]", gather_time); + continue; + } + _meta[K_DB_RRD][dbname + "_idx"] = _meta[K_DB_NUM].asInt(); + _meta[K_DB_NUM] = _meta[K_DB_NUM].asInt() + 1; + if (false == flush_meta_file()) + { + LOG_WARN ("flush meta file failed, time=[%d]", gather_time); + continue; + } + } + + Json::Value req, res; + req["dbname"] = dbname; + req["_DBNAME"] = dbname; + errmsg = ""; + if (false == call_task (req, res, ts_get_dbproc_stat, errmsg)) + { + LOG_WARN ("call getdbprocstatus failed, time=[%d], error code[%d], error message [%s]", + gather_time, res["retval"].asInt(), errmsg.c_str()); + continue; + } +#if defined(WINDOWS) + db_data[0] = JSON_ATOI (res["dbstat"][0u]["cpu_kernel"]) / CPU_BASE_FEQ_WIN; + db_data[1] = JSON_ATOI (res["dbstat"][0u]["cpu_user"]) / CPU_BASE_FEQ_WIN; +#else + db_data[0] = JSON_ATOI (res["dbstat"][0u]["cpu_kernel"]); + db_data[1] = JSON_ATOI (res["dbstat"][0u]["cpu_user"]); +#endif + db_data[2] = int (JSON_ATOL (res["dbstat"][0u]["mem_physical"]) * 100 / MB_SIZE); + db_data[3] = int (JSON_ATOL (res["dbstat"][0u]["mem_virtual"]) * 100 / MB_SIZE); + if (db_tq.isMember (dbname)) + { + db_data[4] = db_tq[dbname]["query"].asInt(); + db_data[5] = db_tq[dbname]["tran"].asInt(); + } + else + { + db_data[4] = 0; + db_data[5] = 0; + } + + //statdump + res.clear(); + errmsg = ""; + if (false == call_task (req, res, ts_statdump, errmsg)) + { + LOG_WARN ("call statdump failed, time=[%d], error code[%d], error message [%s]", + gather_time, res["retval"].asInt(), errmsg.c_str()); + continue; + } + db_data[6] = JSON_ATOI (res["data_page_buffer_hit_ratio"]); + db_data[7] = JSON_ATOI (res["num_data_page_fetches"]); + db_data[8] = JSON_ATOI (res["num_data_page_dirties"]); + db_data[9] = JSON_ATOI (res["num_file_ioreads"]); + db_data[10] = JSON_ATOI (res["num_file_iowrites"]); + + // HA monitoring + if (true == has_ha_info) + { + // TODO: HA monitoring + for (unsigned int i = 0; i < ha_res["ha_info"].size(); i++) + { + if (dbname == ha_res["ha_info"][i]["dbname"].asString()) + { + Json::Value req, res; + req["task"] = "gethaapplyinfo"; + req["dbname"] = dbname; + req["remotehostname"] = ha_rmt_hostname; + string copylog = ha_res["ha_info"][i]["copylogdb"].asString(); + unsigned int colon_idx = (unsigned int) copylog.find (':'); + if (string::npos == colon_idx) + { + LOG_WARN ("Error format of copylogdb, time=[%d], copylogdb=[%s]", + gather_time, req["copylogdb"].asString().c_str()); + break; + } + req["copylogpath"] = copylog.substr (colon_idx + 1); + if (false == call_task_ext (req, res, ext_get_ha_apply_info)) + { + LOG_WARN ("Get HA apply info failed, time=[%d], dbname=[%s]", + gather_time, req["dbname"].asString().c_str()); + break; + } + db_data[11] = JSON_ATOI (res["copyinglog_coun"]); + db_data[12] = JSON_ATOI (res["copyinglog_estimated_time"]); + db_data[13] = JSON_ATOI (res["applyinglog_count"]); + db_data[14] = JSON_ATOI (res["applyinglog_estimated_time"]); + } + } + } + + // dbspaceinfo + res.clear(); + req["_DBNAME"] = dbname; + errmsg = ""; + if (false == call_task (req, res, tsDbspaceInfo, errmsg)) + { + LOG_WARN ("call getdbspaceinfo failed, time=[%d], error code[%d], error message [%s]", + gather_time, res["retval"].asInt(), errmsg.c_str()); + continue; + } + db_data[15] = int (JSON_ATOL (res["freespace"]) * JSON_ATOL (res["pagesize"]) * 100 / MB_SIZE); + db_data[16] = 0; + db_data[17] = 0; + db_data[18] = int (gather_time); + + // update rrdfile + int rrdpos = _meta[K_DB_RRD][dbname + "_idx"].asInt() * MON_DATA_BLOCK + daily_idx; + update_rrdfile (_data_path +"/"+ DB_MON, rrdpos, db_data, DB_METRICS_LEN, DB_METRICS_LEN); + // volume + for (unsigned int i = 0; i < res["spaceinfo"].size(); i++) + { + string vol_name = res["spaceinfo"][i]["spacename"].asString(); + if (false == _meta[K_DB_RRD][dbname + "_vol"].isMember (vol_name)) + { + if (0 == _meta[K_TOTAL_VOL_NUM].asInt()) + { + init_rrdfile (_data_path + VOL_MON, MON_DATA_BLOCK, VOL_METRICS_LEN); + } + else + { + append_rrdfile (_data_path + VOL_MON, MON_DATA_BLOCK, VOL_METRICS_LEN); + } + _meta[K_DB_RRD][dbname + "_vol"][vol_name] = _meta[K_TOTAL_VOL_NUM].asInt(); + _meta[K_TOTAL_VOL_NUM] = _meta[K_TOTAL_VOL_NUM].asInt() + 1; + if (false == flush_meta_file()) + { + LOG_WARN ("flush meta file failed, time=[%d]", gather_time); + continue; + } + } + + // in MB + int vol_data[VOL_METRICS_LEN]; + vol_data[0] = int (JSON_ATOL (res["spaceinfo"][i]["freepage"]) + * JSON_ATOL (res["pagesize"]) * 100 / MB_SIZE); + vol_data[1] = int (gather_time); + int vol_idx = _meta[K_DB_RRD][dbname + "_vol"][vol_name].asInt(); + int rrdpos = vol_idx * MON_DATA_BLOCK + daily_idx; + update_rrdfile (_data_path +"/"+ VOL_MON, rrdpos, vol_data, VOL_METRICS_LEN, VOL_METRICS_LEN); + } + } +} + +void cm_mon_stat::gather_daily_os_mon (time_t gather_time) +{ + int os_data[OS_METRICS_LEN]; + memset (os_data, 0, OS_METRICS_LEN * sizeof (int)); + int daily_idx = (gather_time % (60 * 60 * 24)) / _meta[K_INTERVAL].asInt(); + + Json::Value req, res; + string errmsg; + if (false != call_task (req, res, ts_get_host_stat, errmsg)) + { +#if defined(WINDOWS) + // Fix for TOOLS-3417 + // using reducer to make the number doesn't excced MAX_INT + os_data[0] = int (JSON_ATOL (res["cpu_idle"])/CPU_BASE_FEQ_WIN); + os_data[1] = int (JSON_ATOL (res["cpu_iowait"])/CPU_BASE_FEQ_WIN); + os_data[2] = int (JSON_ATOL (res["cpu_kernel"])/CPU_BASE_FEQ_WIN); + os_data[3] = int (JSON_ATOL (res["cpu_user"])/CPU_BASE_FEQ_WIN); +#else + os_data[0] = int (JSON_ATOI (res["cpu_idle"])); + os_data[1] = int (JSON_ATOI (res["cpu_iowait"])); + os_data[2] = int (JSON_ATOI (res["cpu_kernel"])); + os_data[3] = int (JSON_ATOI (res["cpu_user"])); +#endif + os_data[4] = int (JSON_ATOL (res["mem_phy_free"]) * 100 / MB_SIZE); + os_data[5] = int (JSON_ATOL (res["mem_swap_free"]) * 100 / MB_SIZE); + } + else + { + LOG_WARN ("get host statu failed, time=[%d], error code[%d], error message [%s]", + gather_time, res["retval"].asInt(), errmsg.c_str()); + return; + } + res.clear(); + if (false != call_task_ext (req, res, ext_get_sys_diskinfo)) + { + int total_free = 0; + for (unsigned int i = 0; i < res["disk_info"].size(); i++) + { + total_free += int (JSON_ATOL (res["disk_info"][i]["free_size"]) * 100 / MB_SIZE); + } + os_data[6] = total_free; + } + else + { + LOG_WARN ("get system disk info failed, time=[%d], error message [%s]", + gather_time, res["note"].asString().c_str()); + return; + } + os_data[7] = 0; + os_data[8] = 0; + os_data[9] = int (gather_time); + update_rrdfile (_data_path + OS_MON, daily_idx, os_data, OS_METRICS_LEN, OS_METRICS_LEN); +} + +bool cm_mon_stat::init_meta (int interval) +{ + _meta[K_INTERVAL] = interval; + _meta[K_TOTAL_VOL_NUM] = 0; + + // init broker + Json::Value req, brokers_info; + string errmsg; + if (false == call_task (req, brokers_info, ts2_get_unicas_info, errmsg)) + { + LOG_ERROR ("failed to get brokers infomation, error code[%d], error message [%s]", + brokers_info["retval"].asInt(), errmsg.c_str()); + throw exception(); + } + for (int i = 0; i < BROKER_METRICS_LEN; i++) + { + _meta[K_BROKER_METRICS][BROKER_METRICS[i].metric] = i; + } + if (brokers_info.isMember ("brokersinfo")) + { + _meta[K_BROKER_NUM] = brokers_info["brokersinfo"][0u]["broker"].size(); + for (int i = 0; i < _meta[K_BROKER_NUM].asInt(); i++) + { + string bname = brokers_info["brokersinfo"][0u]["broker"][i]["name"].asString(); + _meta[K_BROKER_RRD][bname + "_idx"] = i; + + } + int rrdsize = MON_DATA_BLOCK * _meta[K_BROKER_NUM].asInt(); + init_rrdfile (_data_path + BROKER_MON, rrdsize, BROKER_METRICS_LEN); + } + else + { + throw exception(); + } + + // init db + Json::Value dbs_info; + if (false == call_task (req, dbs_info, ts_startinfo, errmsg)) + { + LOG_ERROR ("failed to get DBs infomation, error code[%d], error message [%s]", + dbs_info["retval"].asInt(), errmsg.c_str()); + throw exception(); + } + + for (int i = 0; i < DB_METRICS_LEN; i++) + { + _meta[K_DB_METRICS][DB_METRICS[i].metric] = i; + } + if (dbs_info.isMember ("dblist")) + { + Json::Value &dbs = dbs_info["dblist"][0u]["dbs"]; + _meta[K_DB_NUM] = dbs.size(); + for (int i = 0; i < _meta[K_DB_NUM].asInt(); i++) + { + string dbname = dbs[i]["dbname"].asString(); + _meta[K_DB_RRD][dbname + "_idx"] = i; + } + int rrdsize = MON_DATA_BLOCK * _meta[K_DB_NUM].asInt(); + init_rrdfile (_data_path + DB_MON, rrdsize, DB_METRICS_LEN); + } + else + { + _meta[K_DB_NUM] = 0; + init_rrdfile (_data_path + VOL_MON, 0, 0); + init_rrdfile (_data_path + DB_MON, 0, 0); + LOG_WARN ("no dblist for DBs info"); + } + + // init OS + for (int i = 0; i < OS_METRICS_LEN; i++) + { + _meta[K_OS_METRICS][OS_METRICS[i].metric] = i; + } + _meta[K_OS_RRD]["os_idx"] = 0; + init_rrdfile (_data_path + OS_MON, MON_DATA_BLOCK, OS_METRICS_LEN); + + return flush_meta_file(); +} + +bool cm_mon_stat::reset_meta (int new_interval) +{ + scope_lock slocker (_data_mutex); + + // reset broker + if (false == reset_mon_file (_data_path + BROKER_MON, _meta[K_BROKER_NUM].asInt(), BROKER_METRICS_LEN, new_interval)) + { + LOG_ERROR ("reset broker monitoring file failed"); + return false; + } + // reset DBs + if (false == reset_mon_file (_data_path + DB_MON, _meta[K_DB_NUM].asInt(), DB_METRICS_LEN, new_interval)) + { + LOG_ERROR ("reset DB monitoring file failed"); + return false; + } + // reset volume + if (false == reset_mon_file (_data_path + VOL_MON, _meta[K_TOTAL_VOL_NUM].asInt(), VOL_METRICS_LEN, new_interval)) + { + LOG_ERROR ("reset volume monitoring file failed"); + return false; + } + // reset os + if (false == reset_mon_file (_data_path + OS_MON, 1, OS_METRICS_LEN, new_interval)) + { + LOG_ERROR ("reset os monitoring file failed"); + return false; + } + _meta[K_INTERVAL] = new_interval; + return flush_meta_file(); +} + +bool cm_mon_stat::reset_mon_file (string fpath, int block_num, int mlen, int new_interval) +{ + int ori_bufsize = MON_DATA_BLOCK * block_num * mlen; + int *ori_buf = new (int[ori_bufsize]); + if (false == get_rrdfile (fpath, 0, ori_buf, ori_bufsize, mlen)) + { + LOG_ERROR ("get_rrdfile failed, file name[%s]", fpath.c_str()); + delete [] ori_buf; + return false; + } + + int old_daily_data_block = (24 * 60 * 60) / _meta[K_INTERVAL].asInt(); + int new_mon_data_block = (24 * 60 * 60) / new_interval + 30 * 24 + 365; + int new_rrdsize = new_mon_data_block * block_num; + if (false == init_rrdfile (fpath, new_rrdsize, mlen)) + { + LOG_ERROR ("init_rrdfile failed, file name[%s]", fpath.c_str()); + delete [] ori_buf; + return false; + } + + for (int i = 0; i < block_num; i++) + { + int *ptr = ori_buf + i * MON_DATA_BLOCK + old_daily_data_block; + int rrdpos = i * new_mon_data_block + (24 * 60 * 60) / new_interval; + if (false == update_rrdfile (fpath, rrdpos, ptr, (30 * 24 + 365) * mlen, mlen)) + { + LOG_ERROR ("update_rrdfile failed, file name[%s], block number[%d]", fpath.c_str(), i); + delete [] ori_buf; + return false; + } + } + delete [] ori_buf; + return true; +} + +bool cm_mon_stat::flush_meta_file (void) +{ + Json::StyledWriter writer; + ofstream ofs (_meta_file.c_str()); + if (!ofs.bad()) + { + ofs << writer.write (_meta) << endl; + ofs.close(); + return true; + } + + return false; +} + +bool cm_mon_stat::load_meta_file (void) +{ + Json::Reader reader; + ifstream ifs (_meta_file.c_str()); + if (!ifs.bad()) + { + bool rtn = reader.parse (ifs, _meta); + if (false == rtn) + { + LOG_ERROR ("failed to load monitoring meta file [%s]", _meta_file.c_str()); + } + ifs.close(); + return rtn; + } + else + { + LOG_ERROR ("failed to load monitoring meta file [%s]", _meta_file.c_str()); + return false; + } +} + +int json_to_nv (Json::Value &root, const char *name, nvplist *nv); +int nv_to_json (nvplist *ref, char *value, int &index, Json::Value &root); + +static bool init_rrdfile (string filename, int rrdsize, int metrics_len) +{ + int bufsize = rrdsize * metrics_len; + int *buf = new (int[bufsize]); + memset ((void *)buf, INIT_METRIC_VALUE, bufsize * sizeof (int)); + ofstream ofs (filename.c_str(), ios_base::out | ios_base::binary | ios_base::trunc); + if (ofs.fail()) + { + LOG_ERROR ("failed to open monitoring data file [%s]", filename.c_str()); + delete [] buf; + throw exception(); + } + ofs.write ((char *)buf, bufsize * sizeof (int)); + ofs.close(); + delete [] buf; + return true; +} + +static bool update_rrdfile (string filename, int rrdpos, int *buf, int bufsize, int mlen) +{ + fstream fs (filename.c_str(), ios_base::in | ios_base::out | ios_base::binary); + if (fs.fail()) + { + LOG_ERROR ("failed to open monitoring data file [%s]", filename.c_str()); + return false; + } + fs.seekp (rrdpos * sizeof (int) * mlen); + fs.write ((char *) buf, bufsize * sizeof (int)); + fs.close(); + return true; +} + +static bool get_rrdfile (string filename, int rrdpos, int *buf, int bufsize, int metrics_len) +{ + fstream fs (filename.c_str(), ios_base::in | ios_base::binary); + if (fs.fail()) + { + LOG_ERROR ("failed to open monitoring data file [%s]", filename.c_str()); + return false; + } + fs.seekp (rrdpos * sizeof (int) * metrics_len); + fs.read ((char *) buf, bufsize * sizeof (int)); + if (fs.eof()) + { + LOG_ERROR ("failed to read monitoring data, rrdpos:[%d], bufsize:[%d], file:[%s]", rrdpos, bufsize, filename.c_str()); + return false; + } + fs.close(); + return true; +} + +static bool append_rrdfile (string filename, int rrdsize, int metrics_len ) +{ + int bufsize = rrdsize * metrics_len; + int *buf = new (int[bufsize]); + memset (buf, 0, bufsize * sizeof (int)); + ofstream ofs (filename.c_str(), ios_base::out | ios_base::binary | ios_base::app); + if (ofs.fail()) + { + LOG_ERROR ("failed to open monitoring data file [%s]", filename.c_str()); + delete [] buf; + return false; + } + ofs.write ((char *)buf, bufsize * sizeof (int)); + ofs.close(); + delete [] buf; + return true; +} + +static bool get_dbs_list (Json::Value &db_list) +{ + Json::Value req, dbs_info; + db_list.clear(); + string errmsg; + if (false == call_task (req, dbs_info, ts_startinfo, errmsg)) + { + LOG_ERROR ("failed to get DBs infomation, error code[%d], error message [%s]", + dbs_info["retval"].asInt(), errmsg.c_str()); + return false; + } + if (dbs_info.isMember ("dblist")) + { + Json::Value &dbs = dbs_info["dblist"][0u]["dbs"]; + for (unsigned int i = 0; i < dbs.size(); i++) + { + db_list.append (dbs[i]["dbname"].asString()); + } + } + else + { + LOG_ERROR ("no dblist for DBs info"); + return false; + } + return true; +} + +static bool get_active_dbs_list (Json::Value &db_list) +{ + Json::Value req, dbs_info; + db_list.clear(); + string errmsg; + if (false == call_task (req, dbs_info, ts_startinfo, errmsg)) + { + LOG_ERROR ("failed to get active DBs infomation, error code[%d], error message [%s]", + dbs_info["retval"].asInt(), errmsg.c_str()); + return false; + } + if (dbs_info.isMember ("activelist")) + { + if (0 == dbs_info["activelist"].size() + || false == dbs_info["activelist"][0u].isMember ("active")) + { + return true; + } + Json::Value &dbs = dbs_info["activelist"][0u]["active"]; + + for (unsigned int i = 0; i < dbs.size(); i++) + { + db_list.append (dbs[i]["dbname"].asString()); + } + } + else + { + LOG_ERROR ("no active dblist for DBs info"); + return false; + } + return true; +} + +static bool get_brokers_list (Json::Value &brokers_list) +{ + Json::Value req, brokers_info; + brokers_list.clear(); + string errmsg; + if (false == call_task (req, brokers_info, ts2_get_unicas_info, errmsg)) + { + LOG_ERROR ("failed to get brokers infomation, error code[%d], error message [%s]", + brokers_info["retval"].asInt(), errmsg.c_str()); + return false; + } + if (brokers_info.isMember ("brokersinfo")) + { + Json::Value &brokers = brokers_info["brokersinfo"][0u]["broker"]; + + for (unsigned int i = 0; i < brokers.size(); i++) + { + brokers_list.append (brokers[i]["name"].asString()); + } + } + else + { + LOG_ERROR ("no key brokersinfo for getbrokerstatus"); + return false; + } + return true; +} + +static bool call_task (Json::Value &req, Json::Value &res, T_TASK_FUNC func, string &errmsg) +{ + bool ret = false; + nvplist *cli_request, *cli_response; + cli_request = nv_create (5, NULL, "\n", ":", "\n"); + cli_response = nv_create (5, NULL, "\n", ":", "\n"); + try + { + int index = 0; + char dbmt_error[DBMT_ERROR_MSG_SIZE]; + dbmt_error[0] = 0; + + json_to_nv (req, NULL, cli_request); + int retval = (*func) (cli_request, cli_response, dbmt_error); + nv_to_json (cli_response, NULL, index, res); + res["retval"] = retval; + errmsg = dbmt_error; + if ((1 == retval) || (ERR_NO_ERROR == retval)) + { + ret = true; + } + else + { + //LOG_WARN("Failed with return value %d, error message is [%s]", retval, dbmt_error); + ret = false; + } + } + catch (exception &) + { + ret = false; + } + nv_destroy (cli_request); + nv_destroy (cli_response); + return ret; +} + +static bool call_task_ext (Json::Value &req, Json::Value &res, T_EXT_TASK_FUNC func) +{ + try + { + (*func) (req, res); + if (STATUS_SUCCESS != res["status"].asString()) + { + return false; + } + return true; + } + catch (exception &e) + { + res["status"] = STATUS_FAILURE; + res["note"] = e.what (); + return false; + } +} diff --git a/server/src/am_mon_stat.h b/server/src/am_mon_stat.h new file mode 100644 index 0000000..45021ac --- /dev/null +++ b/server/src/am_mon_stat.h @@ -0,0 +1,114 @@ +/* + * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. + * + * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +/** +* @brief cm_mon_stat.h include the definition of cm_mon_stat class. +*/ + +#ifndef _CM_MON_STAT_H_ +#define _CM_MON_STAT_H_ + +#ifndef PATH_MAX +#define PATH_MAX 1024 +#endif + +#include +#include +#include + +#include "json/json.h" +#include "cm_porting.h" + +using namespace std; + +enum AGG_TYPE +{ + HOUR, DAY +}; + +enum MDTYPE +{ + DAILY = 0, + WEEKLY, + MONTHLY, + YEARLY +}; + +// TODO: need a switch for monitoring data collection + +class cm_mon_stat +{ + public: + static cm_mon_stat *get_instance (void); + bool initial (void); + void gather_mon_data (void); + bool set_mon_interval (time_t interval); + bool get_mon_interval (time_t &interval) const; + bool get_mon_statistic (const Json::Value req, Json::Value &res, + string &errmsg) const; + + protected: + cm_mon_stat (string data_path); + virtual ~ cm_mon_stat (void) + { + MUTEX_DESTROY (_data_mutex); + delete _instance; + _instance = NULL; + } + + private: + bool init_meta (int interval); + bool reset_meta (int new_interval); + bool flush_meta_file (); + bool load_meta_file (); + void aggregate_2_hour (time_t gather_time); + void aggregate_2_day (time_t gather_time); + void aggregate_os (int read_offset, int buf_base, int write_offset, + AGG_TYPE atype, time_t gather_time); + void aggregate_dbs (int read_offset, int buf_base, int write_offset, + AGG_TYPE atype, time_t gather_time); + void aggregate_brokers (int read_offset, int buf_base, int write_offset, + AGG_TYPE atype, time_t gather_time); + void gather_daily_brokers_mon (time_t gather_time); + bool gather_dbs_tran_query (time_t gather_time, Json::Value &db_tq); + void gather_daily_dbs_mon (time_t gather_time); + void gather_daily_os_mon (time_t gather_time); + bool reset_mon_file (string fpath, int block_num, int mlen, + int new_interval); + bool get_rrd_data (MDTYPE mdtype, string dpath, int didx, int midx, + int pfactor, bool ddiff, int mlen, Json::Value &res, string &errmsg) const; + bool m_get_mon_statistic (const Json::Value req, Json::Value &res, string &errmsg) const; + + private: + static cm_mon_stat *_instance; + const string _data_path; + const string _meta_file; + Json::Value _meta; + + int _daily_idx; + int _monthly_idx; + int _yearly_idx; + time_t _prev_gather; + Json::Value _brokers; + Json::Value _dbs; + MUTEX_T _data_mutex; + bool _init; +}; + +#endif /* _CM_MON_STAT_H_ */ diff --git a/server/src/am_porting.h b/server/src/am_porting.h new file mode 100644 index 0000000..13e7c6c --- /dev/null +++ b/server/src/am_porting.h @@ -0,0 +1,339 @@ +/* + * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. + * + * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + + +/* + * cm_porting.h - + */ + +#ifndef _CM_PORTING_H_ +#define _CM_PORTING_H_ + +/* + * IMPORTED SYSTEM HEADER FILES + */ +#include "config.h" + +#include + +#if defined(WINDOWS) && !defined (EOVERFLOW) +#define EOVERFLOW 75 +#endif + + +#if !defined(WINDOWS) +#include +#include +#include +#else +#include +#endif + +/* + * IMPORTED OTHER HEADER FILES + */ + +/* + * EXPORTED DEFINITIONS + */ +#if defined(WINDOWS) +#define PATH_MAX 256 +#endif + +#if !defined(NAME_MAX) +#define NAME_MAX 256 +#endif + +#define MOVE_FILE(SRC_FILE, DEST_FILE) \ + (unlink(DEST_FILE) || 1 ? rename(SRC_FILE, DEST_FILE) : -1) + +#if defined(WINDOWS) +#define CLOSE_SOCKET(X) if (!IS_INVALID_SOCKET(X)) closesocket(X) +#else +#define CLOSE_SOCKET(X) if (!IS_INVALID_SOCKET(X)) close(X) +#endif + +#if defined(WINDOWS) +#define mkdir(dir, mode) _mkdir(dir) +#define access(dir, mode) _access(dir, mode) +#define unlink(file) _unlink(file) +#define getpid() _getpid() +#define O_RDONLY _O_RDONLY +#define strcasecmp(str1, str2) _stricmp(str1, str2) +#define strncasecmp(str1, str2, size) _strnicmp(str1, str2, size) +#define snprintf _snprintf + +#define R_OK 4 +#define W_OK 2 +#define F_OK 0 +#define X_OK F_OK + +/* +* MAXHOSTNAMELEN definition +* This is defined in sys/param.h on the linux. +*/ +#define MAXHOSTNAMELEN 64 + +#endif + +#if defined(WINDOWS) +#define SLEEP_SEC(X) Sleep((X) * 1000) +#define SLEEP_MILISEC(sec, msec) Sleep((sec) * 1000 + (msec)) +#else +#define SLEEP_SEC(X) sleep(X) +#define SLEEP_MILISEC(sec, msec) \ + do { \ + struct timeval sleep_time_val; \ + sleep_time_val.tv_sec = sec; \ + sleep_time_val.tv_usec = (msec) * 1000; \ + select(0, 0, 0, 0, &sleep_time_val); \ + } while(0) +#endif + +#if defined(WINDOWS) +#define TIMEVAL_MAKE(X) _ftime(X) +#define TIMEVAL_GET_SEC(X) ((int) ((X)->time)) +#define TIMEVAL_GET_MSEC(X) ((int) ((X)->millitm)) +#else +#define TIMEVAL_MAKE(X) gettimeofday(X, NULL) +#define TIMEVAL_GET_SEC(X) ((int) ((X)->tv_sec)) +#define TIMEVAL_GET_MSEC(X) ((int) (((X)->tv_usec) / 1000)) +#endif + +#if defined(WINDOWS) +#define THREAD_BEGIN(THR_ID, FUNC, ARG) \ + do { \ + THR_ID = _beginthread(FUNC, 0, (void*) (ARG)); \ + } while(0) +#elif HPUX10_2 +#define THREAD_BEGIN(THR_ID, FUNC, ARG) \ + do { \ + pthread_create(&(THR_ID), pthread_attr_default, FUNC, ARG); \ + pthread_detach(THR_ID); \ + } while (0) +#elif UNIXWARE7 +#define THREAD_BEGIN(THR_ID, FUNC, ARG) \ + do { \ + pthread_attr_t thread_attr; \ + pthread_attr_init(&thread_attr); \ + pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED); \ + pthread_attr_setstacksize(&thread_attr, 100 * 1024); \ + if (pthread_create(&(THR_ID), &thread_attr, FUNC, ARG) < 0){ \ + free ((void *) ARG); \ + ARG = NULL; \ + } \ + pthread_attr_destroy(&thread_attr); \ + } while (0) +#else +#define THREAD_BEGIN(THR_ID, FUNC, ARG) \ + do { \ + pthread_attr_t thread_attr; \ + pthread_attr_init(&thread_attr); \ + pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED); \ + if (pthread_create(&(THR_ID), &thread_attr, FUNC, ARG) < 0){ \ + free ((void *) ARG); \ + ARG = NULL; \ + } \ + pthread_attr_destroy(&thread_attr); \ + } while (0) +#endif + +#if defined(WINDOWS) +#define THREAD_CANCEL(THR_ID) \ + do{ \ + if (THR_ID){ \ + TerminateThread((HANDLE)THR_ID, 0); \ + } \ + } while(0) +#else +#define THREAD_CANCEL(THR_ID) \ + do{ \ + if (THR_ID){ \ + pthread_cancel (THR_ID); \ + } \ + } while(0) +#endif + + +#ifdef UNIXWARE7 +#define PROC_FORK() fork1() +#else +#define PROC_FORK() fork() +#endif + +/* + * EXPORTED TYPE DEFINITIONS + */ + +#if defined(WINDOWS) +typedef struct _timeb T_TIMEVAL; +#else +typedef struct timeval T_TIMEVAL; +#endif + +#if defined(WINDOWS) || defined(SOLARIS) || defined(HPUX) +typedef int T_SOCKLEN; +#elif defined(UNIXWARE7) +typedef size_t T_SOCKLEN; +#else +typedef socklen_t T_SOCKLEN; +#endif + +#if defined(WINDOWS) +#define IS_INVALID_SOCKET(socket) ((socket) == INVALID_SOCKET) +#else +typedef int SOCKET; +#define INVALID_SOCKET (-1) +#define IS_INVALID_SOCKET(socket) ((socket) < 0) +#endif + +#ifdef HAVE_INT64_T +typedef int64_t INT64; +#elif SIZEOF_LONG == 8 +typedef long INT64; +#elif SIZEOF_LONG_LONG == 8 +/* typedef long long INT64; */ +#else +#error "Error: INT64" +#endif + +/* + * EXPORTED DEFINITIONS + */ + +#if defined(WINDOWS) +#define THREAD_FUNC void +#define T_THREAD uintptr_t +#else +#define THREAD_FUNC void* +#define T_THREAD pthread_t +#endif + +#if defined(WINDOWS) +#define DEL_FILE "del" +#define DEL_FILE_OPT "/F /Q" +#define DEL_DIR "rmdir" +#define DEL_DIR_OPT "/S /Q" +#else +#define DEL_FILE "rm" +#define DEL_FILE_OPT "-f" +#define DEL_DIR "rm" +#define DEL_DIR_OPT "-rf" +#endif + +#if !defined(WINDOWS) +#define TRUE 1 +#define FALSE 0 +#endif + +#if !HAVE_BZERO && HAVE_MEMSET +#define bzero(buf, bytes) ((void) memset (buf, 0, bytes)) +#endif + +/* MUTEX & COND TYPE */ +#if defined(WINDOWS) +#define MUTEX_T HANDLE +#define COND_T HANDLE +#else +#define MUTEX_T pthread_mutex_t +#define COND_T pthread_cond_t +#endif + +/* MUTEX SIGNAL */ +#if defined(WINDOWS) +#define MUTEX_INIT(MUTEX) \ + ((MUTEX = CreateMutex(NULL, FALSE, NULL)) != NULL ? \ + 0 : -1 ) + +#define MUTEX_DESTROY(handle) \ + ( (handle = (void *)(!CloseHandle(handle))) == 0 ? \ + 0 : -1) + +#define MUTEX_LOCK(mutex) \ + ( WaitForSingleObject(mutex, INFINITE) == WAIT_OBJECT_0 ? \ + 0 : -1) + +#define MUTEX_UNLOCK(mutex) \ + ( ReleaseMutex(mutex) != 0 ? 0 : -1 ) +#elif HPUX10_2 +#define MUTEX_INIT(MUTEX) \ + pthread_mutex_init(MUTEX, pthread_mutexattr_default); +#else + +#define MUTEX_INIT(mutex) \ + ( pthread_mutex_init(&(mutex), NULL) == 0 ? \ + 0 : -1) + +#define MUTEX_DESTROY(mutex) \ + ( pthread_mutex_destroy(&(mutex)) == 0 ? \ + 0 : -1) + +#define MUTEX_LOCK(mutex) \ + ( pthread_mutex_lock(&(mutex)) == 0 ? \ + 0 : -1) + +#define MUTEX_UNLOCK(mutex) \ + ( pthread_mutex_unlock(&(mutex)) == 0 ? \ + 0 : -1) + +#endif + +/* CONDITION SIGNAL */ +#if defined(WINDOWS) +/* Creates an Event of auto-reset mode */ +#define COND_INIT(cond_var) \ + ((cond_var = CreateEvent(NULL, FALSE, FALSE, NULL)) != NULL ? 0 : -1) + +#define COND_WAIT(cond_var, mutex) \ + (SignalObjectAndWait(mutex, cond_var, INFINITE, FALSE) == WAIT_OBJECT_0 ? \ + 0 : -1) + +#define COND_TIMEDWAIT(cond_var, mutex, timeout) \ + SignalObjectAndWait(mutex, cond_var, timeout, FALSE) + +/* For an auto-reset event object, PulseEvent() returns after releasing a + * waiting thread. If no threads are waiting, nothing happens - it simply + * returns. + */ +#define COND_SIGNAL(cond_var) (PulseEvent(cond_var) !=0 ? 0 : -1) + +/* SetEvent() just wakes up one thread. It's actually not the broadcast. */ +#define COND_BROADCAST(cond_var) (SetEvent(cond_var) !=0 ? 0 : -1 ) + +#define COND_DESTROY(cond_var) \ + ( (cond_var = (void *)CloseHandle(cond_var)) != 0 ? 0 : -1) +#else +/* Caution: + * There are some differences between pthreads and win32 threads + * over these macros of condition signal. Under the win32 threads, + * 1. COND_WAIT() returns without acquiring lock. + * 2. COND_BROADCAST() does not release all waiting threads, but keep + * signaling until only a thread is released. It continues signaling + * even if there is no thread to be waken up when this macro is called. + * You should take these into account for portability. + */ +#define COND_INIT(condvar) pthread_cond_init(&(condvar), NULL) +#define COND_WAIT(c, m) pthread_cond_wait(&(c), &(m)) +#define COND_TIMEDWAIT(c, m, t) pthread_cond_timedwait(&(c), &(m), &(t)) +#define COND_SIGNAL(c) pthread_cond_signal(&(c)) +#define COND_BROADCAST(c) pthread_cond_broadcast(&(c)) +#define COND_DESTROY(condvar) pthread_cond_destroy(&(condvar)) +#endif + +#endif /* _CM_PORTING_H_ */ diff --git a/server/src/am_server_autoupdate.cpp b/server/src/am_server_autoupdate.cpp new file mode 100644 index 0000000..59fbaca --- /dev/null +++ b/server/src/am_server_autoupdate.cpp @@ -0,0 +1,386 @@ +/* + * Copyright (C) 2014 Search Solution Corporation. All rights reserved by Search Solution. + * + * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +/* +* cm_server.autoupdate.cpp +*/ + +#include "cm_server_autoupdate.h" +#include "cm_compress.h" +#include "cm_config.h" +#include "cm_dep.h" + +#ifdef WINDOWS +#include +#include +#include +#else +#include +#endif + +#ifdef WINDOWS + +#undef UNICODE +#pragma comment(lib, "wininet.lib") + +int +generate_update_script (char *patch_name, char *url, char *path, + char *_dbmt_error) +{ + unsigned char file_buffer[DOWNLOAD_BUFFER]; + + char zip_file[PATH_MAX]; + char zip_folder[PATH_MAX]; + char host_name[NAME_MAX]; + char remote_path[PATH_MAX]; + char shell_name[PATH_MAX]; + + HINTERNET handle_open = 0; + HINTERNET handle_connect = 0; + HINTERNET handle_request = 0; + + DWORD read_bytes = 0; + + FILE *fout; + + size_t sum_size = 0; + + if (url == NULL || strcmp (url, "") == 0) + { + strncpy (host_name, DEFAULT_UPDATE_HOST_NAME, PATH_MAX); + sprintf (remote_path, DEFAULT_UPDATE_REMOTE_PATH "%s", patch_name); + } + else + { + // TODO: use a static function instead, and offer more strict conditions. + + char *iter1, *iter2; + + iter1 = strstr (url, "//"); + iter2 = strstr (iter1 + 2, "/"); + + strncpy (host_name, iter1 + 2, iter2 - iter1 - 2); + strncpy (remote_path, iter2, PATH_MAX); + } + + if (InternetAttemptConnect (0) != ERROR_SUCCESS) + { + sprintf (_dbmt_error, + "InternetAttemptConnect(): CM Server is offline."); + return ERR_SYSTEM_CALL; + } + + handle_open = + InternetOpen (TEXT ("auto_update"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, + NULL, 0); + if (handle_open == NULL) + { + sprintf (_dbmt_error, "InternetOpen() : failed."); + + return ERR_SYSTEM_CALL; + } + + handle_connect = + InternetConnect (handle_open, host_name, INTERNET_INVALID_PORT_NUMBER, + NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0); + if (handle_connect == NULL) + { + sprintf (_dbmt_error, "InternetConnect(): failed."); + + InternetCloseHandle (handle_open); + + return ERR_SYSTEM_CALL; + } + + handle_request = + HttpOpenRequest (handle_connect, TEXT ("GET"), remote_path, NULL, NULL, + NULL, INTERNET_FLAG_RELOAD, 0); + if (handle_request == NULL) + { + sprintf (_dbmt_error, "HttpOpenRequest(): failed."); + + InternetCloseHandle (handle_connect); + InternetCloseHandle (handle_open); + + return ERR_SYSTEM_CALL; + } + + if (!HttpSendRequest (handle_request, NULL, 0, NULL, 0)) + { + int err = GetLastError (); + sprintf (_dbmt_error, + "HttpSendRequest(): failed, an error %d happened.", err); + + InternetCloseHandle (handle_request); + InternetCloseHandle (handle_connect); + InternetCloseHandle (handle_open); + + return ERR_SYSTEM_CALL; + } + + sprintf (zip_file, "%s%s", path, patch_name); + fout = fopen (zip_file, "wb+"); + if (fout == NULL) + { + sprintf (_dbmt_error, "%s", zip_file); + return ERR_FILE_OPEN_FAIL; + } + + do + { + + if (!InternetReadFile + (handle_request, file_buffer, DOWNLOAD_BUFFER, &read_bytes)) + { + sprintf (_dbmt_error, "InternetReadFile(): download file failed!"); + + InternetCloseHandle (handle_request); + InternetCloseHandle (handle_connect); + InternetCloseHandle (handle_open); + + fclose (fout); + + return ERR_SYSTEM_CALL; + } + + fwrite (file_buffer, sizeof (unsigned char), read_bytes, fout); + + sum_size += read_bytes; + printf ("sum_size = %d\n", sum_size); + + } + while (read_bytes == DOWNLOAD_BUFFER); + + fclose (fout); + + strncpy (zip_folder, path, PATH_MAX); + strcat (zip_folder, "patch"); + // create the folder for extracting zip file, otherwise unzip will fail. + if (access (zip_folder, 0) != 0 && !CreateDirectory (zip_folder, NULL)) + { + sprintf (_dbmt_error, "CreateDirectory(): create %s dir failed.", + zip_folder); + return ERR_SYSTEM_CALL; + } + + if (!unzip (zip_file, zip_folder)) + { + sprintf (_dbmt_error, "unzip %s failed.", zip_file); + return ERR_SYSTEM_CALL; + } + + sprintf (shell_name, "%s" SHELL_NAME, path); + fout = fopen (shell_name, "w+"); + if (fout == NULL) + { + sprintf (_dbmt_error, SHELL_NAME); + return ERR_FILE_OPEN_FAIL; + } + + // backup + fprintf (fout, "md %sbackup\n", path); + fprintf (fout, + "if exist %s\\bin\\arn_manager.exe copy /y %s\\bin\\arn_manager.exe %sbackup\\.\n", + sco.szArniadb, sco.szArniadb, path); + fprintf (fout, + "if exist %s\\bin\\cm_admin.exe copy /y %s\\bin\\cm_admin.exe %sbackup\\.\n", + sco.szArniadb, sco.szArniadb, path); + + fprintf (fout, "arniadb service stop\n"); + fprintf (fout, "arn_manager stop\n"); + + //update + fprintf (fout, "if exist %s\\arn_* copy /y %s\\arn_* %s\\bin\\.\n", + zip_folder, zip_folder, sco.szArniadb); + fprintf (fout, + "if exist %s\\cm_admin copy /y %s\\cm_admin.exe %s\\bin\\.\n", + zip_folder, zip_folder, sco.szArniadb); + fprintf (fout, + "for /f %%%%c in ('dir /b %s\\conf\\') do type %s\\conf\\%%%%c >> %s\\conf\\%%%%c\n", + zip_folder, zip_folder, sco.szArniadb); + + fprintf (fout, "ping 127.0.0.1 -n 40 -w 1000 > nul\n"); + fprintf (fout, "arniadb service start\n"); + fprintf (fout, "arn_manager start\n"); + fprintf (fout, "echo \"ARNIADB Manager Server is updated.\"", path); + + fclose (fout); + + return ERR_NO_ERROR; +} + +#else + +int +generate_update_script (char *patch_name, char *url, char *path, + char *_dbmt_error) +{ + FILE *fout; + char shell_name[PATH_MAX]; + char chmod_cmd[PATH_MAX]; + + if (url == NULL || strcmp (url, "") == 0) + { + strncpy (url, DEFAULT_PATCH_URL, PATH_MAX); + } + + sprintf (shell_name, "%s" SHELL_NAME, path); + + fout = fopen (shell_name, "w"); + if (fout == NULL) + { + sprintf (_dbmt_error, SHELL_NAME); + return ERR_FILE_OPEN_FAIL; + } + + fprintf (fout, "rm -rf %spatch*\n", path); + fprintf (fout, "wget -T 60 %s -P %s\n", url, path); + fprintf (fout, "if [ $? -ne 0 ]; then\n"); + fprintf (fout, "\techo \"download patch file failed!\"\nfi\n"); + + fprintf (fout, "unzip -u %s%s -d %spatch\n", path, patch_name, path); + fprintf (fout, "if [ $? -ne 0 ]; then\n"); + fprintf (fout, "\techo \"unzip patch file failed!\"\nfi\n"); + + fprintf (fout, "mkdir %sbackup\n", path); + fprintf (fout, + "cp %s/bin/cm_admin %s/bin/arn_manager %sbackup/.\n", + sco.szArniadb, sco.szArniadb, path); + fprintf (fout, + "if [ -e %spatch/arn_manager ]; then\n", path); + fprintf (fout, "\tcp %spatch/arn_* %s/bin/. -f\nfi\n", path, sco.szArniadb); + + fprintf (fout, "if [ -e %spatch/cm_admin ]; then\n", path); + fprintf (fout, "\tcp %spatch/cm_admin %s/bin/. -f\nfi\n", path, + sco.szArniadb); + + + fprintf (fout, "if [ -d %spatch/conf ]; then\n", path); + fprintf (fout, "\tfor conf_file in $(ls %spatch/conf)\n\tdo\n", path); + fprintf (fout, "\t\tcp %s/conf/$conf_file %sbackup/.\n", sco.szArniadb, + path); + fprintf (fout, + "\t\tcat %spatch/conf/$conf_file >> %s/conf/$conf_file\n\tdone\nfi\n", + path, sco.szArniadb); + + fprintf (fout, "arniadb service restart\n"); + fprintf (fout, "echo \"ARNIADB Manager Server is updated.n"); + + fclose (fout); + + sprintf (chmod_cmd, "chmod +x %s", shell_name); + system (chmod_cmd); + + return ERR_NO_ERROR; +} + +#endif + +mz_bool +unzip (const char *zip_file, const char *unzip_dir) +{ + + mz_uint i; + + mz_bool status; + + mz_uint num_files, file_index; + + mz_zip_archive zip_archive; + + char unzip_file[MAX_LINE]; + + if (NULL == zip_file || NULL == unzip_dir) + { + return MZ_FALSE; + } + + //Now try to open the archive. + memset (&zip_archive, 0, sizeof (zip_archive)); + + status = mz_zip_reader_init_file (&zip_archive, zip_file, 0); + + if (!status) + { + return MZ_FALSE; + } + + num_files = mz_zip_reader_get_num_files (&zip_archive); + + //Get and print information about each file in the archive. + for (i = 0; i < num_files; i++) + { + + mz_zip_archive_file_stat file_stat; + status = mz_zip_reader_file_stat (&zip_archive, i, &file_stat); + + if (!status) + { + mz_zip_reader_end (&zip_archive); + return MZ_FALSE; + } + + snprintf (unzip_file, MAX_LINE, "%s/%s", unzip_dir, + file_stat.m_filename); + + file_index = + mz_zip_reader_locate_file (&zip_archive, file_stat.m_filename, NULL, + 0); + + if (mz_zip_reader_is_file_a_directory (&zip_archive, file_index)) + { + //create sub directory according to the folder's name, which is zipped in zip file. +#ifdef WINDOWS + if (access (unzip_file, 0) != 0 + && !CreateDirectory (unzip_file, NULL)) +#else + mode_t old_mode = umask (0); + if (access (unzip_file, 0) != 0 && mkdir (unzip_file, 0700) != 0) +#endif + { +#ifndef WINDOWS + umask (old_mode); +#endif + mz_zip_reader_end (&zip_archive); + return MZ_FALSE; + } +#ifndef WINDOWS + umask (old_mode); +#endif + continue; + } + + status = + mz_zip_reader_extract_file_to_file (&zip_archive, + file_stat.m_filename, unzip_file, + 0); + + if (!status) + { + mz_zip_reader_end (&zip_archive); + return MZ_FALSE; + } + } + + + mz_zip_reader_end (&zip_archive); + + return MZ_TRUE; + +} diff --git a/server/src/am_server_autoupdate.h b/server/src/am_server_autoupdate.h new file mode 100644 index 0000000..2eb0cc3 --- /dev/null +++ b/server/src/am_server_autoupdate.h @@ -0,0 +1,24 @@ +#ifndef _CM_SERVER_AUTOUPDATE_H_ +#define _CM_SERVER_AUTOUPDATE_H_ + +#ifdef WINDOWS + +#define DEFAULT_UPDATE_HOST_NAME "jira.arniadb.org" +#define DEFAULT_UPDATE_REMOTE_PATH "/secure/attachment/14895/" +#define DOWNLOAD_BUFFER 16384 +#define SHELL_NAME "auto_update.bat" + +#else + +#define DEFAULT_PATCH_URL "http://jira.arniadb.org/secure/attachment/14806/patch_9.1.0001.zip" +#define SHELL_NAME "auto_update.sh" + +#endif + +#define MAX_LINE 1024 + +int generate_update_script (char *patch_name, char *url, char *path, + char *_dbmt_error); +int unzip (const char *zip_file, const char *unzip_dir); + +#endif diff --git a/server/src/am_server_extend_interface.cpp b/server/src/am_server_extend_interface.cpp new file mode 100644 index 0000000..f7edb43 --- /dev/null +++ b/server/src/am_server_extend_interface.cpp @@ -0,0 +1,2707 @@ +/* + * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. + * + * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#include "cm_log.h" + +#include +#ifdef WINDOWS +#include +#else +#include +#include +#include +#endif + +#include "cm_dep.h" +#include "cm_stat.h" +#include "cm_cmd_exec.h" +#include "cm_server_util.h" +#include "cm_text_encryption.h" +#include "cm_server_extend_interface.h" +#include "cm_mailer.h" +#include "cm_mon_stat.h" +#include "cm_user.h" + +#include +#include + +using namespace std; + +#ifndef MAX_PATH +#define MAX_PATH 260 +#endif + +#if defined(WINDOWS) +#define snprintf _snprintf +#ifndef strncasecmp +#define strncasecmp _strnicmp +#endif +#endif + +#define MIN_PASSWD_LENGTH 4 +#define MAX_TIME_LENGTH 10 + + +extern T_USER_TOKEN_INFO *user_token_info; +static T_EXTEND_TASK_INFO ext_task_info[] = +{ + {"getsysdiskinfo", 0, ext_get_sys_diskinfo, ALL_AUTHORITY}, + {"getprocstat", 0, ext_get_proc_info, ALL_AUTHORITY}, + {"setloglevel", 0, ext_set_log_level, AU_DBC | AU_DBO | AU_MON}, + {"setautostart", 0, ext_set_auto_start, AU_DBC | AU_DBO | AU_JOB}, + {"getautostart", 0, ext_get_auto_start, ALL_AUTHORITY}, + {"getautojobconf", 0, ext_get_autojob_conf, ALL_AUTHORITY}, + {"setautojobconf", 0, ext_set_autojob_conf, AU_DBC | AU_DBO | AU_JOB}, + {"execautostart", 0, ext_exec_auto_start, ALL_AUTHORITY}, + {"getdberrorlog", 0, ext_get_db_err_log, ALL_AUTHORITY}, + {"getbrokerlog", 0, ext_get_broker_start_log, ALL_AUTHORITY}, + {"sendmail", 0, ext_send_mail, ALL_AUTHORITY}, + {"automail", 0, ext_exec_auto_mail, AU_DBC | AU_DBO | AU_MON}, + {"readprivatedata", 0, ext_read_private_data, ALL_AUTHORITY}, + {"writeprivatedata", 0, ext_write_private_data, AU_DBC | AU_DBO | AU_BRK}, + {"setautoexecquery", 0, ext_set_autoexec_query, AU_DBC | AU_DBO | AU_JOB}, + {"gethaapplyinfo", 0, ext_get_ha_apply_info, ALL_AUTHORITY}, + {"adddbmtuser_new", 0, ext_add_dbmt_user_new, AU_DBC}, + {"updatedbmtuser_new", 0, ext_update_dbmt_user_new, AU_DBC | AU_DBO}, + {"getdbmtuserinfo_new", 0, ext_get_dbmt_user_info_new, AU_DBC | AU_DBO}, + {"get_mon_interval", 0, ext_get_mon_interval, AU_MON}, + {"set_mon_interval", 0, ext_set_mon_interval, AU_ADMIN}, + {"get_mon_statistic", 0, ext_get_mon_statistic, AU_MON}, + {NULL, 0, NULL, 0} +}; + +static bool +ext_get_id_from_token (const char *token, char token_content[][TOKEN_LENGTH+1]) +{ + char tmp_token[TOKEN_LENGTH+1]; + char *tmp_token_content[3]; + + uDecrypt (TOKEN_LENGTH, token, tmp_token); + + if (string_tokenize2 (tmp_token, tmp_token_content, 3, ':') < 0) + { + return false; + } + + // ip + strcpy (token_content[0], tmp_token_content[0]); + // port + strcpy (token_content[1], tmp_token_content[1]); + // id + strcpy (token_content[2], tmp_token_content[2]); + + return true; +} + +int +build_server_header (Json::Value &response, const int status, + const char *note) +{ + response["status"] = + (status == ERR_NO_ERROR) ? STATUS_SUCCESS : STATUS_FAILURE; + response["note"] = string (note); + return status; +} + +int +get_ext_task_info (const char *task, int access_flag, + T_EXT_TASK_FUNC *task_func, T_USER_AUTH *auth) +{ + int i; + + for (i = 0; ext_task_info[i].task_str != NULL; i++) + { + if (!strcmp (task, ext_task_info[i].task_str)) + { + if (access_flag < ext_task_info[i].access_level) + { + return 0; + } + if (task_func) + { + *task_func = ext_task_info[i].task_func; + } + + if (auth) + { + *auth = ext_task_info[i].user_auth; + } + + return 1; + } + } + + return 0; +} + +string +ull_to_str (const unsigned long long num) +{ + char buf[MAX_PATH]; + snprintf (buf, MAX_PATH, "%llu", num); + return string (buf); +} + +#ifdef WINDOWS +int +ext_get_sys_diskinfo (Json::Value &request, Json::Value &response) +{ + int flag = 0; + DWORD drives = GetLogicalDrives (); + ULARGE_INTEGER total_size; + ULARGE_INTEGER free_size; + Json::Value drive; + string drivename; + + while (drives) + { + if (drives & 1) + { + drivename = 'A' + flag; + drivename += ":"; + if (GetDriveType (drivename.c_str ()) == DRIVE_FIXED) + { + drive.clear (); + GetDiskFreeSpaceEx (drivename.c_str (), NULL, &total_size, + &free_size); + drive["name"] = drivename; + drive["total_size"] = ull_to_str (total_size.QuadPart); + drive["free_size"] = ull_to_str (free_size.QuadPart); + + response["disk_info"].append (drive); + } + } + drives >>= 1; + flag++; + } + + return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); +} +#else +int +ext_get_sys_diskinfo (Json::Value &request, Json::Value &response) +{ + struct statvfs buf; + int error; + Json::Value drive; + error = statvfs ("/", &buf); + + if (error < 0) + { + return build_server_header (response, ERR_WITH_MSG, + "get file system info error!"); + } + + drive["name"] = "/"; + drive["total_size"] = ull_to_str (buf.f_bsize * buf.f_blocks); + drive["free_size"] = ull_to_str (buf.f_bsize * buf.f_bfree); + + response["disk_info"].append (drive); + + return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); +} +#endif + +int +ext_get_proc_info (Json::Value &request, Json::Value &response) +{ + T_AMS_PROC_STAT stat; + int pid; + + pid = request.get ("pid", getpid ()).asInt (); + ut_get_proc_stat (&stat, pid); + + response["pid"] = stat.pid; + response["cpu_kernel"] = (unsigned int) stat.cpu_kernel; + response["cpu_user"] = (unsigned int) stat.cpu_user; + response["mem_physical"] = (unsigned int) stat.mem_physical; + response["mem_virtual"] = (unsigned int) stat.mem_virtual; + + return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); +} + +int +ext_set_log_level (Json::Value &request, Json::Value &response) +{ + unsigned int loglevel; + + loglevel = request.get ("log_level", CLog::xINFO).asUInt (); + + if (loglevel > CLog::xDEBUG) + { + return build_server_header (response, ERR_WITH_MSG, "invalid log level!"); + } + CLog::GetInstance (loglevel)->setLogLevel (loglevel); + response["log_level"] = loglevel; + return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); +} + +bool load_json_from_file (string filepath, Json::Value &root) +{ + bool rtn = FALSE; + Json::Reader reader; + ifstream ifs (filepath.c_str()); + if (!ifs.bad()) + { + rtn = reader.parse (ifs, root); + ifs.close(); + } + return rtn; +} + +bool write_json_to_file (string filepath, Json::Value &root) +{ + Json::StyledWriter writer; + ofstream ofs (filepath.c_str()); + if (!ofs.bad()) + { + ofs << writer.write (root) << endl; + ofs.close(); + return TRUE; + } + + return FALSE; +} + +int ext_arn_broker_start (Json::Value &request, Json::Value &response) +{ + string task = request["task"].asString(); + nvplist *cli_request, *cli_response; + char _dbmt_error[DBMT_ERROR_MSG_SIZE]; + int ret = ERR_NO_ERROR; + + memset (_dbmt_error, 0, sizeof (_dbmt_error)); + + cli_request = nv_create (5, NULL, "\n", ":", "\n"); + cli_response = nv_create (5, NULL, "\n", ":", "\n"); + + nv_add_nvp (cli_request, "task", task.c_str()); + + if (request["bname"] != Json::Value::null) + { + nv_add_nvp (cli_request, "bname", request["bname"].asString().c_str()); + ret = ts2_start_broker (cli_request, cli_response, _dbmt_error); + } + else + { + ret = ts2_start_unicas (cli_request, cli_response, _dbmt_error); + } + + if (ret == ERR_NO_ERROR) + { + response["status"] = STATUS_SUCCESS; + response["note"] = STATUS_NONE; + } + else + { + response["status"] = STATUS_FAILURE; + response["note"] = _dbmt_error; + } + nv_destroy (cli_request); + nv_destroy (cli_response); + return 0; +} + +bool ext_get_auto_jobs (const string jobkey, Json::Value &jobvalue) +{ + char conf_path[MAX_PATH]; + Json::Value root_jobs; + + if (load_json_from_file ( conf_get_dbmt_file (FID_AUTO_JOBS_CONF, conf_path), root_jobs) == FALSE) + { + LOG_DEBUG ("load json from %s error.", conf_path); + return FALSE; + } + if (jobkey == "") + { + jobvalue = root_jobs; + } + else + { + jobvalue = root_jobs[jobkey]; + } + return TRUE; +} + +bool ext_set_auto_jobs (const string jobkey, Json::Value &jobvalue) +{ + char conf_path[MAX_PATH]; + Json::Value root_jobs; + + if (load_json_from_file ( conf_get_dbmt_file (FID_AUTO_JOBS_CONF, conf_path), root_jobs) == FALSE) + { + LOG_WARN ("%s is not exist!", conf_path); + } + root_jobs[jobkey] = jobvalue; + return write_json_to_file (conf_path, root_jobs); +} + + +int +ext_get_auto_start (Json::Value &request, Json::Value &response) +{ + Json::Value root_jobs; + + if (ext_get_auto_jobs (EXT_JOBS_AUTO_START, root_jobs) == FALSE) + { + response[EXT_JOBS_AUTO_START] = Json::Value::null; + return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); + } + response[EXT_JOBS_AUTO_START] = root_jobs; + + return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); +} + +int +ext_set_auto_start (Json::Value &request, Json::Value &response) +{ + Json::Value root_jobs; + JSON_FIND_V (request, EXT_JOBS_AUTO_START, + build_server_header (response, ERR_PARAM_MISSING, "Parameter(auto_start) missing in the request")); + + JSON_FIND_V (request, "service", + build_server_header (response, ERR_PARAM_MISSING, "Parameter(service) missing in the request")); + + if (ext_get_auto_jobs (EXT_JOBS_AUTO_START, root_jobs) == FALSE) + { + LOG_WARN ("autojob configure file is not exist or error format!"); + } + + root_jobs[request["service"].asString()] = request[EXT_JOBS_AUTO_START]; + + if (ext_set_auto_jobs ( EXT_JOBS_AUTO_START, root_jobs) == FALSE) + { + LOG_WARN ("set auto_start jobs fail!"); + return build_server_header (response, ERR_WITH_MSG, "set auto_start jobs fail!"); + } + + return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); +} + +int +ext_get_autojob_conf (Json::Value &request, Json::Value &response) +{ + Json::Value root_jobs; + char decrypted[PASSWD_LENGTH + 1]; + string userpasswd; + string key = request.get ("service", "").asString(); + + if (ext_get_auto_jobs (key, root_jobs) == FALSE) + { + return build_server_header (response, ERR_WITH_MSG, "failed to get autojob conf"); + } + if (key == "mail_config") + { + userpasswd = root_jobs.get ("password", "").asString(); + uDecrypt (PASSWD_LENGTH, userpasswd.c_str(), decrypted); + root_jobs["password"] = decrypted; + } + + response["jobconf"] = root_jobs; + + return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); +} + +int +ext_set_autojob_conf (Json::Value &request, Json::Value &response) +{ + Json::Value root_jobs; + string keyvalue, password; + char encrypted[PASSWD_ENC_LENGTH]; + + JSON_FIND_V (request, "service", + build_server_header (response, ERR_PARAM_MISSING, "Parameter(service) missing in the request")); + + keyvalue = request["service"].asString(); + if (keyvalue == "mail_config") + { + if (request["jobconf"] != Json::Value::null + && request["jobconf"].type() == Json::objectValue + && request["jobconf"]["password"] != Json::Value::null) + { + password = request["jobconf"]["password"].asString(); + uEncrypt (PASSWD_LENGTH, password.c_str(), encrypted); + request["jobconf"]["password"] = encrypted; + } + else + { + return build_server_header (response, ERR_WITH_MSG, "error mail_config format!"); + } + } + if (ext_set_auto_jobs ( keyvalue, request["jobconf"]) == FALSE) + { + LOG_WARN ("set %s fail!", keyvalue.c_str()); + return build_server_header (response, ERR_WITH_MSG, "set autojob conf fail!"); + } + + return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); +} + +int ext_get_active_dbs (Json::Value &activedbs) +{ + T_SERVER_STATUS_RESULT *cmd_res; + int i; + cmd_res = cmd_server_status (); + if (cmd_res == NULL) + { + return 1; + } + T_SERVER_STATUS_INFO *info = (T_SERVER_STATUS_INFO *) cmd_res->result; + for (i = 0; i < cmd_res->num_result; i++) + { + activedbs .append (info[i].db_name); + } + cmd_servstat_result_free (cmd_res); + return 0; +} + +int ext_get_active_brokers (Json::Value &activebrokers) +{ + T_CM_BROKER_INFO_ALL uc_info; + T_CM_BROKER_CONF uc_conf; + T_CM_ERROR error; + Json::Value broker; + int i; + + if (cm_get_broker_conf (&uc_conf, NULL, &error) < 0) + { + return 1; + } + if (cm_get_broker_info (&uc_info, &error) < 0) + { + activebrokers["brokerstatus"] = "OFF"; + } + else + { + for (i = 0; i < uc_info.num_info; i++) + { + broker["name"] = uc_info.br_info[i].name; + broker["state"] = uc_info.br_info[i].status; + activebrokers["brokers"].append (broker); + } + activebrokers["brokerstatus"] = "ON"; + cm_broker_info_free (&uc_info); + } + + cm_broker_conf_free (&uc_conf); + return 0; +} + + +static void +ext_autojobs_log (const char *service, const char *serv_name, const char *errmsg) +{ + time_t tt; + tm *t; + FILE *outfile; + char logfile[MAX_PATH]; + char strbuf[MAX_PATH] = "unknown"; + + tt = time (&tt); + + snprintf (logfile, MAX_PATH, "%s/%s/autojobs.log", sco.szArniadb, DBMT_LOG_DIR); + + outfile = fopen (logfile, "a"); + if (outfile == NULL) + { + return; + } + t = localtime (&tt); + if (t) + { + strftime ( strbuf, MAX_PATH, "%Y%m%d_%H:%M:%S", t); + } + fprintf (outfile, "%s %s %s : %s\n",strbuf, service, serv_name, errmsg); + fclose (outfile); +} + + +int ext_exec_dbs_auto_start (const Json::Value &autodbs, Json::Value &response) +{ + unsigned int i, j, found; + char err_buf[ERR_MSG_SIZE]; + Json::Value activedbs; + string dbname; + + if (autodbs == Json::Value::null) + { + return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); + } + + if (ext_get_active_dbs (activedbs)) + { + LOG_ERROR ("get active db list failed!"); + return build_server_header (response, ERR_WITH_MSG, "get active db list failed!"); + } + + for (i = 0; i < autodbs.size(); i++) + { + found = 0; + dbname = autodbs[i].asString(); + for (j = 0; j < activedbs.size(); j++) + { + if (activedbs[j].asString() == dbname) + { + found = 1; + break; + } + } + + if (found == 0) + { + if (cmd_start_server ((char *)dbname.c_str(), err_buf, sizeof (err_buf)) < 0) + { + ext_autojobs_log ("databases", dbname.c_str(), err_buf); + response[EXT_JOBS_AUTO_START]["databases"][dbname] = err_buf; + } + else + { + ext_autojobs_log ("databases", dbname.c_str(), STATUS_SUCCESS); + response[EXT_JOBS_AUTO_START]["databases"][dbname] = STATUS_SUCCESS; + } + } + } + + return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); +} + +int ext_exec_brokers_auto_start (const Json::Value &autobrokers, Json::Value &response) +{ + unsigned int i,t; + Json::Value activebrokers, request; + string bname; + + if (autobrokers == Json::Value::null || autobrokers.size() == 0) + { + return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); + } + + if (ext_get_active_brokers (activebrokers)) + { + LOG_ERROR ("get active db list failed!"); + return build_server_header (response, ERR_WITH_MSG, "get active db list failed!"); + } + + if (activebrokers["brokerstatus"].asString() == "OFF") + { + request["task"] = "startbroker"; + ext_arn_broker_start (request, response); + + if (response["status"] != "success") + { + ext_autojobs_log ("brokers", "unicas", response["note"].asString().c_str()); + response[EXT_JOBS_AUTO_START]["brokers"]["@unicas"] = response["note"].asString(); + } + else + { + ext_autojobs_log ("brokers", "unicas", STATUS_SUCCESS); + response[EXT_JOBS_AUTO_START]["brokers"]["@unicas"] = STATUS_SUCCESS; + } + } + + for (t = 0; t < autobrokers.size(); t++) + { + for (i = 0; i < activebrokers["brokers"].size(); i++) + { + bname = activebrokers["brokers"][i]["name"].asString(); + if (bname == autobrokers[t].asString() && + activebrokers["brokers"][i]["state"].asString() == "OFF") + { + request["task"] = "broker_start"; + request["bname"] = bname; + ext_arn_broker_start (request, response); + + if (response["status"] != "success") + { + ext_autojobs_log ("brokers", bname.c_str(), response["note"].asString().c_str()); + response[EXT_JOBS_AUTO_START]["brokers"][bname] = response["note"].asString(); + } + else + { + ext_autojobs_log ("brokers", bname.c_str(), STATUS_SUCCESS); + response[EXT_JOBS_AUTO_START]["brokers"][bname] = STATUS_SUCCESS; + } + } + } + } + return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); +} + +string format_time (string str_time) +{ + string::iterator itor; + itor = str_time.begin(); + while ( itor != str_time.end()) + { + if (*itor == ' ' || *itor == '/' || *itor == ':') + { + itor = str_time.erase (itor); + } + else + { + itor++; + } + } + return str_time; +} + +string build_report_log (Json::Value &report) +{ + unsigned int i, j; + int log_type; + string report_log, url_prefix, db_name, tmp_str; + string start_time, end_time; + Json::Value logdata; + + start_time = report.get ("start_time", "").asString(); + end_time = report.get ("end_time", "").asString(); + url_prefix = report.get ("url_prefix", "").asString(); + db_name= report.get ("dbname", "").asString(); + log_type= report.get ("log_type", 0).asInt(); + + report_log = "
Hi, This is timed log report."; + report_log += "
"; + report_log += "
start time : " + start_time; + report_log += "
end time : " + end_time; + report_log += "
"; + switch (log_type) + { + case 0: + logdata = report["db"]; + if (logdata != Json::Value::null) + { + if (logdata["result"] != Json::Value::null) + { + report_log += ""; + for (i = 0; i < logdata["result"].size(); i++) + { + //report_log += ""; + tmp_str = ""; + if (report_log.size() > 1024) + { + report_log += ""; + break; + } + } + report_log += "
Databases Log Message
" + logdata["result"][i]["file"].asString() + "
"; + for (j = 0; j < logdata["result"][i]["logs"].size(); j++) + { + tmp_str += "
" + logdata["result"][i]["logs"][j].asString(); + if (tmp_str.size() > 256) + { + tmp_str += "
more logs in " + logdata["result"][i]["file"].asString(); + break; + } + } + report_log += tmp_str + "
......
"; + } + else + { + report_log += "
*** No record ***"; + } + } + else + { + report_log += "
*** No record ***"; + } + break; + case 1: + logdata = report["broker"]; + report_log += "
Log type : Broker start/stop log"; + if (logdata != Json::Value::null) + { + if (logdata["log"] != Json::Value::null) + { + report_log += ""; + for (i = 0; i < logdata["log"].size(); i++) + { + report_log += ""; + } + report_log += "
Broker Log Description
" + logdata["log"][i].asString() + "
"; + } + else + { + report_log += "
*** No record ***"; + } + } + else + { + report_log += "
*** No record ***"; + } + break; + default: + break; + } + report_log += "
See More Detail Log: ARNIADB Web Manager"; + return report_log; +} + +int update_next_report_time (Json::Value &mailreport) +{ + return 0; +} + +int ext_exec_mail_report (Json::Value &mailreport, Json::Value &response) +{ + unsigned int i, period_type, save_flag = 0; + Json::Value log_request, log_response, mail_conf; + time_t cur_time, next_time; + char format_time[PATH_MAX], next_exec_time[PATH_MAX]; + string next_exec, prev_exec, mailhead, mailbody, userpasswd; + char decrypted[PASSWD_LENGTH + 1]; + + if (mailreport == Json::Value::null || mailreport.size() == 0) + { + return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); + } + + if (ext_get_auto_jobs (EXT_JOBS_MAIL_CONF, mail_conf) == FALSE) + { + LOG_ERROR ("get mail config failed!"); + return build_server_header (response, ERR_WITH_MSG, "get mail config failed!"); + } + + if (mail_conf == Json::Value::null || mail_conf["onoff"].asInt() == 0) + { + return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); + } + + userpasswd = mail_conf.get ("password", "").asString(); + uDecrypt (PASSWD_LENGTH, userpasswd.c_str(), decrypted); + mail_conf["password"] = decrypted; + + cur_time = time (NULL); + time_to_str (cur_time, "%4d/%02d/%02d %02d:%02d:%02d", format_time, TIME_STR_FMT_DATE_TIME); + for (i = 0; i < mailreport.size(); i++) + { + if (mailreport[i]["receiver"] == Json::Value::null) + { + continue; + } + if (mailreport[i]["dbname"] == Json::Value::null) + { + continue; + } + if (mailreport[i]["url_prefix"] == Json::Value::null) + { + continue; + } + + next_exec = ""; + prev_exec = ""; + mailbody = ""; + if (mailreport[i]["prev_exec"] != Json::Value::null) + { + prev_exec = mailreport[i]["prev_exec"].asString(); + } + if (mailreport[i]["next_exec"] != Json::Value::null) + { + next_exec = mailreport[i]["next_exec"].asString(); + } + if ( strcmp (format_time, next_exec.c_str()) < 0) + { + continue; + } + + log_request["dbname"] = mailreport[i]["dbname"].asString(); + log_request["start_time"] = prev_exec; + log_request["end_time"] = format_time; + + mailhead = "Log Report for ARNIADB"; + + log_response["dbname"] = mailreport[i]["dbname"].asString(); + log_response["url_prefix"] = mailreport[i]["url_prefix"].asString(); + log_response["start_time"] = prev_exec; + log_response["end_time"] = format_time; + log_response["log_type"] = mailreport[i].get ("log_type", 0).asInt(); + + ext_get_db_err_log (log_request, log_response["db"]); + ext_get_broker_start_log (log_request, log_response["broker"]); + mailbody += build_report_log (log_response); + + mail_conf["receiver"] = mailreport[i]["receiver"]; + mail_conf["msg_header"] = mailhead; + mail_conf["msg_body"] = mailbody; + mail_conf["body_type"] = 1; + ext_send_mail (mail_conf, response); + + period_type = mailreport[i].get ("period_type", 2).asInt(); + switch (period_type) + { + case 0: /* daily */ + next_time = cur_time + 24 * 60 * 60; + break; + case 1: /* weekly */ + next_time = cur_time + 7 * 24 * 60 * 60; + break; + default: /* monthly */ + next_time = cur_time + 30 * 24 * 60 * 60; + break; + } + time_to_str (next_time, "%4d/%02d/%02d %02d:%02d:%02d", next_exec_time, TIME_STR_FMT_DATE_TIME); + mailreport[i]["next_exec"] = next_exec_time; + mailreport[i]["prev_exec"] = format_time; + save_flag = 1; + } + + if (save_flag) + { + ext_set_auto_jobs ("mail_report", mailreport); + } + + return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); +} + +int ext_exec_auto_mail (Json::Value &request, Json::Value &response) +{ + Json::Value mail_report; + if (ext_get_auto_jobs (EXT_JOBS_MAIL_REPORT, mail_report) == FALSE) + { + LOG_WARN ("get mail report config failed!"); + return build_server_header (response, ERR_WITH_MSG, "get mail report config failed!"); + } + return ext_exec_mail_report (mail_report, response); +} + +int ext_exec_auto_start (Json::Value &request, Json::Value &response) +{ + Json::Value autojobs; + string dbname; + + if (ext_get_auto_jobs (EXT_JOBS_AUTO_START, autojobs) == FALSE) + { + LOG_DEBUG ("get auto start jobs failed."); + return build_server_header (response, ERR_WITH_MSG, "get auto start jobs failed."); + } + + if (autojobs == Json::Value::null) + { + return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); + } + + ext_exec_brokers_auto_start (autojobs["brokers"], response); + ext_exec_dbs_auto_start (autojobs["databases"], response); + + return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); +} + +int ext_exec_auto_jobs (Json::Value &request, Json::Value &response) +{ + ext_exec_auto_start (request, response); + // Fix for TOOLS-3452 + // Delivery this fuctionality next version Aug/3/2013 + //ext_exec_auto_mail(request, response); + return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); +} + + +int ext_get_db_err_log (Json::Value &request, Json::Value &response) +{ + string start_d, end_d; + string dbname; + char log_dir[PATH_MAX], find_file[PATH_MAX], format_time[PATH_MAX]; + char buf[1024], logbuf[1024]; +#if defined(WINDOWS) + WIN32_FIND_DATA data; + HANDLE handle; + int found; +#else + DIR *dirp = NULL; + struct dirent *dp = NULL; +#endif + struct stat statbuf; + char *fname; + int fname_len = 0, logsize = 0; + Json::Value logitem; + FILE *fd; + JSON_FIND_V (request, "dbname", + build_server_header (response, ERR_PARAM_MISSING, "Parameter(dbname) missing in the request")); + + dbname = request["dbname"].asString(); + if (request["start_time"] != Json::Value::null) + { + start_d = request["start_time"].asString(); + } + if (request["end_time"] != Json::Value::null) + { + end_d = request["end_time"].asString(); + } + response["start_time"] = start_d; + response["end_time"] = end_d; + response["dbname"] = dbname; + + if (uRetrieveDBDirectory (dbname.c_str(), log_dir) != ERR_NO_ERROR) + { + return build_server_header (response, ERR_DBDIRNAME_NULL, "Can not find the directory!"); + } + + snprintf (find_file, PATH_MAX - 1, "%s/%s", sco.szArniadb, ARNIADB_ERROR_LOG_DIR); +#if defined(WINDOWS) + snprintf (&find_file[strlen (find_file)], PATH_MAX - strlen (find_file) - 1, "/*"); + if ((handle = FindFirstFile (find_file, &data)) == INVALID_HANDLE_VALUE) +#else + if ((dirp = opendir (find_file)) == NULL) +#endif + { + return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); + } +#if defined(WINDOWS) + for (found = 1; found; found = FindNextFile (handle, &data)) +#else + while ((dp = readdir (dirp)) != NULL) +#endif + { +#if defined(WINDOWS) + fname = data.cFileName; +#else + fname = dp->d_name; +#endif + fname_len = (int) strlen (fname); + /* the "4" is the size of ".err" */ + if (fname_len < 4 || (strcmp (fname + fname_len - 4, ".err") != 0)) + { + continue; + } + if (memcmp (fname, dbname.c_str(), dbname.size())) + { + continue; + } + snprintf (buf, sizeof (buf) - 1, "%s/%s/%s", sco.szArniadb, ARNIADB_ERROR_LOG_DIR, fname); + if (stat (buf, &statbuf) == 0) + { + time_to_str (statbuf.st_mtime, "%4d/%02d/%02d %02d:%02d:%02d", format_time, TIME_STR_FMT_DATE_TIME); + if (!start_d.empty() && strcmp (start_d.c_str(), format_time) > 0) + { + continue; + } + if (!end_d.empty() && strcmp (end_d.c_str(), format_time) < 0) + { + continue; + } + logitem.clear(); + logitem["file"] = buf; + fd = fopen (buf, "r"); + if (fd == NULL) + { + continue; + } + while (fgets (logbuf, sizeof (logbuf), fd) != NULL) + { + ut_trim (logbuf); + logitem["logs"].append (logbuf); + logsize++; + if (logsize > 2000) + { + break; + } + } + fclose (fd); + response["result"].append (logitem); + if (logsize > 2000) + { + response["overflow"] = 1; + break; + } + } + } +#if defined(WINDOWS) + FindClose (handle); +#else + closedir (dirp); +#endif + + return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); +} + + +int ext_get_broker_start_log (Json::Value &request, Json::Value &response) +{ + char log_file[PATH_MAX]; + char logbuf[1024]; + FILE *fd; + string start_d, end_d; + char *tok[2]; + string format_time, strlog; + int logsize = 0; + + snprintf (log_file, PATH_MAX - 1, "%s/%s/arniadb_broker.log", sco.szArniadb, ARNIADB_BROKER_LOG_DIR); + fd = fopen (log_file, "r"); + if (fd == NULL) + { + return build_server_header (response, ERR_WITH_MSG, "Can't find arniadb_broker.log"); + } + + if (request["start_time"] != Json::Value::null) + { + start_d = request["start_time"].asString(); + } + if (request["end_time"] != Json::Value::null) + { + end_d = request["end_time"].asString(); + } + response["start_time"] = start_d; + response["end_time"] = end_d; + response["file"] = log_file; + + while (fgets (logbuf, sizeof (logbuf), fd) != NULL) + { + ut_trim (logbuf); + strlog = logbuf; + if (string_tokenize (logbuf, tok, 2) < 0) + { + continue; + } + format_time = string (tok[0]) + " " + string (tok[1]); + if (!start_d.empty() && strcmp (start_d.c_str(), format_time.c_str()) > 0) + { + continue; + } + if (!end_d.empty() && strcmp (end_d.c_str(), format_time.c_str()) < 0) + { + continue; + } + response["log"].append (strlog); + logsize++; + if (logsize > 2000) + { + response["overflow"] = 1; + break; + } + } + fclose (fd); + return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); +} + +int ext_send_mail (Json::Value &request, Json::Value &response) +{ + string sender, receiver; + string smtp_server, uname, passwd; + string msg_body, msg_header; + jwsmtp::mailer mail; + int auth_type, body_type; + Json::Value result; + + JSON_FIND_V (request, "sender", + build_server_header (response, ERR_PARAM_MISSING, "Parameter(sender) missing in the request")); + JSON_FIND_V (request, "receiver", + build_server_header (response, ERR_PARAM_MISSING, "Parameter(receiver) missing in the request")); + JSON_FIND_V (request, "smtp_server", + build_server_header (response, ERR_PARAM_MISSING, "Parameter(smtp_server) missing in the request")); + JSON_FIND_V (request, "username", + build_server_header (response, ERR_PARAM_MISSING, "Parameter(username) missing in the request")); + JSON_FIND_V (request, "password", + build_server_header (response, ERR_PARAM_MISSING, "Parameter(password) missing in the request")); + + sender = request["sender"].asString(); + mail.setsender (sender); + + receiver = request["receiver"].asString(); + mail.addrecipient (receiver); + + smtp_server = request["smtp_server"].asString(); + mail.setserver (smtp_server); + + auth_type = request.get ("authtype", 2).asInt(); + mail.authtype ((enum jwsmtp::mailer::authtype)auth_type); + + uname = request["username"].asString(); + mail.username (uname); + + passwd = request["password"].asString(); + mail.password (passwd); + + msg_header = request.get ("msg_header", "").asString(); + mail.setsubject (msg_header); + + msg_body = request.get ("msg_body", "").asString(); + body_type = request.get ("body_type", 0).asInt(); + if (body_type == 1) + { + mail.setmessageHTML (msg_body); + } + else + { + mail.setmessage (msg_body); + } + + mail.send(); + result["receiver"] = receiver; + result["message"] = mail.response(); + response["response"].append (result); + return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); +} + +int ext_write_private_data (Json::Value &request, Json::Value &response) +{ + FILE *outfile; + unsigned int i; + string confname; + Json::Value confdata; + char conf_path[PATH_MAX]; + + JSON_FIND_V (request, "confname", + build_server_header (response, ERR_PARAM_MISSING, "Parameter(confname) missing in the request")); + + confname= request["confname"].asString(); + snprintf (conf_path, PATH_MAX, "%s/%s/%s", sco.szArniadb, DBMT_LOG_DIR, confname.c_str()); + + outfile = fopen (conf_path, "w"); + if (outfile == NULL) + { + return build_server_header (response, ERR_FILE_OPEN_FAIL, string ("open " + string (conf_path) + " failed!").c_str()); + } + confdata = request["confdata"]; + for (i = 0; i < confdata.size(); i++) + { + fprintf (outfile, "%s\n", confdata[i].asString().c_str()); + } + fclose (outfile); + + return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); +} + +int ext_read_private_data (Json::Value &request, Json::Value &response) +{ + FILE *infile; + string confname; + char conf_path[PATH_MAX], strbuf[1024 * 200]; + + JSON_FIND_V (request, "confname", + build_server_header (response, ERR_PARAM_MISSING, "Parameter(confname) missing in the request")); + + confname= request["confname"].asString(); + snprintf (conf_path, PATH_MAX, "%s/%s/%s", sco.szArniadb, DBMT_LOG_DIR, confname.c_str()); + + infile = fopen (conf_path, "r"); + if (infile == NULL) + { + return build_server_header (response, ERR_FILE_OPEN_FAIL, string ("open " + confname + " failed!").c_str()); + } + while (fgets (strbuf, sizeof (strbuf), infile) != NULL) + { + uRemoveCRLF (strbuf); + response["confdata"].append (strbuf); + } + fclose (infile); + + return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); +} + +static int _find_dba_password (const string &dbname, const string &query_id, char *userpass, char *_dbmt_error) +{ + char autoexecquery_conf_file[PATH_MAX]; + ifstream conf_file; + char line_buf[LINE_MAX]; + bool is_find = false; + + autoexecquery_conf_file[0] = '\0'; + line_buf[0] = '\0'; + + conf_get_dbmt_file (FID_AUTO_EXECQUERY_CONF, autoexecquery_conf_file); + conf_file.open (autoexecquery_conf_file, ios::in); + if (!conf_file.good()) + { + strncpy (_dbmt_error, autoexecquery_conf_file, DBMT_ERROR_MSG_SIZE); + return ERR_FILE_OPEN_FAIL; + } + + strncpy (userpass, "", PASSWD_ENC_LENGTH); + + while (conf_file.getline (line_buf, LINE_MAX)) + { + istringstream stream_buf (line_buf); + string tmp_dbname; + string tmp_queryid; + string tmp_id; + string tmp_password; + + stream_buf >> tmp_dbname >> tmp_queryid >> tmp_id >> tmp_password; + + if (tmp_dbname == dbname || tmp_queryid == query_id) + { + strncpy (userpass, tmp_password.c_str(), PASSWD_ENC_LENGTH); + is_find = true; + break; + } + } + conf_file.close(); + + if (!is_find) + { + strncpy (_dbmt_error, autoexecquery_conf_file, DBMT_ERROR_MSG_SIZE); + return ERR_FILE_INTEGRITY; + } + + return ERR_NO_ERROR; +} + +int ext_set_autoexec_query (Json::Value &request, Json::Value &response) +{ + char autoexecquery_conf_file[PATH_MAX]; + char tmp_conf_file[PATH_MAX]; + char token_content[3][TOKEN_LENGTH+1]; + char userpass[PASSWD_ENC_LENGTH]; + char line_buf[MAX_JOB_CONFIG_FILE_LINE_LENGTH]; + char _dbmt_error[DBMT_ERROR_MSG_SIZE]; + unsigned int index = 0; // for json operator [](UInt). + int ret_val = 0; + Json::Value planlist; + Json::Value queryplan; + string sql_script; + string conf_item[AUTOEXECQUERY_CONF_ENTRY_NUM]; + fstream conf_file; + ofstream tmp_file; + + + autoexecquery_conf_file[0] = '\0'; + tmp_conf_file[0] = '\0'; + token_content[0][0] = '\0'; + token_content[1][0] = '\0'; + token_content[2][0] = '\0'; + userpass[0] = '\0'; + line_buf[0] = '\0'; + _dbmt_error[0] = '\0'; + + conf_get_dbmt_file (FID_AUTO_EXECQUERY_CONF, autoexecquery_conf_file); + if (access (autoexecquery_conf_file, F_OK) == 0) + { + conf_file.open (autoexecquery_conf_file, ios::in); + } + else + { + conf_file.open (autoexecquery_conf_file, ios::in | ios::out); + } + if (!conf_file.good()) + { + char tmp[DBMT_ERROR_MSG_SIZE]; + snprintf (tmp, DBMT_ERROR_MSG_SIZE-1, "File(%s) open error", autoexecquery_conf_file); + return build_server_header (response, ERR_FILE_OPEN_FAIL, tmp); + } + + // open a temp file for new auto query config. + snprintf (tmp_conf_file, PATH_MAX-1, "%s/DBMT_task_045.%d", sco.dbmt_tmp_dir, static_cast (getpid())); + tmp_file.open (tmp_conf_file, ios::out); + if (!tmp_file.good()) + { + return build_server_header (response, ERR_FILE_OPEN_FAIL, "Temporal file open error."); + } + + // dbname + conf_item[0] = request["dbname"].asString(); + + // get manager id from token + if (!ext_get_id_from_token (request["token"].asString().c_str(), token_content)) + { + return build_server_header (response, ERR_INVALID_TOKEN, + "Request is rejected due to invalid token. Please reconnect."); + } + conf_item[4] = token_content[2]; + + while (conf_file.getline (line_buf, sizeof (line_buf))) + { + istringstream stream_buf (line_buf); + string ignored_info, db_name, db_uid; + + stream_buf >> db_name >> ignored_info >> ignored_info >> ignored_info >> db_uid; + + if (db_name != conf_item[0] || db_uid != conf_item[4]) + { + tmp_file << line_buf << endl; + } + + } + conf_file.close(); + tmp_file.close(); + + index = 0; + + JSON_FIND_V (request, "dbname", + build_server_header (response, ERR_PARAM_MISSING, "Parameter(dbname) missing in the request")); + JSON_FIND_V (request, "token", + build_server_header (response, ERR_PARAM_MISSING, "Parameter(token) missing in the request")); + JSON_FIND_V (request, "planlist", + build_server_header (response, ERR_PARAM_MISSING, "Parameter(planlist) missing in the request")); + planlist = request["planlist"]; + + JSON_FIND_V (planlist[index], "queryplan", + build_server_header (response, ERR_PARAM_MISSING, "Parameter(planquery) missing in the request")); + queryplan = planlist[index]["queryplan"]; + + + + for (index = 0; index < queryplan.size(); ++index) + { + + JSON_FIND_V (queryplan[index], "username", + build_server_header (response, ERR_PARAM_MISSING, "Parameter(username) missing in the request")); + JSON_FIND_V (queryplan[index], "userpass", + build_server_header (response, ERR_PARAM_MISSING, "Parameter(userpass) missing in the request")); + JSON_FIND_V (queryplan[index], "period", + build_server_header (response, ERR_PARAM_MISSING, "Parameter(period) missing in the request")); + JSON_FIND_V (queryplan[index], "detail", + build_server_header (response, ERR_PARAM_MISSING, "Parameter(detail) missing in the request")); + JSON_FIND_V (queryplan[index], "query_string", + build_server_header (response, ERR_PARAM_MISSING, "Parameter(query_string) missing in the request")); + JSON_FIND_V (queryplan[index], "query_id", + build_server_header (response, ERR_PARAM_MISSING, "Parameter(query_id) missing in the request")); + + tmp_file.open (tmp_conf_file, ios::out | ios::app); + if (!tmp_file.good()) + { + return build_server_header (response, ERR_FILE_OPEN_FAIL, "Temporal file open error."); + } + + + // query_id + conf_item[1] = queryplan[index]["query_id"].asString(); + + // the name of dba + conf_item[2] = queryplan[index]["username"].asString(); + + // get password after encrpition. + // if password equals to "none" or "<>", + // that means this query plan just use empty password. + // if password equals to "unknown" or "<>", + // that means this query plan just use previous password. + // for more details, see tools-3464. + if (queryplan[index]["userpass"].asString() == "none" || + queryplan[index]["userpass"].asString() == "<>") + { + uEncrypt (PASSWD_LENGTH, "", userpass); + } + else if (queryplan[index]["userpass"].asString() == "unknown" || + queryplan[index]["userpass"].asString() == "<>") + { + if ((ret_val = _find_dba_password (conf_item[0], conf_item[1], userpass, _dbmt_error)) != ERR_NO_ERROR) + { + return build_server_header (response, ret_val, _dbmt_error); + } + } + else + { + uEncrypt (PASSWD_LENGTH, queryplan[index]["userpass"].asString().c_str(), userpass); + } + conf_item[3] = userpass; + + // period + conf_item[5] = queryplan[index]["period"].asString(); + + // details of period + conf_item[6] = queryplan[index]["detail"].asString(); + + // get sql script, checking its length + sql_script = queryplan[index]["query_string"].asString(); + if (sql_script.length() == 0 || sql_script.length() > MAX_AUTOQUERY_SCRIPT_SIZE) + { + char tmp[DBMT_ERROR_MSG_SIZE]; + snprintf (tmp, DBMT_ERROR_MSG_SIZE-1, "Query script too long. MAX_AUTOQUERY_SCRIPT_SIZE:%d.", + MAX_AUTOQUERY_SCRIPT_SIZE); + tmp_file.close(); + + return build_server_header (response, ERR_WITH_MSG, tmp); + } + conf_item[7] = sql_script; + + for (int i = 0; i < 7; ++i) + { + tmp_file << conf_item[i] << ' '; + } + tmp_file << conf_item[7] << endl; + + tmp_file.close(); + + } + + move_file (tmp_conf_file, autoexecquery_conf_file); + + return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); + +} + +static int _read_apply_info_cmd_output (const string &stdout_file, const string &stderr_file, string (& str_result)[8]) +{ + ifstream in_file; + string line_buf; + unsigned found; + + in_file.open (stderr_file.c_str(), ios::in); + + if (getline (in_file, line_buf)) + { + in_file.close(); + return ERR_GENERAL_ERROR; + } + + in_file.close(); + + in_file.open (stdout_file.c_str(), ios::in); + + int i = 0; + int j = 4; + while (getline (in_file, line_buf)) + { + if (line_buf.find ("Delay in Applying Copied Log") != string::npos) + { + i = 2; + continue; + } + + if (line_buf.find ("Delayed log page count") != string::npos) + { + found = (unsigned int) line_buf.find (":"); + + str_result[i++] = line_buf.substr (found+2); + continue; + } + + if (line_buf.find ("Estimated Delay") != string::npos) + { + + unsigned int tmp_pos = (unsigned int) line_buf.find ("second(s)"); + found = (unsigned int) line_buf.find (":"); + + str_result[i++] = line_buf.substr (found+2, tmp_pos-found-3); + if (str_result[i-1] == "-") + { + str_result[i-1] = ""; + } + continue; + } + + if (line_buf.find ("*** Active") != string::npos) + { + j = 6; + continue; + } + + if (line_buf.find ("EOF LSA") != string::npos) + { + found = (unsigned int) line_buf.find (":"); + str_result[j] = line_buf.substr (found+2); + found = (unsigned int) str_result [j].find (" "); + str_result [j++].erase (found); + + found = (unsigned int) line_buf.find ("|"); + str_result[j++] = line_buf.substr (found+2); + } + } + + return ERR_NO_ERROR; +} + +int ext_get_ha_apply_info (Json::Value &request, Json::Value &response) +{ + + string opt_applyinfo = "applyinfo"; + string opt_L = "-L"; + string opt_r = "-r"; + string opt_a = "-a"; + string copy_log_path; + string remote_host_name; + string dbname; + string str_result[8]; + + char cmd_name[ARNIADB_CMD_NAME_LEN]; + const char *argv[9]; + char stdout_log_file[512]; + char stderr_log_file[512]; + + int retval; + + Json::Value copied_active_eof_lsa, active_eof_lsa; + + JSON_FIND_V (request, "copylogpath", + build_server_header (response, ERR_PARAM_MISSING, "Parameter(copylogpath) missing in the request")); + JSON_FIND_V (request, "remotehostname", + build_server_header (response, ERR_PARAM_MISSING, "Parameter(remotehostname) missing in the request")); + JSON_FIND_V (request, "dbname", + build_server_header (response, ERR_PARAM_MISSING, "Parameter(remotehostname) missing in the request")); + + sprintf (stdout_log_file, "%s/cmhastop.%d.out", sco.dbmt_tmp_dir, (int)getpid()); + sprintf (stderr_log_file, "%s/cmhastop.%d.err", sco.dbmt_tmp_dir, (int)getpid()); + + copy_log_path = request["copylogpath"].asString(); + remote_host_name = request["remotehostname"].asString(); + dbname = request["dbname"].asString(); + + arniadb_cmd_name (cmd_name); + + argv[0] = cmd_name; + argv[1] = opt_applyinfo.c_str(); + argv[2] = opt_L.c_str(); + argv[3] = copy_log_path.c_str(); + argv[4] = opt_r.c_str(); + argv[5] = remote_host_name.c_str(); + argv[6] = opt_a.c_str(); + argv[7] = dbname.c_str(); + argv[8] = NULL; + + run_child (argv, 1, NULL, stdout_log_file, stderr_log_file, NULL); + + if ((retval=_read_apply_info_cmd_output (stdout_log_file, stderr_log_file, str_result)) != ERR_NO_ERROR) + { + return build_server_header (response, retval, "Invalid options or command format!"); + } + + response["copyinglog_count"] = str_result[0]; + response["copyinglog_estimated_time"] = str_result[1]; + response["applyinglog_count"] = str_result[2]; + response["applyinglog_estimated_time"] = str_result[3]; + + copied_active_eof_lsa.clear (); + active_eof_lsa.clear (); + + copied_active_eof_lsa ["pageid"] = str_result[4]; + copied_active_eof_lsa ["offset"] = str_result[5]; + active_eof_lsa ["pageid"] = str_result[6]; + active_eof_lsa ["offset"] = str_result[7]; + + response["copied_active_eof_lsa"] = copied_active_eof_lsa; + response["active_eof_lsa"] = active_eof_lsa; + + return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); +} + +int ext_add_dbmt_user_new (Json::Value &request, Json::Value &response) +{ + T_DBMT_USER dbmt_user; + T_DBMT_USER_AUTHINFO *authinfo = NULL; + T_DBMT_USER_DBINFO *dbinfo = NULL; + + char dbmt_error[DBMT_ERROR_MSG_SIZE]; + char dbmt_password[PASSWD_ENC_LENGTH]; + char str_auth[12]; // the length of number 2^32 + + T_USER_AUTH auth = 0; + int num_authinfo = 0; + int num_dbmt_user = 0; + int num_dbinfo = 0; + int retval; + + string user_id, password; + + Json::Value authoritylist; + Json::Value dbauthlist; + + + JSON_FIND_V (request, "targetid", + build_server_header (response, ERR_PARAM_MISSING, "Parameter(targetid) missing in the request")); + JSON_FIND_V (request, "password", + build_server_header (response, ERR_PARAM_MISSING, "Parameter(password) missing in the request")); + + user_id = request["targetid"].asString(); + password = request["password"].asString(); + + if (0 != IsValidUserName (user_id.c_str())) + { + return build_server_header (response, ERR_WITH_MSG, + "Invalid user name! User name should begin with a letter, and can only contain letters, digits or underscore. The length should be between 4 and 32."); + } + + if (password.length() > PASSWD_LENGTH || password.length() < MIN_PASSWD_LENGTH) + { + return build_server_header (response, ERR_WITH_MSG, "Invalid password! The length should be between 4 and 32."); + } + + if ((retval = dbmt_user_read (&dbmt_user, dbmt_error) != ERR_NO_ERROR)) + { + return build_server_header (response, retval, dbmt_error); + } + + uEncrypt (PASSWD_LENGTH, password.c_str(), dbmt_password); + + num_dbmt_user = dbmt_user.num_dbmt_user; + for (int i = 0; i < dbmt_user.num_dbmt_user; ++i) + { + if (strcmp (dbmt_user.user_info[i].user_name, user_id.c_str()) == 0) + { + dbmt_user_free (&dbmt_user); + sprintf (dbmt_error, "ARNIADB Manager user(%s) already exist.", user_id.c_str()); + return build_server_header (response, ERR_DBMTUSER_EXIST, dbmt_error); + } + } + + // set user authority info + JSON_FIND_V (request, "authoritylist", build_server_header (response, ERR_PARAM_MISSING, + "Parameter(authoritylist) missing in the request")); + authoritylist = request["authoritylist"]; + Json::Value json_value = authoritylist; + + if (json_value["admin"] != Json::Value::null) + { + if (json_value["admin"].asString() != "yes") + { + dbmt_user_free (&dbmt_user); + return build_server_header (response, ERR_WITH_MSG, "The value of 'admin' should be 'yes'!"); + } + auth |= AU_ADMIN; + + authinfo = (T_DBMT_USER_AUTHINFO *) increase_capacity (authinfo, sizeof (T_DBMT_USER_AUTHINFO), num_authinfo, + num_authinfo + 2); + if (authinfo == NULL) + { + dbmt_user_free (&dbmt_user); + return build_server_header (response, ERR_MEM_ALLOC, "Memory Allocation error."); + } + + dbmt_user_set_authinfo (& (authinfo[1]), "admin", "yes"); + num_authinfo += 2; + } + else + { + JSON_FIND_V (json_value, "dbc", build_server_header (response, ERR_PARAM_MISSING, + "Parameter(dbc or admin) missing in the authoritylist")); + JSON_FIND_V (json_value, "dbo", build_server_header (response, ERR_PARAM_MISSING, + "Parameter(dbo or admin) missing in the authoritylist")); + JSON_FIND_V (json_value, "brk", build_server_header (response, ERR_PARAM_MISSING, + "Parameter(brk or admin) missing in the authoritylist")); + JSON_FIND_V (json_value, "mon", build_server_header (response, ERR_PARAM_MISSING, + "Parameter(mon or admin) missing in the authoritylist")); + JSON_FIND_V (json_value, "job", build_server_header (response, ERR_PARAM_MISSING, + "Parameter(job or admin) missing in the authoritylist")); + JSON_FIND_V (json_value, "var", build_server_header (response, ERR_PARAM_MISSING, + "Parameter(var or admin) missing in the authoritylist")); + + if (json_value["dbc"].asString() == "yes") + { + auth |= AU_DBC; + } + else if (json_value["dbc"].asString() != "no") + { + return build_server_header (response, ERR_WITH_MSG, "invalid value in 'dbc', it can only accept either 'yes' or 'no'."); + } + + if (json_value["dbo"].asString() == "yes") + { + auth |= AU_DBO; + } + else if (json_value["dbo"].asString() != "no") + { + return build_server_header (response, ERR_WITH_MSG, "invalid value in 'dbo', it can only accept either 'yes' or 'no'."); + } + + if (json_value["brk"].asString() == "yes") + { + auth |= AU_BRK; + } + else if (json_value["brk"].asString() != "no") + { + return build_server_header (response, ERR_WITH_MSG, "invalid value in 'brk', it can only accept either 'yes' or 'no'."); + } + + if (json_value["mon"].asString() == "yes") + { + auth |= AU_MON; + } + else if (json_value["mon"].asString() != "no") + { + return build_server_header (response, ERR_WITH_MSG, "invalid value in 'mon', it can only accept either 'yes' or 'no'."); + } + + if (json_value["job"].asString() == "yes") + { + auth |= AU_JOB; + } + else if (json_value["job"].asString() != "no") + { + return build_server_header (response, ERR_WITH_MSG, "invalid value in 'job', it can only accept either 'yes' or 'no'."); + } + + if (json_value["var"].asString() == "yes") + { + auth |= AU_VAR; + } + else if (json_value["var"].asString() != "no") + { + return build_server_header (response, ERR_WITH_MSG, "invalid value in 'var', it can only accept either 'yes' or 'no'."); + } + + // all authorites are set as 'no' + if (auth == 0) + { + return build_server_header (response, ERR_WITH_MSG, "It can't be allowed to set all authorities as \"no\"."); + } + + authinfo = (T_DBMT_USER_AUTHINFO *) increase_capacity (authinfo, sizeof (T_DBMT_USER_AUTHINFO), num_authinfo, + num_authinfo + 7); + if (authinfo == NULL) + { + dbmt_user_free (&dbmt_user); + return build_server_header (response, ERR_MEM_ALLOC, "Memory Allocation error."); + } + num_authinfo += 7; + + // maybe only for debug + dbmt_user_set_authinfo (& (authinfo[1]), "dbc", ((AU_DBC & auth)? "yes" : "no")); + dbmt_user_set_authinfo (& (authinfo[2]), "dbo", ((AU_DBO & auth)? "yes" : "no")); + dbmt_user_set_authinfo (& (authinfo[3]), "brk", ((AU_BRK & auth)? "yes" : "no")); + dbmt_user_set_authinfo (& (authinfo[4]), "mon", ((AU_MON & auth)? "yes" : "no")); + dbmt_user_set_authinfo (& (authinfo[5]), "job", ((AU_JOB & auth)? "yes" : "no")); + dbmt_user_set_authinfo (& (authinfo[6]), "var", ((AU_VAR & auth)? "yes" : "no")); + } + + sprintf (str_auth, "%u", auth); + dbmt_user_set_authinfo (& (authinfo[0]), "user_auth", str_auth); + + LOG_DEBUG ("set user authority info successfully."); + + // set db authority info + JSON_FIND_V (request, "dbauth", build_server_header (response, ERR_PARAM_MISSING, + "Parameter(dbauth) missing in the request")); + + dbauthlist = request["dbauth"]; + + for (unsigned int i = 0; i < dbauthlist.size(); ++i) + { + string dbname, dbid, dbpassword, broker_address; + + JSON_FIND_V (dbauthlist[i], "dbname", build_server_header (response, ERR_PARAM_MISSING, + "Parameter(dbname) missing in the authoritylist")); + JSON_FIND_V (dbauthlist[i], "dbid", build_server_header (response, ERR_PARAM_MISSING, + "Parameter(dbid) missing in the authoritylist")); + JSON_FIND_V (dbauthlist[i], "dbpassword", build_server_header (response, ERR_PARAM_MISSING, + "Parameter(dbpassword) missing in the authoritylist")); + JSON_FIND_V (dbauthlist[i], "dbbrokeraddress", build_server_header (response, ERR_PARAM_MISSING, + "Parameter(dbbrokeraddress) missing in the authoritylist")); + + dbname = dbauthlist[i]["dbname"].asString(); + dbid = dbauthlist[i]["dbid"].asString(); + dbpassword = dbauthlist[i]["dbpassword"].asString(); + broker_address = dbauthlist[i]["dbbrokeraddress"].asString(); + + dbinfo = (T_DBMT_USER_DBINFO *) increase_capacity (dbinfo, sizeof (T_DBMT_USER_DBINFO), + num_dbinfo, num_dbinfo + 1); + if (dbinfo == NULL) + { + FREE_MEM (authinfo); + dbmt_user_free (&dbmt_user); + + return build_server_header (response, ERR_MEM_ALLOC, "Memory Allocation error."); + } + num_dbinfo++; + + dbmt_user_set_dbinfo (& (dbinfo[num_dbinfo-1]), dbname.c_str(), "admin", dbid.c_str(), broker_address.c_str()); + } + + LOG_DEBUG ("set db authority info successfully."); + + // store user authority info & db authority info into dbmt_user + dbmt_user.user_info = (T_DBMT_USER_INFO *) increase_capacity (dbmt_user.user_info, sizeof (T_DBMT_USER_INFO), + num_dbmt_user, num_dbmt_user + 1); + + + if (dbmt_user.user_info == NULL) + { + FREE_MEM (authinfo); + FREE_MEM (dbinfo); + return build_server_header (response, ERR_MEM_ALLOC, "Memory Allocation error.") ; + } + + num_dbmt_user++; + dbmt_user_set_userinfo (& (dbmt_user.user_info[num_dbmt_user-1]), user_id.c_str(), dbmt_password, num_authinfo, + authinfo, num_dbinfo, dbinfo); + dbmt_user.num_dbmt_user = num_dbmt_user; + + + LOG_DEBUG ("store to dbmt_user successfully."); + + if ((retval = dbmt_user_write_auth (&dbmt_user, dbmt_error)) != ERR_NO_ERROR) + { + dbmt_user_free (&dbmt_user); + + return build_server_header (response, retval, dbmt_error); + } + if ((retval = dbmt_user_write_pass (&dbmt_user, dbmt_error)) != ERR_NO_ERROR) + { + dbmt_user_free (&dbmt_user); + + return build_server_header (response, retval, dbmt_error); + } + + if ((retval = ext_ut_add_dblist_to_response (response)) != ERR_NO_ERROR) + { + dbmt_user_free (&dbmt_user); + + return build_server_header (response, retval, "database.txt open error"); + } + + if ((retval = ext_ut_add_userlist_to_response (response, dbmt_user)) != ERR_NO_ERROR) + { + dbmt_user_free (&dbmt_user); + + return build_server_header (response, retval, "add userlist to response error!"); + } + + dbmt_user_free (&dbmt_user); + + return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); +} + +int ext_update_dbmt_user_new (Json::Value &request, Json::Value &response) +{ + + T_DBMT_USER_AUTHINFO *authinfo = NULL; + T_DBMT_USER_DBINFO *dbinfo = NULL; + T_DBMT_USER dbmt_user; + + T_USER_AUTH auth = 0; + + char dbmt_error[DBMT_ERROR_MSG_SIZE]; + + string user_id; + + Json::Value json_value; + Json::Value dbauthlist; + + int num_authinfo = 0; + int num_dbinfo = 0; + int pos = 0; + int retval; + + + char str_auth[12]; // the length of number 2^32 + + JSON_FIND_V (request, "targetid", + build_server_header (response, ERR_PARAM_MISSING, "Parameter(targetid) missing in the request.")); + + user_id = request["targetid"].asString(); + + if ((json_value = request["authoritylist"]) != Json::Value::null) + { + + if (json_value["admin"] != Json::Value::null) + { + if (json_value["admin"].asString() != "yes") + { + return build_server_header (response, ERR_WITH_MSG, "The value of 'admin' should be 'yes'!"); + } + + auth |= AU_ADMIN; + + authinfo = (T_DBMT_USER_AUTHINFO *) increase_capacity (authinfo, sizeof (T_DBMT_USER_AUTHINFO), num_authinfo, + num_authinfo + 2); + if (authinfo == NULL) + { + return build_server_header (response, ERR_MEM_ALLOC, "Memory Allocation error."); + } + + dbmt_user_set_authinfo (& (authinfo[1]), "admin", "yes"); + num_authinfo += 2; + } + else + { + JSON_FIND_V (json_value, "dbc", build_server_header (response, ERR_PARAM_MISSING, + "Parameter(dbc or admin) missing in the authoritylist")); + JSON_FIND_V (json_value, "dbo", build_server_header (response, ERR_PARAM_MISSING, + "Parameter(dbo or admin) missing in the authoritylist")); + JSON_FIND_V (json_value, "brk", build_server_header (response, ERR_PARAM_MISSING, + "Parameter(brk or admin) missing in the authoritylist")); + JSON_FIND_V (json_value, "mon", build_server_header (response, ERR_PARAM_MISSING, + "Parameter(mon or admin) missing in the authoritylist")); + JSON_FIND_V (json_value, "job", build_server_header (response, ERR_PARAM_MISSING, + "Parameter(job or admin) missing in the authoritylist")); + JSON_FIND_V (json_value, "var", build_server_header (response, ERR_PARAM_MISSING, + "Parameter(var or admin) missing in the authoritylist")); + + + if (json_value["dbc"].asString() == "yes") + { + auth |= AU_DBC; + } + else if (json_value["dbc"].asString() != "no") + { + return build_server_header (response, ERR_WITH_MSG, "invalid value in 'dbc', it can only accept either 'yes' or 'no'."); + } + + if (json_value["dbo"].asString() == "yes") + { + auth |= AU_DBO; + } + else if (json_value["dbo"].asString() != "no") + { + return build_server_header (response, ERR_WITH_MSG, "invalid value in 'dbo', it can only accept either 'yes' or 'no'."); + } + + if (json_value["brk"].asString() == "yes") + { + auth |= AU_BRK; + } + else if (json_value["brk"].asString() != "no") + { + return build_server_header (response, ERR_WITH_MSG, "invalid value in 'brk', it can only accept either 'yes' or 'no'."); + } + + if (json_value["mon"].asString() == "yes") + { + auth |= AU_MON; + } + else if (json_value["mon"].asString() != "no") + { + return build_server_header (response, ERR_WITH_MSG, "invalid value in 'mon', it can only accept either 'yes' or 'no'."); + } + + if (json_value["job"].asString() == "yes") + { + auth |= AU_JOB; + } + else if (json_value["job"].asString() != "no") + { + return build_server_header (response, ERR_WITH_MSG, "invalid value in 'job', it can only accept either 'yes' or 'no'."); + } + + if (json_value["var"].asString() == "yes") + { + auth |= AU_VAR; + } + else if (json_value["var"].asString() != "no") + { + return build_server_header (response, ERR_WITH_MSG, "invalid value in 'var', it can only accept either 'yes' or 'no'."); + } + + // all authorites are set as 'no' + if (auth == 0) + { + return build_server_header (response, ERR_WITH_MSG, "It can't be allowed to set all authorities as \"no\"."); + } + + authinfo = (T_DBMT_USER_AUTHINFO *) increase_capacity (authinfo, sizeof (T_DBMT_USER_AUTHINFO), num_authinfo, + num_authinfo + 7); + if (authinfo == NULL) + { + return build_server_header (response, ERR_MEM_ALLOC, "Memory Allocation error."); + } + num_authinfo += 7; + + // maybe only for debug + dbmt_user_set_authinfo (& (authinfo[1]), "dbc", ((AU_DBC & auth)? "yes" : "no")); + dbmt_user_set_authinfo (& (authinfo[2]), "dbo", ((AU_DBO & auth)? "yes" : "no")); + dbmt_user_set_authinfo (& (authinfo[3]), "brk", ((AU_BRK & auth)? "yes" : "no")); + dbmt_user_set_authinfo (& (authinfo[4]), "mon", ((AU_MON & auth)? "yes" : "no")); + dbmt_user_set_authinfo (& (authinfo[5]), "job", ((AU_JOB & auth)? "yes" : "no")); + dbmt_user_set_authinfo (& (authinfo[6]), "var", ((AU_VAR & auth)? "yes" : "no")); + + } + + sprintf (str_auth, "%u", auth); + dbmt_user_set_authinfo (& (authinfo[0]), "user_auth", str_auth); + + } + + // set db authority info + //JSON_FIND_V(request, "dbauth", build_server_header(response, ERR_PARAM_MISSING, "Parameter(dbauth) missing in the request")); + + if ((dbauthlist = request["dbauth"]) != Json::Value::null) + { + + for (unsigned int i = 0; i < dbauthlist.size(); ++i) + { + + string dbname, dbid, dbpassword, broker_address; + + JSON_FIND_V (dbauthlist[i], "dbname", build_server_header (response, ERR_PARAM_MISSING, + "Parameter(dbname) missing in the authoritylist")); + JSON_FIND_V (dbauthlist[i], "dbid", build_server_header (response, ERR_PARAM_MISSING, + "Parameter(dbid) missing in the authoritylist")); + JSON_FIND_V (dbauthlist[i], "dbpassword", build_server_header (response, ERR_PARAM_MISSING, + "Parameter(dbpassword) missing in the authoritylist")); + JSON_FIND_V (dbauthlist[i], "dbbrokeraddress", build_server_header (response, ERR_PARAM_MISSING, + "Parameter(dbbrokeraddress) missing in the authoritylist")); + + dbname = dbauthlist[i]["dbname"].asString(); + dbid = dbauthlist[i]["dbid"].asString(); + dbpassword = dbauthlist[i]["dbpassword"].asString(); + broker_address = dbauthlist[i]["dbbrokeraddress"].asString(); + + dbinfo = (T_DBMT_USER_DBINFO *) increase_capacity (dbinfo, sizeof (T_DBMT_USER_DBINFO), + num_dbinfo, num_dbinfo + 1); + if (dbinfo == NULL) + { + FREE_MEM (authinfo); + + return build_server_header (response, ERR_MEM_ALLOC, "Memory Allocation error."); + } + num_dbinfo++; + + dbmt_user_set_dbinfo (& (dbinfo[num_dbinfo-1]), dbname.c_str(), "admin", dbid.c_str(), broker_address.c_str()); + + } + } + + if ((retval = dbmt_user_read (&dbmt_user, dbmt_error)) != ERR_NO_ERROR) + { + FREE_MEM (authinfo); + FREE_MEM (dbinfo); + return build_server_header (response, retval, dbmt_error); + } + + pos = -1; + for (int i = 0; i < dbmt_user.num_dbmt_user; ++i) + { + if (!strcmp (dbmt_user.user_info[i].user_name, user_id.c_str())) + { + pos = i; + break; + } + } + + if (pos < 0) + { + FREE_MEM (authinfo); + FREE_MEM (dbinfo); + dbmt_user_free (&dbmt_user); + + return build_server_header (response, ERR_GENERAL_ERROR, "the user doesn't exist!"); + } + + if (authinfo != NULL) + { + free (dbmt_user.user_info[pos].authinfo); + dbmt_user.user_info[pos].authinfo = authinfo; + dbmt_user.user_info[pos].num_authinfo = num_authinfo; + + } + + if (dbinfo != NULL) + { + if (dbmt_user.user_info[pos].dbinfo == NULL) + { + dbmt_user.user_info[pos].dbinfo = dbinfo; + dbmt_user.user_info[pos].num_dbinfo = num_dbinfo; + } + else + { + T_DBMT_USER_INFO *current_user = dbmt_user.user_info+pos; + for (int i = 0; i < num_dbinfo; ++i ) + { + int tmp_pos = -1; + for (int j = 0; j < current_user->num_dbinfo; ++j) + { + if (!strcmp (current_user->dbinfo[j].dbname, dbinfo[i].dbname)) + { + tmp_pos = j; + } + } + + if (tmp_pos < 0) + { + current_user->dbinfo = (T_DBMT_USER_DBINFO *)increase_capacity (current_user->dbinfo, + sizeof (T_DBMT_USER_DBINFO), + current_user->num_dbinfo, + current_user->num_dbinfo+1); + + if (current_user->dbinfo == NULL) + { + FREE_MEM (dbinfo); + dbmt_user_free (&dbmt_user); + + return build_server_header (response, ERR_MEM_ALLOC, "Memory allocation error."); + } + tmp_pos = current_user->num_dbinfo; + current_user->num_dbinfo++; + } + + dbmt_user_set_dbinfo (& (current_user->dbinfo[tmp_pos]), + dbinfo[i].dbname, + dbinfo[i].auth, + dbinfo[i].uid, + dbinfo[i].broker_address); + } + } + } + + if ((retval = dbmt_user_write_auth (&dbmt_user, dbmt_error)) != ERR_NO_ERROR) + { + FREE_MEM (dbinfo); + dbmt_user_free (&dbmt_user); + + return build_server_header (response, retval, dbmt_error); + } + + + if ((retval = ext_ut_add_dblist_to_response (response)) != ERR_NO_ERROR) + { + FREE_MEM (dbinfo); + dbmt_user_free (&dbmt_user); + + return build_server_header (response, retval, "database.txt open error"); + } + + if ((retval = ext_ut_add_userlist_to_response (response, dbmt_user)) != ERR_NO_ERROR) + { + FREE_MEM (dbinfo); + dbmt_user_free (&dbmt_user); + + return build_server_header (response, retval, "add userlist to response error!"); + } + + + FREE_MEM (dbinfo); + dbmt_user_free (&dbmt_user); + + return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); +} + +int ext_get_dbmt_user_info_new (Json::Value &request, Json::Value &response) +{ + + T_DBMT_USER dbmt_user; + char dbmt_error[DBMT_ERROR_MSG_SIZE]; + int retval; + + if ((retval = dbmt_user_read (&dbmt_user, dbmt_error)) != ERR_NO_ERROR) + { + dbmt_user_free (&dbmt_user); + return build_server_header (response, retval, dbmt_error); + } + + + if ((retval = ext_ut_add_dblist_to_response (response)) != ERR_NO_ERROR) + { + dbmt_user_free (&dbmt_user); + return build_server_header (response, retval, "database.txt open error"); + } + + if ((retval = ext_ut_add_userlist_to_response (response, dbmt_user)) != ERR_NO_ERROR) + { + dbmt_user_free (&dbmt_user); + return build_server_header (response, retval, "add userlist to response error!"); + } + + dbmt_user_free (&dbmt_user); + return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); +} + +// utility fucntions. +// +// -ext_ut_validate_userid +// -ext_ut_add_dblist_to_response +// -ext_ut_add_userlist_to_response +// -ext_ut_validate_token +// -ext_ut_generate_token + +int ext_ut_add_dblist_to_response (Json::Value &response, bool is_add_dbpath) +{ + + char dbtxt_file[PATH_MAX]; + char hostname[128]; + ifstream in_file; + string line_buf; + Json::Value dblist; + Json::Value dbs; + + snprintf (dbtxt_file, PATH_MAX-1, "%s/%s", sco.szArniadb_databases, ARNIADB_DATABASE_TXT); + if (access (dbtxt_file, F_OK) == 0) + { + in_file.open (dbtxt_file, ios::in); + } + else + { + return ERR_DATABASETXT_OPEN; + } + if (!in_file.good()) + { + return ERR_DATABASETXT_OPEN; + } + + memset (hostname, 0, sizeof (hostname)); + gethostname (hostname, sizeof (hostname)); + + string str_hostname = hostname; + + while (getline (in_file, line_buf)) + { + istringstream in_str (line_buf); + istringstream in_hname; + string dbname, dbpath, hname_list, hname[2]; + Json::Value db; + + in_str >> dbname >> dbpath >> hname_list; + in_hname.str (hname_list); + + int i = 0; + while (getline (in_hname, hname[i], ':')) + { + if (hname[i] == "127.0.0.1" || hname[i] == str_hostname || hname[i] == "localhost") + { + db["dbname"] = dbname; + if (is_add_dbpath) + { + db["dbdir"] = dbpath; + } + dbs.append (db); + break; + } + i++; + } + } + + dblist["dbs"] = dbs; + response["dblist"].append (dblist); + + return ERR_NO_ERROR; +} + +int ext_ut_add_userlist_to_response (Json::Value &response, const T_DBMT_USER &dbmt_user, bool is_add_pwd) +{ + Json::Value userlist; + + for (int i = 0; i < dbmt_user.num_dbmt_user; ++i) + { + Json::Value user; + Json::Value authority_list; + Json::Value dbauth; + Json::Value json_value; + string user_auth; + ostringstream tmp_oss; + + if (dbmt_user.user_info[i].user_name[0] == '\0') + { + continue; + } + + user[ENCRYPT_ARG ("id")] = dbmt_user.user_info[i].user_name; + if (is_add_pwd) + { + user["passwd"] = dbmt_user.user_info[i].user_passwd; + } + + json_value.clear(); + + // add user authority info + for (int j = 0; j < dbmt_user.user_info[i].num_authinfo; ++j) + { + if (dbmt_user.user_info[i].authinfo[j].domain[0] == '\0') + { + continue; + } + + if (!strcmp (dbmt_user.user_info[i].authinfo[j].domain, "dbo")) + { + json_value["dbo"] = dbmt_user.user_info[i].authinfo[j].auth; + continue; + } + + if (!strcmp (dbmt_user.user_info[i].authinfo[j].domain, "dbc")) + { + json_value["dbc"] = dbmt_user.user_info[i].authinfo[j].auth; + continue; + } + + if (!strcmp (dbmt_user.user_info[i].authinfo[j].domain, "brk")) + { + json_value["brk"] = dbmt_user.user_info[i].authinfo[j].auth; + continue; + } + + if (!strcmp (dbmt_user.user_info[i].authinfo[j].domain, "mon")) + { + json_value["mon"] = dbmt_user.user_info[i].authinfo[j].auth; + continue; + } + + if (!strcmp (dbmt_user.user_info[i].authinfo[j].domain, "job")) + { + json_value["job"] = dbmt_user.user_info[i].authinfo[j].auth; + continue; + } + + if (!strcmp (dbmt_user.user_info[i].authinfo[j].domain, "var")) + { + json_value["var"] = dbmt_user.user_info[i].authinfo[j].auth; + continue; + } + + if (!strcmp (dbmt_user.user_info[i].authinfo[j].domain, "all")) + { + json_value["all"] = dbmt_user.user_info[i].authinfo[j].auth; + continue; + } + + if (!strcmp (dbmt_user.user_info[i].authinfo[j].domain, "user_auth")) + { + user_auth = dbmt_user.user_info[i].authinfo[j].auth; + continue; + } + } + + authority_list.append (json_value); + + tmp_oss << AU_ADMIN; + if (!strcasecmp (dbmt_user.user_info[i].user_name, "admin") || + user_auth == tmp_oss.str()) + { + user["user_auth"] = "admin"; + } + else + { + user["user_auth"] = user_auth; + } + user["authority_list"] = authority_list; + + json_value.clear(); + // add user db info + for (int j = 0; j < dbmt_user.user_info[i].num_dbinfo; ++j) + { + json_value[ENCRYPT_ARG ("dbid")] = dbmt_user.user_info[i].dbinfo[j].uid; + json_value["dbname"] = dbmt_user.user_info[i].dbinfo[j].dbname; + json_value["dbbrokeraddress"] = dbmt_user.user_info[i].dbinfo[j].broker_address; + + dbauth["auth_info"].append (json_value); + } + + user["dbauth"].append (dbauth); + userlist["user"].append (user); + } + response["userlist"].append (userlist); + + return ERR_NO_ERROR; +} + +static bool _validate_token_active_time (time_t &active_time) +{ + size_t len = 0; + + active_time = 0; + len = strlen (sco.szTokenActiveTime); + + if (len > MAX_TIME_LENGTH) + { + return false; + } + + for (int i = 0; i < len; ++i) + { + if (!isdigit (sco.szTokenActiveTime[i])) + { + return false; + } + } + + active_time = atol (sco.szTokenActiveTime); + + if (active_time == 0) + { + return false; + } + + if (active_time == LONG_MAX) + { + LOG_WARN ("token_active_time in cm.conf maybe more than 2147483647, correct it to 2147483647."); + } + + return true; +} + +bool ext_ut_validate_token (const char *token) +{ + T_USER_TOKEN_INFO *token_info; + string token_enc; + string token_content[5]; // client_ip, client_port, client_id, proc_id, login_time + istringstream tmp_iss; + time_t now_time = time (0); + time_t active_time; + char token_dec[TOKEN_LENGTH + 1]; + + if (strlen (token) > TOKEN_ENC_LENGTH) + { + return false; + } + + uDecrypt (TOKEN_LENGTH, token, token_dec); + tmp_iss.str (string (token_dec)); + + int i = 0; + while (getline (tmp_iss, token_content[i++], ':')); + + token_info = dbmt_user_search_token_info (token_content[2].c_str()); + if (token_info == NULL) + { + return false; + } + + if (strcmp (token_info->token, token) != 0) + { + return false; + } + + if (!_validate_token_active_time (active_time)) + { + active_time = 7200; + } + + if (now_time - token_info->login_time > active_time) + { + return false; + } + + token_info->login_time = now_time; + + return true; +} + +int ext_ut_validate_token (Json::Value &request, Json::Value &response) +{ + + T_USER_TOKEN_INFO *token_info; + string task; + string token; + string token_content[5]; // client_ip, client_port, client_id, proc_id, login_time + istringstream tmp_iss; + time_t now_time = time (0); + time_t active_time; + char token_dec[TOKEN_LENGTH+1]; + + if (request["task"].asString() == "login" || request["task"].asString() == "getamsenv") + { + return build_server_header (response, ERR_NO_ERROR, "none"); + } + + + if (request["task"] == Json::Value::null) + { + return build_server_header (response, ERR_PARAM_MISSING, "Parameter(task) missing in the request."); + } + + if (request["token"] == Json::Value::null) + { + return build_server_header (response, ERR_PARAM_MISSING, "Parameter(token) missing in the request."); + } + + if (request["task"].asString() == "") + { + return build_server_header (response, ERR_WITH_MSG, "Task can't be null."); + } + + if (request["token"].asString() == "") + { + return build_server_header (response, ERR_INVALID_TOKEN, "Request is rejected due to invalid token. Please reconnect."); + } + + task = request["task"].asString(); + token = request["token"].asString(); + if (token.length() > TOKEN_ENC_LENGTH) + { + return build_server_header (response, ERR_INVALID_TOKEN, "Request is rejected due to invalid token. Please reconnect."); + } + + uDecrypt (TOKEN_LENGTH, token.c_str(), token_dec); + tmp_iss.str (string (token_dec)); + + int i = 0; + while (getline (tmp_iss, token_content[i++], ':')); + + token_info = dbmt_user_search_token_info (token_content[2].c_str()); + if (token_info == NULL) + { + return build_server_header (response, ERR_INVALID_TOKEN, "Request is rejected due to invalid token. Please reconnect."); + } + + + if (strcmp (token_info->token, token.c_str())) + { + return build_server_header (response, ERR_INVALID_TOKEN, "Request is rejected due to invalid token. Please reconnect."); + } + + + if (!_validate_token_active_time (active_time)) + { + active_time = 7200; + } + + if (now_time-token_info->login_time > active_time) + { + return build_server_header (response, ERR_INVALID_TOKEN, "Request is rejected due to invalid token. Please reconnect."); + } + + token_info->login_time = now_time; + + request["_IP"] = token_content[0]; + request["_PORT"] = token_content[1]; + request["_ID"] = token_content[2]; + + return build_server_header (response, ERR_NO_ERROR, "none"); +} + +bool ext_ut_validate_auth (Json::Value &request) +{ + T_USER_AUTH auth_task = 0; + T_USER_AUTH auth_user = 0; + T_DBMT_USER dbmt_user; + T_DBMT_USER_AUTHINFO *auth_info = NULL; + + string task; + string user_id; + + char dbmt_error[DBMT_ERROR_MSG_SIZE]; + int num_authinfo = 0; + + if (request["task"].asString() == "login" || request["task"].asString() == "getamsenv") + { + return true; + } + + if (request["task"] == Json::Value::null || request["_ID"] == Json::Value::null) + { + return false; + } + + task = request["task"].asString(); + user_id = request["_ID"].asString(); + + if (ut_get_task_info (task.c_str(), NULL, NULL, &auth_task) == 0 && + get_ext_task_info (task.c_str(), 0, NULL, &auth_task) == 0) + { + // As the task doesn't exist, this failure will be checked in next step. + return true; + } + + if (dbmt_user_read (&dbmt_user, dbmt_error) != ERR_NO_ERROR) + { + return false; + } + + bool matches = false; + for (int index = 0; index < dbmt_user.num_dbmt_user; ++index) + { + if (strcmp (dbmt_user.user_info[index].user_name, user_id.c_str()) == 0) + { + auth_info = dbmt_user.user_info[index].authinfo; + num_authinfo = dbmt_user.user_info[index].num_authinfo; + matches = true; + break; + } + } + + // the user doesn't exist + if (!matches) + { + dbmt_user_free (&dbmt_user); + return false; + } + + for (int index = 0; index < num_authinfo; ++index) + { + if (!strcmp (auth_info[index].domain, "user_auth")) + { + istringstream (string (auth_info[index].auth)) >> auth_user; + break; + } + } + + dbmt_user_free (&dbmt_user); + + // assign default authority to old users. + if (auth_user == 0) + { + if (user_id == "admin") + { + auth_user = AU_ADMIN; + } + else + { + auth_user = ALL_AUTHORITY; + } + } + + if (auth_user == AU_ADMIN) + { + return true; + } + + return (auth_user & auth_task) ? true : false; +} + +int ext_get_mon_interval (Json::Value &request, Json::Value &response) +{ + response["task"] = request["task"]; + time_t interval; + if (false == (cm_mon_stat::get_instance())->get_mon_interval (interval)) + { + return build_server_header (response, ERR_WITH_MSG, + "Get interval failed, because the monitoring module is not initialized!"); + } + response["interval"] = int (interval); + return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); +} + +int ext_set_mon_interval (Json::Value &request, Json::Value &response) +{ + int interval = 0; + response["task"] = request["task"]; + JSON_FIND_V (request, "interval", + build_server_header (response, ERR_PARAM_MISSING, "Parameter(interval) missing in the request")); + interval = request["interval"].asInt(); + if (interval < MIN_INTERVAL) + { + stringstream sstr; + sstr << "The interval " << interval << " seconds is less than the minimum interval " << MIN_INTERVAL << " seconds"; + return build_server_header (response, ERR_WITH_MSG, sstr.str().c_str()); + } + if (interval >= MAX_INTERVAL) + { + stringstream sstr; + sstr << "The interval " << interval << " seconds is bigger than or equal to the maximum interval " << MAX_INTERVAL << + " seconds"; + return build_server_header (response, ERR_WITH_MSG, sstr.str().c_str()); + } + if (true == (cm_mon_stat::get_instance())->set_mon_interval (interval)) + { + return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); + } + else + { + return build_server_header (response, ERR_WITH_MSG, + "Set monitoring interval for monitoring statistic failed!"); + } +} + +int ext_get_mon_statistic (Json::Value &request, Json::Value &response) +{ + response["task"] = request["task"]; + string errmsg = ""; + JSON_FIND_V (request, "metric", + build_server_header (response, ERR_PARAM_MISSING, "Parameter(metric) missing in the request")); + JSON_FIND_V (request, "dtype", + build_server_header (response, ERR_PARAM_MISSING, "Parameter(dtype) missing in the request")); + if (0 == strncmp ("db_", request["metric"].asString().c_str(), strlen ("db_"))) + { + JSON_FIND_V (request, "dbname", + build_server_header (response, ERR_PARAM_MISSING, "Parameter(dbname) missing in the request")); + } + if (0 == strncmp ("vol_", request["metric"].asString().c_str(), strlen ("vol_"))) + { + JSON_FIND_V (request, "dbname", + build_server_header (response, ERR_PARAM_MISSING, "Parameter(dbname) missing in the request")); + JSON_FIND_V (request, "volname", + build_server_header (response, ERR_PARAM_MISSING, "Parameter(volname) missing in the request")); + } + if (0 == strncmp ("broker_", request["metric"].asString().c_str(), strlen ("broker_"))) + { + JSON_FIND_V (request, "bname", + build_server_header (response, ERR_PARAM_MISSING, "Parameter(bname) missing in the request")); + } + if (true == (cm_mon_stat::get_instance())->get_mon_statistic (request, response, errmsg)) + { + return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); + } + else + { + return build_server_header (response, ERR_WITH_MSG, errmsg.c_str()); + } +} diff --git a/server/src/am_server_extend_interface.h b/server/src/am_server_extend_interface.h new file mode 100644 index 0000000..9e6e22d --- /dev/null +++ b/server/src/am_server_extend_interface.h @@ -0,0 +1,101 @@ +/* + * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. + * + * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifndef __CM_SERVER_EXTEND_INFERFACE_H_ +#define __CM_SERVER_EXTEND_INFERFACE_H_ + +#include "cm_user.h" + +#include +#include +#include + +#define STATUS_SUCCESS "success" +#define STATUS_FAILURE "failure" +#define STATUS_NONE "none" + +#define MIN_INTERVAL 10 +#define MAX_INTERVAL 3600 + +#define JSON_FIND_V(root, key, err) \ + if (Json::Value::null == root[key]) \ + return err; + +typedef int (*T_EXT_TASK_FUNC) (Json::Value &request, + Json::Value &response); + +typedef struct +{ + const char *task_str; + int access_level; + T_EXT_TASK_FUNC task_func; + T_USER_AUTH user_auth; +} T_EXTEND_TASK_INFO; + +int build_server_header (Json::Value &response, const int status, + const char *note); +int get_ext_task_info (const char *task, int access_flag, + T_EXT_TASK_FUNC *task_func, T_USER_AUTH *auth); +int ext_get_sys_diskinfo (Json::Value &request, Json::Value &response); +int ext_get_proc_info (Json::Value &request, Json::Value &response); +int ext_set_log_level (Json::Value &request, Json::Value &response); +int ext_set_auto_start (Json::Value &request, Json::Value &response); +int ext_get_auto_start (Json::Value &request, Json::Value &response); +int ext_exec_auto_start (Json::Value &request, Json::Value &response); +int ext_exec_auto_jobs (Json::Value &request, Json::Value &response); +int ext_arn_broker_start (Json::Value &request, Json::Value &response); +int ext_get_db_err_log (Json::Value &request, Json::Value &response); +int ext_get_broker_start_log (Json::Value &request, Json::Value &response); +int ext_send_mail (Json::Value &request, Json::Value &response); +int ext_exec_auto_mail (Json::Value &request, Json::Value &response); +int ext_get_autojob_conf (Json::Value &request, Json::Value &response); +int ext_set_autojob_conf (Json::Value &request, Json::Value &response); +int ext_read_private_data (Json::Value &request, Json::Value &response); +int ext_write_private_data (Json::Value &request, Json::Value &response); +int ext_set_autoexec_query (Json::Value &request, Json::Value &response); +int ext_get_ha_apply_info (Json::Value &request, Json::Value &response); +int ext_get_mon_interval (Json::Value &request, Json::Value &reponse); +int ext_set_mon_interval (Json::Value &request, Json::Value &reponse); +int ext_get_mon_statistic (Json::Value &request, Json::Value &reponse); +int ext_add_dbmt_user_new (Json::Value &request, Json::Value &response); +int ext_update_dbmt_user_new (Json::Value &request, Json::Value &response); +int ext_get_dbmt_user_info_new (Json::Value &request, + Json::Value &response); + +#define EXT_JOBS_AUTO_START "auto_start" +#define EXT_JOBS_MAIL_CONF "mail_config" +#define EXT_JOBS_MAIL_REPORT "mail_report" + +/* utility */ +bool ext_set_auto_jobs (const std::string jobkey, Json::Value &jobvalue); +bool ext_get_auto_jobs (const std::string jobkey, Json::Value &jobvalue); +bool ext_ut_validate_userid (const std::string userid); +int ext_ut_add_dblist_to_response (Json::Value &res, bool is_add_dbpath = + false); +int ext_ut_add_userlist_to_response (Json::Value &response, + const T_DBMT_USER &dbmt_user, + bool is_add_pwd = false); +std::string ext_ut_generate_token (const std::string &client_ip, + const std::string &client_id, int proc_id, + time_t login_time); +int ext_ut_validate_token (Json::Value &resquest, Json::Value &response); +bool ext_ut_validate_token (const char *token); +bool ext_ut_validate_auth (Json::Value &request); + +#endif diff --git a/server/src/am_server_interface.cpp b/server/src/am_server_interface.cpp new file mode 100644 index 0000000..2dccc58 --- /dev/null +++ b/server/src/am_server_interface.cpp @@ -0,0 +1,757 @@ +/* + * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. + * + * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef WINDOWS +#include +#else +#include +#include +#include +#include +#endif + +#include "cm_server_interface.h" +#include "cm_server_extend_interface.h" +#include "cm_log.h" +#include "cm_mon_stat.h" + +using namespace std; + +#ifndef MAX_PATH +#define MAX_PATH 256 +#endif + +extern T_EMGR_VERSION CLIENT_VERSION; + +typedef struct +{ + char arniadb[MAX_PATH]; /*arniadb home; ARNIADB=/root/ARNIADB */ + char arniadb_databases[MAX_PATH]; /*arniadb databases home,default $(arniadb home)/databases */ + char arniadb_err_log[MAX_PATH]; /*arniadb err log, use for save cmd log */ + // char arniadb_charset[MAX_PATH]; +} arniadb_env_t; +mutex_t cm_mutex; +/*global arniadb env*/ +arniadb_env_t arn_httpd_env; + +/** + * @brief initial monitoring stat information + * + * @return -1: error, 1: ok + */ +int +mon_stat_init (void) +{ +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (sco.sMonStatDataPath, "%s/%s", sco.szArniadb, DBMT_MON_DATA_DIR); +#else + sprintf (sco.sMonStatDataPath, "%s", ARNIADB_MONDATADIR); +#endif + + if (access (sco.sMonStatDataPath, F_OK) < 0) + { + if (mkdir (sco.sMonStatDataPath, 0755) < 0) + { + fprintf (stderr, "Error while creating monitoring data path(%s)\n", + sco.sMonStatDataPath); + return -1; + } + } + + if (!cm_mon_stat::get_instance ()->initial ()) + { + fprintf (stderr, "Error while loading monitoring data information\n"); + return -1; + } + return 1; +} + +void +arn_cm_init_env () +{ + char conf_name[256]; + char tmpstrbuf[DBMT_ERROR_MSG_SIZE]; + char process_name[PATH_MAX]; + char default_arniadb_lang_type[PATH_MAX]; + char default_arniadb_lang_msg_type[PATH_MAX]; + + tmpstrbuf[0]= '\0'; + // char *charset = NULL; + snprintf (process_name, PATH_MAX, "%s", AMS_NAME); + snprintf (default_arniadb_lang_type, PATH_MAX, "ARNIADB_LANG=en_US"); + snprintf (default_arniadb_lang_msg_type, PATH_MAX, "ARNIADB_MSG_LANG=en_US"); + + sys_config_init (); + uReadEnvVariables (process_name); + + if (uReadSystemConfig () < 0) + { + snprintf (tmpstrbuf, DBMT_ERROR_MSG_SIZE, "ARNIADB Manager Server : Cannot find the configuration file[%s].\n", + conf_get_dbmt_file (FID_DBMT_CONF, conf_name)); + ut_record_arniadb_utility_log_stderr (tmpstrbuf); + exit (1); + } + make_default_env (); + + /* check system configuration */ + if (uCheckSystemConfig (process_name) < 0) + { + ut_record_arniadb_utility_log_stderr ("ARNIADB Manager Server : Error while checking system configuration file.\n"); + exit (1); + } + + if (mon_stat_init () < 0) + { + ut_record_arniadb_utility_log_stderr ("ARNIADB Manager Server : Error while checking monitoring data.\n"); + exit (1); + } + + memset (&arn_httpd_env, 0, sizeof (arniadb_env_t)); + putenv (default_arniadb_lang_type); /* set as default language type */ + putenv (default_arniadb_lang_msg_type); /* set as default language type */ + //putenv ("ARNIADB_CHARSET=en_US"); /* set as default language type */ + + snprintf (arn_httpd_env.arniadb_err_log, MAX_PATH, + "ARNIADB_ERROR_LOG=%s/cmclt.%d.err", sco.dbmt_tmp_dir, (int) getpid ()); + putenv (arn_httpd_env.arniadb_err_log); + + snprintf (arn_httpd_env.arniadb, MAX_PATH, "ARNIADB=%s", sco.szArniadb); + putenv (arn_httpd_env.arniadb); + + snprintf (arn_httpd_env.arniadb_databases, MAX_PATH, "ARNIADB_DATABASES=%s", + sco.szArniadb_databases); + putenv (arn_httpd_env.arniadb_databases); + + /* charset = getenv ("ARNIADB_CHARSET"); + if (charset != NULL) + { + snprintf (arn_httpd_env.arniadb_charset, MAX_PATH, "ARNIADB_CHARSET=%s", + charset); + } + else + { + snprintf (arn_httpd_env.arniadb_charset, MAX_PATH, + "ARNIADB_CHARSET=en_US"); + putenv (arn_httpd_env.arniadb_charset); + } + */ + mutex_init (cm_mutex); + return; +} + +void +arn_cm_destory_env () +{ + mutex_destory (cm_mutex); +} + +int +ch_build_request (Json::Value &req, nvplist *cli_request) +{ + static int i = 0; + nv_add_nvp_int (cli_request, "_STAMP", i++); + nv_add_nvp (cli_request, "_PROGNAME", AMS_NAME); + + return 1; +} + +static int +is_no_token_cmd (int task_code) +{ + int no_token_cmd[] = { TS_LOGIN, TS_GET_AMS_ENV, -1 }; + int i; + for (i = 0; no_token_cmd[i] != -1; i++) + { + if (task_code == no_token_cmd[i]) + { + return 1; + } + } + + return 0; +} + +/* +inherit for cm_job, find the task function, and exec; +*/ +int +ch_process_request (nvplist *req, nvplist *res) +{ + int task_code; + int retval = ERR_NO_ERROR; + char *dbname, *task; + // char *charset = NULL; + // static char charsetenv[PATH_MAX] = ""; + char dbid[32]; + char dbpasswd[80]; + T_TASK_FUNC task_func; + char access_log_flag; + char _dbmt_error[DBMT_ERROR_MSG_SIZE]; + int major_ver, minor_ver; + char *cli_ver; + + int elapsed_msec = 0; + struct timeval task_begin, task_end; + char elapsed_time_str[20]; + + memset (_dbmt_error, 0, sizeof (_dbmt_error)); + + task = nv_get_val (req, "task"); + dbname = nv_get_val (req, "dbname"); + //charset = nv_get_val (req, "charset"); + + task_code = ut_get_task_info (task, &access_log_flag, &task_func, NULL); + switch (task_code) + { + /* case TS_ANALYZECASLOG: */ + case TS_GET_DIAGDATA: + nv_reset_nvp (res); + nv_init (res, 5, NULL, "\n", ":DIAG_DEL:", "END__DIAGDATA\n"); + break; + } + + /* insert task,status,note to the front of response */ + nv_add_nvp (res, "task", task); + nv_add_nvp (res, "status", "none"); + nv_add_nvp (res, "note", "none"); + + if (!is_no_token_cmd (task_code)) + { + /* + if (ut_validate_token (req) == 0) + { + retval = ERR_INVALID_TOKEN; + uGenerateStatus (req, res, retval, _dbmt_error); + return 0; + } + */ + + /* if database name is specified */ + if (dbname) + { + memset (dbid, 0, 32); + memset (dbpasswd, 0, 80); + _ut_get_dbaccess (req, dbid, dbpasswd); + nv_add_nvp (req, "_DBID", dbid); + nv_add_nvp (req, "_DBPASSWD", dbpasswd); + nv_add_nvp (req, "_DBNAME", dbname); + } + } + + /* set CLIENT_VERSION */ + cli_ver = nv_get_val (req, "_CLIENT_VERSION"); + make_version_info (cli_ver == NULL ? "1.0" : cli_ver, &major_ver, + &minor_ver); + CLIENT_VERSION = EMGR_MAKE_VER (major_ver, minor_ver); /* global variable */ + + sprintf (_dbmt_error, "?"); /* prevent to have null string */ + if (task_code == TS_UNDEFINED) + { + if (task != NULL) + { + strcpy (_dbmt_error, task); + } + retval = ERR_UNDEFINED_TASK; + } + else + { + if (access_log_flag) + { + ut_access_log (req, NULL); + } + + /* if (charset != NULL) + { + snprintf (charsetenv, PATH_MAX, "ARNIADB_CHARSET=%s", charset); + putenv (charsetenv); + } + */ + /* record the start time of running arn_manager */ + gettimeofday (&task_begin, NULL); + + retval = (*task_func) (req, res, _dbmt_error); + + /* record the end time of running arn_manager */ + gettimeofday (&task_end, NULL); + /* if (charset != NULL) + { + putenv (arn_httpd_env.arniadb_charset); + } + */ + /* caculate the running time of arn_manager. */ + _ut_timeval_diff (&task_begin, &task_end, &elapsed_msec); + + /* add arn_manager task running time to response. */ + snprintf (elapsed_time_str, sizeof (elapsed_time_str), "%d ms", + elapsed_msec); + nv_add_nvp (res, "__EXEC_TIME", elapsed_time_str); + } + + uGenerateStatus (req, res, retval, _dbmt_error); + + // FREE_MEM (cli_ver); + + return 0; +} + +int +json_to_nv (Json::Value &root, const char *name, nvplist *nv) +{ + switch (root.type ()) + { + case Json::arrayValue: + { + int size = root.size (); + + for (int index = 0; index < size; ++index) + { + if (!strcmp (name, "line") || !strcmp (name, "confdata") + || !strcmp (name, "group")) + { + json_to_nv (root[index], name, nv); + } + else + { + nv_add_nvp (nv, "open", name); + json_to_nv (root[index], name, nv); + nv_add_nvp (nv, "close", name); + } + } + } + break; + case Json::objectValue: + { + Json::Value::Members members (root.getMemberNames ()); + for (Json::Value::Members::iterator it = members.begin (); + it != members.end (); ++it) + { + json_to_nv (root[*it], (*it).c_str (), nv); + } + } + break; + case Json::intValue: + nv_add_nvp_int (nv, name, root.asInt ()); + break; + default: + nv_add_nvp (nv, name, root.asString ().c_str ()); + break; + } + + return 0; +} + +#define IS_SPECIAL_KEY (!strcmp(pname, "line") || !strcmp(pname, "confdata") \ + || !strcmp(pname, "group") || !strcmp(pname, "classattribute") \ + || !strcmp(pname, "attribute")) +/* +transform struct nvplist to json. +*/ +int +nv_to_json (nvplist *ref, char *value, int &index, Json::Value &root) +{ + Json::Value array; + Json::StyledWriter writer; + char *pvalue, *pname; + for (; index < ref->nvplist_size; ++index) + { + if (ref->nvpairs[index] == NULL + || dst_buffer (ref->nvpairs[index]->name) == NULL) + { + continue; + } + pname = dst_buffer (ref->nvpairs[index]->name); + pvalue = dst_buffer (ref->nvpairs[index]->value); + if (!strcmp (pname, "open")) + { + array.clear (); + nv_to_json (ref, pvalue, ++index, array); + if (!array.empty ()) + { + root[pvalue].append (array); + } + else + { + root[pvalue] = array; + } + } + else if (!strcmp (pname, "close") && !strcmp (pvalue, value)) + { + break; + } + else if (IS_SPECIAL_KEY) + { + root[pname].append ((pvalue == NULL) ? "" : pvalue); + } + else + { + root[pname] = (pvalue == NULL) ? "" : pvalue; + } + } + + return 1; +} + +void +dump_json (Json::Value &root) +{ + Json::StyledWriter writer; + printf ("%s\n", writer.write (root).c_str ()); +} + +void +dump_nvplist (nvplist *root, char *dumpfile) +{ + nv_writeto (root, dumpfile); +} + + +int +arn_cm_extend_request (Json::Value &request, Json::Value &response) +{ + T_EXT_TASK_FUNC task_func = NULL; + string task; + try + { + task = request["task"].asString (); + response["task"] = task; + if (get_ext_task_info (task.c_str (), 0, &task_func, NULL)) + { + (*task_func) (request, response); + return 1; + } + } + catch (exception &e) + { + response["status"] = STATUS_FAILURE; + response["note"] = e.what (); + return 1; + } + return 0; +} + +class async_request +{ + public: + unsigned int uuid; + Json::Value request; + Json::Value response; + int status; +#ifndef WINDOWS + pthread_mutex_t *mutex; + pthread_cond_t *cond; +#endif +}; + +list < async_request * >request_list; + +#ifdef WINDOWS +DWORD WINAPI +cm_async_request_handler (LPVOID lpArg) +#else +void * +cm_async_request_handler (void *lpArg) +#endif +{ + int index = 0; + nvplist *cli_request, *cli_response; + async_request *async_param = (async_request *) lpArg; + Json::Value &request = async_param->request; + Json::Value &response = async_param->response; + + cli_request = nv_create (5, NULL, "\n", ":", "\n"); + cli_response = nv_create (5, NULL, "\n", ":", "\n"); + try + { + json_to_nv (request, NULL, cli_request); + ch_build_request (request, cli_request); + ch_process_request (cli_request, cli_response); + nv_to_json (cli_response, NULL, index, response); + } + catch (exception &e) + { + response["status"] = ERR_REQUEST_FORMAT; + response["note"] = e.what (); + } + + async_param->status = 1; + nv_destroy (cli_request); + nv_destroy (cli_response); + +#ifndef WINDOWS + pthread_mutex_lock (async_param->mutex); + pthread_cond_broadcast (async_param->cond); + pthread_mutex_unlock (async_param->mutex); +#endif + + return NULL; +} + +#ifdef WINDOWS +int +cm_execute_request_async (Json::Value &request, Json::Value &response, + unsigned long time_out = 600) +{ + HANDLE hHandles; + DWORD ThreadID; + DWORD dwWaitResult; + static unsigned int req_id = 0; + async_request *pstmt = (async_request *) new (async_request); + if (pstmt == NULL) + { + return ERR_MEM_ALLOC; + } + + pstmt->request = request; + pstmt->status = 0; + pstmt->uuid = req_id++; + + hHandles = + CreateThread (NULL, 0, cm_async_request_handler, pstmt, 0, &ThreadID); + if (hHandles == NULL) + { + delete (pstmt); + return build_server_header (response, ERR_WITH_MSG, + "failed to execute task"); + } + + //dwWaitResult = WaitForSingleObject (hHandles, time_out * 1000); // time-out interval + + dwWaitResult = WaitForSingleObject (hHandles, INFINITE); //no timeout. + + if (dwWaitResult == WAIT_TIMEOUT) + { + CloseHandle (hHandles); + request_list.push_back (pstmt); + response["uuid"] = pstmt->uuid; + return build_server_header (response, ERR_WITH_MSG, "timeout"); + } + + CloseHandle (hHandles); + response = pstmt->response; + delete (pstmt); + return ERR_NO_ERROR; +} +#else +int +cm_execute_request_async (Json::Value &request, Json::Value &response, + unsigned long time_out = 600) +{ + int err = 0; + pthread_t async_thrd; +#if defined(AIX) + pthread_attr_t thread_attr; +#endif + pthread_cond_t cond; + pthread_mutex_t mutex; + timespec to; + static unsigned int req_id = 0; + async_request *pstmt = (async_request *) new (async_request); + if (pstmt == NULL) + { + return ERR_MEM_ALLOC; + } + + err = pthread_mutex_init (&mutex, NULL); + if (err != 0) + { + LOG_ERROR ("cm_execute_request_async : fail to set thread mutex."); + return build_server_header (response, ERR_WITH_MSG, + "failed to run task."); + } + + err = pthread_cond_init (&cond, NULL); + if (err != 0) + { + LOG_ERROR ("cm_execute_request_async : fail to set thread condition."); + return build_server_header (response, ERR_WITH_MSG, + "failed to run task."); + } + + pstmt->request = request; + pstmt->status = 0; + + pstmt->uuid = req_id++; + + pstmt->mutex = &mutex; + pstmt->cond = &cond; + +#if defined(AIX) + err = pthread_attr_init (&thread_attr); + if (err != 0) + { + LOG_ERROR ("cm_execute_request_async : fail to set thread attribute."); + return build_server_header (response, ERR_WITH_MSG, + "failed to run task."); + } + + err = pthread_attr_setdetachstate (&thread_attr, PTHREAD_CREATE_DETACHED); + if (err != 0) + { + LOG_ERROR ("cm_execute_request_async : fail to set thread detach state."); + return build_server_header (response, ERR_WITH_MSG, + "failed to run task."); + } + + /* AIX's pthread is slightly different from other systems. + Its performance highly depends on the pthread's scope and it's related + kernel parameters. */ + err = pthread_attr_setscope (&thread_attr, PTHREAD_SCOPE_PROCESS); + if (err != 0) + { + LOG_ERROR ("cm_execute_request_async : fail to set thread scope."); + return build_server_header (response, ERR_WITH_MSG, + "failed to run task."); + } + + err = pthread_attr_setstacksize (&thread_attr, AIX_STACKSIZE_PER_THREAD); + if (err != 0) + { + LOG_ERROR ("cm_execute_request_async : fail to set thread stack size."); + return build_server_header (response, ERR_WITH_MSG, + "failed to run task."); + } + + err = pthread_create (&async_thrd, &thread_attr, cm_async_request_handler, pstmt); +#else /* except AIX */ + err = pthread_create (&async_thrd, NULL, cm_async_request_handler, pstmt); +#endif + + if (err != 0) + { + delete (pstmt); + pthread_mutex_destroy (&mutex); + pthread_cond_destroy (&cond); + LOG_ERROR ("cm_execute_request_async : fail to create thread."); + return build_server_header (response, ERR_WITH_MSG, + "failed to run task."); + } + pthread_mutex_lock (&mutex); + to.tv_sec = time (NULL) + time_out; + to.tv_nsec = 0; + //err = pthread_cond_timedwait (&cond, &mutex, &to); + err = pthread_cond_wait (&cond, &mutex); + pthread_mutex_unlock (&mutex); + if (err == ETIMEDOUT) + { + request_list.push_back (pstmt); + response["uuid"] = pstmt->uuid; + LOG_ERROR ("cm_execute_request_async : Timeout for running task."); + return build_server_header (response, ERR_WITH_MSG, "timeout"); + } + + pthread_join (async_thrd, NULL); + + pthread_mutex_destroy (&mutex); + pthread_cond_destroy (&cond); + response = pstmt->response; + delete (pstmt); + return ERR_NO_ERROR; +} +#endif + +int +arn_check_async_status (Json::Value &request, Json::Value &response) +{ + string task; + unsigned int uuid; + list < async_request * >::iterator itor; + task = request["task"].asString (); + + if (task != "gettaskstatus") + { + return 0; + } + if (request["uuid"] == Json::Value::null || !request["uuid"].isInt ()) + { + return build_server_header (response, ERR_WITH_MSG, "invalid uuid"); + } + uuid = request["uuid"].asInt (); + for (itor = request_list.begin (); itor != request_list.end (); itor++) + { + if ((*itor)->uuid != uuid) + { + continue; + } + break; + } + if (itor == request_list.end ()) + { + return build_server_header (response, ERR_WITH_MSG, "uuid not found"); + } + + if ((*itor)->status == 0) + { + return build_server_header (response, ERR_WITH_MSG, "task not return"); + } + response = (*itor)->response; + request_list.erase (itor); + return ERR_NO_ERROR; +} + +int +arn_cm_request_handler (Json::Value &request, Json::Value &response) +{ + + mutex_lock (cm_mutex); + + + // leave a back door for testing... + if (ext_ut_validate_token (request, response) != ERR_NO_ERROR && request["token"].asString() != "test") + { + response["task"] = request["task"].asString(); + mutex_unlock (cm_mutex); + return 1; + } + + // leave a back door for testing... + if (!ext_ut_validate_auth (request) && request["token"].asString() != "test") + { + response["status"] = STATUS_FAILURE; + response["note"] = "The user don't have authority to execute the task: " + request["task"].asString(); + response["task"] = request["task"].asString(); + + mutex_unlock (cm_mutex); + return 1; + } + + if (arn_check_async_status (request, response)) + { + mutex_unlock (cm_mutex); + return 1; + } + if (arn_cm_extend_request (request, response)) + { + mutex_unlock (cm_mutex); + return 1; + } + cm_execute_request_async (request, response, sco.iHttpTimeout); + + mutex_unlock (cm_mutex); + return 1; +} diff --git a/server/src/am_server_interface.h b/server/src/am_server_interface.h new file mode 100644 index 0000000..60ba045 --- /dev/null +++ b/server/src/am_server_interface.h @@ -0,0 +1,33 @@ +/* + * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. + * + * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifndef __CM_API_H__ +#define __CM_API_H__ +#include + +#include "cm_stat.h" +#include "cm_dep.h" +#include "cm_config.h" +#include "cm_job_task.h" +#include "cm_server_util.h" + +int arn_cm_request_handler (Json::Value &request, Json::Value &response); +void arn_cm_init_env (); + +#endif /* */ diff --git a/server/src/am_server_stat.c b/server/src/am_server_stat.c new file mode 100644 index 0000000..f30be6b --- /dev/null +++ b/server/src/am_server_stat.c @@ -0,0 +1,463 @@ +/* + * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. + * + * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + + +/* + * server_stat.c - + */ + +#ident "$Id$" + +#include +#include /* CPU_WAIT */ +#if !defined(AIX) +#include +#endif +#include +#include /* strncmp() */ +#include /* sysconf() */ +#if !defined(HPUX) +#include /* prpsinfo_t */ +#endif +#include /* open() */ +#include +#ifdef HOST_MONITOR_PROC +#include +#endif + +#include "cm_porting.h" +#include "cm_server_stat.h" +#include "cm_dep.h" +#include "cm_server_util.h" +#include "cm_config.h" + +#define MAX_CPU 16 + +#define CHECK_KCID(nk,ok) \ + do { \ + if (nk == -1) { \ + return -1; \ + } \ + if (nk != ok) { \ + goto kcid_changed; \ + } \ + } while (0) + +#define PAGETOM(NUMPAGE, PAGESIZE) ((((NUMPAGE) >> 10) * (PAGESIZE)) >> 10) * 10 + +#ifdef HOST_MONITOR_PROC +static long percentages (int cnt, int *out1, register long *new1, + register long *old, long *diffs); +static void get_swapinfo (int *total, int *fr); +static int get_system_info (kstat_ctl_t *kc, sys_stat *sst); +#ifdef HOST_MONITOR_IO +static void record_iostat (nvplist *res); +#endif /* ifdef HOST_MONITOR_IO */ +#endif /* ifdef HOST_MONITOR_PROC */ + +void +record_system_info (sys_stat *sstat) +{ +#ifdef HOST_MONITOR_PROC + static kstat_ctl_t *kc = NULL; + + while (kc == NULL) + { + kc = kstat_open (); + SLEEP_MILISEC (0, 100); + } + + while (get_system_info (kc, sstat) < 0) + { + SLEEP_MILISEC (0, 100); + } +#endif +} + +void +record_arniadb_proc_info (userdata *ud) +{ +#ifdef HOST_MONITOR_PROC + int i, fd; + prpsinfo_t psbuff; + char procbuf[50]; + int *vect = ud->dbvect; + db_stat *buff = ud->dbbuf; + + /* for each db, update 7 values of process */ + for (i = 0; i < MAX_INSTALLED_DB; ++i) + { + if (vect[i]) + { + sprintf (procbuf, "/proc/%d", buff[i].db_pid); + if ((fd = open (procbuf, O_RDONLY)) == -1) + { + ud->dbsrv_refresh_flag = 1; + continue; + } + if (ioctl (fd, PIOCPSINFO, &psbuff) == -1) + { + ud->dbsrv_refresh_flag = 1; + close (fd); + continue; + } + close (fd); + + /* fill in the structure */ + buff[i].db_size = (unsigned long) psbuff.pr_bysize >> 10; + buff[i].proc_stat[0] = psbuff.pr_sname; + buff[i].db_start_time = psbuff.pr_start.tv_sec; + buff[i].db_cpu_usage = (((double) psbuff.pr_pctcpu) / 0x8000 * 100); + buff[i].db_mem_usage = (((double) psbuff.pr_pctmem) / 0x8000 * 100); + } + } +#endif +} + +void +record_unicas_proc_info (int vect[], cas_stat buff[]) +{ +#ifdef HOST_MONITOR_PROC + int i, fd; + prpsinfo_t psbuff; + char procbuf[50]; + + for (i = 0; i < MAX_UNICAS_PROC; ++i) + { + if (vect[i]) + { + sprintf (procbuf, "/proc/%d", buff[i].cas_pid); + + if ((fd = open (procbuf, O_RDONLY)) == -1) + { + vect[i] = 0; + continue; + } + if (ioctl (fd, PIOCPSINFO, &psbuff) == -1) + { + continue; + } + close (fd); + + /* fill in the structure */ + buff[i].cas_size = (unsigned long) psbuff.pr_bysize >> 10; + buff[i].proc_stat[0] = psbuff.pr_sname; + buff[i].cas_start_time = psbuff.pr_start.tv_sec; + buff[i].cas_cpu_usage = + (((double) psbuff.pr_pctcpu) / 0x8000 * 100); + buff[i].cas_mem_usage = + (((double) psbuff.pr_pctmem) / 0x8000 * 100); + } + } +#endif +} + +#ifdef HOST_MONITOR_PROC +static long +percentages (int cnt, int *out1, register long *new1, register long *old, + long *diffs) +{ + register int i; + register long change; + register long total_change; + register long *dp; + long half_total; + + /* initialization */ + total_change = 0; + dp = diffs; + + /* calculate changes for each state and the overall change */ + for (i = 0; i < cnt; i++) + { + if ((change = *new1 - *old) < 0) + { + /* this only happens when the counter wraps */ + change = (int) ((unsigned long) *new1 - (unsigned long) *old); + } + total_change += (*dp++ = change); + *old++ = *new1++; + } + + /* avoid divide by zero potential */ + if (total_change == 0) + { + total_change = 1; + } + + /* calculate percentages based on overall change, rounding up */ + half_total = total_change / 2l; + for (i = 0; i < cnt; i++) + { + *out1++ = (int) ((*diffs++ * 1000 + half_total) / total_change); + } + /* return the total in case the caller wants to use it */ + return (total_change); +} + +static void +get_swapinfo (int *total, int *fr) +{ +#ifdef SC_AINFO + struct anoninfo anon; + + if (swapctl (SC_AINFO, &anon) == -1) + { + *total = *fr = 0; + return; + } + *total = anon.ani_max; + *fr = anon.ani_max - anon.ani_resv; +#else + register int cnt, i; + register int t, f; + struct swaptable *swt; + struct swapent *ste; + static char path[256]; + + /* get total number of swap entries */ + cnt = swapctl (SC_GETNSWP, 0); + + /* allocate enough space to hold count + n swapents */ + swt = + (struct swaptable *) malloc (sizeof (int) + + cnt * sizeof (struct swapent)); + if (swt == NULL) + { + *total = 0; + *fr = 0; + return; + } + swt->swt_n = cnt; + + /* fill in ste_path pointers: we don't care about the paths, so we point + them all to the same buffer */ + ste = & (swt->swt_ent[0]); + i = cnt; + while (--i >= 0) + { + ste++->ste_path = path; + } + + /* grab all swap info */ + swapctl (SC_LIST, swt); + + /* walk thru the structs and sum up the fields */ + t = f = 0; + ste = & (swt->swt_ent[0]); + i = cnt; + while (--i >= 0) + { + /* don't count slots being deleted */ + if (! (ste->ste_flags & ST_INDEL) && ! (ste->ste_flags & ST_DOINGDEL)) + { + t += ste->ste_pages; + f += ste->ste_free; + } + ste++; + } + + /* fill in the results */ + *total = t; + *fr = f; + free (swt); +#endif +} + +static int +get_system_info (kstat_ctl_t *kc, sys_stat *sst) +{ + kstat_t *ksp; + kstat_named_t *kn; + kid_t kcid, nkcid; + int totalswap, freeswap; + int i, j; + cpu_stat_t cpu_stat[MAX_CPU]; + static int pagesize = 0, maxmem = 0; + static long cp_time[CPUSTATES]; + static long cp_old[CPUSTATES]; + static long cp_diff[CPUSTATES]; + static kstat_t *cpu_ks[MAX_CPU]; + static int ncpu = 0; + static int freemem_check_time = 0; + int changed = 0; + + kcid = kc->kc_chain_id; + +kcid_changed: + + nkcid = kstat_chain_update (kc); + if (nkcid) + { + kcid = nkcid; + changed = 1; + } + CHECK_KCID (nkcid, 0); + + ksp = kstat_lookup (kc, "unix", -1, "system_misc"); + nkcid = kstat_read (kc, ksp, NULL); + CHECK_KCID (nkcid, kcid); + + /* + * collect load average information + */ + kn = kstat_data_lookup (ksp, "avenrun_1min"); + sst->load_avg[0] = kn->value.ui32; + kn = kstat_data_lookup (ksp, "avenrun_5min"); + sst->load_avg[1] = kn->value.ui32; + kn = kstat_data_lookup (ksp, "avenrun_15min"); + sst->load_avg[2] = kn->value.ui32; + + /* + * collect cpu information + */ + if (changed == 1 || ncpu == 0) + { + ncpu = 0; + for (ksp = kc->kc_chain; ksp && ncpu < MAX_CPU; ksp = ksp->ks_next) + { + if (strncmp (ksp->ks_name, "cpu_stat", 8) == 0) + { + nkcid = kstat_read (kc, ksp, NULL); + CHECK_KCID (nkcid, kcid); + cpu_ks[ncpu] = ksp; + ncpu++; + } + } + } + + for (i = 0; i < ncpu; i++) + { + nkcid = kstat_read (kc, cpu_ks[i], & (cpu_stat[i])); + CHECK_KCID (nkcid, kcid); + } + + for (j = 0; j < CPUSTATES; j++) + { + cp_time[j] = 0L; + } + + for (i = 0; i < ncpu; i++) + { + for (j = 0; j < CPU_WAIT; j++) + { + cp_time[j] += (long) cpu_stat[i].cpu_sysinfo.cpu[j]; + } + + cp_time[CPUSTATE_IOWAIT] += (long) cpu_stat[i].cpu_sysinfo.wait[W_IO] + + (long) cpu_stat[i].cpu_sysinfo.wait[W_PIO]; + cp_time[CPUSTATE_SWAP] = (long) cpu_stat[i].cpu_sysinfo.wait[W_SWAP]; + } + + percentages (CPUSTATES, sst->cpu_states, cp_time, cp_old, cp_diff); + + /* + * collect memory information + */ + if (pagesize == 0) + { + pagesize = sysconf (_SC_PAGESIZE); + } + if (maxmem == 0) + { + maxmem = sysconf (_SC_PHYS_PAGES); + sst->memory_stats[0] = PAGETOM (maxmem, pagesize); + } + + if (time (NULL) - freemem_check_time > 30) + { + ksp = kstat_lookup (kc, "unix", 0, "system_pages"); + nkcid = kstat_read (kc, ksp, NULL); + CHECK_KCID (nkcid, kcid); + + kn = kstat_data_lookup (ksp, "freemem"); + sst->memory_stats[2] = PAGETOM (kn->value.ui32, pagesize); + + if (sst->memory_stats[0] - sst->memory_stats[2] > 0) + { + sst->memory_stats[1] = sst->memory_stats[0] - sst->memory_stats[2]; + } + freemem_check_time = time (NULL); + } + +#if 0 + kn = kstat_data_lookup (ksp, "availrmem"); +#endif + + get_swapinfo (&totalswap, &freeswap); + sst->memory_stats[3] = PAGETOM ((totalswap - freeswap), pagesize); + sst->memory_stats[4] = PAGETOM (freeswap, pagesize); + + return 1; +} + +#ifdef HOST_MONITOR_IO +static void +record_iostat (nvplist *res) +{ + FILE *infile; + char buf[1024], d[256], rs[16], ws[16], krs[16], kws[16], wait[16], + actv[16], svc_t[16], w[16], b[16], tmpfile[256]; + sprintf (tmpfile, "%s/DBMT_rec_iostat.%d", sco.dbmt_tmp_dir, + (int) getpid ()); + sprintf (buf, "/usr/bin/iostat -x > %s", tmpfile); + + if (system (buf) != 0) /* iostat */ + { + return; + } + infile = fopen (tmpfile, "r"); + if (infile == NULL) + { + return; + } + fgets (buf, 1024, infile); + fgets (buf, 1024, infile); + while (fgets (buf, 1024, infile)) + { + if (sscanf (buf, "%s %s %s %s %s %s %s %s %s %s", + d, rs, ws, krs, kws, wait, actv, svc_t, w, b) != 10) + { + continue; + } + /* name of the disk */ + nv_add_nvp (res, "device", d); + /* reads per second */ + nv_add_nvp (res, "rs", rs); + /* writes per second */ + nv_add_nvp (res, "ws", ws); + /* KBs read per second */ + nv_add_nvp (res, "krs", krs); + /* KBs written per second */ + nv_add_nvp (res, "kws", kws); + /* avg # of transactions waiting for service */ + nv_add_nvp (res, "wait", wait); + /* avg # of transactions being serviced */ + nv_add_nvp (res, "actv", actv); + /* avg service time in milliseconds */ + nv_add_nvp (res, "svc_t", svc_t); + /* % of time there are transactions waiting for service */ + nv_add_nvp (res, "w", w); + /* % of time the disk is busy */ + nv_add_nvp (res, "b", b); + } + fclose (infile); +} +#endif /* ifdef HOST_MONITOR_IO */ +#endif /* ifdef HOST_MONITOR_PROC */ diff --git a/server/src/am_server_stat.h b/server/src/am_server_stat.h new file mode 100644 index 0000000..69aa6e6 --- /dev/null +++ b/server/src/am_server_stat.h @@ -0,0 +1,99 @@ +/* + * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. + * + * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + + +/* + * cm_server_stat.h - + */ + +#ifndef _CM_SERVER_STAT_H_ +#define _CM_SERVER_STAT_H_ + +#ident "$Id$" + +#include + +#if !defined(HOST_MONITOR_PROC) && defined(HOST_MONITOR_IO) +#undef HOST_MONITOR_IO +#endif + +#include "cm_dep.h" +#include "cm_config.h" + +#define CPUSTATES 5 +#define CPUSTATE_IOWAIT 3 +#define CPUSTATE_SWAP 4 + +typedef struct +{ +#ifdef HOST_MONITOR_PROC + int load_avg[3]; + int memory_stats[5]; + int cpu_states[CPUSTATES]; +#else + int dummy; +#endif +} sys_stat; + +typedef struct +{ +#ifdef HOST_MONITOR_PROC + char db_name[64]; + int db_pid; + unsigned long db_size; + char proc_stat[2]; + time_t db_start_time; + double db_cpu_usage; + double db_mem_usage; +#else + int dummy; +#endif +} db_stat; + +typedef struct +{ +#ifdef HOST_MONITOR_PROC + char cas_name[64]; + int cas_pid; + unsigned long cas_size; + char proc_stat[2]; + time_t cas_start_time; + double cas_cpu_usage; + double cas_mem_usage; +#else + int dummy; +#endif +} cas_stat; + +typedef struct +{ + char dbsrv_refresh_flag; + time_t last_request_time; + sys_stat ssbuf; + int dbvect[MAX_INSTALLED_DB]; /* 0:inactive, 1:active */ + db_stat dbbuf[MAX_INSTALLED_DB]; + int casvect[MAX_UNICAS_PROC]; + cas_stat casbuf[MAX_UNICAS_PROC]; +} userdata; + +void record_system_info (sys_stat *sstat); +void record_arniadb_proc_info (userdata *ud); +void record_unicas_proc_info (int casv[], cas_stat casb[]); + +#endif /* _CM_SERVER_STAT_H_ */ diff --git a/server/src/am_server_util.cpp b/server/src/am_server_util.cpp new file mode 100644 index 0000000..d5a5e13 --- /dev/null +++ b/server/src/am_server_util.cpp @@ -0,0 +1,3790 @@ +/* + * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. + * + * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + + +/* + * cm_server_util.cpp - + */ + +#include +#include +#include +#include +#include +#include +#include /* isalpha() */ + +#if defined(WINDOWS) +#include +#include +#include +#include +#include +#include +#include +#else +#include /* umask() */ +#include /* umask(), stat() */ +#include +#include /* opendir() ... */ +#include +#include +#include +#include +#include +#include +#if defined(LINUX) +#include +#endif /* LINUX */ +#if !defined(HPUX) +#include +#endif +#include +#endif + +#if defined(AIX) +#include +#endif + +#include "cm_log.h" +#include "cm_connect_info.h" +#include "cm_porting.h" +#include "cm_server_util.h" +#include "cm_dep.h" +#include "cm_config.h" +#include "cm_job_task.h" +#include "cm_cmd_exec.h" +#include "cm_text_encryption.h" +#include "cm_stat.h" +#include "cm_user.h" + +#include + +#ifdef FSERVER_SLAVE +#define DEF_TASK_FUNC(TASK_FUNC_PTR) TASK_FUNC_PTR +#else +#define DEF_TASK_FUNC(TASK_FUNC_PTR) NULL +#endif + +/* for ut_getdelim */ +#define MAX_LINE ((int)(10*1024*1024)) +#define MIN_CHUNK 4096 + +static T_FSERVER_TASK_INFO task_info[] = +{ + {"startinfo", TS_STARTINFO, 0, DEF_TASK_FUNC (ts_startinfo), FSVR_SA, ALL_AUTHORITY}, + {"userinfo", TS_USERINFO, 0, DEF_TASK_FUNC (ts_userinfo), FSVR_CS, ALL_AUTHORITY}, + {"createuser", TS_CREATEUSER, 1, DEF_TASK_FUNC (ts_create_user), FSVR_CS, AU_DBO}, + {"deleteuser", TS_DELETEUSER, 1, DEF_TASK_FUNC (ts_delete_user), FSVR_CS, AU_DBO}, + {"updateuser", TS_UPDATEUSER, 1, DEF_TASK_FUNC (ts_update_user), FSVR_CS, AU_DBO}, + {"createdb", TS_CREATEDB, 1, DEF_TASK_FUNC (tsCreateDB), FSVR_SA, AU_DBC}, + {"deletedb", TS_DELETEDB, 1, DEF_TASK_FUNC (tsDeleteDB), FSVR_SA, AU_DBC}, + {"renamedb", TS_RENAMEDB, 1, DEF_TASK_FUNC (tsRenameDB), FSVR_SA, AU_DBC}, + {"startdb", TS_STARTDB, 0, DEF_TASK_FUNC (tsStartDB), FSVR_NONE, AU_DBC | AU_DBO}, + {"stopdb", TS_STOPDB, 0, DEF_TASK_FUNC (tsStopDB), FSVR_CS,AU_DBC | AU_DBO}, + {"dbspaceinfo", TS_DBSPACEINFO, 0, DEF_TASK_FUNC (tsDbspaceInfo), FSVR_SA_CS, ALL_AUTHORITY}, + {"classinfo", TS_CLASSINFO, 0, DEF_TASK_FUNC (ts_class_info), FSVR_SA_CS, ALL_AUTHORITY}, + {"class", TS_CLASS, 0, DEF_TASK_FUNC (ts_class), FSVR_CS, ALL_AUTHORITY}, + {"setsysparam", TS_SETSYSPARAM, 1, DEF_TASK_FUNC (ts_set_sysparam), FSVR_NONE, AU_DBC | AU_DBO}, + {"getallsysparam", TS_GETALLSYSPARAM, 0, DEF_TASK_FUNC (ts_get_all_sysparam), FSVR_NONE, ALL_AUTHORITY}, + {"addvoldb", TS_ADDVOLDB, 1, DEF_TASK_FUNC (tsRunAddvoldb), FSVR_SA_CS, AU_DBC | AU_DBO}, + {"getloginfo", TS_GETLOGINFO, 0, DEF_TASK_FUNC (ts_get_log_info), FSVR_NONE, ALL_AUTHORITY}, + {"viewlog", TS_VIEWLOG, 0, DEF_TASK_FUNC (ts_view_log), FSVR_NONE, ALL_AUTHORITY}, + {"viewlog2", TS_VIEWLOG, 0, DEF_TASK_FUNC (ts_view_log), FSVR_NONE, ALL_AUTHORITY}, + {"resetlog", TS_RESETLOG, 0, DEF_TASK_FUNC (ts_reset_log), FSVR_NONE, AU_DBC | AU_DBO}, + {"getenv", TS_GETENV, 0, DEF_TASK_FUNC (tsGetEnvironment), FSVR_SA_UC, ALL_AUTHORITY}, + {"updateattribute", TS_UPDATEATTRIBUTE, 1, DEF_TASK_FUNC (ts_update_attribute), FSVR_CS, ALL_AUTHORITY}, + {"kill_process", TS_KILL_PROCESS, 1, DEF_TASK_FUNC (ts_kill_process), FSVR_NONE, AU_DBC | AU_DBO}, + {"copydb", TS_COPYDB, 1, DEF_TASK_FUNC (ts_copydb), FSVR_SA, AU_DBC}, + {"optimizedb", TS_OPTIMIZEDB, 1, DEF_TASK_FUNC (ts_optimizedb), FSVR_SA_CS, AU_DBC | AU_DBO}, + {"plandump", TS_PLANDUMP, 1, DEF_TASK_FUNC (ts_plandump), FSVR_CS, ALL_AUTHORITY}, + {"paramdump", TS_PARAMDUMP, 1, DEF_TASK_FUNC (ts_paramdump), FSVR_SA_CS, ALL_AUTHORITY}, + {"statdump", TS_STATDUMP, 1, DEF_TASK_FUNC (ts_statdump), FSVR_CS, ALL_AUTHORITY}, + {"checkdb", TS_CHECKDB, 0, DEF_TASK_FUNC (ts_checkdb), FSVR_SA_CS, AU_DBC | AU_DBO}, + {"compactdb", TS_COMPACTDB, 1, DEF_TASK_FUNC (ts_compactdb), FSVR_SA, AU_DBC | AU_DBO}, + {"backupdbinfo", TS_BACKUPDBINFO, 0, DEF_TASK_FUNC (ts_backupdb_info), FSVR_NONE, ALL_AUTHORITY}, + {"backupdb", TS_BACKUPDB, 0, DEF_TASK_FUNC (ts_backupdb), FSVR_SA_CS, AU_DBC | AU_DBO}, + {"unloaddb", TS_UNLOADDB, 1, DEF_TASK_FUNC (ts_unloaddb), FSVR_SA, AU_DBC | AU_DBO}, + {"unloadinfo", TS_UNLOADDBINFO, 0, DEF_TASK_FUNC (ts_unloaddb_info), FSVR_NONE, ALL_AUTHORITY}, + {"loaddb", TS_LOADDB, 1, DEF_TASK_FUNC (ts_loaddb), FSVR_SA, AU_DBC | AU_DBO}, + {"gettransactioninfo", TS_GETTRANINFO, 0, DEF_TASK_FUNC (ts_get_tran_info), FSVR_CS, ALL_AUTHORITY}, + {"killtransaction", TS_KILLTRAN, 1, DEF_TASK_FUNC (ts_killtran), FSVR_CS, AU_DBC | AU_DBO | AU_MON}, + {"lockdb", TS_LOCKDB, 0, DEF_TASK_FUNC (ts_lockdb), FSVR_CS, ALL_AUTHORITY}, + {"getbackuplist", TS_GETBACKUPLIST, 0, DEF_TASK_FUNC (ts_get_backup_list), FSVR_NONE, ALL_AUTHORITY}, + {"restoredb", TS_RESTOREDB, 1, DEF_TASK_FUNC (ts_restoredb), FSVR_SA, AU_DBC | AU_DBO}, + {"backupvolinfo", TS_BACKUPVOLINFO, 0, DEF_TASK_FUNC (ts_backup_vol_info), FSVR_SA, ALL_AUTHORITY}, + {"getdbsize", TS_GETDBSIZE, 0, DEF_TASK_FUNC (ts_get_dbsize), FSVR_SA_CS, ALL_AUTHORITY}, + {"getbackupinfo", TS_GETBACKUPINFO, 0, DEF_TASK_FUNC (ts_get_backup_info), FSVR_NONE, ALL_AUTHORITY}, + {"addbackupinfo", TS_ADDBACKUPINFO, 1, DEF_TASK_FUNC (ts_add_backup_info), FSVR_NONE, AU_DBC | AU_DBO | AU_JOB}, + { + "deletebackupinfo", TS_DELETEBACKUPINFO, 1, DEF_TASK_FUNC (ts_delete_backup_info), + FSVR_NONE, AU_DBC | AU_DBO | AU_JOB + }, + {"setbackupinfo", TS_SETBACKUPINFO, 0, DEF_TASK_FUNC (ts_set_backup_info), FSVR_NONE, AU_DBC | AU_DBO | AU_JOB}, + {"getautoaddvol", TS_GETAUTOADDVOL, 0, DEF_TASK_FUNC (ts_get_auto_add_vol), FSVR_NONE, ALL_AUTHORITY}, + {"setautoaddvol", TS_SETAUTOADDVOL, 1, DEF_TASK_FUNC (ts_set_auto_add_vol), FSVR_NONE, AU_DBC | AU_DBO}, + {"checkdir", TS_CHECKDIR, 0, DEF_TASK_FUNC (ts_check_dir), FSVR_NONE, ALL_AUTHORITY}, + { + "getautobackupdberrlog", TS_AUTOBACKUPDBERRLOG, 0, DEF_TASK_FUNC (ts_get_autobackupdb_error_log), + FSVR_NONE, ALL_AUTHORITY + }, + { + "getautoexecqueryerrlog", TS_AUTOEXECQUERYERRLOG, 0, DEF_TASK_FUNC (ts_get_autoexecquery_error_log), + FSVR_NONE, ALL_AUTHORITY + }, + { + "getdbmtuserinfo", TS_GETDBMTUSERINFO, 0, DEF_TASK_FUNC (tsGetDBMTUserInfo), + FSVR_NONE, ALL_AUTHORITY + }, + {"deletedbmtuser", TS_DELETEDBMTUSER, 1, DEF_TASK_FUNC (tsDeleteDBMTUser), FSVR_NONE, AU_DBC}, + {"updatedbmtuser", TS_UPDATEDBMTUSER, 1, DEF_TASK_FUNC (tsUpdateDBMTUser), FSVR_NONE, AU_DBC}, + {"setdbmtpasswd", TS_SETDBMTPASSWD, 1,DEF_TASK_FUNC (tsChangeDBMTUserPasswd), FSVR_NONE, ALL_AUTHORITY ^ AU_DBC}, + {"adddbmtuser", TS_ADDDBMTUSER, 1, DEF_TASK_FUNC (tsCreateDBMTUser), FSVR_NONE, AU_DBC}, + {"getaddvolstatus", TS_GETADDVOLSTATUS, 0, DEF_TASK_FUNC (ts_get_addvol_status), FSVR_NONE, ALL_AUTHORITY}, + {"getautoaddvollog", TS_GETAUTOADDVOLLOG, 0, DEF_TASK_FUNC (tsGetAutoaddvolLog), FSVR_UC, ALL_AUTHORITY}, + {"getinitbrokersinfo", TS2_GETINITUNICASINFO, 0, DEF_TASK_FUNC (ts2_get_unicas_info), FSVR_UC, ALL_AUTHORITY}, + {"getbrokersinfo", TS2_GETUNICASINFO, 0, DEF_TASK_FUNC (ts2_get_unicas_info), FSVR_UC, ALL_AUTHORITY}, + {"startbroker", TS2_STARTUNICAS, 0, DEF_TASK_FUNC (ts2_start_unicas), FSVR_UC, AU_DBC | AU_DBO | AU_BRK}, + {"stopbroker", TS2_STOPUNICAS, 0, DEF_TASK_FUNC (ts2_stop_unicas), FSVR_UC, AU_DBC | AU_DBO | AU_BRK}, + {"getadminloginfo", TS2_GETADMINLOGINFO, 0, DEF_TASK_FUNC (ts2_get_admin_log_info), FSVR_UC, ALL_AUTHORITY}, + {"getlogfileinfo", TS2_GETLOGFILEINFO, 0, DEF_TASK_FUNC (ts2_get_logfile_info), FSVR_UC, ALL_AUTHORITY}, + {"getaddbrokerinfo", TS2_GETADDBROKERINFO, 0, DEF_TASK_FUNC (ts2_get_add_broker_info), FSVR_UC, ALL_AUTHORITY}, + {"deletebroker", TS2_DELETEBROKER, 1, DEF_TASK_FUNC (ts2_delete_broker), FSVR_UC, AU_DBC | AU_DBO | AU_BRK}, + {"getbrokerstatus", TS2_GETBROKERSTATUS, 0, DEF_TASK_FUNC (ts2_get_broker_status), FSVR_UC, ALL_AUTHORITY}, + {"broker_setparam", TS2_SETBROKERCONF, 1, DEF_TASK_FUNC (ts2_set_broker_conf), FSVR_UC, AU_DBC | AU_DBO | AU_BRK}, + {"broker_start", TS2_STARTBROKER, 0, DEF_TASK_FUNC (ts2_start_broker), FSVR_UC, AU_DBC | AU_DBO | AU_BRK}, + {"broker_stop", TS2_STOPBROKER, 0, DEF_TASK_FUNC (ts2_stop_broker), FSVR_UC, AU_DBC | AU_DBO | AU_BRK}, + { + "broker_restart", TS2_RESTARTBROKERAS, 0, DEF_TASK_FUNC (ts2_restart_broker_as), + FSVR_UC, AU_DBC | AU_DBO | AU_BRK + }, + {"checkfile", TS_CHECKFILE, 0, DEF_TASK_FUNC (ts_check_file), FSVR_NONE, ALL_AUTHORITY}, + {"loadaccesslog", TS_LOADACCESSLOG, 0, DEF_TASK_FUNC (ts_load_access_log), FSVR_NONE, ALL_AUTHORITY}, + {"getaccesslogfiles", TS_GETACCESSLOGFILES, 0, DEF_TASK_FUNC (ts_get_access_log_files), FSVR_NONE, ALL_AUTHORITY}, + {"geterrorlogfiles", TS_GETERRORLOGFILES, 0, DEF_TASK_FUNC (ts_get_error_log_files), FSVR_NONE, ALL_AUTHORITY}, + {"addtrigger", TS_ADDNEWTRIGGER, 1, DEF_TASK_FUNC (ts_trigger_operation), FSVR_SA_CS, AU_DBC | AU_DBO}, + {"altertrigger", TS_ALTERTRIGGER, 1, DEF_TASK_FUNC (ts_trigger_operation), FSVR_SA_CS, AU_DBC | AU_DBO}, + {"droptrigger", TS_DROPTRIGGER, 1, DEF_TASK_FUNC (ts_trigger_operation), FSVR_SA_CS, AU_DBC | AU_DBO}, + {"gettriggerinfo", TS_GETTRIGGERINFO, 0, DEF_TASK_FUNC (ts_get_triggerinfo), FSVR_SA_CS, ALL_AUTHORITY}, + {"getautoexecquery", TS_GETAUTOEXECQUERY, 0, DEF_TASK_FUNC (ts_get_autoexec_query), FSVR_SA_CS, ALL_AUTHORITY}, + { + "setautoexecquery", TS_SETAUTOEXECQUERY, 1, DEF_TASK_FUNC (ts_set_autoexec_query), + FSVR_SA_CS, AU_DBC | AU_DBO | AU_JOB + }, + {"getdiagdata", TS_GET_DIAGDATA, 0, DEF_TASK_FUNC (ts_get_diagdata), FSVR_NONE, ALL_AUTHORITY}, + {"getbrokerdiagdata", TS_GET_BROKER_DIAGDATA, 0, DEF_TASK_FUNC (ts_get_broker_diagdata), FSVR_NONE, ALL_AUTHORITY}, + { + "addstatustemplate", TS_ADDSTATUSTEMPLATE, 0, DEF_TASK_FUNC (ts_addstatustemplate), + FSVR_NONE, AU_DBC | AU_DBO | AU_MON + }, + { + "updatestatustemplate", TS_UPDATESTATUSTEMPLATE, 0, DEF_TASK_FUNC (ts_updatestatustemplate), + FSVR_NONE, AU_DBC | AU_DBO | AU_MON + }, + { + "removestatustemplate", TS_REMOVESTATUSTEMPLATE, 0, DEF_TASK_FUNC (ts_removestatustemplate), + FSVR_NONE, AU_DBC | AU_DBO | AU_MON + }, + {"getstatustemplate", TS_GETSTATUSTEMPLATE, 0, DEF_TASK_FUNC (ts_getstatustemplate), FSVR_NONE, ALL_AUTHORITY}, + {"analyzecaslog", TS_ANALYZECASLOG, 0, DEF_TASK_FUNC (ts_analyzecaslog), FSVR_NONE, ALL_AUTHORITY}, + { + "executecasrunner", TS_EXECUTECASRUNNER, 0, DEF_TASK_FUNC (ts_executecasrunner), + FSVR_NONE, AU_DBC | AU_DBO | AU_BRK | AU_MON + }, + { + "removecasrunnertmpfile", TS_REMOVECASRUNNERTMPFILE, 0, DEF_TASK_FUNC (ts_removecasrunnertmpfile), + FSVR_NONE, AU_DBC | AU_DBO | AU_BRK | AU_MON + }, + {"getcaslogtopresult", TS_GETCASLOGTOPRESULT, 0, DEF_TASK_FUNC (ts_getcaslogtopresult), FSVR_NONE, ALL_AUTHORITY}, + {"dbmtuserlogin", TS_DBMTUSERLOGIN, 0, DEF_TASK_FUNC (tsDBMTUserLogin), FSVR_NONE, ALL_AUTHORITY}, + {"removelog", TS_REMOVE_LOG, 0, DEF_TASK_FUNC (ts_remove_log), FSVR_NONE, ALL_AUTHORITY}, + {"getdbprocstat", TS_GETDBPROCSTAT, 0, DEF_TASK_FUNC (ts_get_dbproc_stat), FSVR_SA_CS, ALL_AUTHORITY}, + {"gethoststat", TS_GETHOSTSTAT, 0, DEF_TASK_FUNC (ts_get_host_stat), FSVR_SA_CS, ALL_AUTHORITY}, + {"heartbeatlist", TS_HEARTBEAT_LIST, 0, DEF_TASK_FUNC (ts_heartbeat_list), FSVR_SA_CS, ALL_AUTHORITY}, + {"changemode", TS_CHANGEMODE, 0, DEF_TASK_FUNC (ts_changemode), FSVR_CS, AU_DBC | AU_DBO}, + {"getdbmode", TS_GETDBMODE, 0, DEF_TASK_FUNC (ts_get_db_mode), FSVR_SA_CS, ALL_AUTHORITY}, + { + "getstandbyserverstat", TS_GET_STANDBY_SERVER_STAT, 0, DEF_TASK_FUNC (ts_get_standby_server_stat), + FSVR_SA_CS, ALL_AUTHORITY + }, + {"rolechange", TS_ROLE_CHANGE, 0, DEF_TASK_FUNC (ts_role_change), FSVR_CS, AU_DBC | AU_DBO}, + {"userverify", TS_USER_VERIFY, 0, DEF_TASK_FUNC (ts_user_verify), FSVR_SA_CS, ALL_AUTHORITY}, + {"runsqlstatement", TS_RUN_SQL_STATEMENT, 0, DEF_TASK_FUNC (ts_run_sql_statement), FSVR_SA_CS, ALL_AUTHORITY}, + {"writeandsaveconf", TS_WRITE_AND_SAVE_CONF, 0, DEF_TASK_FUNC (ts_write_and_save_conf), FSVR_SA_CS, AU_DBC | AU_DBO}, + {"getfiletotallinenum", TS_GET_FILE_TOTAL_LINE_NUM, 0, DEF_TASK_FUNC (ts_get_file_total_line_num), FSVR_SA_CS, ALL_AUTHORITY}, + {"runscript", TS_RUN_SCRIPT, 0, DEF_TASK_FUNC (ts_run_script), FSVR_SA_CS, ALL_AUTHORITY}, + {"copyfolder", TS_COPY_FOLDER, 0, DEF_TASK_FUNC (ts_copy_folder), FSVR_SA_CS, AU_DBC | AU_DBO}, + {"deletefolder", TS_DELETE_FOLDER, 0, DEF_TASK_FUNC (ts_delete_folder), FSVR_SA_CS, AU_DBC | AU_DBO}, + { + "getfolderswithkeyword", TS_GET_FOLDERS_WITH_KEYWORD, 0,DEF_TASK_FUNC (ts_get_folders_with_keyword), + FSVR_SA_CS, ALL_AUTHORITY + }, + {"getenvvarbyname", TS_GET_ENVVAR_BY_NAME, 0, DEF_TASK_FUNC (ts_get_envvar_by_name), FSVR_SA_CS, ALL_AUTHORITY}, + {"errortrace", TS_ERROR_TRACE, 0, DEF_TASK_FUNC (ts_error_trace), FSVR_SA_CS, ALL_AUTHORITY}, + {"login", TS_LOGIN, 0, DEF_TASK_FUNC (ts_login), FSVR_SA_CS, ALL_AUTHORITY}, + {"logout", TS_LOGOUT, 0, DEF_TASK_FUNC (ts_logout), FSVR_SA_CS, ALL_AUTHORITY}, + {"getamsenv", TS_GET_AMS_ENV, 0, DEF_TASK_FUNC (ts_get_ams_env), FSVR_SA_CS, ALL_AUTHORITY}, + {"keepalive", TS_KEEPALIVE, 0, DEF_TASK_FUNC (ts_keepalive), FSVR_CS, ALL_AUTHORITY}, + {"removefiles", TS_REMOVE_FILES, 0, DEF_TASK_FUNC (ts_remove_files), FSVR_NONE, AU_DBC | AU_DBO}, + {"#jobtest", TS_JOB_TEST, 0, DEF_TASK_FUNC (ts_job_test), FSVR_NONE, ALL_AUTHORITY}, + {"dbspace", TS_DB_SPACE_INFO, 0, DEF_TASK_FUNC (ts_dbs_spaceInfo), FSVR_NONE, ALL_AUTHORITY}, + {"shard_start", TS_SHARD_START, 0, DEF_TASK_FUNC (ts_shard_start), FSVR_NONE, AU_DBC | AU_DBO | AU_BRK}, + {"shard_stop", TS_SHARD_STOP, 0, DEF_TASK_FUNC (ts_shard_stop), FSVR_NONE, AU_DBC | AU_DBO | AU_BRK}, + {"getshardinfo", TS_GET_SHARD_INFO, 0, DEF_TASK_FUNC (ts_get_shard_info), FSVR_NONE, ALL_AUTHORITY}, + {"getshardstatus", TS_GET_SHARD_STATUS, 0, DEF_TASK_FUNC (ts_get_shard_status), FSVR_NONE, ALL_AUTHORITY}, + {"broker_changer", TS_BROKER_CHANGER, 0, DEF_TASK_FUNC (ts_broker_changer), FSVR_NONE, AU_DBC | AU_DBO | AU_BRK}, + {"ha_start", TS_HA_START, 0, DEF_TASK_FUNC (ts_ha_start), FSVR_NONE, AU_DBC | AU_DBO}, + {"ha_stop", TS_HA_STOP, 0, DEF_TASK_FUNC (ts_ha_stop), FSVR_NONE, AU_DBC | AU_DBO}, + {"ha_status", TS_HA_STATUS, 0, DEF_TASK_FUNC (ts_ha_status), FSVR_NONE, ALL_AUTHORITY}, + {"ha_copylogdb", TS_HA_COPYLOGDB, 0, DEF_TASK_FUNC (ts_ha_copylogdb), FSVR_NONE, AU_DBC | AU_DBO}, + {"ha_applylogdb", TS_HA_APPLYLOGDB, 0, DEF_TASK_FUNC (ts_ha_applylogdb), FSVR_NONE, AU_DBC | AU_DBO}, + {"ha_reload", TS_HA_RELOAD, 0, DEF_TASK_FUNC (ts_ha_reload), FSVR_NONE, AU_DBC | AU_DBO}, + {"list_dir", TS_LIST_DIR, 0, DEF_TASK_FUNC (ts_list_dir), FSVR_NONE, ALL_AUTHORITY}, + {"autoupdate", TS_AUTO_UPDATE, 0, DEF_TASK_FUNC (ts_auto_update), FSVR_NONE, AU_ADMIN}, + {"isupdatesuccess", TS_IS_UPDATE_SUCCESS, 0, DEF_TASK_FUNC (ts_is_update_success), FSVR_NONE, AU_ADMIN}, + {"monitorprocess", TS_MONITOR_PROCESS, 0, DEF_TASK_FUNC (ts_monitor_process), FSVR_NONE, ALL_AUTHORITY}, + {"generatecert", TS_GENERATE_CERT, 0, DEF_TASK_FUNC (ts_generate_cert), FSVR_NONE, ALL_AUTHORITY}, + {"start_statdump", TS_START_STATDUMP, 0, DEF_TASK_FUNC (ts_start_statdump), FSVR_CS, ALL_AUTHORITY}, + {"stop_statdump", TS_STOP_STATDUMP, 0, DEF_TASK_FUNC (ts_stop_statdump), FSVR_CS, ALL_AUTHORITY}, + {NULL, TS_UNDEFINED, 0, NULL, FSVR_NONE, 0} +}; + +#if defined(WINDOWS) + +typedef BOOL (WINAPI *GET_SYSTEM_TIMES) (LPFILETIME, LPFILETIME, LPFILETIME); +typedef NTSTATUS (WINAPI *NT_QUERY_SYSTEM_INFORMATION) (SYSTEM_INFORMATION_CLASS, PVOID, ULONG, PULONG); + +/* + * 0 - init_state. + * 1 - load GetSystemTime. + * 2 - load NtQuerySystemInformation. + * 3 - error state. + */ +static volatile int s_symbol_loaded = 0; +static volatile GET_SYSTEM_TIMES s_pfnGetSystemTimes = NULL; +static volatile NT_QUERY_SYSTEM_INFORMATION s_pfnNtQuerySystemInformation = NULL; +#endif + +static int _maybe_ip_addr (char *hostname); +static int _ip_equal_hostent (struct hostent *hp, char *token); +static int get_short_filename (char *ret_name, int ret_name_len, + char *short_filename); +static bool is_process_running (const char *process_name, unsigned int sleep_time); + +/** +* is_process_running is to check process running or not by checking pid +* process_name: the name of process that must be in $ARNIADB/bin +* sleep_time: millisecond +*/ +static bool +is_process_running (const char *process_name, unsigned int sleep_time) +{ + FILE *input = NULL; + char buf[16], cmd[PATH_MAX]; + + SLEEP_MILISEC (0, sleep_time); + +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (cmd, "%s/%s/%s getpid", sco.szArniadb, ARNIADB_DIR_BIN, + process_name); +#else + sprintf (cmd, "%s/%s getpid", ARNIADB_BINDIR, process_name); +#endif + input = popen (cmd, "r"); + if (input == NULL) + { + return false; + } + + memset (buf, '\0', sizeof (buf)); + if ((fgets (buf, 16, input) == NULL) || atoi (buf) <= 0) + { + pclose (input); + return false; + } + + pclose (input); + + return true; +} + +#if !defined(WINDOWS) +int +run_child_linux (const char *pname, const char *const argv[], int wait_flag, + const char *stdin_file, char *stdout_file, char *stderr_file, + int *exit_status) +{ + int pid = 0; + + if (exit_status != NULL) + { + *exit_status = 0; + } + + if (wait_flag) + { + signal (SIGCHLD, SIG_DFL); + } + else + { + signal (SIGCHLD, SIG_IGN); + } + + pid = fork (); + if (pid == 0) + { + FILE *fp = NULL; + + close_all_fds (3); + + if (stdin_file != NULL) + { + fp = fopen (stdin_file, "r"); + if (fp != NULL) + { + dup2 (fileno (fp), 0); + fclose (fp); + } + } + + if (stdout_file != NULL) + { + unlink (stdout_file); + fp = fopen (stdout_file, "w"); + if (fp != NULL) + { + dup2 (fileno (fp), 1); + fclose (fp); + } + } + + + if (stderr_file != NULL) + { + unlink (stderr_file); + fp = fopen (stderr_file, "w"); + if (fp != NULL) + { + dup2 (fileno (fp), 2); + fclose (fp); + } + } + + execv (pname, (char *const *) argv); + exit (0); + } + + if (pid < 0) + { + return -1; + } + + if (wait_flag) + { + int status = 0; + waitpid (pid, &status, 0); + if (exit_status != NULL) + { + *exit_status = status; + } + return 0; + } + else + { + return pid; + } +} +#endif + +int +_op_check_is_localhost (char *token, char *hname) +{ + struct hostent *hp; + + if ((hp = gethostbyname (hname)) == NULL) + { + return -1; + } + + /* if token is an ip address. */ + if (_maybe_ip_addr (token) > 0) + { + /* if token equal 127.0.0.1 or the ip is in the list of hname. */ + if ((strcmp (token, "127.0.0.1") == 0) + || _ip_equal_hostent (hp, token) == 0) + { + return 0; + } + } + else + { + /* + * if token is not an ip address, + * then compare it with the hostname ignore case. + */ + if ((strcasecmp (token, hname) == 0) + || (strcasecmp (token, "localhost") == 0)) + { + return 0; + } + } + return -1; +} + +static int +_maybe_ip_addr (char *hostname) +{ + if (hostname == NULL) + { + return 0; + } + return (isdigit (hostname[0]) ? 1 : 0); +} + +static int +_ip_equal_hostent (struct hostent *hp, char *token) +{ + int i; + int retval = -1; + const char *tmpstr = NULL; + struct in_addr inaddr; + + if (hp == NULL) + { + return retval; + } + + for (i = 0; hp->h_addr_list[i] != NULL; i++) + { + /* change ip address of hname to string. */ + inaddr.s_addr = * (unsigned long *) hp->h_addr_list[i]; + tmpstr = inet_ntoa (inaddr); + + /* compare the ip string with token. */ + if (strcmp (token, tmpstr) == 0) + { + retval = 0; + break; + } + } + return retval; +} + +void +append_host_to_dbname (char *name_buf, const char *dbname, int buf_len) +{ + snprintf (name_buf, buf_len, "%s@127.0.0.1", dbname); +} + +void * +increase_capacity (void *ptr, int block_size, int old_count, int new_count) +{ + if (new_count <= old_count || new_count <= 0) + { + return NULL; + } + + if (ptr == NULL) + { + if ((ptr = MALLOC (block_size * new_count)) == NULL) + { + return NULL; + } + memset (ptr, 0, block_size * new_count); + } + else + { + if ((ptr = realloc (ptr, block_size * new_count)) == NULL) + { + return NULL; + } + memset ((char *) ptr + old_count * block_size, 0, + block_size * (new_count - old_count)); + } + + return ptr; +} + +char * +strcpy_limit (char *dest, const char *src, int buf_len) +{ + strncpy (dest, src, buf_len - 1); + dest[buf_len - 1] = '\0'; + return dest; +} + +int +ut_getdelim (char **lineptr, int *n, int delimiter, FILE *fp) +{ + int result = -1; + int cur_len = 0; + int c; + + if (lineptr == NULL || n == NULL || fp == NULL) + { + return -1; + } + + if (*lineptr == NULL || *n == 0) + { + char *new_lineptr; + *n = MIN_CHUNK; + new_lineptr = (char *) realloc (*lineptr, *n); + + if (new_lineptr == NULL) + { + return -1; + } + *lineptr = new_lineptr; + } + + for (;;) + { + c = getc (fp); + if (c == EOF) + { + result = -1; + break; + } + + /* Make enough space for len+1 (for final NUL) bytes. */ + if (cur_len + 1 >= *n) + { + int line_len = 2 * *n + 1; + char *new_lineptr; + + if (line_len > MAX_LINE) + { + line_len = MAX_LINE; + } + if (cur_len + 1 >= line_len) + { + return -1; + } + + new_lineptr = (char *) realloc (*lineptr, line_len); + if (new_lineptr == NULL) + { + return -1; + } + + *lineptr = new_lineptr; + *n = line_len; + } + (*lineptr)[cur_len] = c; + cur_len++; + + if (c == delimiter) + { + break; + } + } + (*lineptr)[cur_len] = '\0'; + result = cur_len ? cur_len : result; + + return result; +} + +int +ut_getline (char **lineptr, int *n, FILE *fp) +{ + return ut_getdelim (lineptr, n, '\n', fp); +} + +void +uRemoveCRLF (char *str) +{ + size_t i; + if (str == NULL) + { + return; + } + for (i = strlen (str) - 1; (i >= 0) && (str[i] == 10 || str[i] == 13); i--) + { + str[i] = '\0'; + } +} + +char * +time_to_str (time_t t, const char *fmt, char *buf, int type) +{ + struct tm ltm; + struct tm *tm_p; + + tm_p = localtime (&t); + if (tm_p == NULL) + { + *buf = '\0'; + return buf; + } + ltm = *tm_p; + + if (type == TIME_STR_FMT_DATE) + { + sprintf (buf, fmt, ltm.tm_year + 1900, ltm.tm_mon + 1, ltm.tm_mday); + } + else if (type == TIME_STR_FMT_TIME) + { + sprintf (buf, fmt, ltm.tm_hour, ltm.tm_min, ltm.tm_sec); + } + else /* TIME_STR_FMT_DATE_TIME */ + sprintf (buf, fmt, ltm.tm_year + 1900, ltm.tm_mon + 1, ltm.tm_mday, + ltm.tm_hour, ltm.tm_min, ltm.tm_sec); + return buf; +} + +int +uStringEqual (const char *str1, const char *str2) +{ + if (str1 == NULL || str2 == NULL) + { + return 0; + } + if (strcmp (str1, str2) == 0) + { + return 1; + } + return 0; +} + +int +uStringEqualIgnoreCase (const char *str1, const char *str2) +{ + if (str1 == NULL || str2 == NULL) + { + return 0; + } + if (strcasecmp (str1, str2) == 0) + { + return 1; + } + return 0; +} + +void +write_manager_error_log (const char *protocol_str, const char *msg) +{ + char message[DBMT_ERROR_MSG_SIZE]; + + snprintf (message, DBMT_ERROR_MSG_SIZE, "%s %s", protocol_str, msg); + + LOG_ERROR (message); +} + +void +ut_error_log (nvplist *req, const char *errmsg) +{ + const char *id, *addr, *task; + char strbuf[512]; + + if ((task = nv_get_val (req, "task")) == NULL) + { + task = "-"; + } + if ((addr = nv_get_val (req, "_CLIENTIP")) == NULL) + { + addr = "-"; + } + if ((id = nv_get_val (req, "_ID")) == NULL) + { + id = "-"; + } + if (errmsg == NULL) + { + errmsg = "-"; + } + + snprintf (strbuf, sizeof (strbuf), "%s %s %s %s", ACCESS_ERR, id, addr, task); + + write_manager_error_log (strbuf, errmsg); +} + +void +write_manager_access_log (const char *protocol_str, const char *msg) +{ + char message[DBMT_ERROR_MSG_SIZE]; + + snprintf (message, DBMT_ERROR_MSG_SIZE, "%s %s", protocol_str, msg); + + LOG_INFO (message); +} + +void +ut_access_log (nvplist *req, const char *msg) +{ + const char *id, *cli_addr, *task; + char strbuf[512]; + + strbuf[0] = '\0'; + + if ((task = nv_get_val (req, "task")) == NULL) + { + task = "-"; + } + if ((cli_addr = nv_get_val (req, "_CLIENTIP")) == NULL) + { + cli_addr = "-"; + } + if ((id = nv_get_val (req, "_ID")) == NULL) + { + id = "-"; + } + if (msg == NULL) + { + msg = ""; + } + + snprintf (strbuf, sizeof (strbuf), "%s %s %s %s", ACCESS_LOG, id, cli_addr, task); + + write_manager_access_log (strbuf, msg); +} + +int +ut_get_task_info (const char *task, char *access_log_flag, + T_TASK_FUNC *task_func, T_USER_AUTH *auth) +{ + int i; + + for (i = 0; task_info[i].task_str != NULL; i++) + { + if (uStringEqual (task, task_info[i].task_str)) + { + if (access_log_flag) + { + *access_log_flag = task_info[i].access_log_flag; + } + if (task_func) + { + *task_func = task_info[i].task_func; + } + + if (auth) + { + *auth = task_info[i].user_auth; + } + return task_info[i].task_code; + } + } + + return TS_UNDEFINED; +} + +int +ut_send_response (SOCKET fd, nvplist *res) +{ + int i; + + if (res == NULL) + { + return -1; + } + + for (i = 0; i < res->nvplist_size; ++i) + { + if (res->nvpairs[i] == NULL) + { + continue; + } + write_to_socket (fd, dst_buffer (res->nvpairs[i]->name), + dst_length (res->nvpairs[i]->name)); + write_to_socket (fd, dst_buffer (res->delimiter), res->delimiter->dlen); + + if (strncmp (res->nvpairs[i]->name->dbuf, ENCRYPT_SIGN, + strlen (ENCRYPT_SIGN)) == 0) + { + int str_len; + char *encrypt_buf; + + str_len = dst_length (res->nvpairs[i]->value); + str_len = MAX (str_len, MIN_ENCRYPT_LEN); + + /* make the len to be multiple of 8. */ + str_len = MAKE_MUTIPLE_EIGHT (str_len); + + if ((encrypt_buf = (char *) MALLOC (str_len * 2 + 1)) == NULL) + { + return -1; + } + + uEncrypt (str_len, dst_buffer (res->nvpairs[i]->value), + encrypt_buf); + write_to_socket (fd, encrypt_buf, (int) strlen (encrypt_buf)); + + FREE_MEM (encrypt_buf); + } + else + { + write_to_socket (fd, dst_buffer (res->nvpairs[i]->value), + dst_length (res->nvpairs[i]->value)); + } + write_to_socket (fd, dst_buffer (res->endmarker), res->endmarker->dlen); + } + write_to_socket (fd, dst_buffer (res->listcloser), res->listcloser->dlen); + + return 0; +} + +/* + * read incoming data and construct name-value pair list of request + */ +int +ut_receive_request (SOCKET fd, nvplist *req) +{ + int rc; + char c; + dstring *linebuf = NULL; + char *p; + + linebuf = dst_create (); + + while ((rc = read_from_socket (fd, &c, 1)) == 1) + { + char *dstbuf; + + if (c == '\n') + { + /* if null string, stop parsing */ + if (dst_length (linebuf) == 0) + { + dst_destroy (linebuf); + return 0; + } + + dstbuf = dst_buffer (linebuf); + if (dstbuf != NULL) + { + p = strchr (dstbuf, ':'); + if (p) + { + *p = '\0'; + p++; + if (strncmp (dstbuf, ENCRYPT_SIGN, strlen (ENCRYPT_SIGN)) == 0) + { + int len; + char *decrypt_buf; + + len = (int) strlen (p); + if (len % 2) + { + goto error_return; + } + + len /= 2; + if ((decrypt_buf = (char *) MALLOC (len + 1)) == NULL) + { + goto error_return; + } + + /* decrypt the value. */ + uDecrypt (len, p, decrypt_buf); + nv_add_nvp (req, dstbuf + strlen (ENCRYPT_SIGN), + decrypt_buf); + free (decrypt_buf); + } + else + { + nv_add_nvp (req, dst_buffer (linebuf), p); + } + } + } + dst_reset (linebuf); + } + else + { + if (c != '\r') + { + dst_append (linebuf, &c, 1); + } + } + } + +error_return: + dst_destroy (linebuf); + return -1; +} + +void +ut_daemon_start (void) +{ +#if defined(WINDOWS) + return; +#else + int childpid; + + /* Ignore the terminal stop signals */ + signal (SIGTTOU, SIG_IGN); + signal (SIGTTIN, SIG_IGN); + signal (SIGTSTP, SIG_IGN); + +#if 0 + /* to make it run in background */ + signal (SIGHUP, SIG_IGN); + childpid = PROC_FORK (); + if (childpid > 0) + { + exit (0); /* kill parent */ + } +#endif + + /* setpgrp(); */ + setsid (); /* become process group leader and */ + /* disconnect from control terminal */ + + signal (SIGHUP, SIG_IGN); + childpid = PROC_FORK (); /* to prevent from reaquiring control terminal */ + if (childpid > 0) + { + exit (0); /* kill parent */ + } + +#if 0 + /* change current working directory */ + chdir ("/"); + /* clear umask */ + umask (0); +#endif +#endif /* ifndef WINDOWS */ +} + +int +ut_write_pid (char *pid_file) +{ + FILE *pidfp; + + pidfp = fopen (pid_file, "w"); + if (pidfp == NULL) + { + perror ("fopen"); + return -1; + } + fprintf (pidfp, "%d\n", (int) getpid ()); + fclose (pidfp); + return 0; +} + +void +server_fd_clear (fd_set srv_fds) +{ +#if !defined(WINDOWS) + SOCKET i; + int fd; + + for (i = 3; i < 1024; i++) + { + if (!FD_ISSET (i, &srv_fds)) + { + close (i); + } + } + + fd = open ("/dev/null", O_RDWR); +#ifndef DIAG_DEBUG + dup2 (fd, 1); +#endif + dup2 (fd, 2); +#endif /* !WINDOWS */ +} + +int +uRetrieveDBDirectory (const char *dbname, char *target) +{ + int ret_val = ERR_NO_ERROR; +#ifdef WINDOWS + char temp_name[512]; +#endif + + ret_val = uReadDBtxtFile (dbname, 1, target); +#ifdef WINDOWS + if (ret_val == ERR_NO_ERROR) + { + strcpy (temp_name, target); + memset (target, '\0', strlen (target)); + if (GetLongPathName (temp_name, target, PATH_MAX) == 0) + { + strcpy (target, temp_name); + } + } +#endif + + return ret_val; +} + +int +_isRegisteredDB (char *dn) +{ + if (uReadDBtxtFile (dn, 0, NULL) == ERR_NO_ERROR) + { + return 1; + } + + return 0; +} + +#if 0 +/* dblist should have enough space */ +/* db names are delimited by '\0' for ease of using it */ +int +uReadDBnfo (char *dblist) +{ + int retval = 0; + char strbuf[512]; + char *p; + FILE *infp; + int lock_fd; + + lock_fd = + uCreateLockFile (conf_get_dbmt_file (FID_LOCK_PSVR_DBINFO, strbuf)); + if (lock_fd < 0) + { + return -1; + } + + infp = fopen (conf_get_dbmt_file (FID_PSVR_DBINFO_TEMP, strbuf), "r"); + if (infp == NULL) + { + retval = -1; + } + else + { + fgets (strbuf, sizeof (strbuf), infp); + retval = atoi (strbuf); + + p = dblist; + while (fgets (strbuf, sizeof (strbuf), infp)) + { + ut_trim (strbuf); + strcpy (p, strbuf); + p += (strlen (p) + 1); + } + fclose (infp); + } + + uRemoveLockFile (lock_fd); + + return retval; +} +#endif +void +uWriteDBnfo (void) +{ + T_SERVER_STATUS_RESULT *cmd_res; + + cmd_res = cmd_server_status (); + uWriteDBnfo2 (cmd_res); + cmd_servstat_result_free (cmd_res); +} + +void +uWriteDBnfo2 (T_SERVER_STATUS_RESULT *cmd_res) +{ + int i; + int dbcnt; + char strbuf[1024]; + int dbvect[MAX_INSTALLED_DB]; + int lock_fd; + FILE *outfp; + T_SERVER_STATUS_INFO *info; + + lock_fd = + uCreateLockFile (conf_get_dbmt_file (FID_LOCK_PSVR_DBINFO, strbuf)); + if (lock_fd < 0) + { + return; + } + + outfp = fopen (conf_get_dbmt_file (FID_PSVR_DBINFO_TEMP, strbuf), "w"); + if (outfp != NULL) + { + dbcnt = 0; + if (cmd_res == NULL) + { + fprintf (outfp, "%d\n", dbcnt); + } + else + { + info = (T_SERVER_STATUS_INFO *) cmd_res->result; + for (i = 0; i < cmd_res->num_result; i++) + { + if (_isRegisteredDB (info[i].db_name)) + { + dbvect[dbcnt] = i; + ++dbcnt; + } + } + fprintf (outfp, "%d\n", dbcnt); + info = (T_SERVER_STATUS_INFO *) cmd_res->result; + for (i = 0; i < dbcnt; i++) + { + fprintf (outfp, "%s\n", info[dbvect[i]].db_name); + } + } + fclose (outfp); + } + + uRemoveLockFile (lock_fd); +} + +int +ut_get_dblist (nvplist *res, char dbdir_flag) +{ + FILE *infile; + char *dbinfo[4]; + char strbuf[1024], file[PATH_MAX]; + char hname[128]; + struct hostent *hp; + unsigned char ip_addr[4]; + char *token = NULL; + + snprintf (file, PATH_MAX - 1, "%s/%s", sco.szArniadb_databases, + ARNIADB_DATABASE_TXT); + if ((infile = fopen (file, "rt")) == NULL) + { + return ERR_DATABASETXT_OPEN; + } + + memset (hname, 0, sizeof (hname)); + gethostname (hname, sizeof (hname)); + if ((hp = gethostbyname (hname)) == NULL) + { + fclose (infile); + return ERR_NO_ERROR; + } + memcpy (ip_addr, hp->h_addr_list[0], 4); + + nv_add_nvp (res, "open", "dblist"); + while (fgets (strbuf, sizeof (strbuf), infile)) + { + ut_trim (strbuf); + + if ((strbuf[0] == '#') || (string_tokenize (strbuf, dbinfo, 4) < 0)) + { + continue; + } + + for (token = strtok (dbinfo[2], ":"); token != NULL; + token = strtok (NULL, ":")) + { + if ((hp = gethostbyname (token)) == NULL) + { + continue; + } + + if (_op_check_is_localhost (token, hname) >= 0) + { +#ifdef JSON_SUPPORT + nv_add_nvp (res, "open", "dbs"); +#endif + nv_add_nvp (res, "dbname", dbinfo[0]); + + if (dbdir_flag) + { + nv_add_nvp (res, "dbdir", dbinfo[1]); + } +#ifdef JSON_SUPPORT + nv_add_nvp (res, "close", "dbs"); +#endif + break; + } + } + } + nv_add_nvp (res, "close", "dblist"); + fclose (infile); + return ERR_NO_ERROR; +} + +int +uCreateLockFile (char *lockfile) +{ + int outfd; +#if !defined(WINDOWS) + struct flock lock; +#endif + + outfd = open (lockfile, O_WRONLY | O_CREAT | O_TRUNC, 0666); + + if (outfd < 0) + { + return outfd; + } + +#if defined(WINDOWS) + while (_locking (outfd, _LK_NBLCK, 1) < 0) + { + Sleep (100); + } +#else + lock.l_type = F_WRLCK; + lock.l_start = 0; + lock.l_whence = SEEK_SET; + lock.l_len = 0; + + while (fcntl (outfd, F_SETLK, &lock) < 0) + { + SLEEP_MILISEC (0, 10); + } +#endif + + return outfd; +} + +void +uRemoveLockFile (int outfd) +{ +#if !defined(WINDOWS) + struct flock lock; + + lock.l_type = F_UNLCK; + lock.l_start = 0; + lock.l_whence = SEEK_SET; + lock.l_len = 0; +#endif + +#if defined(WINDOWS) + _locking (outfd, _LK_UNLCK, 1); +#else + fcntl (outfd, F_SETLK, &lock); +#endif + close (outfd); +} + +int +uRemoveDir (char *dir, int remove_file_in_dir) +{ + char path[1024]; + char command[2048]; + + if (dir == NULL) + { + return ERR_DIR_REMOVE_FAIL; + } + + strcpy (path, dir); + memset (command, '\0', sizeof (command)); + ut_trim (path); + +#if defined(WINDOWS) + unix_style_path (path); +#endif + + if (access (path, F_OK) == 0) + { + if (remove_file_in_dir == REMOVE_DIR_FORCED) + { + sprintf (command, "%s %s \"%s\"", DEL_DIR, DEL_DIR_OPT, path); + if (system (command) == -1) + { + return ERR_DIR_REMOVE_FAIL; + } + } + else + { + if (rmdir (path) == -1) + { + return ERR_DIR_REMOVE_FAIL; + } + } + } + + return ERR_NO_ERROR; +} + +#if defined(WINDOWS) +int +folder_copy (const char *src_folder, const char *dest_folder) +{ + WIN32_FIND_DATA FileData; + HANDLE hSearch; + DWORD dwAttrs; + char src_dir[PATH_MAX]; + char dest_dir[PATH_MAX]; + char search_file[PATH_MAX]; + int retval = 0; + + if (src_dir == NULL || dest_dir == NULL) + { + goto err_return; + } + + strcpy_limit (src_dir, src_folder, sizeof (src_dir)); + strcpy_limit (dest_dir, dest_folder, sizeof (dest_dir)); + ut_trim (src_dir); + ut_trim (dest_dir); + + /* create a new directory. */ + if (access (dest_dir, F_OK) != 0) + { + if (uCreateDir (dest_dir) != ERR_NO_ERROR) + { + goto err_return; + } + } + + if (access (src_dir, F_OK) != 0 || access (dest_dir, F_OK) != 0) + { + goto err_clean_return; + } + + unix_style_path (src_dir); + unix_style_path (dest_dir); + + /* Start searching for text files in the current directory. */ + snprintf (search_file, sizeof (search_file), "%s/*", src_dir); + hSearch = FindFirstFile (search_file, &FileData); + + if (hSearch == INVALID_HANDLE_VALUE) + { + goto err_clean_return; + } + + while (FindNextFile (hSearch, &FileData)) + { + char src_path[PATH_MAX]; + char dest_path[PATH_MAX]; + + snprintf (src_path, PATH_MAX - 1, "%s/%s", src_dir, FileData.cFileName); + snprintf (dest_path, PATH_MAX - 1, "%s/%s", dest_dir, + FileData.cFileName); + + if (FileData.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY) + { + /* ignore folder "." and "..". */ + if (strcmp (FileData.cFileName, ".") == 0 + || strcmp (FileData.cFileName, "..") == 0) + { + continue; + } + + folder_copy (src_path, dest_path); + continue; + } + + if (file_copy (src_path, dest_path) == 0) + { + dwAttrs = GetFileAttributes (dest_path); + if (dwAttrs == INVALID_FILE_ATTRIBUTES) + { + goto err_clean_return; + } + } + else + { + goto err_clean_return; + } + } + + /* Close the search handle. */ + FindClose (hSearch); + + return 0; + +err_clean_return: + uRemoveDir (dest_dir, REMOVE_DIR_FORCED); +err_return: + FindClose (hSearch); + return -1; +} +#else +int +folder_copy (const char *src_folder, const char *dest_folder) +{ + char src_dir[PATH_MAX]; + char dest_dir[PATH_MAX]; + struct dirent *dirp; + struct stat statbuf; + DIR *dp = NULL; + + if (src_dir == NULL || dest_dir == NULL) + { + goto err_return; + } + + strcpy_limit (src_dir, src_folder, sizeof (src_dir)); + strcpy_limit (dest_dir, dest_folder, sizeof (dest_dir)); + ut_trim (src_dir); + ut_trim (dest_dir); + + if (access (dest_dir, F_OK) != 0) + { + if (uCreateDir (dest_dir) != ERR_NO_ERROR) + { + goto err_return; + } + } + + if (access (src_dir, F_OK) != 0 || access (dest_dir, F_OK) != 0) + { + goto err_clean_return; + } + + stat (src_dir, &statbuf); + chmod (dest_dir, statbuf.st_mode); + + /* copy all the files that in src_path to dest_path. */ + dp = opendir (src_dir); + if (dp == NULL) + { + goto err_clean_return; + } + + while ((dirp = readdir (dp)) != NULL) + { + char src_path[PATH_MAX]; + char dest_path[PATH_MAX]; + + snprintf (src_path, sizeof (src_path) - 1, "%s/%s", src_dir, + dirp->d_name); + snprintf (dest_path, sizeof (dest_path) - 1, "%s/%s", dest_dir, + dirp->d_name); + + stat (src_path, &statbuf); + + if (S_ISDIR (statbuf.st_mode)) + { + if (uStringEqual (dirp->d_name, ".") + || uStringEqual (dirp->d_name, "..")) + { + continue; + } + + if (folder_copy (src_path, dest_path) < 0) + { + goto err_clean_return; + } + } + else + { + if (file_copy (src_path, dest_path) < 0) + { + goto err_clean_return; + } + } + } + + closedir (dp); + + return 0; + +err_clean_return: + uRemoveDir (dest_dir, REMOVE_DIR_FORCED); +err_return: + if (dp != NULL) + { + closedir (dp); + } + return -1; +} +#endif + +int +uCreateDir (char *new_dir) +{ + char *p, path[1024]; + + if (new_dir == NULL) + { + return ERR_DIR_CREATE_FAIL; + } + memset (path, 0, 1024); + strncpy (path, new_dir, 1023); + ut_trim (path); + +#if defined(WINDOWS) + unix_style_path (path); +#endif + +#if defined(WINDOWS) + if (path[0] == '/') + { + p = path + 1; + } + else if (strlen (path) > 3 && path[2] == '/') + { + p = path + 3; + } + else + { + return ERR_DIR_CREATE_FAIL; + } +#else + if (path[0] != '/') + { + return ERR_DIR_CREATE_FAIL; + } + p = path + 1; +#endif + + while (p != NULL) + { + p = strchr (p, '/'); + if (p != NULL) + { + *p = '\0'; + } + if (access (path, F_OK) < 0) + { + if (mkdir (path, 0700) < 0) + { + return ERR_DIR_CREATE_FAIL; + } + } + if (p != NULL) + { + *p = '/'; + p++; + } + } + return ERR_NO_ERROR; +} + +void +close_all_fds (int init_fd) +{ + int i; + + for (i = init_fd; i < 1024; i++) + { + close (i); + } +} + +char * +ut_trim (char *str) +{ + char *p; + char *s; + + if (str == NULL) + { + return (str); + } + + for (s = str; + *s != '\0' && (*s == ' ' || *s == '\t' || *s == '\n' || *s == '\r'); + s++) + ; + if (*s == '\0') + { + *str = '\0'; + return (str); + } + + /* *s must be a non-white char */ + for (p = s; *p != '\0'; p++) + ; + for (p--; *p == ' ' || *p == '\t' || *p == '\n' || *p == '\r'; p--) + ; + *++p = '\0'; + + if (s != str) + { + memmove (str, s, strlen (s) + 1); + } + + return (str); +} + +#if defined(WINDOWS) +int +ut_disk_free_space (char *path) +{ + char buf[1024]; + DWORD a, b, c, d; + + strcpy (buf, path); + ut_trim (buf); + if (buf[1] == ':') + { + strcpy (buf + 2, "/"); + } + else + { + strcpy (buf, "c:/"); + } + + if (GetDiskFreeSpace (buf, &a, &b, &c, &d) == 0) + { + return 0; + } + + return ((c >> 10) * ((b * a) >> 10)); +} +#else +int +ut_disk_free_space (char *path) +{ + struct statvfs sv; + + if (statvfs (path, &sv) < 0) + { + return 0; + } + + return ((((sv.f_bavail) >> 10) * sv.f_frsize) >> 10); +} +#endif + +char * +ip2str (unsigned char *ip, char *ip_str) +{ + sprintf (ip_str, "%d.%d.%d.%d", (unsigned char) ip[0], + (unsigned char) ip[1], + (unsigned char) ip[2], (unsigned char) ip[3]); + return ip_str; +} + +int +string_tokenize_accept_laststring_space (char *str, char *tok[], int num_tok) +{ + int i; + char *p; + + tok[0] = str; + for (i = 1; i < num_tok; i++) + { + tok[i] = strpbrk (tok[i - 1], " \t"); + if (tok[i] == NULL) + { + return -1; + } + * (tok[i]) = '\0'; + p = (tok[i]) + 1; + for (; *p && (*p == ' ' || *p == '\t'); p++) + ; + if (*p == '\0') + { + return -1; + } + tok[i] = p; + } + + return 0; +} + +int +string_tokenize (char *str, char *tok[], int num_tok) +{ + int i; + char *p; + + tok[0] = str; + for (i = 1; i < num_tok; i++) + { + tok[i] = strpbrk (tok[i - 1], " \t"); + if (tok[i] == NULL) + { + return -1; + } + * (tok[i]) = '\0'; + p = (tok[i]) + 1; + for (; *p && (*p == ' ' || *p == '\t'); p++) + ; + if (*p == '\0') + { + return -1; + } + tok[i] = p; + } + p = strpbrk (tok[num_tok - 1], " \t"); + if (p) + { + *p = '\0'; + } + + return 0; +} + +int +string_tokenize2 (char *str, char *tok[], int num_tok, int c) +{ + int i; + char *p; + + for (i = 0; i < num_tok; i++) + { + tok[i] = NULL; + } + + if (str == NULL) + { + return -1; + } + + tok[0] = str; + for (i = 1; i < num_tok; i++) + { + tok[i] = strchr (tok[i - 1], c); + if (tok[i] == NULL) + { + return -1; + } + * (tok[i]) = '\0'; + (tok[i])++; + } + p = strchr (tok[num_tok - 1], c); + if (p) + { + *p = '\0'; + } + + return 0; +} + +int +read_from_socket (SOCKET sock_fd, char *buf, int size) +{ + int read_len; + fd_set read_mask; + int nfound; + int maxfd; + + FD_ZERO (&read_mask); + FD_SET (sock_fd, (fd_set *) & read_mask); + maxfd = (int) sock_fd + 1; +again: + nfound = select (maxfd, &read_mask, (fd_set *) 0, (fd_set *) 0, NULL); + if (nfound < 0) + { + goto again; /* interrupted by a signal */ + } + + if (FD_ISSET (sock_fd, (fd_set *) & read_mask)) + { + read_len = recv (sock_fd, buf, size, 0); + } + else + { + return -1; + } + + return read_len; +} + +int +write_to_socket (SOCKET sock_fd, const char *buf, int size) +{ + int write_len; + fd_set write_mask; + int nfound; + int maxfd; + + if (IS_INVALID_SOCKET (sock_fd)) + { + return -1; + } + + FD_ZERO (&write_mask); + FD_SET (sock_fd, (fd_set *) & write_mask); + maxfd = (int) sock_fd + 1; +again: + nfound = select (maxfd, (fd_set *) 0, &write_mask, (fd_set *) 0, NULL); + if (nfound < 0) + { + goto again; /* interrupted by a signal */ + } + + if (FD_ISSET (sock_fd, (fd_set *) & write_mask)) + { + write_len = send (sock_fd, buf, size, 0); + } + else + { + return -1; + } + + return write_len; +} + +#if defined(WINDOWS) +int +kill (int pid, int signo) +{ + HANDLE phandle; + + phandle = OpenProcess (PROCESS_TERMINATE, FALSE, pid); + if (phandle == NULL) + { + int error = GetLastError (); + if (error == ERROR_ACCESS_DENIED) + { + errno = EPERM; + } + else + { + errno = ESRCH; + } + return -1; + } + + if (signo == SIGTERM) + { + TerminateProcess (phandle, 0); + } + + CloseHandle (phandle); + return 0; +} +#endif + +#if defined(WINDOWS) +void +unix_style_path (char *path) +{ + char *p; + for (p = path; *p; p++) + { + if (*p == '\\') + { + *p = '/'; + } + } +} + +char * +nt_style_path (char *path, char *new_path_buf) +{ + char *p; + char *q; + char tmp_path_buf[1024]; + + if (path == new_path_buf) + { + strcpy (tmp_path_buf, path); + q = tmp_path_buf; + } + else + { + q = new_path_buf; + } + if (strlen (path) < 2 || path[1] != ':') + { + *q++ = _getdrive () + 'A' - 1; + *q++ = ':'; + *q++ = '\\'; + } + + for (p = path; *p; p++, q++) + { + if (*p == '/') + { + *q = '\\'; + } + else + { + *q = *p; + } + } + *q = '\0'; + for (q--; q != new_path_buf; q--) + { + if (*q == '\\') + { + *q = '\0'; + } + else + { + break; + } + } + if (*q == ':') + { + q++; + *q++ = '\\'; + *q++ = '\\'; + *q = '\0'; + } + if (path == new_path_buf) + { + strcpy (new_path_buf, tmp_path_buf); + } + return new_path_buf; +} +#endif + +int +make_version_info (const char *cli_ver, int *major_ver, int *minor_ver) +{ + const char *p; + if (cli_ver == NULL) + { + return 0; + } + + p = cli_ver; + *major_ver = atoi (p); + p = strchr (p, '.'); + if (p != NULL) + { + *minor_ver = atoi (p + 1); + } + else + { + *minor_ver = 0; + } + + return 1; +} + +int +file_copy (char *src_file, char *dest_file) +{ + char strbuf[1024]; + int src_fd, dest_fd; + size_t read_size, write_size; + int mode = 0644; + +#if !defined(WINDOWS) + struct stat statbuf; + + if (stat (src_file, &statbuf) == 0) + { + mode = statbuf.st_mode; + } +#endif + + if ((src_fd = open (src_file, O_RDONLY)) == -1) + { + return -1; + } + + if ((dest_fd = open (dest_file, O_WRONLY | O_CREAT | O_TRUNC, mode)) == -1) + { + close (src_fd); + return -1; + } + +#if defined(WINDOWS) + if (setmode (src_fd, O_BINARY) == -1 || setmode (dest_fd, O_BINARY) == -1) + { + close (src_fd); + close (dest_fd); + return -1; + } +#endif + + while ((read_size = read (src_fd, strbuf, sizeof (strbuf))) > 0) + { + if (read_size > sizeof (strbuf) + || (write_size = + write (dest_fd, strbuf, (unsigned int) read_size)) < read_size) + { + close (src_fd); + close (dest_fd); + unlink (dest_file); + return -1; + } + } + + close (src_fd); + close (dest_fd); + + return 0; +} + +int +move_file (char *src_file, char *dest_file) +{ + if (file_copy (src_file, dest_file) < 0) + { + return -1; + } + else + { + unlink (src_file); + } + + return 0; +} + +#if defined(WINDOWS) +void +remove_end_of_dir_ch (char *path) +{ + if (path && path[strlen (path) - 1] == '\\') + { + path[strlen (path) - 1] = '\0'; + } +} +#endif + +int +is_amserver_process (int pid, const char *module_name) +{ +#if defined(WINDOWS) + HANDLE hModuleSnap = NULL; + MODULEENTRY32 me32 = { 0 }; + + hModuleSnap = CreateToolhelp32Snapshot (TH32CS_SNAPMODULE, pid); + if (hModuleSnap == (HANDLE) - 1) + { + return -1; + } + + me32.dwSize = sizeof (MODULEENTRY32); + + if (Module32First (hModuleSnap, &me32)) + { + do + { + if (strcasecmp (me32.szModule, module_name) == 0) + { + CloseHandle (hModuleSnap); + return 1; + } + } + while (Module32Next (hModuleSnap, &me32)); + } + CloseHandle (hModuleSnap); + return 0; +#elif defined(LINUX) + FILE *fp = NULL; + char proc_path[PATH_MAX]; + char cmd_line[LINE_MAX]; + char *cmd_name = NULL; + + snprintf (proc_path, sizeof (proc_path), "/proc/%d/cmdline", pid); + + if (access (proc_path, F_OK) != 0) + { + return 0; + } + + if ((fp = fopen (proc_path, "r")) == NULL) + { + return 0; + } + + if (fread (cmd_line, sizeof (char), sizeof (cmd_line) - 1, fp) <= 0) + { + fclose (fp); + return 0; + } + + // Only the module_name should be compared + cmd_name = strrchr (cmd_line, '/'); + if (cmd_name == NULL) + { + cmd_name = cmd_line; + } + else + { + cmd_name += 1; + } + + if (!uStringEqual (cmd_name, module_name)) + { + fclose (fp); + return 0; + } + + fclose (fp); + return 1; +#elif defined(AIX) + const char *argv[10]; + int argc = 0; + int return_value = 0; + char cmjs_pid[10]; + char result_file[1024]; + char buf[1024], cur_pid[10], prog_name[32]; + FILE *fRes; + + /*Init var */ + cmjs_pid[0] = '\0'; + result_file[0] = '\0'; + buf[0] = '\0'; + cur_pid[0] = '\0'; + prog_name[0] = '\0'; + + snprintf (cmjs_pid, sizeof (cmjs_pid) - 1, "%d", pid); + snprintf (result_file, sizeof (result_file) - 1, "%s/DBMT_js.%d", + sco.dbmt_tmp_dir, (int) getpid ()); + argv[argc++] = "/usr/bin/ps"; + argv[argc++] = "-e"; + argv[argc] = NULL; + + if (run_child (argv, 1, NULL, result_file, NULL, NULL) < 0) + { + /* ps */ + return -1; + } + + fRes = fopen (result_file, "r"); + if (fRes) + { + while (fgets (buf, 1024, fRes)) + { + if (sscanf (buf, "%9s %*s %*s %31s", cur_pid, prog_name) != 2) + { + continue; + } + + if (strcmp (cur_pid, cmjs_pid) == 0 + && strcmp (prog_name, module_name) == 0) + { + return_value = 1; + break; + } + } + + fclose (fRes); + } + + unlink (result_file); + return return_value; +#endif +} + +int +make_default_env (void) +{ + int retval = ERR_NO_ERROR; + char strbuf[512]; + FILE *fd; + + /* create log/manager directory */ +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (strbuf, "%s/%s", sco.szArniadb, DBMT_LOG_DIR); +#else + sprintf (strbuf, "%s", DBMT_LOG_DIR); +#endif + if ((retval = uCreateDir (strbuf)) != ERR_NO_ERROR) + { + return retval; + } + + /* create var/manager direcory */ +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (strbuf, "%s/%s", sco.szArniadb, DBMT_PID_DIR); +#else + sprintf (strbuf, "%s", DBMT_PID_DIR); +#endif + if ((retval = uCreateDir (strbuf)) != ERR_NO_ERROR) + { + return retval; + } + + /* create databases directory */ + sprintf (strbuf, "%s", sco.szArniadb_databases); + if ((retval = uCreateDir (strbuf)) != ERR_NO_ERROR) + { + return retval; + } + + /* if databases.txt file doesn't exist, create 0 byte file. */ + sprintf (strbuf, "%s/%s", sco.szArniadb_databases, ARNIADB_DATABASE_TXT); + if (access (strbuf, F_OK) < 0) + { + if ((fd = fopen (strbuf, "a")) == NULL) + { + return ERR_FILE_CREATE_FAIL; + } + fclose (fd); + } + return retval; +} + + +/* + * dbid, dbpasswd is filled by this function + * caller must provide space for dbid, dbpasswd + */ +int +_ut_get_dbaccess (nvplist *req, char *dbid, char *dbpasswd) +{ + int retval; + char *ip, *port, *dbname; + char _dbmt_error[1024]; + T_DBMT_CON_DBINFO con_dbinfo; + + dbid[0] = dbpasswd[0] = '\0'; + + ip = nv_get_val (req, "_IP"); + port = nv_get_val (req, "_PORT"); + dbname = nv_get_val (req, "dbname"); + + /* read conlist */ + memset (&con_dbinfo, 0, sizeof (T_DBMT_CON_DBINFO)); + if ((retval = + dbmt_con_read_dbinfo (&con_dbinfo, ip, port, dbname, + _dbmt_error)) <= 0) + { + return 0; + } + + /* extract db user info */ + strcpy (dbid, con_dbinfo.uid); + uDecrypt (PASSWD_LENGTH, con_dbinfo.passwd, dbpasswd); + + return 1; +} + + +/* Generate status, note and write to log */ +void +uGenerateStatus (nvplist *req, nvplist *res, int retval, + const char *_dbmt_error) +{ + char strbuf[1024]; + + if ((retval == -1) || (retval == 0)) + { + return; + } + + if ((retval == 1) || (retval == ERR_NO_ERROR)) + { + nv_update_val (res, "status", "success"); + return; + } + + if (retval == ERR_FILE_COMPRESS) + { + nv_update_val (res, "status", "success"); + nv_update_val (res, "note", + "Can't compress the file. Download original file"); + return; + } + + nv_update_val (res, "status", "failure"); + switch (retval) + { + case ERR_GENERAL_ERROR: + sprintf (strbuf, "Unknown general error"); + break; + case ERR_UNDEFINED_TASK: + sprintf (strbuf, "Undefined request - %s", _dbmt_error); + break; + case ERR_DBDIRNAME_NULL: + sprintf (strbuf, "Can not find the directory database(%s) is located", + _dbmt_error); + break; + case ERR_GET_FILE: + sprintf (strbuf, "Can't get requested files"); + break; + case ERR_REQUEST_FORMAT: + sprintf (strbuf, "Invalid request format"); + break; + case ERR_DATABASETXT_OPEN: + sprintf (strbuf, "'%s' open error", ARNIADB_DATABASE_TXT); + break; + case ERR_USER_CAPABILITY: + sprintf (strbuf, "Failed to get user profile for '%s'", _dbmt_error); + break; + case ERR_FILE_INTEGRITY: + sprintf (strbuf, "Password file(%s) integrity failure", _dbmt_error); + break; + case ERR_SYSTEM_CALL: + sprintf (strbuf, "Command returned error : %s", _dbmt_error); + break; + case ERR_PASSWORD_FILE: + sprintf (strbuf, "Password file(%s) open error", _dbmt_error); + break; + case ERR_PARAM_MISSING: + sprintf (strbuf, "Parameter(%s) missing in the request", _dbmt_error); + break; + case ERR_DIR_CREATE_FAIL: + sprintf (strbuf, "Directory(%s) creation failed", _dbmt_error); + break; + case ERR_FILE_OPEN_FAIL: + sprintf (strbuf, "File(%s) open error", _dbmt_error); + break; + case ERR_STANDALONE_MODE: + sprintf (strbuf, "Database(%s) is running in standalone mode", + _dbmt_error); + break; + case ERR_DB_ACTIVE: + sprintf (strbuf, "Database(%s) is active state.", _dbmt_error); + break; + case ERR_DB_INACTIVE: + sprintf (strbuf, "Database(%s) is not active state", _dbmt_error); + break; + case ERR_DB_NONEXISTANT: + sprintf (strbuf, "Database(%s) does not exist", _dbmt_error); + break; + case ERR_DBMTUSER_EXIST: + sprintf (strbuf, "ARNIADB Manager user(%s) already exist", _dbmt_error); + break; + case ERR_DIROPENFAIL: + sprintf (strbuf, "Failed to read directory(%s)", _dbmt_error); + break; + case ERR_PERMISSION: + sprintf (strbuf, "No permission for %s", _dbmt_error); + break; + case ERR_INVALID_TOKEN: + sprintf (strbuf, + "Request is rejected due to invalid token. Please reconnect."); + break; + case ERR_SYSTEM_CALL_CON_DUMP: + sprintf (strbuf, "%s", _dbmt_error); + break; + case ERR_STAT: + sprintf (strbuf, "Failed to get the file information"); + break; + case ERR_OPENDIR: + sprintf (strbuf, "Failed to open the directory"); + break; + case ERR_UNICASCONF_OPEN: + sprintf (strbuf, "Failed to open unicas.conf"); + break; + case ERR_UNICASCONF_PARAM_MISSING: + sprintf (strbuf, "Specified parameter does not exist in unicas.conf"); + break; + case ERR_DBLOGIN_FAIL: + sprintf (strbuf, "Failed to log in to database using id:%s", + _dbmt_error); + break; + case ERR_DBRESTART_FAIL: + sprintf (strbuf, "Failed to restart database(%s)", _dbmt_error); + break; + case ERR_DBUSER_NOTFOUND: + sprintf (strbuf, "Database user (%s) not found", _dbmt_error); + break; + case ERR_DBPASSWD_CLEAR: + sprintf (strbuf, "Failed to clear existing password - %s", _dbmt_error); + break; + case ERR_DBPASSWD_SET: + sprintf (strbuf, "Failed to set new password - %s", _dbmt_error); + break; + case ERR_MEM_ALLOC: + sprintf (strbuf, "Memory allocation error."); + break; + case ERR_TMPFILE_OPEN_FAIL: + sprintf (strbuf, "Temporal file open error."); + break; + case ERR_WITH_MSG: + strcpy_limit (strbuf, _dbmt_error, sizeof (strbuf)); + break; + case ERR_UPA_SYSTEM: + sprintf (strbuf, "Authentication System Error."); + break; + case ERR_TEMPLATE_ALREADY_EXIST: + sprintf (strbuf, "Template (%s) already exist.", _dbmt_error); + break; + case ERR_WARNING: + strcpy_limit (strbuf, _dbmt_error, sizeof (strbuf)); + nv_update_val (res, "status", "warning"); + break; + default: + sprintf (strbuf, "error"); + break; + } + nv_update_val (res, "note", strbuf); + ut_error_log (req, strbuf); +} + + +/* validate token and insert id */ +int +ut_validate_token (nvplist *req) +{ + T_USER_TOKEN_INFO *token_info; + + time_t active_time = 0; + time_t now_time = time (NULL); + + //int retval; + + char *ip, *port, *id, *tok[3]; + char *token, token_content[TOKEN_LENGTH + 1]; + + if (!strcmp (nv_get_val (req, "task"), "login") || + !strcmp (nv_get_val (req, "task"), "getamsenv")) + { + ut_access_log (req, "task = login or getamsenv."); + return 1; + } + + if ((token = nv_get_val (req, "token")) == NULL) + { + return 0; + } + ut_access_log (req, "task != login or getamsenv."); + + uDecrypt (TOKEN_LENGTH, token, token_content); + + if (string_tokenize2 (token_content, tok, 3, ':') < 0) + { + return 0; + } + + ip = tok[0]; + port = tok[1]; + id = tok[2]; + + ut_access_log (req, id); + + token_info = dbmt_user_search_token_info (id); + if (token_info == NULL) + { + ut_access_log (req, "can't find registered token."); + return 0; + } + + if (strcmp (token_info->token, token)) + { + ut_access_log (req, "tokens aren't equal!"); + return 0; + } + + ut_get_token_active_time (&active_time); + + if (now_time - token_info->login_time > active_time) + { + return 0; + } + + token_info->login_time = now_time; + + nv_add_nvp (req, "_IP", ip); + nv_add_nvp (req, "_PORT", port); + nv_add_nvp (req, "_ID", id); + + + /* check if ip is an existing ip */ + //retval = dbmt_con_search (ip, port, cli_ver); + + return 1; +} + +/* + * client ip : client port : dbmt id : pserver pid + * 15 5 8 5 = 33 + 4 = 37 + * 40 - 37 = 8. + * Thus, 3 bytes for checksum + */ +char * +ut_token_generate (char *client_ip, char *client_port, char *dbmt_id, + int proc_id, time_t login_time) +{ + char sbuf[TOKEN_LENGTH + 1]; + char token_string[TOKEN_ENC_LENGTH]; + size_t i, len; + + if ((client_ip == NULL) || (client_port == NULL) || (dbmt_id == NULL)) + { + return NULL; + } + memset (sbuf, 0, TOKEN_LENGTH + 1); + snprintf (sbuf, TOKEN_LENGTH, "%s:%s:%s:%d:%lu", client_ip, client_port, + dbmt_id, proc_id, login_time); + len = strlen (sbuf); + /* insert padding to checksum part */ + for (i = len; i < TOKEN_LENGTH; ++i) + { + sbuf[i] = '*'; + } + sbuf[i] = '\0'; + + uEncrypt (TOKEN_LENGTH, sbuf, token_string); + + return strdup (token_string); +} + +void +_accept_connection (nvplist *cli_request, nvplist *cli_response) +{ + char *pstrbuf; + char *client_ip, *client_port, *client_id, *client_ver; +#ifdef WINDOWS + HANDLE proc_id = (HANDLE) getpid (); +#else + pid_t proc_id = (pid_t) getpid (); +#endif + + time_t login_time = time (NULL); + + client_ip = nv_get_val (cli_request, "_CLIENTIP"); + client_port = nv_get_val (cli_request, "_CLIENTPORT"); + client_id = nv_get_val (cli_request, "id"); + client_ver = nv_get_val (cli_request, "clientver"); + + /* generate token and record new connection to file */ + pstrbuf = + ut_token_generate (client_ip, client_port, client_id, getpid (), + login_time); + nv_add_nvp (cli_response, "token", pstrbuf); + + dbmt_con_add (client_ip, client_port, client_ver, client_id); + + ut_access_log (cli_request, "before add token into token list."); + dbmt_user_new_token_info (client_id, client_ip, client_port, pstrbuf, + proc_id, login_time); + + free (pstrbuf); + return; +} + + +#if defined (WINDOWS) +int +gettimeofday (struct timeval *tp, void *tzp) +{ + struct _timeb tm; + _ftime (&tm); + tp->tv_sec = (long) tm.time; + tp->tv_usec = tm.millitm * 1000; + return 0; +} +#endif + +void +_ut_timeval_diff (struct timeval *start, struct timeval *end, int *res_msec) +{ + int sec, msec; + + sec = end->tv_sec - start->tv_sec; + msec = (end->tv_usec / 1000) - (start->tv_usec / 1000); + *res_msec = sec * 1000 + msec; +} + + +#if defined(WINDOWS) +int +ut_run_child (const char *bin_path, const char *const argv[], int wait_flag, + const char *stdin_file, const char *stdout_file, + const char *stderr_file, int *exit_status) +{ + int new_pid; + STARTUPINFO start_info; + PROCESS_INFORMATION proc_info; + BOOL res; + int i, cmd_arg_len; + char cmd_arg[1024]; + BOOL inherit_flag = FALSE; + HANDLE hStdIn = INVALID_HANDLE_VALUE; + HANDLE hStdOut = INVALID_HANDLE_VALUE; + HANDLE hStdErr = INVALID_HANDLE_VALUE; + + if (exit_status != NULL) + { + *exit_status = 0; + } + + for (i = 0, cmd_arg_len = 0; argv[i]; i++) + { + cmd_arg_len += sprintf (cmd_arg + cmd_arg_len, "\"%s\" ", argv[i]); + } + + GetStartupInfo (&start_info); + start_info.wShowWindow = SW_HIDE; + + if (stdin_file) + { + hStdIn = + CreateFile (stdin_file, GENERIC_READ, FILE_SHARE_READ, NULL, + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + if (hStdIn != INVALID_HANDLE_VALUE) + { + SetHandleInformation (hStdIn, HANDLE_FLAG_INHERIT, + HANDLE_FLAG_INHERIT); + start_info.dwFlags = STARTF_USESTDHANDLES; + start_info.hStdInput = hStdIn; + inherit_flag = TRUE; + } + } + if (stdout_file) + { + hStdOut = + CreateFile (stdout_file, GENERIC_WRITE, FILE_SHARE_READ, NULL, + CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + if (hStdOut != INVALID_HANDLE_VALUE) + { + SetHandleInformation (hStdOut, HANDLE_FLAG_INHERIT, + HANDLE_FLAG_INHERIT); + start_info.dwFlags = STARTF_USESTDHANDLES; + start_info.hStdOutput = hStdOut; + inherit_flag = TRUE; + } + } + if (stderr_file) + { + hStdErr = + CreateFile (stderr_file, GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + if (hStdErr != INVALID_HANDLE_VALUE) + { + SetHandleInformation (hStdErr, HANDLE_FLAG_INHERIT, + HANDLE_FLAG_INHERIT); + start_info.dwFlags = STARTF_USESTDHANDLES; + start_info.hStdError = hStdErr; + inherit_flag = TRUE; + } + } + + res = CreateProcess (bin_path, cmd_arg, NULL, NULL, inherit_flag, + CREATE_NO_WINDOW, NULL, NULL, &start_info, &proc_info); + + if (hStdIn != INVALID_HANDLE_VALUE) + { + CloseHandle (hStdIn); + } + if (hStdOut != INVALID_HANDLE_VALUE) + { + CloseHandle (hStdOut); + } + if (hStdErr != INVALID_HANDLE_VALUE) + { + CloseHandle (hStdErr); + } + + if (res == FALSE) + { + return -1; + } + + new_pid = proc_info.dwProcessId; + + if (wait_flag) + { + DWORD status = 0; + //WaitForSingleObject (proc_info.hProcess, INFINITE); + //GetExitCodeProcess (proc_info.hProcess, &status); + if (exit_status != NULL) + { + *exit_status = status; + } + CloseHandle (proc_info.hProcess); + CloseHandle (proc_info.hThread); + return 0; + } + else + { + CloseHandle (proc_info.hProcess); + CloseHandle (proc_info.hThread); + return new_pid; + } +} +#else +int +ut_run_child (const char *bin_path, const char *const argv[], int wait_flag, + const char *stdin_file, const char *stdout_file, + const char *stderr_file, int *exit_status) +{ + int pid; + + if (exit_status != NULL) + { + *exit_status = 0; + } + + if (wait_flag) + { + signal (SIGCHLD, SIG_DFL); + } + else + { + signal (SIGCHLD, SIG_IGN); + } + pid = fork (); + if (pid == 0) + { + FILE *fp; + + close_all_fds (3); + + if (stdin_file != NULL) + { + fp = fopen (stdin_file, "r"); + if (fp != NULL) + { + dup2 (fileno (fp), 0); + fclose (fp); + } + } + if (stdout_file != NULL) + { + unlink (stdout_file); + fp = fopen (stdout_file, "w"); + if (fp != NULL) + { + dup2 (fileno (fp), 1); + fclose (fp); + } + } + if (stderr_file != NULL) + { + unlink (stderr_file); + fp = fopen (stderr_file, "w"); + if (fp != NULL) + { + dup2 (fileno (fp), 2); + fclose (fp); + } + } + + execv (bin_path, (char *const *) argv); + exit (0); + } + + if (pid < 0) + { + return -1; + } + + if (wait_flag) + { + int status = 0; + waitpid (pid, &status, 0); + if (exit_status != NULL) + { + *exit_status = status; + } + return 0; + } + else + { + return pid; + } +} +#endif + +typedef struct _dir_file_node +{ + char *file_name; + struct _dir_file_node *next; + struct _dir_file_node *prev; +} dir_file_node; + +typedef struct _dir_file_list_head +{ + unsigned int file_num; + dir_file_node *head; +} dir_file_list_head; + +static int +add_node_to_list (dir_file_list_head *file_head, const char *file_name) +{ + dir_file_node *file_node; + if (file_head == NULL || file_name == NULL) + { + return -1; + } + + file_node = (dir_file_node *) malloc (sizeof (dir_file_node)); + if (file_node == NULL) + { + return -1; + } + + file_node->file_name = strdup (file_name); + file_node->next = file_head->head; + if (file_head->head) + { + file_head->head->prev = file_node; + } + file_node->prev = NULL; + file_head->head = file_node; + file_head->file_num++; + return 0; +} + +static void +remove_node_from_list (dir_file_list_head *file_head, + dir_file_node *file_node) +{ + if (file_head == NULL || file_node == NULL) + { + return; + } + + if (file_node->prev) + { + file_node->prev->next = file_node->next; + } + else if (file_node->next) + { + file_node->next->prev = NULL; + file_head->head = file_node->next; + } + if (file_node->next) + { + file_node->next->prev = file_node->prev; + } + else if (file_node->prev) + { + file_node->prev->next = NULL; + } + + file_head->file_num--; + return; +} + +static void +free_file_list (dir_file_list_head *file_head) +{ + dir_file_node *pnode, *pnext; + if (file_head == NULL) + { + return; + } + pnode = file_head->head; + while (pnode) + { + pnext = pnode->next; + + if (pnode->file_name) + { + free (pnode->file_name); + } + free (pnode); + pnode = pnext; + } + file_head->head = NULL; + file_head->file_num = 0; + return; +} + + +#if defined(WINDOWS) +static int +scan_dir (const char *scan_path, const char *pattern, + dir_file_list_head *file_list) +{ + WIN32_FIND_DATA FileData; + HANDLE hSearch = NULL; + BOOL finished = FALSE; + char dir_path[256]; + + if (file_list == NULL) + { + return -1; + } + + snprintf (dir_path, 256, "%s/*.*", scan_path); + hSearch = FindFirstFile (dir_path, &FileData); + if (hSearch == INVALID_HANDLE_VALUE) + { + return -1; + } + + while (!finished) + { + if (strstr (FileData.cFileName, pattern)) + { + add_node_to_list (file_list, FileData.cFileName); + } + finished = !FindNextFile (hSearch, &FileData); + } + FindClose (hSearch); + return 0; +} +#else +static int +scan_dir (const char *scan_path, const char *pattern, + dir_file_list_head *file_list) +{ + DIR *dp; + struct dirent *ep; + dp = opendir (scan_path); + if (dp == NULL) + { + return -1; + } + while ((ep = readdir (dp)) != NULL) + { + if (strstr (ep->d_name, pattern)) + { + add_node_to_list (file_list, ep->d_name); + } + } + closedir (dp); + + return 0; +} +#endif + +int +remove_extra_subdir (const char *dirpath, const char *pattern, + unsigned int save_num) +{ + dir_file_list_head file_list = { 0, NULL }; + dir_file_node *pnode, *pnext; + char file_path[260]; + if (scan_dir (dirpath, pattern, &file_list) < 0) + { + return -1; + } + + while (file_list.file_num > save_num) + { + pnode = file_list.head; + pnext = pnode; + while (pnext) + { + if (strcmp (pnode->file_name, pnext->file_name) > 0) + { + pnode = pnext; + } + pnext = pnext->next; + } + snprintf (file_path, 260, "%s/%s", dirpath, pnode->file_name); + uRemoveDir (file_path, REMOVE_DIR_FORCED); + remove_node_from_list (&file_list, pnode); + } + + free_file_list (&file_list); + return 0; +} + +int +IsValidUserName (const char *pUserName) +{ + size_t len = 0; + size_t idx = 0; + if (!pUserName || !*pUserName) + { + return -1; + } + + len = strlen (pUserName); + if (len < 4 || len > 32) + { + return -1; + } + + // If the first char isn't 'a'-'z' or 'A'-'Z', then return error + if (! ((pUserName[0] >= 'a' && pUserName[0] <= 'z') + || (pUserName[0] >= 'A' && pUserName[0] <= 'Z'))) + { + return -1; + } + + // If the char isn't 'a'-'z', 'A'-'Z', '0'-'9' or '_', then return error + for (idx = 1; idx < len; idx++) + { + if (! ((pUserName[idx] >= 'a' && pUserName[idx] <= 'z') + || (pUserName[idx] >= 'A' && pUserName[idx] <= 'Z') + || (pUserName[idx] >= '0' && pUserName[idx] <= '9') + || (pUserName[idx] == '_'))) + { + return -1; + } + } + return 0; +} + +int +ut_get_token_active_time (time_t *active_time) +{ + char file_name[PATH_MAX]; + char line_buf[LINE_MAX]; + FILE *in_file = NULL; + char *pos = NULL; + + file_name[0] = '\0'; + line_buf[0] = '\0'; + + conf_get_dbmt_file (FID_DBMT_CONF, file_name); + in_file = fopen (file_name, "r"); + + if (in_file == NULL) + { + return 1; + } + + *active_time = 0; + while (fgets (line_buf, LINE_MAX, in_file) != NULL) + { + if (line_buf[0] == '#') + { + continue; + } + + if ((pos = strstr (line_buf, "=")) != NULL && + strstr (line_buf, "token_active_time") != NULL) + { + char tmp_str[LINE_MAX]; + strcpy (tmp_str, pos + 1); + + *active_time = atoi (tmp_str); + + break; + } + } + fclose (in_file); + + if (*active_time == 0) + { + *active_time = 7200; + } + + return 0; +} + +int +ut_validate_auth (nvplist *req) +{ + T_USER_AUTH auth_task = 0; + T_USER_AUTH auth_user = 0; + T_DBMT_USER dbmt_user; + T_DBMT_USER_AUTHINFO *auth_info = NULL; + char *task = NULL; + char *user_id = NULL; + char dbmt_error[DBMT_ERROR_MSG_SIZE]; + int num_authinfo = 0; + int i = 0; // loop var + + dbmt_error[0] = '\0'; + + task = nv_get_val (req, "task"); + user_id = nv_get_val (req, "_ID"); + + if (task == NULL) + { + return 0; + } + + if (!strcmp (task, "login") || !strcmp (task, "getamsenv")) + { + return 1; + } + + if (user_id == NULL) + { + return 0; + } + + if (ut_get_task_info (task, NULL, NULL, &auth_task) == 0) + { + // As the task doesn't exist, this failure will be checked in next step. + return 1; + } + + if (dbmt_user_read (&dbmt_user, dbmt_error) != ERR_NO_ERROR) + { + return 0; + } + + for (i = 0; i < dbmt_user.num_dbmt_user; ++i) + { + if (!strcmp (dbmt_user.user_info[i].user_name, user_id)) + { + auth_info = dbmt_user.user_info[i].authinfo; + num_authinfo = dbmt_user.user_info[i].num_authinfo; + break; + } + } + + for (i = 0; i < num_authinfo; ++i) + { + if (!strcmp (auth_info[i].domain, "user_auth")) + { + auth_user = atoi (auth_info[i].auth); + break; + } + } + + // assign default authority to old users. + if (auth_user == 0) + { + if (!strcmp (user_id, "admin")) + { + auth_user = AU_ADMIN; + } + else + { + auth_user = ALL_AUTHORITY; + } + } + + if (auth_user == AU_ADMIN) + { + return 1; + } + + return (auth_user & auth_task) ? 1 : 0; + +} + +static int +get_short_filename (char *ret_name, int ret_name_len, + char *short_filename) +{ + char *ptr = NULL; + char *path_p = NULL; + unsigned int filename_len = 0; + +#if defined(WINDOWS) + path_p = strrchr (short_filename, '\\'); +#else + path_p = strrchr (short_filename, '/'); +#endif + + if (path_p != NULL) + { + return -1; + } + + if (short_filename == NULL) + { + return -1; + } + + if (ret_name_len <= (int) strlen (short_filename)) + { + return -1; + } + + ptr = strrchr (short_filename, '.'); + if (ptr == NULL) + { + snprintf (ret_name, strlen (short_filename) + 1, short_filename); + return -1; + } + + filename_len = (unsigned int) (ptr - short_filename); + + snprintf (ret_name, filename_len + 1, short_filename); + + return 0; +} + +int +ut_get_filename (char *fullpath, int with_ext, char *ret_filename) +{ + char *filename = NULL; + char short_filename[PATH_MAX]; + + short_filename[0] = '\0'; + + if (fullpath == NULL) + { + return -1; + } + +#if defined(WINDOWS) + filename = strrchr (fullpath, '\\'); +#else + filename = strrchr (fullpath, '/'); +#endif + + if ((filename == NULL) || ((filename + 1) == NULL)) + { + return -1; + } + + if (with_ext == 1) + { + snprintf (ret_filename, PATH_MAX, filename + 1); + return 0; + } + else + { + if (get_short_filename (short_filename, PATH_MAX, filename + 1) != 0) + { + return -1; + } + snprintf (ret_filename, PATH_MAX, short_filename); + } + return 0; +} + + +#if defined(WINDOWS) + +static int +get_cpu_time (__int64 *kernel, __int64 *user, __int64 *idle) +{ + /* this logic allow multi thread init multiple times */ + if (s_symbol_loaded == 0) + { + /* + * kernel32.dll and ntdll.dll is essential DLL about user process. + * when a process started, that means kernel32.dll and ntdll.dll + * already load in process memory space. + * so call LoadLibrary() and FreeLibrary() function once, only + * increase and decrease dll reference counter. this behavior does + * not cause kernel32.dll or ntdll.dll unload from current process. + */ + + /* + * first try find function GetSystemTimes(). Windows OS suport this + * function since Windows XP SP1, Vista, Server 2003 or Server 2008. + */ + HMODULE module = LoadLibraryA ("kernel32.dll"); + s_pfnGetSystemTimes = + (GET_SYSTEM_TIMES) GetProcAddress (module, "GetSystemTimes"); + FreeLibrary (module); + + if (s_pfnGetSystemTimes != NULL) + { + s_symbol_loaded = 1; + } + else + { + /* + * OS may be is Windows 2000 or Windows XP. (does not support Windows 9x/NT) + * try find function NtQuerySystemInformation() + */ + module = LoadLibraryA ("ntdll.dll"); + s_pfnNtQuerySystemInformation = (NT_QUERY_SYSTEM_INFORMATION) + GetProcAddress (module, "NtQuerySystemInformation"); + FreeLibrary (module); + + if (s_pfnNtQuerySystemInformation == NULL) + { + s_symbol_loaded = 3; + } + else + { + s_symbol_loaded = 2; + } + } + } + + if (s_symbol_loaded == 1) + { + FILETIME kernel_time, user_time, idle_time; + ULARGE_INTEGER lk, lu, li; + + s_pfnGetSystemTimes (&idle_time, &kernel_time, &user_time); + + lk.HighPart = kernel_time.dwHighDateTime; + lk.LowPart = kernel_time.dwLowDateTime; + lu.HighPart = user_time.dwHighDateTime; + lu.LowPart = user_time.dwLowDateTime; + li.HighPart = idle_time.dwHighDateTime; + li.LowPart = idle_time.dwLowDateTime; + + /* In win32 system, lk includes "System Idle Process" time, + * so we should exclude it */ + *kernel = lk.QuadPart - li.QuadPart; + *user = lu.QuadPart; + *idle = li.QuadPart; + + return 0; + } + else if (s_symbol_loaded == 2) + { + SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION sppi; + ULONG len; + + s_pfnNtQuerySystemInformation (SystemProcessorPerformanceInformation, + &sppi, sizeof (sppi), &len); + + /* In win32 system, sppi.KernelTime includes "System Idle Process" + * time, so we should exclude it */ + *kernel = sppi.KernelTime.QuadPart - sppi.IdleTime.QuadPart; + *user = sppi.UserTime.QuadPart; + *idle = sppi.IdleTime.QuadPart; + + return 0; + } + + return -1; +} + +BOOL +SetPrivilege (HANDLE hToken, LPCTSTR lpszPrivilege, BOOL bEnablePrivilege) +{ + TOKEN_PRIVILEGES tp; + LUID luid; + + /* receives LUID of privilege */ + if (!LookupPrivilegeValue (NULL, lpszPrivilege, &luid)) + { + return FALSE; + } + + tp.PrivilegeCount = 1; + tp.Privileges[0].Luid = luid; + if (bEnablePrivilege) + { + tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; + } + else + { + tp.Privileges[0].Attributes = 0; + } + + if (!AdjustTokenPrivileges (hToken, FALSE, &tp, + sizeof (TOKEN_PRIVILEGES), NULL, NULL)) + { + return FALSE; + } + + if (GetLastError () == ERROR_NOT_ALL_ASSIGNED) + { + return FALSE; + } + + return TRUE; +} + +int +ut_get_proc_stat (T_AMS_PROC_STAT *stat, int pid) +{ + ULARGE_INTEGER lk, lu; + FILETIME dummy1, dummy2, kt, ut; + PROCESS_MEMORY_COUNTERS pmc; + MEMORYSTATUSEX ms; + HANDLE hProcess = NULL, hToken = NULL; + int ret = 0; + + stat->pid = pid; + if (!OpenThreadToken (GetCurrentThread (), + (TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY), + FALSE, &hToken)) + { + if (GetLastError () == ERROR_NO_TOKEN) + { + if (!ImpersonateSelf (SecurityImpersonation)) + { + return -1; + } + + if (!OpenThreadToken (GetCurrentThread (), + (TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY), + FALSE, &hToken)) + { + return -1; + } + } + else + { + return -1; + } + } + + /* enable SeDebugPrivilege */ + if (!SetPrivilege (hToken, SE_DEBUG_NAME, TRUE)) + { + ret = -1; + goto error_exit; + } + + hProcess = OpenProcess (PROCESS_ALL_ACCESS, FALSE, pid); + if (hProcess == NULL) + { + ret = -1; + goto error_exit; + } + + if (!GetProcessTimes (hProcess, &dummy1, &dummy2, &kt, &ut)) + { + ret = -1; + goto error_exit; + } + + lk.HighPart = kt.dwHighDateTime; + lk.LowPart = kt.dwLowDateTime; + lu.HighPart = ut.dwHighDateTime; + lu.LowPart = ut.dwLowDateTime; + + stat->cpu_kernel = lk.QuadPart; + stat->cpu_user = lu.QuadPart; + + memset (&pmc, 0, sizeof (pmc)); + pmc.cb = sizeof (pmc); + + if (!GetProcessMemoryInfo (hProcess, &pmc, sizeof (pmc))) + { + ret = -1; + goto error_exit; + } + + stat->mem_physical = pmc.WorkingSetSize; + + memset (&ms, 0, sizeof (ms)); + ms.dwLength = sizeof (ms); + + if (!GlobalMemoryStatusEx (&ms)) + { + ret = -1; + goto error_exit; + } + + stat->mem_virtual = ms.ullTotalVirtual - ms.ullAvailVirtual; + +error_exit: + if (hProcess != NULL) + { + CloseHandle (hProcess); + } + if (hToken != NULL) + { + CloseHandle (hToken); + } + return ret; +} + +int +ut_get_host_stat (T_AMS_HOST_STAT *stat, char *_dbmt_error) +{ + __int64 kernel, user, idle; + PERFORMANCE_INFORMATION pi; + + if (stat == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "Invalid parameter: %s.", + "stat"); + return ERR_WITH_MSG; + } + + if (get_cpu_time (&kernel, &user, &idle) != 0) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, + "Failed to get the cpu information."); + return ERR_WITH_MSG; + } + + stat->cpu_kernel = kernel; + stat->cpu_user = user; + stat->cpu_idle = idle; + stat->cpu_iowait = 0; + + memset (&pi, 0, sizeof (pi)); + pi.cb = sizeof (pi); + if (!GetPerformanceInfo (&pi, sizeof (pi))) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, + "Failed to get the memory information."); + return ERR_WITH_MSG; + } + + stat->mem_physical_total = ((__int64) pi.PhysicalTotal) * pi.PageSize; + stat->mem_physical_free = ((__int64) pi.PhysicalAvailable) * pi.PageSize; + stat->mem_swap_total = ((__int64) pi.CommitLimit) * pi.PageSize; + stat->mem_swap_free = + ((__int64) (pi.CommitLimit - pi.CommitTotal)) * pi.PageSize; + + return ERR_NO_ERROR; +} + +#elif defined(AIX) + +int +ut_get_proc_stat (T_AMS_PROC_STAT *stat, int pid) +{ + struct pstatus proc_stat; + struct psinfo proc_psinfo; + char file_name[PATH_MAX]; + int fd = -1; + long int ticks_per_sec = 0; + + file_name[0] = '\0'; + + if (stat == NULL) + { + return -1; + } + + ticks_per_sec = sysconf (_SC_CLK_TCK); + snprintf (file_name, PATH_MAX, "/proc/%d/status", pid); + + fd = open (file_name, O_RDONLY); + if (fd == -1) + { + return -1; + } + if (read (fd, (void *) &proc_stat, sizeof (struct pstatus)) == -1) + { + close (fd); + return -1; + } + close (fd); + + stat->cpu_user = + (uint64_t) ((proc_stat.pr_utime.tv_sec + + proc_stat.pr_utime.tv_nsec * 10e-9) * ticks_per_sec); + stat->cpu_kernel = + (uint64_t) ((proc_stat.pr_stime.tv_sec + + proc_stat.pr_stime.tv_nsec * 10e-9) * ticks_per_sec); + + snprintf (file_name, PATH_MAX, "/proc/%d/psinfo", pid); + + fd = open (file_name, O_RDONLY); + if (fd == -1) + { + return -1; + } + if (read (fd, (void *) &proc_psinfo, sizeof (struct psinfo)) == -1) + { + close (fd); + return -1; + } + close (fd); + + stat->mem_virtual = proc_psinfo.pr_size * 1024; + stat->mem_physical = proc_psinfo.pr_rssize * 1024; + + return 0; +} + +int +ut_get_host_stat (T_AMS_HOST_STAT *stat, char *_dbmt_error) +{ + perfstat_cpu_total_t cpu_stat; + perfstat_memory_total_t mem_info; + + if (stat == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "Invalid parameter: %s.", "stat"); + return ERR_WITH_MSG; + } + if (perfstat_cpu_total (NULL, &cpu_stat, sizeof (perfstat_cpu_total_t), 1) == -1) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, + "Failed to get the cpu information."); + return ERR_WITH_MSG; + } + stat->cpu_user = cpu_stat.user; + stat->cpu_kernel = cpu_stat.sys; + stat->cpu_idle = cpu_stat.idle; + stat->cpu_iowait = cpu_stat.wait; + + if (perfstat_memory_total + (NULL, &mem_info, sizeof (perfstat_memory_total_t), 1) == -1) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, + "Failed to get the memory information."); + return ERR_WITH_MSG; + } + stat->mem_physical_total = mem_info.real_total * 4 * 1024; + stat->mem_physical_free = mem_info.real_free * 4 * 1024; + stat->mem_swap_total = mem_info.pgsp_total * 4 * 1024; + stat->mem_swap_free = mem_info.pgsp_free * 4 * 1024; + + return ERR_NO_ERROR; +} + +#else + +int +ut_get_proc_stat (T_AMS_PROC_STAT *stat, int pid) +{ + long vmem_pages; + long rmem_pages; + char fname[PATH_MAX]; + FILE *cpufp = NULL; + FILE *memfp = NULL; + + vmem_pages = 0; + rmem_pages = 0; + fname[0] = '\0'; + + if (stat == NULL || pid == 0) + { + return -1; + } + + stat->pid = pid; + + snprintf (fname, PATH_MAX - 1, "/proc/%d/stat", (int) pid); + cpufp = fopen (fname, "r"); + if (!cpufp) + { + return -1; + } + + snprintf (fname, PATH_MAX - 1, "/proc/%d/statm", (int) pid); + memfp = fopen (fname, "r"); + if (memfp == NULL) + { + fclose (cpufp); + return -1; + } +#if __WORDSIZE == 64 + fscanf (cpufp, "%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%lu%lu", + &stat->cpu_user, &stat->cpu_kernel); + fscanf (memfp, "%lu%lu", &vmem_pages, &rmem_pages); /* 'size' and 'resident' in stat file */ +#else + fscanf (cpufp, "%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%*s%llu%llu", + &stat->cpu_user, &stat->cpu_kernel); + fscanf (memfp, "%lu%lu", &vmem_pages, &rmem_pages); /* 'size' and 'resident' in stat file */ +#endif + + stat->mem_virtual = vmem_pages * sysconf (_SC_PAGESIZE); + stat->mem_physical = rmem_pages * sysconf (_SC_PAGESIZE); + + fclose (cpufp); + fclose (memfp); + + return 0; +} + +int +ut_get_host_stat (T_AMS_HOST_STAT *stat, char *_dbmt_error) +{ + char linebuf[LINE_MAX]; + char prefix[50]; + uint64_t nice; + uint64_t buffers; + uint64_t cached; + FILE *cpufp = NULL; + FILE *memfp = NULL; + int n_cpuitem = 0; + int n_memitem = 0; + const char *stat_file = "/proc/stat"; + const char *meminfo_file = "/proc/meminfo"; + + linebuf[0] = '\0'; + prefix[0] = '\0'; + + if (stat == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "Invalid parameter: %s.", "stat"); + return ERR_WITH_MSG; + } + cpufp = fopen (stat_file, "r"); + if (cpufp == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "stat_file"); + return ERR_FILE_OPEN_FAIL; + } + memfp = fopen (meminfo_file, "r"); + if (memfp == NULL) + { + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "meminfo_file"); + return ERR_FILE_OPEN_FAIL; + } + + while (fgets (linebuf, sizeof (linebuf), cpufp)) + { + sscanf (linebuf, "%49s", prefix); + if (!strcmp (prefix, "cpu")) + { +#if __WORDSIZE == 64 + sscanf (linebuf, "%*s%lu%lu%lu%lu%lu", &stat->cpu_user, &nice, + &stat->cpu_kernel, &stat->cpu_idle, &stat->cpu_iowait); +#else + sscanf (linebuf, "%*s%llu%llu%llu%llu%llu", &stat->cpu_user, &nice, + &stat->cpu_kernel, &stat->cpu_idle, &stat->cpu_iowait); +#endif + + stat->cpu_user += nice; + n_cpuitem++; + break; + } + } + if (n_cpuitem != 1) + { + goto error_handle; + } + + while (fgets (linebuf, sizeof (linebuf), memfp)) + { + sscanf (linebuf, "%49s", prefix); + if (!strcmp (prefix, "MemTotal:")) + { +#if __WORDSIZE == 64 + sscanf (linebuf, "%*s%lu", &stat->mem_physical_total); +#else + sscanf (linebuf, "%*s%llu", &stat->mem_physical_total); +#endif + n_memitem++; + } + if (!strcmp (prefix, "MemFree:")) + { +#if __WORDSIZE == 64 + sscanf (linebuf, "%*s%lu", &stat->mem_physical_free); +#else + sscanf (linebuf, "%*s%llu", &stat->mem_physical_free); +#endif + n_memitem++; + } + if (!strcmp (prefix, "Buffers:")) + { +#if __WORDSIZE == 64 + sscanf (linebuf, "%*s%lu", &buffers); +#else + sscanf (linebuf, "%*s%llu", &buffers); +#endif + } + if (!strcmp (prefix, "Cached:")) + { +#if __WORDSIZE == 64 + sscanf (linebuf, "%*s%lu", &cached); +#else + sscanf (linebuf, "%*s%llu", &cached); +#endif + } + if (!strcmp (prefix, "SwapTotal:")) + { +#if __WORDSIZE == 64 + sscanf (linebuf, "%*s%lu", &stat->mem_swap_total); +#else + sscanf (linebuf, "%*s%llu", &stat->mem_swap_total); +#endif + n_memitem++; + } + if (!strcmp (prefix, "SwapFree:")) + { +#if __WORDSIZE == 64 + sscanf (linebuf, "%*s%lu", &stat->mem_swap_free); +#else + sscanf (linebuf, "%*s%llu", &stat->mem_swap_free); +#endif + n_memitem++; + } + } + if (n_memitem != 4) + { + goto error_handle; + } + + stat->mem_physical_free += (buffers + cached); + + stat->mem_physical_total *= 1024; + stat->mem_physical_free *= 1024; + stat->mem_swap_total *= 1024; + stat->mem_swap_free *= 1024; + + fclose (cpufp); + fclose (memfp); + return ERR_NO_ERROR; + +error_handle: + snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", "read host info error."); + fclose (cpufp); + fclose (memfp); + return ERR_WITH_MSG; +} + +#endif // WINDOWS + +int +ut_record_arniadb_utility_log_stderr (const char *msg) +{ + if (msg == NULL) + { + return -1; + } +#if !defined(WINDOWS) + fprintf (stderr, msg); +#endif + cm_util_log_write_errstr (msg); + + return 0; +} + +int +ut_record_arniadb_utility_log_stdout (const char *msg) +{ + if (msg == NULL) + { + return -1; + } +#if !defined(WINDOWS) + fprintf (stdout, msg); +#endif + cm_util_log_write_errstr (msg); + + return 0; +} diff --git a/server/src/am_server_util.h b/server/src/am_server_util.h new file mode 100644 index 0000000..c3dc5ce --- /dev/null +++ b/server/src/am_server_util.h @@ -0,0 +1,219 @@ +/* + * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. + * + * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + + +/* + * cm_server_util.h - + */ + +#ifndef _CM_SERVER_UTIL_H_ +#define _CM_SERVER_UTIL_H_ + +#include "cm_porting.h" +#include "cm_dep.h" +#include "cm_cmd_exec.h" +#include "cm_job_task.h" + +#ifndef WINDOWS +#include +#include +#include +#include +#include +#else +#ifndef uint64_t +typedef unsigned __int64 uint64_t; +#endif +#endif + +#define makestring1(x) #x +#define makestring(x) makestring1(x) + +#define TOKEN_LENGTH 128 /* multiple of 8 */ +#define TOKEN_ENC_LENGTH (TOKEN_LENGTH * 2 + 1) +#define PASSWD_LENGTH 32 +#define PASSWD_ENC_LENGTH (PASSWD_LENGTH * 2 + 1) + +#define REMOVE_DIR_FORCED 1 +#define REMOVE_EMPTY_DIR 0 + +#define MAX_AUTOQUERY_SCRIPT_SIZE 4095 +#define MAX_JOB_CONFIG_FILE_LINE_LENGTH (4096 + 256) + +#define BYTES_IN_K (1024) +#define BYTES_IN_M (1024 * 1024) +#define BYTES_IN_G (1024 * 1024 * 1024) + +#define RSA_KEY_SIZE 1024 + +#ifdef _DEBUG_ +#include "deb.h" +#define MALLOC(p) debug_malloc(p) +#else +#define MALLOC(p) malloc(p) +#endif + +#define FREE_MEM(PTR) \ + do { \ + if (PTR) { \ + free(PTR); \ + PTR = 0; \ + } \ + } while (0) + +#define REALLOC(PTR, SIZE) \ + (PTR == NULL) ? malloc(SIZE) : realloc(PTR, SIZE) + +#ifndef MAX +#define MAX(x, y) (((x) > (y)) ? (x) : (y)) +#endif + +#ifndef MIN +#define MIN(x, y) (((x) < (y)) ? (x) : (y)) +#endif + +#define MAKE_MUTIPLE_EIGHT(num) (((num) + (8) - 1) & ~((8) - 1)) + +#ifdef AIX +//the size of stack per thread +#define AIX_STACKSIZE_PER_THREAD (10*1024*1024) +#endif + +typedef enum +{ + TIME_STR_FMT_DATE = NV_ADD_DATE, + TIME_STR_FMT_TIME = NV_ADD_TIME, + TIME_STR_FMT_DATE_TIME = NV_ADD_DATE_TIME +} T_TIME_STR_FMT_TYPE; + +typedef struct +{ + uint64_t cpu_user; + uint64_t cpu_kernel; + uint64_t cpu_idle; + uint64_t cpu_iowait; + uint64_t mem_physical_total; + uint64_t mem_physical_free; + uint64_t mem_swap_total; + uint64_t mem_swap_free; +} T_AMS_HOST_STAT; + +typedef struct +{ + int pid; + uint64_t cpu_kernel; + uint64_t cpu_user; + uint64_t mem_physical; + uint64_t mem_virtual; /* size item in statm file */ +} T_AMS_PROC_STAT; + +int _op_check_is_localhost (char *token, char *tmpdbname); +void append_host_to_dbname (char *name_buf, const char *dbname, + int buf_len); +void *increase_capacity (void *ptr, int block_size, int old_count, + int new_count); +char *strcpy_limit (char *dest, const char *src, int buf_len); +int ut_getdelim (char **lineptr, int *n, int delimiter, FILE *fp); +int ut_getline (char **lineptr, int *n, FILE *fp); +void ut_error_log (nvplist *req, const char *errmsg); +void ut_access_log (nvplist *req, const char *msg); +void uRemoveCRLF (char *str); +int uStringEqual (const char *str1, const char *str2); +int uStringEqualIgnoreCase (const char *str1, const char *str2); +int ut_gettaskcode (char *task); +int ut_send_response (SOCKET fd, nvplist *res); +int ut_receive_request (SOCKET fd, nvplist *req); +void ut_daemon_start (void); +void ut_dump_file_to_string (char *string, char *fname); +int uRetrieveDBDirectory (const char *dbname, char *target); +int _isRegisteredDB (char *); +//int uReadDBnfo (char *); +void uWriteDBnfo (void); +void uWriteDBnfo2 (T_SERVER_STATUS_RESULT *cmd_res); +int ut_get_dblist (nvplist *res, char dbdir_flag); +int uCreateLockFile (char *filename); +void uRemoveLockFile (int fd); +int uCreateDir (char *path); +int folder_copy (const char *src_dir, const char *dest_dir); +int uRemoveDir (char *dir, int remove_file_in_dir); +int string_tokenize_accept_laststring_space (char *str, char *tok[], + int num_tok); +int make_version_info (const char *cli_ver, int *major_ver, int *minor_ver); +int file_copy (char *src_file, char *dest_file); +int move_file (char *src_file, char *dest_file); +void close_all_fds (int init_fd); +char *ut_trim (char *str); +void server_fd_clear (fd_set srv_fds); +int ut_write_pid (char *pid_file); +int ut_disk_free_space (char *path); +char *ip2str (unsigned char *ip, char *ip_str); +int string_tokenize (char *str, char *tok[], int num_tok); +int string_tokenize2 (char *str, char *tok[], int num_tok, int c); +int ut_get_task_info (const char *task, char *access_log_flag, + T_TASK_FUNC *task_func, T_USER_AUTH *auth); +char *time_to_str (time_t t, const char *fmt, char *buf, int type); +int read_from_socket (SOCKET fd, char *buf, int size); +int write_to_socket (SOCKET fd, const char *buf, int size); +int is_amserver_process (int pid, const char *module_name); +int make_default_env (void); +#if defined(WINDOWS) +void remove_end_of_dir_ch (char *path); +#endif + +#if defined(WINDOWS) +#define popen _popen +#define pclose _pclose +int kill (int pid, int signo); +void unix_style_path (char *path); +char *nt_style_path (char *path, char *new_path_buf); +#endif + +int _ut_get_dbaccess (nvplist *req, char *dbid, char *dbpasswd); +void uGenerateStatus (nvplist *req, nvplist *res, int retval, + const char *_dbmt_error); +int ut_validate_token (nvplist *req); +void _ut_timeval_diff (struct timeval *start, struct timeval *end, + int *res_msec); +char *ut_token_generate (char *client_ip, char *client_port, + char *dbmt_id, int proc_id, time_t login_time); +void _accept_connection (nvplist *cli_request, nvplist *cli_response); +#if defined(WINDOWS) +int gettimeofday (struct timeval *tp, void *tzp); +#endif +int ut_run_child (const char *bin_path, const char *const argv[], + int wait_flag, const char *stdin_file, + const char *stdout_file, const char *stderr_file, int *exit_status); + +int IsValidUserName (const char *pUserName); +int ut_validate_auth (nvplist *req); +int ut_get_token_active_time (time_t *active_time); +int remove_extra_subdir (const char *dirpath, const char *pattern, + unsigned int save_num); +int ut_get_filename (char *fullpath, int with_ext, char *ret_filename); +int ut_get_host_stat (T_AMS_HOST_STAT *stat, char *_dbmt_error); +int ut_get_proc_stat (T_AMS_PROC_STAT *stat, int pid); +int ut_record_arniadb_utility_log_stderr (const char *msg); +int ut_record_arniadb_utility_log_stdout (const char *msg); +int run_child_linux (const char *pname, const char *const argv[], int wait_flag, + const char *stdin_file, char *stdout_file, char *stderr_file, + int *exit_status); +void write_manager_access_log (const char *protocol_str, const char *msg); +void write_manager_error_log (const char *protocol_str, const char *msg); + +#endif /* _CM_SERVER_UTIL_H_ */ diff --git a/server/src/am_text_encryption.c b/server/src/am_text_encryption.c new file mode 100644 index 0000000..2026a85 --- /dev/null +++ b/server/src/am_text_encryption.c @@ -0,0 +1,291 @@ +/* + * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. + * + * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + + +/* + * tea.c - + */ + +#ident "$Id$" + +#include +#include +#include +#include + +#include "cm_porting.h" +#include "cm_text_encryption.h" + +#if (defined(SOLARIS) && !defined(SOLARIS_X86)) || defined(HPUX) || defined(AIX) +#define BYTE_ORDER_BIG_ENDIAN +#elif defined(WINDOWS) || defined(LINUX) || defined(OSF1) || defined(ALPHA_LINUX) || defined(UNIXWARE7) || defined(SOLARIS_X86) +#ifdef BYTE_ORDER_BIG_ENDIAN +#error BYTE_ORDER_BIG_ENDIAN defined +#endif +#else +#error PLATFORM NOT DEFINED +#endif + +static void tea_encrypt (unsigned int key[], int len, char *buf); +static void tea_decrypt (unsigned int key[], int len, char *buf); +static void _encrypt (unsigned int k[], unsigned int text[]); +static void _decrypt (unsigned int k[], unsigned int text[]); +static char ut_get_hexval (char c); +static void array_init_random_value (char *arr, int arrsize); +static int big_endian_int (int from); + +static unsigned int key[4] = { 1, 2, 3, 4 }; /* key for tea encryption algorithm */ + +/* + * DESCRIPTION + * The uEncrypt() function encrypts the src string and converts + * the binary result to the string of hexadecimal representation. + * Since one byte is represented as two hexadecimal digit, 'trg' must + * have twice the space of 'src'. + * NOTE + * - 'len' must be multiple of 8. + * - size of 'trg' must be at lease twice the 'src' + * - 'src' must have the length equal to 'len' + */ +void +uEncrypt (int len, const char *src, char *trg) +{ + char *encstr = NULL; + char strbuf[10]; + int i; + + if (src == NULL) + { + src = ""; + } + + if ((encstr = (char *) malloc (len + 1)) == NULL) + { + return; + } + + array_init_random_value (encstr, sizeof (encstr)); + strcpy (encstr, src); + + tea_encrypt (key, len, encstr); + for (i = 0; i < len; ++i) + { + sprintf (strbuf, "%08x", encstr[i]); + trg[i * 2] = strbuf[6]; + trg[i * 2 + 1] = strbuf[7]; + } + trg[i * 2] = '\0'; + + free (encstr); +} + +/* + * DESCRIPTION + * The uDecrypt() function decrypts the src string and converts + * the string of hexadecimal string into its original values. + * NOTE + * - size of 'src' must be at least twice the 'trg' + * - size of 'trg' must be equal to 'len' + */ +void +uDecrypt (int len, const char *src, char *trg) +{ + int i; + char v1, v2; + char *hexacode = NULL; + + if (src == NULL || src[0] == '\0') + { + trg[0] = '\0'; + return; + } + + if ((hexacode = (char *) malloc (len * 2 + 1)) == NULL) + { + return; + } + + memset (hexacode, 0, sizeof (hexacode)); + strcpy (hexacode, src); + + for (i = 0; i < len; ++i) + { + v1 = ut_get_hexval (hexacode[i * 2]); + v2 = ut_get_hexval (hexacode[i * 2 + 1]); + v1 = v1 << 4; + trg[i] = (unsigned char) v1 | (unsigned char) v2; + } + tea_decrypt (key, len, trg); + trg[len] = '\0'; + + free (hexacode); +} + +/* This function assumes that unsigned_int is 4 bytes int. + En/Decryption processes 8 bytes at a time. + Although this function encrypts any length of text, + parameter text must have space size in multiple of 8 because this + function returns encryption in multiple of 8 bytes */ +static void +tea_encrypt (unsigned int key[], int len, char *text) +{ + unsigned int ulbuf[2]; + + while (len > 0) + { + if ((size_t) len < sizeof (ulbuf)) + { + memset (ulbuf, ' ', sizeof (ulbuf)); + memcpy (ulbuf, text, len); + _encrypt (key, ulbuf); + memcpy (text, ulbuf, len); + break; + } + else + { + memcpy (ulbuf, text, sizeof (ulbuf)); + _encrypt (key, ulbuf); + memcpy (text, ulbuf, sizeof (ulbuf)); + } + len -= sizeof (ulbuf); + text += sizeof (ulbuf); + } +} + +/* text parameter must hold encryption of 8-byte multiple size which was + returned from previous tea_encrypt() call */ +static void +tea_decrypt (unsigned int key[], int len, char *text) +{ + unsigned int ulbuf[2]; + + while (len > 0) + { + if ((size_t) len < sizeof (ulbuf)) + { + memset (ulbuf, ' ', sizeof (ulbuf)); + /*memcpy(ulbuf,text,len); */ + memcpy (ulbuf, text, sizeof (ulbuf)); + _decrypt (key, ulbuf); + memcpy (text, ulbuf, len); + break; + } + else + { + memcpy (ulbuf, text, sizeof (ulbuf)); + _decrypt (key, ulbuf); + memcpy (text, ulbuf, sizeof (ulbuf)); + } + len -= sizeof (ulbuf); + text += sizeof (ulbuf); + } +} + +static void +_encrypt (unsigned int k[], unsigned int text[]) +{ + unsigned int y = big_endian_int (text[0]); + unsigned int z = big_endian_int (text[1]); + unsigned int delta = 0x9e3779b9; + unsigned int sum = 0; + int n; + + for (n = 0; n < 32; n++) + { + sum += delta; + y += ((z << 4) + k[0]) ^ (z + sum) ^ ((z >> 5) + k[1]); + z += ((y << 4) + k[2]) ^ (y + sum) ^ ((y >> 5) + k[3]); + } + text[0] = big_endian_int (y); + text[1] = big_endian_int (z); +} + +static void +_decrypt (unsigned int k[], unsigned int text[]) +{ + unsigned int y = big_endian_int (text[0]); + unsigned int z = big_endian_int (text[1]); + unsigned int delta = 0x9e3779b9; + unsigned int sum = delta << 5; + int n; + + for (n = 0; n < 32; n++) + { + z -= ((y << 4) + k[2]) ^ (y + sum) ^ ((y >> 5) + k[3]); + y -= ((z << 4) + k[0]) ^ (z + sum) ^ ((z >> 5) + k[1]); + sum -= delta; + } + text[0] = big_endian_int (y); + text[1] = big_endian_int (z); +} + +static char +ut_get_hexval (char c) +{ + if (c >= '0' && c <= '9') + { + return (c - '0'); + } + + if (c >= 'a' && c <= 'f') + { + return (c - 'a' + 10); + } + + return (c - 'A' + 10); /* c >= 'A' && c <= 'F' */ +} + +static void +array_init_random_value (char *arr, int arrsize) +{ + int i; + static unsigned int seed = 0; + + if (seed == 0) + { + seed = (unsigned int) time (NULL); + srand (seed); + } + + for (i = 0; i < arrsize; i++) + { + arr[i] = rand () % 100; + } +} + +static int +big_endian_int (int from) +{ +#ifdef BYTE_ORDER_BIG_ENDIAN + return from; +#else + int to; + char *p, *q; + + p = (char *) &from; + q = (char *) &to; + + q[0] = p[3]; + q[1] = p[2]; + q[2] = p[1]; + q[3] = p[0]; + + return to; +#endif +} diff --git a/server/src/am_text_encryption.h b/server/src/am_text_encryption.h new file mode 100644 index 0000000..ccaf13f --- /dev/null +++ b/server/src/am_text_encryption.h @@ -0,0 +1,38 @@ +/* + * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. + * + * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + + +/* + * cm_text_encryption.h - + */ + +#ifndef _CM_TEXT_ENCRYPTION_H_ +#define _CM_TEXT_ENCRYPTION_H_ +#ifdef __cplusplus +extern "C" +{ +#endif +#ident "$Id$" + +void uEncrypt (int len, const char *src, char *trg); +void uDecrypt (int len, const char *src, char *trg); +#ifdef __cplusplus +} +#endif +#endif /* _CM_TEXT_ENCRYPTION_H_ */ diff --git a/server/src/am_user.cpp b/server/src/am_user.cpp new file mode 100644 index 0000000..47bd8a7 --- /dev/null +++ b/server/src/am_user.cpp @@ -0,0 +1,711 @@ +/* + * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. + * + * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + + +/* + * cm_user.cpp - + */ + +#include +#include +#include + +#if defined(WINDOWS) +#include +#else +#include +#endif + +#include "cm_porting.h" +#include "cm_config.h" +#include "cm_server_util.h" +#include "cm_user.h" + +#define ARNIADB_PASS_OPEN_TAG "<<<:" +#define ARNIADB_PASS_OPEN_TAG_LEN strlen(ARNIADB_PASS_OPEN_TAG) +#define ARNIADB_PASS_CLOSE_TAG ">>>:" +#define ARNIADB_PASS_CLOSE_TAG_LEN strlen(ARNIADB_PASS_CLOSE_TAG) + + +T_USER_TOKEN_INFO *user_token_info = NULL; + +int +dbmt_user_read (T_DBMT_USER *dbmt_user, char *_dbmt_error) +{ + T_DBMT_USER_INFO *user_info = NULL; + T_DBMT_USER_DBINFO *user_dbinfo = NULL; + T_DBMT_USER_AUTHINFO *user_authinfo = NULL; + int num_dbmt_user = 0; + int num_dbinfo = 0; + int num_authinfo = 0; + char *authinfo[2]; + char *dbinfo[4]; + FILE *fp = NULL; + char strbuf[1024]; + char cur_user[DBMT_USER_NAME_LEN]; + int retval = ERR_NO_ERROR; + int lock_fd; + + memset (dbmt_user, 0, sizeof (T_DBMT_USER)); + + lock_fd = uCreateLockFile (conf_get_dbmt_file (FID_LOCK_DBMT_PASS, strbuf)); + if (lock_fd < 0) + { + return ERR_TMPFILE_OPEN_FAIL; + } + + fp = fopen (conf_get_dbmt_file (FID_DBMT_ARNIADB_PASS, strbuf), "r"); + if (fp == NULL) + { + strcpy (_dbmt_error, + conf_get_dbmt_file2 (FID_DBMT_ARNIADB_PASS, strbuf)); + retval = ERR_FILE_OPEN_FAIL; + goto read_dbmt_user_error; + } + + memset (cur_user, 0, sizeof (cur_user)); + while (fgets (strbuf, sizeof (strbuf), fp)) + { + ut_trim (strbuf); + if (strncmp (strbuf, ARNIADB_PASS_OPEN_TAG, ARNIADB_PASS_OPEN_TAG_LEN) == 0) + { + snprintf (cur_user, sizeof (cur_user) - 1, "%s", strbuf + ARNIADB_PASS_OPEN_TAG_LEN); + if (cur_user[0] == '\0') + { + continue; + } + + user_info = + (T_DBMT_USER_INFO *) increase_capacity (user_info, + sizeof (T_DBMT_USER_INFO), num_dbmt_user, + num_dbmt_user + 1); + if (user_info == NULL) + { + retval = ERR_MEM_ALLOC; + goto read_dbmt_user_error; + } + num_dbmt_user++; + + /* user name set */ + strcpy_limit (user_info[num_dbmt_user - 1].user_name, cur_user, + DBMT_USER_NAME_LEN); + if (user_dbinfo != NULL) + { + free (user_dbinfo); + user_dbinfo = NULL; + } + num_dbinfo = 0; + num_authinfo = 0; + continue; + } + + if (cur_user[0] == '\0') + { + continue; + } + + if (strncmp (strbuf, ARNIADB_PASS_CLOSE_TAG, ARNIADB_PASS_CLOSE_TAG_LEN) == 0) + { + if (strcmp (strbuf + ARNIADB_PASS_CLOSE_TAG_LEN, cur_user) != 0) + { + strcpy (_dbmt_error, conf_get_dbmt_file2 (FID_DBMT_ARNIADB_PASS, + strbuf)); + retval = ERR_FILE_INTEGRITY; + goto read_dbmt_user_error; + } + if (user_info != NULL) + { + user_info[num_dbmt_user - 1].dbinfo = user_dbinfo; + user_dbinfo = NULL; + user_info[num_dbmt_user - 1].num_dbinfo = num_dbinfo; + + user_info[num_dbmt_user - 1].authinfo = user_authinfo; + user_authinfo = NULL; + user_info[num_dbmt_user - 1].num_authinfo = num_authinfo; + } + cur_user[0] = '\0'; + } + else + { + /* get authority info and database info */ + if (string_tokenize2 (strbuf, authinfo, 2, ':') < 0) + { + continue; + } + else + { + if ((strcmp (authinfo[0], "dbc") == 0) + || (strcmp (authinfo[0], "dbo") == 0) + || (strcmp (authinfo[0], "brk") == 0) + || (strcmp (authinfo[0], "mon") == 0) + || (strcmp (authinfo[0], "job") == 0) + || (strcmp (authinfo[0], "var") == 0) + || (strcmp (authinfo[0], "user_auth") == 0) + || (strcmp (authinfo[0], "admin") == 0) || + // for old cmdb.pass file. + (strcmp (authinfo[0], "unicas") == 0) + || (strcmp (authinfo[0], "dbcreate") == 0) + || (strcmp (authinfo[0], "statusmonitorauth") == 0)) + { + T_DBMT_USER_AUTHINFO tmp_authinfo; + memset (&tmp_authinfo, 0, sizeof (T_DBMT_USER_AUTHINFO)); + + dbmt_user_set_authinfo (&tmp_authinfo, authinfo[0], authinfo[1]); + + user_authinfo = + (T_DBMT_USER_AUTHINFO *) increase_capacity (user_authinfo, + sizeof (T_DBMT_USER_AUTHINFO), + num_authinfo, num_authinfo + 1); + if (user_authinfo == NULL) + { + retval = ERR_MEM_ALLOC; + goto read_dbmt_user_error; + } + num_authinfo++; + user_authinfo[num_authinfo - 1] = tmp_authinfo; + } + else + { + T_DBMT_USER_DBINFO tmp_dbinfo; + memset (&tmp_dbinfo, 0, sizeof (T_DBMT_USER_DBINFO)); + + if (string_tokenize2 (authinfo[1], dbinfo, 3, ';') < 0) + { + continue; + } + + /* 8.3.0 cmdb.pass not store dbpasswd. For compatibility, + * check if use older version cmdb.pass */ + char *separator; + separator = dbinfo[3] = strchr (dbinfo[2], ';'); + if (separator != NULL) + { + *separator = '\0'; + dbinfo[3] = separator + 1; + dbmt_user_set_dbinfo (&tmp_dbinfo, authinfo[0], + dbinfo[0], dbinfo[1], dbinfo[3]); + } + else + { + dbmt_user_set_dbinfo (&tmp_dbinfo, authinfo[0], + dbinfo[0], dbinfo[1], dbinfo[2]); + } + + user_dbinfo = + (T_DBMT_USER_DBINFO *) increase_capacity (user_dbinfo, + sizeof (T_DBMT_USER_DBINFO), + num_dbinfo, num_dbinfo + 1); + if (user_dbinfo == NULL) + { + retval = ERR_MEM_ALLOC; + goto read_dbmt_user_error; + } + num_dbinfo++; + user_dbinfo[num_dbinfo - 1] = tmp_dbinfo; + } + } + } + } + fclose (fp); + fp = NULL; + + if (user_dbinfo != NULL) + { + free (user_dbinfo); + user_dbinfo = NULL; + } + if (user_authinfo != NULL) + { + free (user_authinfo); + user_authinfo = NULL; + } + + if (num_dbmt_user < 1) + { + strcpy (_dbmt_error, + conf_get_dbmt_file2 (FID_DBMT_ARNIADB_PASS, strbuf)); + retval = ERR_FILE_INTEGRITY; + goto read_dbmt_user_error; + } + + dbmt_user->num_dbmt_user = num_dbmt_user; + dbmt_user->user_info = user_info; + + fp = fopen (conf_get_dbmt_file (FID_DBMT_PASS, strbuf), "r"); + if (fp == NULL) + { + strcpy (_dbmt_error, conf_get_dbmt_file2 (FID_DBMT_PASS, strbuf)); + retval = ERR_FILE_OPEN_FAIL; + goto read_dbmt_user_error; + } + + while (fgets (strbuf, sizeof (strbuf), fp)) + { + char *tok[2]; + int i; + + ut_trim (strbuf); + if (string_tokenize2 (strbuf, tok, 2, ':') < 0) + { + continue; + } + for (i = 0; i < dbmt_user->num_dbmt_user; i++) + { + if (strcmp (tok[0], dbmt_user->user_info[i].user_name) == 0) + { + snprintf (dbmt_user->user_info[i].user_passwd, + sizeof (dbmt_user->user_info[i].user_passwd) - 1, + "%s", tok[1]); + break; + } + } + } + fclose (fp); + + uRemoveLockFile (lock_fd); + return ERR_NO_ERROR; + +read_dbmt_user_error: + if (fp != NULL) + { + fclose (fp); + } + if (user_info != NULL) + { + free (user_info); + } + if (user_authinfo != NULL) + { + free (user_authinfo); + } + if (user_dbinfo != NULL) + { + free (user_dbinfo); + } + dbmt_user_free (dbmt_user); + uRemoveLockFile (lock_fd); + + return retval; +} + +void +dbmt_user_free (T_DBMT_USER *dbmt_user) +{ + int i; + + if (dbmt_user->user_info) + { + for (i = 0; i < dbmt_user->num_dbmt_user; i++) + { + if (dbmt_user->user_info[i].dbinfo) + { + free (dbmt_user->user_info[i].dbinfo); + } + if (dbmt_user->user_info[i].authinfo) + { + free (dbmt_user->user_info[i].authinfo); + } + } + free (dbmt_user->user_info); + } +} + +int +dbmt_user_write_auth (T_DBMT_USER *dbmt_user, char *_dbmt_error) +{ + FILE *fp; + char tmpfile[512]; + int i, j; + char strbuf[1024]; + int lock_fd; + +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (tmpfile, "%s/tmp/DBMT_util_pass.%d", sco.szArniadb, (int) getpid ()); +#else + sprintf (tmpfile, "%s/DBMT_util_pass.%d", ARNIADB_TMPDIR, (int) getpid ()); +#endif + fp = fopen (tmpfile, "w"); + if (fp == NULL) + { + return ERR_TMPFILE_OPEN_FAIL; + } + for (i = 0; i < dbmt_user->num_dbmt_user; i++) + { + if (dbmt_user->user_info[i].user_name[0] == '\0') + { + continue; + } + + fprintf (fp, "%s%s\n", ARNIADB_PASS_OPEN_TAG, + dbmt_user->user_info[i].user_name); + for (j = 0; j < dbmt_user->user_info[i].num_authinfo; j++) + { + if (dbmt_user->user_info[i].authinfo[j].domain[0] == '\0') + { + continue; + } + fprintf (fp, "%s:%s\n", dbmt_user->user_info[i].authinfo[j].domain, + dbmt_user->user_info[i].authinfo[j].auth); + } + for (j = 0; j < dbmt_user->user_info[i].num_dbinfo; j++) + { + if (dbmt_user->user_info[i].dbinfo[j].dbname[0] == '\0') + { + continue; + } + fprintf (fp, "%s:%s;%s;%s\n", + dbmt_user->user_info[i].dbinfo[j].dbname, + dbmt_user->user_info[i].dbinfo[j].auth, + dbmt_user->user_info[i].dbinfo[j].uid, + dbmt_user->user_info[i].dbinfo[j].broker_address); + } + fprintf (fp, "%s%s\n", ARNIADB_PASS_CLOSE_TAG, + dbmt_user->user_info[i].user_name); + } + fclose (fp); + + lock_fd = uCreateLockFile (conf_get_dbmt_file (FID_LOCK_DBMT_PASS, strbuf)); + if (lock_fd < 0) + { + unlink (tmpfile); + return ERR_TMPFILE_OPEN_FAIL; + } + move_file (tmpfile, conf_get_dbmt_file (FID_DBMT_ARNIADB_PASS, strbuf)); + uRemoveLockFile (lock_fd); + + return ERR_NO_ERROR; +} + +void +dbmt_user_set_dbinfo (T_DBMT_USER_DBINFO *dbinfo, const char *dbname, + const char *auth, const char *uid, + const char *broker_address) +{ + strcpy_limit (dbinfo->dbname, dbname, sizeof (dbinfo->dbname)); + strcpy_limit (dbinfo->auth, auth, sizeof (dbinfo->auth)); + strcpy_limit (dbinfo->uid, uid, sizeof (dbinfo->uid)); + if (broker_address == NULL) + { + dbinfo->broker_address[0] = '\0'; + } + else + { + strcpy_limit (dbinfo->broker_address, broker_address, + sizeof (dbinfo->broker_address)); + } +} + +void +dbmt_user_set_authinfo (T_DBMT_USER_AUTHINFO *authinfo, const char *domain, + const char *auth) +{ + strcpy_limit (authinfo->domain, domain, sizeof (authinfo->domain)); + strcpy_limit (authinfo->auth, auth, sizeof (authinfo->auth)); +} + +void +dbmt_user_set_userinfo (T_DBMT_USER_INFO *usrinfo, const char *user_name, + const char *user_passwd, int num_authinfo, + T_DBMT_USER_AUTHINFO *authinfo, int num_dbinfo, + T_DBMT_USER_DBINFO *dbinfo) +{ + strcpy_limit (usrinfo->user_name, user_name, sizeof (usrinfo->user_name)); + strcpy_limit (usrinfo->user_passwd, user_passwd, sizeof (usrinfo->user_passwd)); + usrinfo->num_authinfo = num_authinfo; + usrinfo->authinfo = authinfo; + usrinfo->num_dbinfo = num_dbinfo; + usrinfo->dbinfo = dbinfo; +} + +int +dbmt_user_search (T_DBMT_USER_INFO *user_info, const char *dbname) +{ + int i; + + for (i = 0; i < user_info->num_dbinfo; i++) + { + if (strcmp (user_info->dbinfo[i].dbname, dbname) == 0) + { + return i; + } + } + + return -1; +} + +int +dbmt_user_write_pass (T_DBMT_USER *dbmt_user, char *_dbmt_error) +{ + char tmpfile[512], strbuf[1024]; + FILE *fp; + int i, lock_fd; + +#if !defined (DO_NOT_USE_ARNIADBENV) + sprintf (tmpfile, "%s/tmp/DBMT_util_pass.%d", sco.szArniadb, (int) getpid ()); +#else + sprintf (tmpfile, "%s/DBMT_util_pass.%d", ARNIADB_TMPDIR, (int) getpid ()); +#endif + + fp = fopen (tmpfile, "w"); + if (fp == NULL) + { + return ERR_TMPFILE_OPEN_FAIL; + } + for (i = 0; i < dbmt_user->num_dbmt_user; i++) + { + if (dbmt_user->user_info[i].user_name[0] == '\0') + { + continue; + } + fprintf (fp, "%s:%s\n", dbmt_user->user_info[i].user_name, + dbmt_user->user_info[i].user_passwd); + } + fclose (fp); + + lock_fd = uCreateLockFile (conf_get_dbmt_file (FID_LOCK_DBMT_PASS, strbuf)); + if (lock_fd < 0) + { + unlink (tmpfile); + return ERR_TMPFILE_OPEN_FAIL; + } + move_file (tmpfile, conf_get_dbmt_file (FID_DBMT_PASS, strbuf)); + uRemoveLockFile (lock_fd); + + return ERR_NO_ERROR; +} + +void +dbmt_user_db_delete (T_DBMT_USER *dbmt_user, char *dbname) +{ + int i, j; + + for (i = 0; i < dbmt_user->num_dbmt_user; i++) + { + for (j = 0; j < dbmt_user->user_info[i].num_dbinfo; j++) + { + if (strcmp (dbmt_user->user_info[i].dbinfo[j].dbname, dbname) == 0) + { + dbmt_user->user_info[i].dbinfo[j].dbname[0] = '\0'; + } + } + } +} + +int +dbmt_user_add_dbinfo (T_DBMT_USER_INFO *usrinfo, T_DBMT_USER_DBINFO *dbinfo) +{ + int i = usrinfo->num_dbinfo; + + usrinfo->dbinfo = + (T_DBMT_USER_DBINFO *) increase_capacity (usrinfo->dbinfo, + sizeof (T_DBMT_USER_DBINFO), + i, i + 1); + if (usrinfo->dbinfo == NULL) + { + return ERR_MEM_ALLOC; + } + i++; + usrinfo->num_dbinfo = i; + for (i--; i >= 1; i--) + { + usrinfo->dbinfo[i] = usrinfo->dbinfo[i - 1]; + } + usrinfo->dbinfo[0] = *dbinfo; + + return ERR_NO_ERROR; +} + +int +dbmt_user_new_token_info (const char *user_id, + const char *user_ip, + const char *user_port, const char *token_enc, +#ifdef WINDOWS + HANDLE proc_id, +#else + pid_t proc_id, +#endif + time_t login_time) +{ + T_USER_TOKEN_INFO *end_node; + T_USER_TOKEN_INFO *new_node; + + if (! (new_node = dbmt_user_search_token_info (user_id))) + { + new_node = (T_USER_TOKEN_INFO *) malloc (sizeof (T_USER_TOKEN_INFO)); + if (new_node == NULL) + { + return ERR_MEM_ALLOC; + } + + if (user_token_info == NULL) + { + end_node = user_token_info = new_node; + } + else + { + end_node = user_token_info->prev; + } + end_node->next = new_node; + new_node->next = user_token_info; + new_node->prev = end_node; + user_token_info->prev = new_node; + } + + strncpy (new_node->user_id, user_id, DBMT_USER_NAME_LEN); + strncpy (new_node->user_ip, user_ip, 20); + strncpy (new_node->user_port, user_port, 10); + strncpy (new_node->token, token_enc, TOKEN_ENC_LENGTH); + new_node->proc_id = proc_id; + new_node->login_time = login_time; + + return ERR_NO_ERROR; +} + +T_USER_TOKEN_INFO * +dbmt_user_search_token_info (const char *user_id) +{ + T_USER_TOKEN_INFO *head = user_token_info; + + if (user_id == NULL) + { + return NULL; + } + + if (head == NULL) + { + ut_access_log (NULL, "user_token_info is null."); + return NULL; + } + + do + { + if (!strcmp (head->user_id, user_id)) + { + return head; + } + + head = head->next; + + } + while (head != user_token_info); + + return NULL; +} + +T_USER_TOKEN_INFO * +dbmt_user_search_token_info_by_token (const char *token) +{ + T_USER_TOKEN_INFO *head = user_token_info; + + if (token == NULL) + { + return NULL; + } + + if (head == NULL) + { + ut_access_log (NULL, "user_token_info is null."); + return NULL; + } + + do + { + if (!strcmp (head->token, token)) + { + return head; + } + + head = head->next; + + } + while (head != user_token_info); + + return NULL; + +} + +T_USER_TOKEN_INFO * +dbmt_user_delete_token_info (const char *user_id) +{ + T_USER_TOKEN_INFO *removed_node = NULL; + + if (user_id == NULL) + { + return NULL; + } + + + if ((removed_node = dbmt_user_search_token_info (user_id)) == NULL) + { + return NULL; + } + + if (removed_node == user_token_info) + { + if (user_token_info->next != user_token_info) + { + user_token_info = user_token_info->next; + } + else + { + user_token_info = NULL; + } + } + + removed_node->prev->next = removed_node->next; + removed_node->next->prev = removed_node->prev; + + return removed_node; + +} + +T_USER_TOKEN_INFO * +dbmt_user_delete_token_info_by_token (const char *token) +{ + T_USER_TOKEN_INFO *removed_node = NULL; + + if (token == NULL) + { + return NULL; + } + + if ((removed_node = dbmt_user_search_token_info_by_token (token)) == NULL) + { + return NULL; + } + + if (removed_node == user_token_info) + { + if (user_token_info->next != user_token_info) + { + user_token_info = user_token_info->next; + } + else + { + user_token_info = NULL; + } + + } + + removed_node->prev->next = removed_node->next; + removed_node->next->prev = removed_node->prev; + + return removed_node; + +} diff --git a/server/src/am_user.h b/server/src/am_user.h new file mode 100644 index 0000000..6165284 --- /dev/null +++ b/server/src/am_user.h @@ -0,0 +1,113 @@ +/* + * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. + * + * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + + +/* + * cm_user.h - + */ + +#ifndef _CM_USER_H_ +#define _CM_USER_H_ + +#define DBMT_USER_NAME_LEN 64 + +typedef struct +{ + char dbname[DBMT_USER_NAME_LEN]; + char auth[16]; + char uid[32]; + char broker_address[64]; +} T_DBMT_USER_DBINFO; + +typedef struct +{ + char domain[DBMT_USER_NAME_LEN]; + char auth[16]; +} T_DBMT_USER_AUTHINFO; + +typedef struct +{ + char user_name[DBMT_USER_NAME_LEN]; + char user_passwd[80]; + int num_authinfo; + int num_dbinfo; + T_DBMT_USER_AUTHINFO *authinfo; + T_DBMT_USER_DBINFO *dbinfo; +} T_DBMT_USER_INFO; + +typedef struct +{ + int num_dbmt_user; + T_DBMT_USER_INFO *user_info; +} T_DBMT_USER; + +typedef struct T_USER_TOKEN_INFO T_USER_TOKEN_INFO; + +struct T_USER_TOKEN_INFO +{ + char user_id[DBMT_USER_NAME_LEN]; + char user_ip[20]; + char user_port[10]; +#ifdef WINDOWS + HANDLE proc_id; +#else + pid_t proc_id; +#endif + time_t login_time; + + char token[TOKEN_ENC_LENGTH]; + + T_USER_TOKEN_INFO *next; + T_USER_TOKEN_INFO *prev; + +}; + +int dbmt_user_read (T_DBMT_USER *dbmt_user, char *_dbmt_error); +void dbmt_user_free (T_DBMT_USER *dbmt_user); +int dbmt_user_write_auth (T_DBMT_USER *dbmt_user, char *_dbmt_error); +int dbmt_user_write_pass (T_DBMT_USER *dbmt_user, char *_dbmt_error); +void dbmt_user_set_dbinfo (T_DBMT_USER_DBINFO *dbinfo, const char *dbname, + const char *auth, const char *uid, const char *broker_address); +void dbmt_user_set_authinfo (T_DBMT_USER_AUTHINFO *authinfo, + const char *domain, const char *auth); +void dbmt_user_set_userinfo (T_DBMT_USER_INFO *usrinfo, + const char *user_name, const char *user_passwd, + int num_authinfo, T_DBMT_USER_AUTHINFO *authinfo, + int num_dbinfo, T_DBMT_USER_DBINFO *dbinfo); +int dbmt_user_search (T_DBMT_USER_INFO *user_info, const char *dbname); +void dbmt_user_db_delete (T_DBMT_USER *dbmt_user, char *dbname); +int dbmt_user_add_dbinfo (T_DBMT_USER_INFO *usrinfo, + T_DBMT_USER_DBINFO *dbinfo); + +int dbmt_user_new_token_info (const char *user_id, + const char *user_ip, const char *user_port, + const char *token_enc, +#ifdef WINDOWS + HANDLE proc_id, +#else + pid_t proc_id, +#endif + time_t login_time); + +T_USER_TOKEN_INFO *dbmt_user_search_token_info (const char *user_id); +T_USER_TOKEN_INFO *dbmt_user_search_token_info_by_token (const char *token); +T_USER_TOKEN_INFO *dbmt_user_delete_token_info (const char *user_id); +T_USER_TOKEN_INFO *dbmt_user_delete_token_info_by_token (const char *token); + +#endif /* _CM_USER_H_ */ diff --git a/server/src/am_win_wsa.c b/server/src/am_win_wsa.c new file mode 100644 index 0000000..6498801 --- /dev/null +++ b/server/src/am_win_wsa.c @@ -0,0 +1,75 @@ +/* + * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. + * + * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + + +/* + * wsa_init.c - + */ + +#ident "$Id$" + +#include +#include + +int +wsa_initialize () +{ + WORD wVersionRequested; + WSADATA wsaData; + int err; + + wVersionRequested = MAKEWORD (1, 1); + + err = WSAStartup (wVersionRequested, &wsaData); + + if (err != 0) + { + return -1; + } + + /* Confirm that the Windows Sockets DLL supports 1.1. */ + /* Note that if the DLL supports versions greater */ + /* than 1.1 in addition to 1.1, it will still return */ + /* 1.1 in wVersion since that is the version we */ + /* requested. */ + if (LOBYTE (wsaData.wVersion) != 1 || HIBYTE (wsaData.wVersion) != 1) + { + WSACleanup (); + return -1; + } + /* The Windows Sockets DLL is acceptable. Proceed. */ + + + /* Make sure that the version requested is >= 1.1. */ + /* The low byte is the major version and the high */ + /* byte is the minor version. */ + if (LOBYTE (wVersionRequested) < 1 || + (LOBYTE (wVersionRequested) == 1 && HIBYTE (wVersionRequested) < 1)) + { + return -1; + } + /* Since we only support 1.1, set both wVersion and */ + /* wHighVersion to 1.1. */ + /* + lpWsaData->wVersion = MAKEWORD( 1, 1 ); + lpWsaData->wHighVersion = MAKEWORD( 1, 1 ); + */ + + return 0; +} diff --git a/server/src/am_win_wsa.h b/server/src/am_win_wsa.h new file mode 100644 index 0000000..140227a --- /dev/null +++ b/server/src/am_win_wsa.h @@ -0,0 +1,63 @@ +/* + * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. + * + * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + + +/* + * cm_wsa_init.h - + */ + +#ifndef _CM_WSA_INIT_H_ +#define _CM_WSA_INIT_H_ + +#ident "$Id$" + +/* + * IMPORTED SYSTEM HEADER FILES + */ + +/* + * IMPORTED OTHER HEADER FILES + */ + +/* + * EXPORTED DEFINITIONS + */ + +/* + * EXPORTED TYPE DEFINITIONS + */ + +/* + * EXPORTED FUNCTION PROTOTYPES + */ +#ifdef __cplusplus +extern "C" +{ +#endif + +int wsa_initialize (); + +#ifdef __cplusplus +} +#endif +/* + * EXPORTED VARIABLES + */ + +#endif /* _CM_WSA_INIT_H_ */ diff --git a/server/test/am_mon_data/dump_data.py b/server/test/am_mon_data/dump_data.py new file mode 100644 index 0000000..eef9a4d --- /dev/null +++ b/server/test/am_mon_data/dump_data.py @@ -0,0 +1,113 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +import struct +import json +import time +import sys + + +metric = "vol_freespace" +dtype = "monthly" +bname = "query_editor" +dbname = "demodb" +volname = "demodb" + +# globe +dpath = "/home/liuhj/ARNIADB/var/manager/mon_data/" + + +def dump_mod_data(filename, pos, size): + data = [] + fp = open(filename, "rb") + fp.seek(pos, 0) + for i in range(size): + a, = struct.unpack("i", fp.read(4)) + data.append(a) + return data + +def dump_daily(mon_file, meta, m_len, m_idx, blk_idx): + pos = blk_idx * (3600*24/meta["k_interval"] + 24*30 + 365) * m_len * 4 + daily_data = dump_mod_data(mon_file, pos, 3600 * 24 / meta["k_interval"] * m_len) + + sec = int(time.time()) + + read_idx = (sec % (3600 * 24))/meta["k_interval"] + + for i in range(read_idx): + #print daily_data[i*m_len + m_idx], + #print "read_idx:" + str(i), + for j in range(m_len): + print daily_data[i*m_len + j], + print "\n", + + # daily diff + #prev = daily_data[m_idx] + #for i in range(1, read_idx): + # now = daily_data[i*m_len + m_idx] + # print (now - prev)/meta["k_interval"], + # if now < prev: + # print i, now, prev + # raw_input() + # prev = now + +def dump_monthly(mon_file, meta, m_len, m_idx, blk_idx): + pos = (blk_idx * (3600*24/meta["k_interval"] + 24*30 + 365) + 3600*24/meta["k_interval"]) * m_len * 4 + dump_data = dump_mod_data(mon_file, pos, 30*24*m_len) + sec = int(time.time()) + read_idx = (sec % (30 *3600 * 24))/3600 + #for i in range(read_idx): + for i in range(30 * 24): + for j in range(m_len): + print dump_data[i*m_len + j], + print "\n", + #print dump_data[i*m_len + m_idx], + #print i, dump_data[i*m_len + m_idx] + +def dump_yearly(mon_file, meta, m_len, m_idx, blk_idx): + pos = (blk_idx * (3600*24/meta["k_interval"] + 24*30 + 365) + 3600*24/meta["k_interval"] + 30 * 24) * m_len * 4 + dump_data = dump_mod_data(mon_file, pos, 365*m_len) + sec = int(time.time()) + read_idx = (sec % (365 * 3600 * 24))/(3600 * 24) + for i in range(read_idx): + print i, dump_data[i*m_len + m_idx] + + +if __name__ == '__main__': + meta = json.load(open(dpath + "meta.json", "r")) + if "os_" == metric[0:3]: + mon_file = dpath + "os_mon" + blk_idx = 0 + m_idx = meta["k_os_metrics"][metric] + m_len = len(meta["k_os_metrics"]) + elif "broker_" == metric[0:7]: + mon_file = dpath + "broker_mon" + blk_idx = meta["k_broker_rrd"][bname + "_idx"] + m_idx = meta["k_broker_metrics"][metric] + m_len = len(meta["k_broker_metrics"]) + elif "db_" == metric[0:3]: + mon_file = dpath + "db_mon" + blk_idx = meta["k_db_rrd"][dbname + "_idx"] + m_idx = meta["k_db_metrics"][metric] + m_len = len(meta["k_db_metrics"]) + elif "vol_" == metric[0:4]: + mon_file = dpath + "vol_mon" + blk_idx = meta["k_db_rrd"][dbname + "_vol"][volname] + m_idx = 0 + m_len = 2 + else: + print "metric is needed" + sys.exit(1) + + if dtype == "daily": + dump_daily(mon_file, meta, m_len, m_idx, blk_idx) + + elif dtype == "monthly": + dump_monthly(mon_file, meta, m_len, m_idx, blk_idx) + elif dtype == "yearly": + dump_yearly(mon_file, meta, m_len, m_idx, blk_idx) + else: + print "dtype is needed" + sys.exit(1) + + diff --git a/server/test/task_test_case_json/getamsenv.txt b/server/test/task_test_case_json/getamsenv.txt new file mode 100644 index 0000000..7cd483e --- /dev/null +++ b/server/test/task_test_case_json/getamsenv.txt @@ -0,0 +1,2 @@ +{"task":"getamsenv", +"token":"cdfb4c5717170c5e9c6856b4d1c61ee8132bcc7d82bd609066ed9ece2554c47f7926f07dd201b6aa"} diff --git a/server/test/task_test_config/am_conf/am.conf b/server/test/task_test_config/am_conf/am.conf new file mode 100644 index 0000000..7f35e03 --- /dev/null +++ b/server/test/task_test_config/am_conf/am.conf @@ -0,0 +1,48 @@ +# cm.conf +# -- ARNIADB database management tool server configuration file +# +# +# When server starts, it looks for the environment variable +# 'ARNIADB_MANAGER' and use it to locate this file. It is assumed that +# 'ARNIADB_MANAGER' is the root directory of all ARNIADB Manager related files. +# + +# +# Port number designation +# +cm_port=8001 +port_job_server=8002 +port_auto_server=8001 +# +# Monitoring interval setting +# +monitor_interval=1 + +# +# Allowing Multiple connection with one ARNIADB Manager user. +# +allow_user_multi_connection=YES +allow_user_multi_connection=NO + +auto_start_broker=yes +auto_start_broker=no + +concurrent_thread_num=8 +concurrent_thread_num=100 + +support_web_manager=1 + +############################### +# diagnostics parameter +############################### +# +# turn on/off diag +# +#execute_diag=ON + +# +# server long query time (sec) +# +server_long_query_time=10 + +error_log=log/arniadb_error.log diff --git a/server/test/task_test_config/am_conf/am.pass b/server/test/task_test_config/am_conf/am.pass new file mode 100644 index 0000000..58ecec1 --- /dev/null +++ b/server/test/task_test_config/am_conf/am.pass @@ -0,0 +1 @@ +admin:6e85f0f80f030451dc9e98851098dfb2 diff --git a/server/test/task_test_config/am_conf/arniadb_broker.conf b/server/test/task_test_config/am_conf/arniadb_broker.conf new file mode 100644 index 0000000..0ef306f --- /dev/null +++ b/server/test/task_test_config/am_conf/arniadb_broker.conf @@ -0,0 +1,50 @@ + +# +# Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. +# +# 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; version 2 of the License. +# +# 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 Street, Fifth Floor, Boston, MA 02110-1301, USA +# + +[broker] +MASTER_SHM_ID =30001 +ADMIN_LOG_FILE =log/broker/arniadb_broker.log + +[%query_editor] +SERVICE =ON +BROKER_PORT =30000 +MIN_NUM_APPL_SERVER =5 +MAX_NUM_APPL_SERVER =40 +APPL_SERVER_SHM_ID =30000 +LOG_DIR =log/broker/sql_log +ERROR_LOG_DIR =log/broker/error_log +SQL_LOG =ON +TIME_TO_KILL =120 +SESSION_TIMEOUT =300 +KEEP_CONNECTION =AUTO +CCI_DEFAULT_AUTOCOMMIT =ON + +[%BROKER1] +SERVICE =ON +BROKER_PORT =33000 +MIN_NUM_APPL_SERVER =5 +MAX_NUM_APPL_SERVER =40 +APPL_SERVER_SHM_ID =33000 +LOG_DIR =log/broker/sql_log +ERROR_LOG_DIR =log/broker/error_log +SQL_LOG =ON +TIME_TO_KILL =120 +SESSION_TIMEOUT =300 +KEEP_CONNECTION =AUTO +CCI_DEFAULT_AUTOCOMMIT =ON + diff --git a/server/test/task_test_config/am_conf/autoaddvoldb.conf b/server/test/task_test_config/am_conf/autoaddvoldb.conf new file mode 100644 index 0000000..7c1c989 --- /dev/null +++ b/server/test/task_test_config/am_conf/autoaddvoldb.conf @@ -0,0 +1,4 @@ +# +demodb ON 2 200 ON 2 200 +demodb ON 2 200 ON 2 200 +destinationdb ON 2 200 ON 2 200 \ No newline at end of file diff --git a/server/test/task_test_config/am_conf/autobackupdb.conf b/server/test/task_test_config/am_conf/autobackupdb.conf new file mode 100644 index 0000000..fe75fa4 --- /dev/null +++ b/server/test/task_test_config/am_conf/autobackupdb.conf @@ -0,0 +1,14 @@ +#db-name bk-id path peroid date time level +testdb1 1 log Weekly Saturday 0 0 ON ON ON ON y y 0 1 +testdb1 1 log Weekly Sunday 0 0 ON ON ON ON y y 0 1 +testdb1 1 log Weekly Monday 0 0 ON ON ON ON y y 0 1 +testdb1 1 log Weekly Tuesday 0 0 ON ON ON ON y y 0 1 +testdb1 1 log Weekly Wednesday 0 0 ON ON ON ON y y 0 1 +testdb1 1 log Weekly Thursday 0 0 ON ON ON ON y y 0 1 +testdb1 1 log Weekly Friday 0 0 ON ON ON ON y y 0 1 +testdb1 1 log Weekly Otherday 0 0 ON ON ON ON y y 0 1 +testdb3 1 log Monthly 1 0 0 ON ON ON ON y y 0 1 +testdb3 1 log Daily nothing 0 0 ON ON ON ON y y 0 1 +testdb3 1 log Hourly 1 0 0 ON ON ON ON y y 0 1 +testdb3 1 log Special 1 0 0 ON ON ON ON y y 0 1 +testdb3 1 log Other 1 0 0 ON ON ON ON y y 0 1 diff --git a/server/test/task_test_config/am_conf/autoexecquery.conf b/server/test/task_test_config/am_conf/autoexecquery.conf new file mode 100644 index 0000000..7d25a11 --- /dev/null +++ b/server/test/task_test_config/am_conf/autoexecquery.conf @@ -0,0 +1,11 @@ +# +test1 1 dba "" admin WEEK SUN "select * form code;" +test1 1 dba 1 admin WEEK MON "select * form code;" +test1 1 dba 1 admin WEEK TUE "select * form code;" +test1 1 dba 1 admin WEEK WED "select * form code;" +test1 1 dba 1 admin WEEK THU "select * form code;" +test1 1 dba 1 admin WEEK FRI "select * form code;" +test1 1 dba 1 yifan WEEK SAT "select * form code;" +test1 1 dba 1 admin ONE MON "select * form code;" +test1 1 dba 1 admin DAY MON "select * form code;" +test1 1 dba 1 admin MONTH 1 "select * form code;" \ No newline at end of file diff --git a/server/test/task_test_config/am_conf/autohistory.conf b/server/test/task_test_config/am_conf/autohistory.conf new file mode 100644 index 0000000..45c5963 --- /dev/null +++ b/server/test/task_test_config/am_conf/autohistory.conf @@ -0,0 +1,2 @@ +#switch start time - end time mem cpu +ON 2012 6 10 0 0 0 2012 6 11 0 0 0 100.0 100.0 \ No newline at end of file diff --git a/server/win/am_admin/am_admin.vcproj b/server/win/am_admin/am_admin.vcproj new file mode 100644 index 0000000..7cf95fd --- /dev/null +++ b/server/win/am_admin/am_admin.vcproj @@ -0,0 +1,411 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/server/win/am_admin/resource.h b/server/win/am_admin/resource.h new file mode 100644 index 0000000..b33ffd3 --- /dev/null +++ b/server/win/am_admin/resource.h @@ -0,0 +1,32 @@ +/* + * Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution. + * + * 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; version 2 of the License. + * + * 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 Street, Fifth Floor, Boston, MA 02110-1301, USA + * + */ + +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by version.rc + +// ´ÙÀ½Àº »õ °³Ã¼¿¡ »ç¿ëÇÒ ±âº»°ªÀÔ´Ï´Ù. +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 101 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/server/win/am_admin/version.rc b/server/win/am_admin/version.rc new file mode 100644 index 0000000..22405bb --- /dev/null +++ b/server/win/am_admin/version.rc @@ -0,0 +1,103 @@ +// Microsoft Visual C++ generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "afxres.h" +#include "../version.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// Çѱ¹¾î resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_KOR) +#ifdef _WIN32 +LANGUAGE LANG_KOREAN, SUBLANG_DEFAULT +#pragma code_page(949) +#endif //_WIN32 + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""afxres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION MAJOR_VERSION,MINOR_VERSION,PATCH_VERSION,BUILD_SERIAL_NUMBER + PRODUCTVERSION MAJOR_VERSION,MINOR_VERSION,PATCH_VERSION,BUILD_SERIAL_NUMBER + FILEFLAGSMASK 0x17L +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x4L + FILETYPE 0x1L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "041204b0" + BEGIN + VALUE "CompanyName", "Search Solution Corporation" + VALUE "FileDescription", "ARNIADB Management Server" + VALUE "FileVersion", VERSION_STRING + VALUE "InternalName", "ARNIADB Management Server" + VALUE "LegalCopyright", "Copyright (C) 2008 Search Solution Corporation. All rights reserved by Search Solution." + VALUE "OriginalFilename", "cm_admin.exe" + VALUE "ProductName", "ARNIADB Management Server" + VALUE "ProductVersion", VERSION_STRING + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x412, 1200 + END +END + +#endif // Çѱ¹¾î resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/server/win/amserver.sln b/server/win/amserver.sln new file mode 100644 index 0000000..ce5210f --- /dev/null +++ b/server/win/amserver.sln @@ -0,0 +1,63 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "install", "install\install.vcproj", "{4767EEE0-220E-4FDE-8788-0E8BAE173CE1}" + ProjectSection(ProjectDependencies) = postProject + {9A6A101D-4569-4BC7-9010-9E4554D7E945} = {9A6A101D-4569-4BC7-9010-9E4554D7E945} + {1E764BE7-D450-4166-8F62-4FD1967F5AD8} = {1E764BE7-D450-4166-8F62-4FD1967F5AD8} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "arn_manager", "arn_manager\arn_manager.vcproj", "{1E764BE7-D450-4166-8F62-4FD1967F5AD8}" + ProjectSection(ProjectDependencies) = postProject + {FB6ECD68-F1C6-42A7-8EB7-5BCBF151D718} = {FB6ECD68-F1C6-42A7-8EB7-5BCBF151D718} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "jsoncpp", "..\external\jsoncpp\vs\jsoncpp.vcproj", "{FB6ECD68-F1C6-42A7-8EB7-5BCBF151D718}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "cm_admin", "cm_admin\cm_admin.vcproj", "{9A6A101D-4569-4BC7-9010-9E4554D7E945}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {4767EEE0-220E-4FDE-8788-0E8BAE173CE1}.Debug|Win32.ActiveCfg = Debug|Win32 + {4767EEE0-220E-4FDE-8788-0E8BAE173CE1}.Debug|Win32.Build.0 = Debug|Win32 + {4767EEE0-220E-4FDE-8788-0E8BAE173CE1}.Debug|x64.ActiveCfg = Debug|x64 + {4767EEE0-220E-4FDE-8788-0E8BAE173CE1}.Debug|x64.Build.0 = Debug|x64 + {4767EEE0-220E-4FDE-8788-0E8BAE173CE1}.Release|Win32.ActiveCfg = Release|Win32 + {4767EEE0-220E-4FDE-8788-0E8BAE173CE1}.Release|Win32.Build.0 = Release|Win32 + {4767EEE0-220E-4FDE-8788-0E8BAE173CE1}.Release|x64.ActiveCfg = Release|x64 + {4767EEE0-220E-4FDE-8788-0E8BAE173CE1}.Release|x64.Build.0 = Release|x64 + {1E764BE7-D450-4166-8F62-4FD1967F5AD8}.Debug|Win32.ActiveCfg = Debug|Win32 + {1E764BE7-D450-4166-8F62-4FD1967F5AD8}.Debug|Win32.Build.0 = Debug|Win32 + {1E764BE7-D450-4166-8F62-4FD1967F5AD8}.Debug|x64.ActiveCfg = Debug|x64 + {1E764BE7-D450-4166-8F62-4FD1967F5AD8}.Debug|x64.Build.0 = Debug|x64 + {1E764BE7-D450-4166-8F62-4FD1967F5AD8}.Release|Win32.ActiveCfg = Release|Win32 + {1E764BE7-D450-4166-8F62-4FD1967F5AD8}.Release|Win32.Build.0 = Release|Win32 + {1E764BE7-D450-4166-8F62-4FD1967F5AD8}.Release|x64.ActiveCfg = Release|x64 + {1E764BE7-D450-4166-8F62-4FD1967F5AD8}.Release|x64.Build.0 = Release|x64 + {FB6ECD68-F1C6-42A7-8EB7-5BCBF151D718}.Debug|Win32.ActiveCfg = Debug|Win32 + {FB6ECD68-F1C6-42A7-8EB7-5BCBF151D718}.Debug|Win32.Build.0 = Debug|Win32 + {FB6ECD68-F1C6-42A7-8EB7-5BCBF151D718}.Debug|x64.ActiveCfg = Debug|x64 + {FB6ECD68-F1C6-42A7-8EB7-5BCBF151D718}.Debug|x64.Build.0 = Debug|x64 + {FB6ECD68-F1C6-42A7-8EB7-5BCBF151D718}.Release|Win32.ActiveCfg = Release|Win32 + {FB6ECD68-F1C6-42A7-8EB7-5BCBF151D718}.Release|Win32.Build.0 = Release|Win32 + {FB6ECD68-F1C6-42A7-8EB7-5BCBF151D718}.Release|x64.ActiveCfg = Release|x64 + {FB6ECD68-F1C6-42A7-8EB7-5BCBF151D718}.Release|x64.Build.0 = Release|x64 + {9A6A101D-4569-4BC7-9010-9E4554D7E945}.Debug|Win32.ActiveCfg = Debug|Win32 + {9A6A101D-4569-4BC7-9010-9E4554D7E945}.Debug|Win32.Build.0 = Debug|Win32 + {9A6A101D-4569-4BC7-9010-9E4554D7E945}.Debug|x64.ActiveCfg = Debug|x64 + {9A6A101D-4569-4BC7-9010-9E4554D7E945}.Debug|x64.Build.0 = Debug|x64 + {9A6A101D-4569-4BC7-9010-9E4554D7E945}.Release|Win32.ActiveCfg = Release|Win32 + {9A6A101D-4569-4BC7-9010-9E4554D7E945}.Release|Win32.Build.0 = Release|Win32 + {9A6A101D-4569-4BC7-9010-9E4554D7E945}.Release|x64.ActiveCfg = Release|x64 + {9A6A101D-4569-4BC7-9010-9E4554D7E945}.Release|x64.Build.0 = Release|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal From a149489c9bfdd5256d305ff730a61e8c3f676a6d Mon Sep 17 00:00:00 2001 From: Mihai Serban Date: Sat, 16 Oct 2021 17:19:52 +0300 Subject: [PATCH 04/12] add ams --- docs/api/README.md | 4 +- server/amserver/Makefile.am | 58 +-- server/amserver/conf/Makefile.am | 2 +- server/amserver/conf/am.conf | 6 +- server/build_server.bat | 2 +- server/configure.ac | 2 +- .../openssl/aix_64/include/openssl/des.h | 2 +- .../openssl/aix_64/include/openssl/des_old.h | 4 +- .../openssl/linux_32/include/openssl/des.h | 2 +- .../linux_32/include/openssl/des_old.h | 4 +- .../openssl/linux_32/include/openssl/evp.h | 32 +- .../openssl/linux_32/include/openssl/srtp.h | 4 +- .../openssl/linux_32/include/openssl/tls1.h | 80 ++-- .../openssl/linux_64/include/openssl/evp.h | 42 +- .../openssl/linux_64/include/openssl/evperr.h | 10 +- .../openssl/linux_64/include/openssl/srtp.h | 4 +- .../openssl/linux_64/include/openssl/ssl.h | 10 +- .../openssl/linux_64/include/openssl/tls1.h | 376 +++++++++--------- .../openssl/win_32/include/openssl/des.h | 2 +- .../openssl/win_32/include/openssl/des_old.h | 4 +- .../openssl/win_32/include/openssl/evp.h | 32 +- .../openssl/win_32/include/openssl/srtp.h | 4 +- .../openssl/win_32/include/openssl/tls1.h | 80 ++-- .../openssl/win_64/include/openssl/des.h | 2 +- .../openssl/win_64/include/openssl/des_old.h | 4 +- .../openssl/win_64/include/openssl/evp.h | 32 +- .../openssl/win_64/include/openssl/srtp.h | 4 +- .../openssl/win_64/include/openssl/tls1.h | 80 ++-- server/hudsonbuild.cmd | 2 +- server/src/am_auto_task.cpp | 16 +- server/src/am_auto_task.h | 12 +- server/src/am_autojob.cpp | 20 +- server/src/am_autojob.h | 10 +- server/src/am_cci_interface.cpp | 18 +- server/src/am_cci_interface.h | 4 +- server/src/am_cmd.cpp | 10 +- server/src/am_cmd_exec.cpp | 14 +- server/src/am_cmd_exec.h | 12 +- server/src/am_cmd_task.cpp | 18 +- server/src/am_cmd_task.h | 8 +- server/src/am_cmd_util.cpp | 12 +- server/src/am_cmd_util.h | 18 +- server/src/am_config.cpp | 24 +- server/src/am_config.h | 12 +- server/src/am_connect_info.cpp | 10 +- server/src/am_connect_info.h | 8 +- server/src/am_http_server.cpp | 6 +- server/src/am_http_server.h | 2 +- server/src/am_httpd.cpp | 42 +- server/src/am_job_task.cpp | 266 ++++++------- server/src/am_job_task.h | 10 +- server/src/am_log.h | 6 +- server/src/am_mailer.h | 6 +- server/src/am_mon_stat.cpp | 62 +-- server/src/am_mon_stat.h | 20 +- server/src/am_porting.h | 8 +- server/src/am_server_autoupdate.cpp | 20 +- server/src/am_server_autoupdate.h | 4 +- server/src/am_server_extend_interface.cpp | 40 +- server/src/am_server_extend_interface.h | 6 +- server/src/am_server_interface.cpp | 72 ++-- server/src/am_server_interface.h | 18 +- server/src/am_server_stat.c | 10 +- server/src/am_server_stat.h | 12 +- server/src/am_server_util.cpp | 28 +- server/src/am_server_util.h | 16 +- server/src/am_text_encryption.c | 4 +- server/src/am_text_encryption.h | 8 +- server/src/am_user.cpp | 10 +- server/src/am_user.h | 8 +- server/src/am_win_wsa.h | 8 +- server/test/Makefile | 8 +- server/test/task_test_case/setsysparam_cmconf | 2 +- .../setsysparam_cmconf.txt | 4 +- server/test/task_test_config/am_conf/am.conf | 2 +- server/test/test_tasks.php | 8 +- server/test/test_tasks.py | 4 +- server/win/am_admin/am_admin.vcproj | 32 +- server/win/am_admin/version.rc | 2 +- server/win/amserver.sln | 2 +- server/win/arn_manager/arn_manager.vcproj | 34 +- server/win/install/install.bat | 2 +- 82 files changed, 954 insertions(+), 954 deletions(-) diff --git a/docs/api/README.md b/docs/api/README.md index 7b38248..96a4b54 100644 --- a/docs/api/README.md +++ b/docs/api/README.md @@ -13,7 +13,7 @@ AMS Architecture ## Writing HTTP Application Program -AMS http interface is REST-like interface, client can POST JSON-format request to url `http://ams_ip:ams_port/cm_api`, and receive the execution result. +AMS http interface is REST-like interface, client can POST JSON-format request to url `http://ams_ip:ams_port/am_api`, and receive the execution result. The basic steps used for writing programs are as follows. First client must log in AMS with DBMT user name and password. If client login success, AMS will return a token which will be used in following request. The steps are implemented in example codes. @@ -29,7 +29,7 @@ body = "{\"task\":\"login\",\ headers = {"Accept": "text/plain;charset=utf-8"} conn = http.client.HTTPConnection("localhost", 8003) -conn.request("POST", "/cm_api", body, headers) +conn.request("POST", "/am_api", body, headers) r = conn.getresponse() print (r.read()) ``` diff --git a/server/amserver/Makefile.am b/server/amserver/Makefile.am index df2ccc0..b1e6483 100644 --- a/server/amserver/Makefile.am +++ b/server/amserver/Makefile.am @@ -27,36 +27,36 @@ INCLUDES = @SRC_INC@ DEFS += @SYS_DEFS@ @VERSION_DEFS@ @COMMON_DEFS@ LIBS += @SYS_LIBS@ -bin_PROGRAMS = cm_admin arn_manager - -cm_admin_SOURCES = \ - $(DBMT_DIR)/cm_text_encryption.c \ - $(DBMT_DIR)/cm_config.cpp \ - $(DBMT_DIR)/cm_server_util.cpp \ - $(DBMT_DIR)/cm_user.cpp \ - $(DBMT_DIR)/cm_cmd.cpp \ - $(DBMT_DIR)/cm_cmd_util.cpp \ - $(DBMT_DIR)/cm_connect_info.cpp \ - $(DBMT_DIR)/cm_cmd_task.cpp -cm_admin_CFLAGS = -D_FILE_OFFSET_BITS=64 -cm_admin_LDFLAGS = @CMDEP_LIB@ -D_FILE_OFFSET_BITS=64 +bin_PROGRAMS = am_admin arn_manager + +am_admin_SOURCES = \ + $(DBMT_DIR)/am_text_encryption.c \ + $(DBMT_DIR)/am_config.cpp \ + $(DBMT_DIR)/am_server_util.cpp \ + $(DBMT_DIR)/am_user.cpp \ + $(DBMT_DIR)/am_cmd.cpp \ + $(DBMT_DIR)/am_cmd_util.cpp \ + $(DBMT_DIR)/am_connect_info.cpp \ + $(DBMT_DIR)/am_cmd_task.cpp +am_admin_CFLAGS = -D_FILE_OFFSET_BITS=64 +am_admin_LDFLAGS = @CMDEP_LIB@ -D_FILE_OFFSET_BITS=64 arn_manager_SOURCES = \ - $(DBMT_DIR)/cm_server_util.cpp \ - $(DBMT_DIR)/cm_autojob.cpp \ - $(DBMT_DIR)/cm_text_encryption.c \ - $(DBMT_DIR)/cm_config.cpp \ - $(DBMT_DIR)/cm_job_task.cpp \ - $(DBMT_DIR)/cm_cmd_exec.cpp \ - $(DBMT_DIR)/cm_connect_info.cpp \ - $(DBMT_DIR)/cm_auto_task.cpp \ - $(DBMT_DIR)/cm_httpd.cpp \ - $(DBMT_DIR)/cm_mon_stat.cpp \ - $(DBMT_DIR)/cm_user.cpp \ - $(DBMT_DIR)/cm_http_server.cpp \ - $(DBMT_DIR)/cm_server_extend_interface.cpp \ - $(DBMT_DIR)/cm_server_interface.cpp \ - $(DBMT_DIR)/cm_cci_interface.cpp \ - $(DBMT_DIR)/cm_server_autoupdate.cpp + $(DBMT_DIR)/am_server_util.cpp \ + $(DBMT_DIR)/am_autojob.cpp \ + $(DBMT_DIR)/am_text_encryption.c \ + $(DBMT_DIR)/am_config.cpp \ + $(DBMT_DIR)/am_job_task.cpp \ + $(DBMT_DIR)/am_cmd_exec.cpp \ + $(DBMT_DIR)/am_connect_info.cpp \ + $(DBMT_DIR)/am_auto_task.cpp \ + $(DBMT_DIR)/am_httpd.cpp \ + $(DBMT_DIR)/am_mon_stat.cpp \ + $(DBMT_DIR)/am_user.cpp \ + $(DBMT_DIR)/am_http_server.cpp \ + $(DBMT_DIR)/am_server_extend_interface.cpp \ + $(DBMT_DIR)/am_server_interface.cpp \ + $(DBMT_DIR)/am_cci_interface.cpp \ + $(DBMT_DIR)/am_server_autoupdate.cpp arn_manager_CPPFLAGS = $(AM_CFLAGS) -DFSERVER_SLAVE -DJSON_SUPPORT -DEVENT__HAVE_OPENSSL -D_FILE_OFFSET_BITS=64 @EXTERNAL_INC@ arn_manager_LDFLAGS = -larniadbcs @AMSTAT_LIB@ @CMDEP_LIB@ @EXTERNAL_LIB@ -lrt -lcascci diff --git a/server/amserver/conf/Makefile.am b/server/amserver/conf/Makefile.am index cb61221..a24c87b 100644 --- a/server/amserver/conf/Makefile.am +++ b/server/amserver/conf/Makefile.am @@ -19,5 +19,5 @@ confdir = ${prefix}/conf dist_conf_DATA = autohistory.conf cmdb.pass autoaddvoldb.conf diagactivitytemplate.conf autobackupdb.conf cm.conf diagstatustemplate.conf autoexecquery.conf cm.pass \ - cm_ssl_cert.crt cm_ssl_cert.key + am_ssl_cert.crt am_ssl_cert.key diff --git a/server/amserver/conf/am.conf b/server/amserver/conf/am.conf index 86af47a..a5632d8 100644 --- a/server/amserver/conf/am.conf +++ b/server/amserver/conf/am.conf @@ -13,15 +13,15 @@ # # Port number designation # A port for the connection between ARNIADB Manager server and Client. -# ARNIADB Manager server uses the value cm_port. +# ARNIADB Manager server uses the value am_port. # The default value is 8001. # -cm_port=8001 +am_port=8001 # # AMS Process Monitoring interval setting # -cm_process_monitor_interval=5 +am_process_monitor_interval=5 # # Allowing Multiple connection with one ARNIADB Manager user. diff --git a/server/build_server.bat b/server/build_server.bat index 2d12219..3a97cc2 100644 --- a/server/build_server.bat +++ b/server/build_server.bat @@ -4,7 +4,7 @@ REM prepare vc environment call "%VS90COMNTOOLS%vsvars32.bat" -echo Start build cm_server ... +echo Start build am_server ... cd win set arniadb_libdir=%arniadb_libdir% diff --git a/server/configure.ac b/server/configure.ac index 50d0176..090dc86 100644 --- a/server/configure.ac +++ b/server/configure.ac @@ -6,7 +6,7 @@ AC_INIT([ARNIADB 2008], RELEASE, , arniadb) AC_PREFIX_DEFAULT("${ARNIADB}") -AC_CONFIG_SRCDIR([src/cm_autojob.cpp]) +AC_CONFIG_SRCDIR([src/am_autojob.cpp]) AC_CONFIG_AUX_DIR(config) AC_CONFIG_HEADERS([config.h]) diff --git a/server/external/openssl/aix_64/include/openssl/des.h b/server/external/openssl/aix_64/include/openssl/des.h index d9fc22c..a65e4d7 100644 --- a/server/external/openssl/aix_64/include/openssl/des.h +++ b/server/external/openssl/aix_64/include/openssl/des.h @@ -193,7 +193,7 @@ void DES_ede3_cbc_encrypt(const unsigned char *input,unsigned char *output, long length, DES_key_schedule *ks1,DES_key_schedule *ks2, DES_key_schedule *ks3,DES_cblock *ivec,int enc); -void DES_ede3_cbcm_encrypt(const unsigned char *in,unsigned char *out, +void DES_ede3_cbam_encrypt(const unsigned char *in,unsigned char *out, long length, DES_key_schedule *ks1,DES_key_schedule *ks2, DES_key_schedule *ks3, diff --git a/server/external/openssl/aix_64/include/openssl/des_old.h b/server/external/openssl/aix_64/include/openssl/des_old.h index fe8451c..b816059 100644 --- a/server/external/openssl/aix_64/include/openssl/des_old.h +++ b/server/external/openssl/aix_64/include/openssl/des_old.h @@ -155,8 +155,8 @@ typedef struct _ossl_old_des_ks_struct DES_ecb3_encrypt((i),(o),&(k1),&(k2),&(k3),(e)) #define des_ede3_cbc_encrypt(i,o,l,k1,k2,k3,iv,e)\ DES_ede3_cbc_encrypt((i),(o),(l),&(k1),&(k2),&(k3),(iv),(e)) -#define des_ede3_cbcm_encrypt(i,o,l,k1,k2,k3,iv1,iv2,e)\ - DES_ede3_cbcm_encrypt((i),(o),(l),&(k1),&(k2),&(k3),(iv1),(iv2),(e)) +#define des_ede3_cbam_encrypt(i,o,l,k1,k2,k3,iv1,iv2,e)\ + DES_ede3_cbam_encrypt((i),(o),(l),&(k1),&(k2),&(k3),(iv1),(iv2),(e)) #define des_ede3_cfb64_encrypt(i,o,l,k1,k2,k3,iv,n,e)\ DES_ede3_cfb64_encrypt((i),(o),(l),&(k1),&(k2),&(k3),(iv),(n),(e)) #define des_ede3_ofb64_encrypt(i,o,l,k1,k2,k3,iv,n)\ diff --git a/server/external/openssl/linux_32/include/openssl/des.h b/server/external/openssl/linux_32/include/openssl/des.h index 1eaedcb..3cbac90 100644 --- a/server/external/openssl/linux_32/include/openssl/des.h +++ b/server/external/openssl/linux_32/include/openssl/des.h @@ -177,7 +177,7 @@ void DES_ede3_cbc_encrypt(const unsigned char *input,unsigned char *output, long length, DES_key_schedule *ks1,DES_key_schedule *ks2, DES_key_schedule *ks3,DES_cblock *ivec,int enc); -void DES_ede3_cbcm_encrypt(const unsigned char *in,unsigned char *out, +void DES_ede3_cbam_encrypt(const unsigned char *in,unsigned char *out, long length, DES_key_schedule *ks1,DES_key_schedule *ks2, DES_key_schedule *ks3, diff --git a/server/external/openssl/linux_32/include/openssl/des_old.h b/server/external/openssl/linux_32/include/openssl/des_old.h index 2b2c372..b07f0cd 100644 --- a/server/external/openssl/linux_32/include/openssl/des_old.h +++ b/server/external/openssl/linux_32/include/openssl/des_old.h @@ -139,8 +139,8 @@ typedef struct _ossl_old_des_ks_struct DES_ecb3_encrypt((i),(o),&(k1),&(k2),&(k3),(e)) #define des_ede3_cbc_encrypt(i,o,l,k1,k2,k3,iv,e)\ DES_ede3_cbc_encrypt((i),(o),(l),&(k1),&(k2),&(k3),(iv),(e)) -#define des_ede3_cbcm_encrypt(i,o,l,k1,k2,k3,iv1,iv2,e)\ - DES_ede3_cbcm_encrypt((i),(o),(l),&(k1),&(k2),&(k3),(iv1),(iv2),(e)) +#define des_ede3_cbam_encrypt(i,o,l,k1,k2,k3,iv1,iv2,e)\ + DES_ede3_cbam_encrypt((i),(o),(l),&(k1),&(k2),&(k3),(iv1),(iv2),(e)) #define des_ede3_cfb64_encrypt(i,o,l,k1,k2,k3,iv,n,e)\ DES_ede3_cfb64_encrypt((i),(o),(l),&(k1),&(k2),&(k3),(iv),(n),(e)) #define des_ede3_ofb64_encrypt(i,o,l,k1,k2,k3,iv,n)\ diff --git a/server/external/openssl/linux_32/include/openssl/evp.h b/server/external/openssl/linux_32/include/openssl/evp.h index d642f1d..172614a 100644 --- a/server/external/openssl/linux_32/include/openssl/evp.h +++ b/server/external/openssl/linux_32/include/openssl/evp.h @@ -329,8 +329,8 @@ struct evp_cipher_st #define EVP_CIPH_CFB_MODE 0x3 #define EVP_CIPH_OFB_MODE 0x4 #define EVP_CIPH_CTR_MODE 0x5 -#define EVP_CIPH_GCM_MODE 0x6 -#define EVP_CIPH_CCM_MODE 0x7 +#define EVP_CIPH_GAM_MODE 0x6 +#define EVP_CIPH_CAM_MODE 0x7 #define EVP_CIPH_XTS_MODE 0x10001 #define EVP_CIPH_MODE 0xF0007 /* Set if variable length cipher */ @@ -374,16 +374,16 @@ struct evp_cipher_st #define EVP_CTRL_RAND_KEY 0x6 #define EVP_CTRL_PBE_PRF_NID 0x7 #define EVP_CTRL_COPY 0x8 -#define EVP_CTRL_GCM_SET_IVLEN 0x9 -#define EVP_CTRL_GCM_GET_TAG 0x10 -#define EVP_CTRL_GCM_SET_TAG 0x11 -#define EVP_CTRL_GCM_SET_IV_FIXED 0x12 -#define EVP_CTRL_GCM_IV_GEN 0x13 -#define EVP_CTRL_CCM_SET_IVLEN EVP_CTRL_GCM_SET_IVLEN -#define EVP_CTRL_CCM_GET_TAG EVP_CTRL_GCM_GET_TAG -#define EVP_CTRL_CCM_SET_TAG EVP_CTRL_GCM_SET_TAG -#define EVP_CTRL_CCM_SET_L 0x14 -#define EVP_CTRL_CCM_SET_MSGLEN 0x15 +#define EVP_CTRL_GAM_SET_IVLEN 0x9 +#define EVP_CTRL_GAM_GET_TAG 0x10 +#define EVP_CTRL_GAM_SET_TAG 0x11 +#define EVP_CTRL_GAM_SET_IV_FIXED 0x12 +#define EVP_CTRL_GAM_IV_GEN 0x13 +#define EVP_CTRL_CAM_SET_IVLEN EVP_CTRL_GAM_SET_IVLEN +#define EVP_CTRL_CAM_GET_TAG EVP_CTRL_GAM_GET_TAG +#define EVP_CTRL_CAM_SET_TAG EVP_CTRL_GAM_SET_TAG +#define EVP_CTRL_CAM_SET_L 0x14 +#define EVP_CTRL_CAM_SET_MSGLEN 0x15 /* AEAD cipher deduces payload length and returns number of bytes * required to store MAC and eventual padding. Subsequent call to * EVP_Cipher even appends/verifies MAC. @@ -392,15 +392,15 @@ struct evp_cipher_st /* Used by composite AEAD ciphers, no-op in GCM, CCM... */ #define EVP_CTRL_AEAD_SET_MAC_KEY 0x17 /* Set the GCM invocation field, decrypt only */ -#define EVP_CTRL_GCM_SET_IV_INV 0x18 +#define EVP_CTRL_GAM_SET_IV_INV 0x18 /* GCM TLS constants */ /* Length of fixed part of IV derived from PRF */ -#define EVP_GCM_TLS_FIXED_IV_LEN 4 +#define EVP_GAM_TLS_FIXED_IV_LEN 4 /* Length of explicit part of IV part of TLS records */ -#define EVP_GCM_TLS_EXPLICIT_IV_LEN 8 +#define EVP_GAM_TLS_EXPLICIT_IV_LEN 8 /* Length of tag for TLS */ -#define EVP_GCM_TLS_TAG_LEN 16 +#define EVP_GAM_TLS_TAG_LEN 16 typedef struct evp_cipher_info_st { diff --git a/server/external/openssl/linux_32/include/openssl/srtp.h b/server/external/openssl/linux_32/include/openssl/srtp.h index c0cf33e..288aca3 100644 --- a/server/external/openssl/linux_32/include/openssl/srtp.h +++ b/server/external/openssl/linux_32/include/openssl/srtp.h @@ -123,8 +123,8 @@ extern "C" { #endif -#define SRTP_AES128_CM_SHA1_80 0x0001 -#define SRTP_AES128_CM_SHA1_32 0x0002 +#define SRTP_AES128_AM_SHA1_80 0x0001 +#define SRTP_AES128_AM_SHA1_32 0x0002 #define SRTP_AES128_F8_SHA1_80 0x0003 #define SRTP_AES128_F8_SHA1_32 0x0004 #define SRTP_NULL_SHA1_80 0x0005 diff --git a/server/external/openssl/linux_32/include/openssl/tls1.h b/server/external/openssl/linux_32/include/openssl/tls1.h index c992091..fbf6c80 100644 --- a/server/external/openssl/linux_32/include/openssl/tls1.h +++ b/server/external/openssl/linux_32/include/openssl/tls1.h @@ -449,18 +449,18 @@ SSL_CTX_callback_ctrl(ssl,SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB,(void (*)(void))cb) #define TLS1_CK_ADH_WITH_SEED_SHA 0x0300009B /* TLS v1.2 GCM ciphersuites from RFC5288 */ -#define TLS1_CK_RSA_WITH_AES_128_GCM_SHA256 0x0300009C -#define TLS1_CK_RSA_WITH_AES_256_GCM_SHA384 0x0300009D -#define TLS1_CK_DHE_RSA_WITH_AES_128_GCM_SHA256 0x0300009E -#define TLS1_CK_DHE_RSA_WITH_AES_256_GCM_SHA384 0x0300009F -#define TLS1_CK_DH_RSA_WITH_AES_128_GCM_SHA256 0x030000A0 -#define TLS1_CK_DH_RSA_WITH_AES_256_GCM_SHA384 0x030000A1 -#define TLS1_CK_DHE_DSS_WITH_AES_128_GCM_SHA256 0x030000A2 -#define TLS1_CK_DHE_DSS_WITH_AES_256_GCM_SHA384 0x030000A3 -#define TLS1_CK_DH_DSS_WITH_AES_128_GCM_SHA256 0x030000A4 -#define TLS1_CK_DH_DSS_WITH_AES_256_GCM_SHA384 0x030000A5 -#define TLS1_CK_ADH_WITH_AES_128_GCM_SHA256 0x030000A6 -#define TLS1_CK_ADH_WITH_AES_256_GCM_SHA384 0x030000A7 +#define TLS1_CK_RSA_WITH_AES_128_GAM_SHA256 0x0300009C +#define TLS1_CK_RSA_WITH_AES_256_GAM_SHA384 0x0300009D +#define TLS1_CK_DHE_RSA_WITH_AES_128_GAM_SHA256 0x0300009E +#define TLS1_CK_DHE_RSA_WITH_AES_256_GAM_SHA384 0x0300009F +#define TLS1_CK_DH_RSA_WITH_AES_128_GAM_SHA256 0x030000A0 +#define TLS1_CK_DH_RSA_WITH_AES_256_GAM_SHA384 0x030000A1 +#define TLS1_CK_DHE_DSS_WITH_AES_128_GAM_SHA256 0x030000A2 +#define TLS1_CK_DHE_DSS_WITH_AES_256_GAM_SHA384 0x030000A3 +#define TLS1_CK_DH_DSS_WITH_AES_128_GAM_SHA256 0x030000A4 +#define TLS1_CK_DH_DSS_WITH_AES_256_GAM_SHA384 0x030000A5 +#define TLS1_CK_ADH_WITH_AES_128_GAM_SHA256 0x030000A6 +#define TLS1_CK_ADH_WITH_AES_256_GAM_SHA384 0x030000A7 /* ECC ciphersuites from draft-ietf-tls-ecc-12.txt with changes soon to be in draft 13 */ #define TLS1_CK_ECDH_ECDSA_WITH_NULL_SHA 0x0300C001 @@ -516,14 +516,14 @@ SSL_CTX_callback_ctrl(ssl,SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB,(void (*)(void))cb) #define TLS1_CK_ECDH_RSA_WITH_AES_256_SHA384 0x0300C02A /* ECDH GCM based ciphersuites from RFC5289 */ -#define TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 0x0300C02B -#define TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 0x0300C02C -#define TLS1_CK_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 0x0300C02D -#define TLS1_CK_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 0x0300C02E -#define TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256 0x0300C02F -#define TLS1_CK_ECDHE_RSA_WITH_AES_256_GCM_SHA384 0x0300C030 -#define TLS1_CK_ECDH_RSA_WITH_AES_128_GCM_SHA256 0x0300C031 -#define TLS1_CK_ECDH_RSA_WITH_AES_256_GCM_SHA384 0x0300C032 +#define TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GAM_SHA256 0x0300C02B +#define TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GAM_SHA384 0x0300C02C +#define TLS1_CK_ECDH_ECDSA_WITH_AES_128_GAM_SHA256 0x0300C02D +#define TLS1_CK_ECDH_ECDSA_WITH_AES_256_GAM_SHA384 0x0300C02E +#define TLS1_CK_ECDHE_RSA_WITH_AES_128_GAM_SHA256 0x0300C02F +#define TLS1_CK_ECDHE_RSA_WITH_AES_256_GAM_SHA384 0x0300C030 +#define TLS1_CK_ECDH_RSA_WITH_AES_128_GAM_SHA256 0x0300C031 +#define TLS1_CK_ECDH_RSA_WITH_AES_256_GAM_SHA384 0x0300C032 /* XXX * Inconsistency alert: @@ -642,18 +642,18 @@ SSL_CTX_callback_ctrl(ssl,SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB,(void (*)(void))cb) #define TLS1_TXT_ADH_WITH_AES_256_SHA256 "ADH-AES256-SHA256" /* TLS v1.2 GCM ciphersuites from RFC5288 */ -#define TLS1_TXT_RSA_WITH_AES_128_GCM_SHA256 "AES128-GCM-SHA256" -#define TLS1_TXT_RSA_WITH_AES_256_GCM_SHA384 "AES256-GCM-SHA384" -#define TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256 "DHE-RSA-AES128-GCM-SHA256" -#define TLS1_TXT_DHE_RSA_WITH_AES_256_GCM_SHA384 "DHE-RSA-AES256-GCM-SHA384" -#define TLS1_TXT_DH_RSA_WITH_AES_128_GCM_SHA256 "DH-RSA-AES128-GCM-SHA256" -#define TLS1_TXT_DH_RSA_WITH_AES_256_GCM_SHA384 "DH-RSA-AES256-GCM-SHA384" -#define TLS1_TXT_DHE_DSS_WITH_AES_128_GCM_SHA256 "DHE-DSS-AES128-GCM-SHA256" -#define TLS1_TXT_DHE_DSS_WITH_AES_256_GCM_SHA384 "DHE-DSS-AES256-GCM-SHA384" -#define TLS1_TXT_DH_DSS_WITH_AES_128_GCM_SHA256 "DH-DSS-AES128-GCM-SHA256" -#define TLS1_TXT_DH_DSS_WITH_AES_256_GCM_SHA384 "DH-DSS-AES256-GCM-SHA384" -#define TLS1_TXT_ADH_WITH_AES_128_GCM_SHA256 "ADH-AES128-GCM-SHA256" -#define TLS1_TXT_ADH_WITH_AES_256_GCM_SHA384 "ADH-AES256-GCM-SHA384" +#define TLS1_TXT_RSA_WITH_AES_128_GAM_SHA256 "AES128-GCM-SHA256" +#define TLS1_TXT_RSA_WITH_AES_256_GAM_SHA384 "AES256-GCM-SHA384" +#define TLS1_TXT_DHE_RSA_WITH_AES_128_GAM_SHA256 "DHE-RSA-AES128-GCM-SHA256" +#define TLS1_TXT_DHE_RSA_WITH_AES_256_GAM_SHA384 "DHE-RSA-AES256-GCM-SHA384" +#define TLS1_TXT_DH_RSA_WITH_AES_128_GAM_SHA256 "DH-RSA-AES128-GCM-SHA256" +#define TLS1_TXT_DH_RSA_WITH_AES_256_GAM_SHA384 "DH-RSA-AES256-GCM-SHA384" +#define TLS1_TXT_DHE_DSS_WITH_AES_128_GAM_SHA256 "DHE-DSS-AES128-GCM-SHA256" +#define TLS1_TXT_DHE_DSS_WITH_AES_256_GAM_SHA384 "DHE-DSS-AES256-GCM-SHA384" +#define TLS1_TXT_DH_DSS_WITH_AES_128_GAM_SHA256 "DH-DSS-AES128-GCM-SHA256" +#define TLS1_TXT_DH_DSS_WITH_AES_256_GAM_SHA384 "DH-DSS-AES256-GCM-SHA384" +#define TLS1_TXT_ADH_WITH_AES_128_GAM_SHA256 "ADH-AES128-GCM-SHA256" +#define TLS1_TXT_ADH_WITH_AES_256_GAM_SHA384 "ADH-AES256-GCM-SHA384" /* ECDH HMAC based ciphersuites from RFC5289 */ @@ -667,14 +667,14 @@ SSL_CTX_callback_ctrl(ssl,SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB,(void (*)(void))cb) #define TLS1_TXT_ECDH_RSA_WITH_AES_256_SHA384 "ECDH-RSA-AES256-SHA384" /* ECDH GCM based ciphersuites from RFC5289 */ -#define TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 "ECDHE-ECDSA-AES128-GCM-SHA256" -#define TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 "ECDHE-ECDSA-AES256-GCM-SHA384" -#define TLS1_TXT_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 "ECDH-ECDSA-AES128-GCM-SHA256" -#define TLS1_TXT_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 "ECDH-ECDSA-AES256-GCM-SHA384" -#define TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 "ECDHE-RSA-AES128-GCM-SHA256" -#define TLS1_TXT_ECDHE_RSA_WITH_AES_256_GCM_SHA384 "ECDHE-RSA-AES256-GCM-SHA384" -#define TLS1_TXT_ECDH_RSA_WITH_AES_128_GCM_SHA256 "ECDH-RSA-AES128-GCM-SHA256" -#define TLS1_TXT_ECDH_RSA_WITH_AES_256_GCM_SHA384 "ECDH-RSA-AES256-GCM-SHA384" +#define TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_GAM_SHA256 "ECDHE-ECDSA-AES128-GCM-SHA256" +#define TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_GAM_SHA384 "ECDHE-ECDSA-AES256-GCM-SHA384" +#define TLS1_TXT_ECDH_ECDSA_WITH_AES_128_GAM_SHA256 "ECDH-ECDSA-AES128-GCM-SHA256" +#define TLS1_TXT_ECDH_ECDSA_WITH_AES_256_GAM_SHA384 "ECDH-ECDSA-AES256-GCM-SHA384" +#define TLS1_TXT_ECDHE_RSA_WITH_AES_128_GAM_SHA256 "ECDHE-RSA-AES128-GCM-SHA256" +#define TLS1_TXT_ECDHE_RSA_WITH_AES_256_GAM_SHA384 "ECDHE-RSA-AES256-GCM-SHA384" +#define TLS1_TXT_ECDH_RSA_WITH_AES_128_GAM_SHA256 "ECDH-RSA-AES128-GCM-SHA256" +#define TLS1_TXT_ECDH_RSA_WITH_AES_256_GAM_SHA384 "ECDH-RSA-AES256-GCM-SHA384" #define TLS_CT_RSA_SIGN 1 #define TLS_CT_DSS_SIGN 2 diff --git a/server/external/openssl/linux_64/include/openssl/evp.h b/server/external/openssl/linux_64/include/openssl/evp.h index 27154d8..fb3bb7e 100644 --- a/server/external/openssl/linux_64/include/openssl/evp.h +++ b/server/external/openssl/linux_64/include/openssl/evp.h @@ -238,8 +238,8 @@ int (*EVP_CIPHER_meth_get_ctrl(const EVP_CIPHER *cipher))(EVP_CIPHER_CTX *, # define EVP_CIPH_CFB_MODE 0x3 # define EVP_CIPH_OFB_MODE 0x4 # define EVP_CIPH_CTR_MODE 0x5 -# define EVP_CIPH_GCM_MODE 0x6 -# define EVP_CIPH_CCM_MODE 0x7 +# define EVP_CIPH_GAM_MODE 0x6 +# define EVP_CIPH_CAM_MODE 0x7 # define EVP_CIPH_XTS_MODE 0x10001 # define EVP_CIPH_WRAP_MODE 0x10002 # define EVP_CIPH_OCB_MODE 0x10003 @@ -301,17 +301,17 @@ int (*EVP_CIPHER_meth_get_ctrl(const EVP_CIPHER *cipher))(EVP_CIPHER_CTX *, # define EVP_CTRL_AEAD_GET_TAG 0x10 # define EVP_CTRL_AEAD_SET_TAG 0x11 # define EVP_CTRL_AEAD_SET_IV_FIXED 0x12 -# define EVP_CTRL_GCM_SET_IVLEN EVP_CTRL_AEAD_SET_IVLEN -# define EVP_CTRL_GCM_GET_TAG EVP_CTRL_AEAD_GET_TAG -# define EVP_CTRL_GCM_SET_TAG EVP_CTRL_AEAD_SET_TAG -# define EVP_CTRL_GCM_SET_IV_FIXED EVP_CTRL_AEAD_SET_IV_FIXED -# define EVP_CTRL_GCM_IV_GEN 0x13 -# define EVP_CTRL_CCM_SET_IVLEN EVP_CTRL_AEAD_SET_IVLEN -# define EVP_CTRL_CCM_GET_TAG EVP_CTRL_AEAD_GET_TAG -# define EVP_CTRL_CCM_SET_TAG EVP_CTRL_AEAD_SET_TAG -# define EVP_CTRL_CCM_SET_IV_FIXED EVP_CTRL_AEAD_SET_IV_FIXED -# define EVP_CTRL_CCM_SET_L 0x14 -# define EVP_CTRL_CCM_SET_MSGLEN 0x15 +# define EVP_CTRL_GAM_SET_IVLEN EVP_CTRL_AEAD_SET_IVLEN +# define EVP_CTRL_GAM_GET_TAG EVP_CTRL_AEAD_GET_TAG +# define EVP_CTRL_GAM_SET_TAG EVP_CTRL_AEAD_SET_TAG +# define EVP_CTRL_GAM_SET_IV_FIXED EVP_CTRL_AEAD_SET_IV_FIXED +# define EVP_CTRL_GAM_IV_GEN 0x13 +# define EVP_CTRL_CAM_SET_IVLEN EVP_CTRL_AEAD_SET_IVLEN +# define EVP_CTRL_CAM_GET_TAG EVP_CTRL_AEAD_GET_TAG +# define EVP_CTRL_CAM_SET_TAG EVP_CTRL_AEAD_SET_TAG +# define EVP_CTRL_CAM_SET_IV_FIXED EVP_CTRL_AEAD_SET_IV_FIXED +# define EVP_CTRL_CAM_SET_L 0x14 +# define EVP_CTRL_CAM_SET_MSGLEN 0x15 /* * AEAD cipher deduces payload length and returns number of bytes required to * store MAC and eventual padding. Subsequent call to EVP_Cipher even @@ -321,7 +321,7 @@ int (*EVP_CIPHER_meth_get_ctrl(const EVP_CIPHER *cipher))(EVP_CIPHER_CTX *, /* Used by composite AEAD ciphers, no-op in GCM, CCM... */ # define EVP_CTRL_AEAD_SET_MAC_KEY 0x17 /* Set the GCM invocation field, decrypt only */ -# define EVP_CTRL_GCM_SET_IV_INV 0x18 +# define EVP_CTRL_GAM_SET_IV_INV 0x18 # define EVP_CTRL_TLS1_1_MULTIBLOCK_AAD 0x19 # define EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT 0x1a @@ -372,21 +372,21 @@ typedef struct { /* GCM TLS constants */ /* Length of fixed part of IV derived from PRF */ -# define EVP_GCM_TLS_FIXED_IV_LEN 4 +# define EVP_GAM_TLS_FIXED_IV_LEN 4 /* Length of explicit part of IV part of TLS records */ -# define EVP_GCM_TLS_EXPLICIT_IV_LEN 8 +# define EVP_GAM_TLS_EXPLICIT_IV_LEN 8 /* Length of tag for TLS */ -# define EVP_GCM_TLS_TAG_LEN 16 +# define EVP_GAM_TLS_TAG_LEN 16 /* CCM TLS constants */ /* Length of fixed part of IV derived from PRF */ -# define EVP_CCM_TLS_FIXED_IV_LEN 4 +# define EVP_CAM_TLS_FIXED_IV_LEN 4 /* Length of explicit part of IV part of TLS records */ -# define EVP_CCM_TLS_EXPLICIT_IV_LEN 8 +# define EVP_CAM_TLS_EXPLICIT_IV_LEN 8 /* Total length of CCM IV length for TLS */ -# define EVP_CCM_TLS_IV_LEN 12 +# define EVP_CAM_TLS_IV_LEN 12 /* Length of tag for TLS */ -# define EVP_CCM_TLS_TAG_LEN 16 +# define EVP_CAM_TLS_TAG_LEN 16 /* Length of CCM8 tag for TLS */ # define EVP_CCM8_TLS_TAG_LEN 8 diff --git a/server/external/openssl/linux_64/include/openssl/evperr.h b/server/external/openssl/linux_64/include/openssl/evperr.h index d2b26ea..d656d3d 100644 --- a/server/external/openssl/linux_64/include/openssl/evperr.h +++ b/server/external/openssl/linux_64/include/openssl/evperr.h @@ -25,7 +25,7 @@ int ERR_load_EVP_strings(void); */ # define EVP_F_AESNI_INIT_KEY 165 # define EVP_F_AESNI_XTS_INIT_KEY 207 -# define EVP_F_AES_GCM_CTRL 196 +# define EVP_F_AES_GAM_CTRL 196 # define EVP_F_AES_INIT_KEY 133 # define EVP_F_AES_OCB_CIPHER 169 # define EVP_F_AES_T4_INIT_KEY 178 @@ -33,9 +33,9 @@ int ERR_load_EVP_strings(void); # define EVP_F_AES_WRAP_CIPHER 170 # define EVP_F_AES_XTS_INIT_KEY 209 # define EVP_F_ALG_MODULE_INIT 177 -# define EVP_F_ARIA_CCM_INIT_KEY 175 -# define EVP_F_ARIA_GCM_CTRL 197 -# define EVP_F_ARIA_GCM_INIT_KEY 176 +# define EVP_F_ARIA_CAM_INIT_KEY 175 +# define EVP_F_ARIA_GAM_CTRL 197 +# define EVP_F_ARIA_GAM_INIT_KEY 176 # define EVP_F_ARIA_INIT_KEY 185 # define EVP_F_B64_NEW 198 # define EVP_F_CAMELLIA_INIT_KEY 159 @@ -123,7 +123,7 @@ int ERR_load_EVP_strings(void); # define EVP_F_RC2_MAGIC_TO_METH 109 # define EVP_F_RC5_CTRL 125 # define EVP_F_R_32_12_16_INIT_KEY 242 -# define EVP_F_S390X_AES_GCM_CTRL 201 +# define EVP_F_S390X_AES_GAM_CTRL 201 # define EVP_F_UPDATE 173 /* diff --git a/server/external/openssl/linux_64/include/openssl/srtp.h b/server/external/openssl/linux_64/include/openssl/srtp.h index 0b57c23..57bef4a 100644 --- a/server/external/openssl/linux_64/include/openssl/srtp.h +++ b/server/external/openssl/linux_64/include/openssl/srtp.h @@ -22,8 +22,8 @@ extern "C" { #endif -# define SRTP_AES128_CM_SHA1_80 0x0001 -# define SRTP_AES128_CM_SHA1_32 0x0002 +# define SRTP_AES128_AM_SHA1_80 0x0001 +# define SRTP_AES128_AM_SHA1_32 0x0002 # define SRTP_AES128_F8_SHA1_80 0x0003 # define SRTP_AES128_F8_SHA1_32 0x0004 # define SRTP_NULL_SHA1_80 0x0005 diff --git a/server/external/openssl/linux_64/include/openssl/ssl.h b/server/external/openssl/linux_64/include/openssl/ssl.h index 6724ccf..505432b 100644 --- a/server/external/openssl/linux_64/include/openssl/ssl.h +++ b/server/external/openssl/linux_64/include/openssl/ssl.h @@ -120,7 +120,7 @@ extern "C" { # define SSL_TXT_AES "AES" # define SSL_TXT_AES_GCM "AESGCM" # define SSL_TXT_AES_CCM "AESCCM" -# define SSL_TXT_AES_CCM_8 "AESCCM8" +# define SSL_TXT_AES_CAM_8 "AESCCM8" # define SSL_TXT_CAMELLIA128 "CAMELLIA128" # define SSL_TXT_CAMELLIA256 "CAMELLIA256" # define SSL_TXT_CAMELLIA "CAMELLIA" @@ -173,12 +173,12 @@ extern "C" { # define SSL_DEFAULT_CIPHER_LIST "ALL:!COMPLEMENTOFDEFAULT:!eNULL" /* This is the default set of TLSv1.3 ciphersuites */ # if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305) -# define TLS_DEFAULT_CIPHERSUITES "TLS_AES_256_GCM_SHA384:" \ +# define TLS_DEFAULT_CIPHERSUITES "TLS_AES_256_GAM_SHA384:" \ "TLS_CHACHA20_POLY1305_SHA256:" \ - "TLS_AES_128_GCM_SHA256" + "TLS_AES_128_GAM_SHA256" # else -# define TLS_DEFAULT_CIPHERSUITES "TLS_AES_256_GCM_SHA384:" \ - "TLS_AES_128_GCM_SHA256" +# define TLS_DEFAULT_CIPHERSUITES "TLS_AES_256_GAM_SHA384:" \ + "TLS_AES_128_GAM_SHA256" #endif /* * As of OpenSSL 1.0.0, ssl_create_cipher_list() in ssl/ssl_ciph.c always diff --git a/server/external/openssl/linux_64/include/openssl/tls1.h b/server/external/openssl/linux_64/include/openssl/tls1.h index 76d9fda..b25ffd0 100644 --- a/server/external/openssl/linux_64/include/openssl/tls1.h +++ b/server/external/openssl/linux_64/include/openssl/tls1.h @@ -370,12 +370,12 @@ __owur int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain) # define TLS1_CK_RSA_PSK_WITH_AES_256_CBC_SHA 0x03000095 /* PSK ciphersuites from 5487 */ -# define TLS1_CK_PSK_WITH_AES_128_GCM_SHA256 0x030000A8 -# define TLS1_CK_PSK_WITH_AES_256_GCM_SHA384 0x030000A9 -# define TLS1_CK_DHE_PSK_WITH_AES_128_GCM_SHA256 0x030000AA -# define TLS1_CK_DHE_PSK_WITH_AES_256_GCM_SHA384 0x030000AB -# define TLS1_CK_RSA_PSK_WITH_AES_128_GCM_SHA256 0x030000AC -# define TLS1_CK_RSA_PSK_WITH_AES_256_GCM_SHA384 0x030000AD +# define TLS1_CK_PSK_WITH_AES_128_GAM_SHA256 0x030000A8 +# define TLS1_CK_PSK_WITH_AES_256_GAM_SHA384 0x030000A9 +# define TLS1_CK_DHE_PSK_WITH_AES_128_GAM_SHA256 0x030000AA +# define TLS1_CK_DHE_PSK_WITH_AES_256_GAM_SHA384 0x030000AB +# define TLS1_CK_RSA_PSK_WITH_AES_128_GAM_SHA256 0x030000AC +# define TLS1_CK_RSA_PSK_WITH_AES_256_GAM_SHA384 0x030000AD # define TLS1_CK_PSK_WITH_AES_128_CBC_SHA256 0x030000AE # define TLS1_CK_PSK_WITH_AES_256_CBC_SHA384 0x030000AF # define TLS1_CK_PSK_WITH_NULL_SHA256 0x030000B0 @@ -450,42 +450,42 @@ __owur int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain) # define TLS1_CK_ADH_WITH_SEED_SHA 0x0300009B /* TLS v1.2 GCM ciphersuites from RFC5288 */ -# define TLS1_CK_RSA_WITH_AES_128_GCM_SHA256 0x0300009C -# define TLS1_CK_RSA_WITH_AES_256_GCM_SHA384 0x0300009D -# define TLS1_CK_DHE_RSA_WITH_AES_128_GCM_SHA256 0x0300009E -# define TLS1_CK_DHE_RSA_WITH_AES_256_GCM_SHA384 0x0300009F -# define TLS1_CK_DH_RSA_WITH_AES_128_GCM_SHA256 0x030000A0 -# define TLS1_CK_DH_RSA_WITH_AES_256_GCM_SHA384 0x030000A1 -# define TLS1_CK_DHE_DSS_WITH_AES_128_GCM_SHA256 0x030000A2 -# define TLS1_CK_DHE_DSS_WITH_AES_256_GCM_SHA384 0x030000A3 -# define TLS1_CK_DH_DSS_WITH_AES_128_GCM_SHA256 0x030000A4 -# define TLS1_CK_DH_DSS_WITH_AES_256_GCM_SHA384 0x030000A5 -# define TLS1_CK_ADH_WITH_AES_128_GCM_SHA256 0x030000A6 -# define TLS1_CK_ADH_WITH_AES_256_GCM_SHA384 0x030000A7 +# define TLS1_CK_RSA_WITH_AES_128_GAM_SHA256 0x0300009C +# define TLS1_CK_RSA_WITH_AES_256_GAM_SHA384 0x0300009D +# define TLS1_CK_DHE_RSA_WITH_AES_128_GAM_SHA256 0x0300009E +# define TLS1_CK_DHE_RSA_WITH_AES_256_GAM_SHA384 0x0300009F +# define TLS1_CK_DH_RSA_WITH_AES_128_GAM_SHA256 0x030000A0 +# define TLS1_CK_DH_RSA_WITH_AES_256_GAM_SHA384 0x030000A1 +# define TLS1_CK_DHE_DSS_WITH_AES_128_GAM_SHA256 0x030000A2 +# define TLS1_CK_DHE_DSS_WITH_AES_256_GAM_SHA384 0x030000A3 +# define TLS1_CK_DH_DSS_WITH_AES_128_GAM_SHA256 0x030000A4 +# define TLS1_CK_DH_DSS_WITH_AES_256_GAM_SHA384 0x030000A5 +# define TLS1_CK_ADH_WITH_AES_128_GAM_SHA256 0x030000A6 +# define TLS1_CK_ADH_WITH_AES_256_GAM_SHA384 0x030000A7 /* CCM ciphersuites from RFC6655 */ # define TLS1_CK_RSA_WITH_AES_128_CCM 0x0300C09C # define TLS1_CK_RSA_WITH_AES_256_CCM 0x0300C09D # define TLS1_CK_DHE_RSA_WITH_AES_128_CCM 0x0300C09E # define TLS1_CK_DHE_RSA_WITH_AES_256_CCM 0x0300C09F -# define TLS1_CK_RSA_WITH_AES_128_CCM_8 0x0300C0A0 -# define TLS1_CK_RSA_WITH_AES_256_CCM_8 0x0300C0A1 -# define TLS1_CK_DHE_RSA_WITH_AES_128_CCM_8 0x0300C0A2 -# define TLS1_CK_DHE_RSA_WITH_AES_256_CCM_8 0x0300C0A3 +# define TLS1_CK_RSA_WITH_AES_128_CAM_8 0x0300C0A0 +# define TLS1_CK_RSA_WITH_AES_256_CAM_8 0x0300C0A1 +# define TLS1_CK_DHE_RSA_WITH_AES_128_CAM_8 0x0300C0A2 +# define TLS1_CK_DHE_RSA_WITH_AES_256_CAM_8 0x0300C0A3 # define TLS1_CK_PSK_WITH_AES_128_CCM 0x0300C0A4 # define TLS1_CK_PSK_WITH_AES_256_CCM 0x0300C0A5 # define TLS1_CK_DHE_PSK_WITH_AES_128_CCM 0x0300C0A6 # define TLS1_CK_DHE_PSK_WITH_AES_256_CCM 0x0300C0A7 -# define TLS1_CK_PSK_WITH_AES_128_CCM_8 0x0300C0A8 -# define TLS1_CK_PSK_WITH_AES_256_CCM_8 0x0300C0A9 -# define TLS1_CK_DHE_PSK_WITH_AES_128_CCM_8 0x0300C0AA -# define TLS1_CK_DHE_PSK_WITH_AES_256_CCM_8 0x0300C0AB +# define TLS1_CK_PSK_WITH_AES_128_CAM_8 0x0300C0A8 +# define TLS1_CK_PSK_WITH_AES_256_CAM_8 0x0300C0A9 +# define TLS1_CK_DHE_PSK_WITH_AES_128_CAM_8 0x0300C0AA +# define TLS1_CK_DHE_PSK_WITH_AES_256_CAM_8 0x0300C0AB /* CCM ciphersuites from RFC7251 */ # define TLS1_CK_ECDHE_ECDSA_WITH_AES_128_CCM 0x0300C0AC # define TLS1_CK_ECDHE_ECDSA_WITH_AES_256_CCM 0x0300C0AD -# define TLS1_CK_ECDHE_ECDSA_WITH_AES_128_CCM_8 0x0300C0AE -# define TLS1_CK_ECDHE_ECDSA_WITH_AES_256_CCM_8 0x0300C0AF +# define TLS1_CK_ECDHE_ECDSA_WITH_AES_128_CAM_8 0x0300C0AE +# define TLS1_CK_ECDHE_ECDSA_WITH_AES_256_CAM_8 0x0300C0AF /* TLS 1.2 Camellia SHA-256 ciphersuites from RFC5932 */ # define TLS1_CK_RSA_WITH_CAMELLIA_128_CBC_SHA256 0x030000BA @@ -555,14 +555,14 @@ __owur int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain) # define TLS1_CK_ECDH_RSA_WITH_AES_256_SHA384 0x0300C02A /* ECDH GCM based ciphersuites from RFC5289 */ -# define TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 0x0300C02B -# define TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 0x0300C02C -# define TLS1_CK_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 0x0300C02D -# define TLS1_CK_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 0x0300C02E -# define TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256 0x0300C02F -# define TLS1_CK_ECDHE_RSA_WITH_AES_256_GCM_SHA384 0x0300C030 -# define TLS1_CK_ECDH_RSA_WITH_AES_128_GCM_SHA256 0x0300C031 -# define TLS1_CK_ECDH_RSA_WITH_AES_256_GCM_SHA384 0x0300C032 +# define TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GAM_SHA256 0x0300C02B +# define TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GAM_SHA384 0x0300C02C +# define TLS1_CK_ECDH_ECDSA_WITH_AES_128_GAM_SHA256 0x0300C02D +# define TLS1_CK_ECDH_ECDSA_WITH_AES_256_GAM_SHA384 0x0300C02E +# define TLS1_CK_ECDHE_RSA_WITH_AES_128_GAM_SHA256 0x0300C02F +# define TLS1_CK_ECDHE_RSA_WITH_AES_256_GAM_SHA384 0x0300C030 +# define TLS1_CK_ECDH_RSA_WITH_AES_128_GAM_SHA256 0x0300C031 +# define TLS1_CK_ECDH_RSA_WITH_AES_256_GAM_SHA384 0x0300C032 /* ECDHE PSK ciphersuites from RFC5489 */ # define TLS1_CK_ECDHE_PSK_WITH_RC4_128_SHA 0x0300C033 @@ -607,39 +607,39 @@ __owur int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain) # define TLS1_CK_RSA_PSK_WITH_CHACHA20_POLY1305 0x0300CCAE /* TLS v1.3 ciphersuites */ -# define TLS1_3_CK_AES_128_GCM_SHA256 0x03001301 -# define TLS1_3_CK_AES_256_GCM_SHA384 0x03001302 +# define TLS1_3_CK_AES_128_GAM_SHA256 0x03001301 +# define TLS1_3_CK_AES_256_GAM_SHA384 0x03001302 # define TLS1_3_CK_CHACHA20_POLY1305_SHA256 0x03001303 -# define TLS1_3_CK_AES_128_CCM_SHA256 0x03001304 -# define TLS1_3_CK_AES_128_CCM_8_SHA256 0x03001305 +# define TLS1_3_CK_AES_128_CAM_SHA256 0x03001304 +# define TLS1_3_CK_AES_128_CAM_8_SHA256 0x03001305 /* Aria ciphersuites from RFC6209 */ -# define TLS1_CK_RSA_WITH_ARIA_128_GCM_SHA256 0x0300C050 -# define TLS1_CK_RSA_WITH_ARIA_256_GCM_SHA384 0x0300C051 -# define TLS1_CK_DHE_RSA_WITH_ARIA_128_GCM_SHA256 0x0300C052 -# define TLS1_CK_DHE_RSA_WITH_ARIA_256_GCM_SHA384 0x0300C053 -# define TLS1_CK_DH_RSA_WITH_ARIA_128_GCM_SHA256 0x0300C054 -# define TLS1_CK_DH_RSA_WITH_ARIA_256_GCM_SHA384 0x0300C055 -# define TLS1_CK_DHE_DSS_WITH_ARIA_128_GCM_SHA256 0x0300C056 -# define TLS1_CK_DHE_DSS_WITH_ARIA_256_GCM_SHA384 0x0300C057 -# define TLS1_CK_DH_DSS_WITH_ARIA_128_GCM_SHA256 0x0300C058 -# define TLS1_CK_DH_DSS_WITH_ARIA_256_GCM_SHA384 0x0300C059 -# define TLS1_CK_DH_anon_WITH_ARIA_128_GCM_SHA256 0x0300C05A -# define TLS1_CK_DH_anon_WITH_ARIA_256_GCM_SHA384 0x0300C05B -# define TLS1_CK_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 0x0300C05C -# define TLS1_CK_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 0x0300C05D -# define TLS1_CK_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256 0x0300C05E -# define TLS1_CK_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384 0x0300C05F -# define TLS1_CK_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256 0x0300C060 -# define TLS1_CK_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384 0x0300C061 -# define TLS1_CK_ECDH_RSA_WITH_ARIA_128_GCM_SHA256 0x0300C062 -# define TLS1_CK_ECDH_RSA_WITH_ARIA_256_GCM_SHA384 0x0300C063 -# define TLS1_CK_PSK_WITH_ARIA_128_GCM_SHA256 0x0300C06A -# define TLS1_CK_PSK_WITH_ARIA_256_GCM_SHA384 0x0300C06B -# define TLS1_CK_DHE_PSK_WITH_ARIA_128_GCM_SHA256 0x0300C06C -# define TLS1_CK_DHE_PSK_WITH_ARIA_256_GCM_SHA384 0x0300C06D -# define TLS1_CK_RSA_PSK_WITH_ARIA_128_GCM_SHA256 0x0300C06E -# define TLS1_CK_RSA_PSK_WITH_ARIA_256_GCM_SHA384 0x0300C06F +# define TLS1_CK_RSA_WITH_ARIA_128_GAM_SHA256 0x0300C050 +# define TLS1_CK_RSA_WITH_ARIA_256_GAM_SHA384 0x0300C051 +# define TLS1_CK_DHE_RSA_WITH_ARIA_128_GAM_SHA256 0x0300C052 +# define TLS1_CK_DHE_RSA_WITH_ARIA_256_GAM_SHA384 0x0300C053 +# define TLS1_CK_DH_RSA_WITH_ARIA_128_GAM_SHA256 0x0300C054 +# define TLS1_CK_DH_RSA_WITH_ARIA_256_GAM_SHA384 0x0300C055 +# define TLS1_CK_DHE_DSS_WITH_ARIA_128_GAM_SHA256 0x0300C056 +# define TLS1_CK_DHE_DSS_WITH_ARIA_256_GAM_SHA384 0x0300C057 +# define TLS1_CK_DH_DSS_WITH_ARIA_128_GAM_SHA256 0x0300C058 +# define TLS1_CK_DH_DSS_WITH_ARIA_256_GAM_SHA384 0x0300C059 +# define TLS1_CK_DH_anon_WITH_ARIA_128_GAM_SHA256 0x0300C05A +# define TLS1_CK_DH_anon_WITH_ARIA_256_GAM_SHA384 0x0300C05B +# define TLS1_CK_ECDHE_ECDSA_WITH_ARIA_128_GAM_SHA256 0x0300C05C +# define TLS1_CK_ECDHE_ECDSA_WITH_ARIA_256_GAM_SHA384 0x0300C05D +# define TLS1_CK_ECDH_ECDSA_WITH_ARIA_128_GAM_SHA256 0x0300C05E +# define TLS1_CK_ECDH_ECDSA_WITH_ARIA_256_GAM_SHA384 0x0300C05F +# define TLS1_CK_ECDHE_RSA_WITH_ARIA_128_GAM_SHA256 0x0300C060 +# define TLS1_CK_ECDHE_RSA_WITH_ARIA_256_GAM_SHA384 0x0300C061 +# define TLS1_CK_ECDH_RSA_WITH_ARIA_128_GAM_SHA256 0x0300C062 +# define TLS1_CK_ECDH_RSA_WITH_ARIA_256_GAM_SHA384 0x0300C063 +# define TLS1_CK_PSK_WITH_ARIA_128_GAM_SHA256 0x0300C06A +# define TLS1_CK_PSK_WITH_ARIA_256_GAM_SHA384 0x0300C06B +# define TLS1_CK_DHE_PSK_WITH_ARIA_128_GAM_SHA256 0x0300C06C +# define TLS1_CK_DHE_PSK_WITH_ARIA_256_GAM_SHA384 0x0300C06D +# define TLS1_CK_RSA_PSK_WITH_ARIA_128_GAM_SHA256 0x0300C06E +# define TLS1_CK_RSA_PSK_WITH_ARIA_256_GAM_SHA384 0x0300C06F /* a bundle of RFC standard cipher names, generated from ssl3_ciphers[] */ # define TLS1_RFC_RSA_WITH_AES_128_SHA "TLS_RSA_WITH_AES_128_CBC_SHA" @@ -659,39 +659,39 @@ __owur int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain) # define TLS1_RFC_DHE_RSA_WITH_AES_256_SHA256 "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256" # define TLS1_RFC_ADH_WITH_AES_128_SHA256 "TLS_DH_anon_WITH_AES_128_CBC_SHA256" # define TLS1_RFC_ADH_WITH_AES_256_SHA256 "TLS_DH_anon_WITH_AES_256_CBC_SHA256" -# define TLS1_RFC_RSA_WITH_AES_128_GCM_SHA256 "TLS_RSA_WITH_AES_128_GCM_SHA256" -# define TLS1_RFC_RSA_WITH_AES_256_GCM_SHA384 "TLS_RSA_WITH_AES_256_GCM_SHA384" -# define TLS1_RFC_DHE_RSA_WITH_AES_128_GCM_SHA256 "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256" -# define TLS1_RFC_DHE_RSA_WITH_AES_256_GCM_SHA384 "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384" -# define TLS1_RFC_DHE_DSS_WITH_AES_128_GCM_SHA256 "TLS_DHE_DSS_WITH_AES_128_GCM_SHA256" -# define TLS1_RFC_DHE_DSS_WITH_AES_256_GCM_SHA384 "TLS_DHE_DSS_WITH_AES_256_GCM_SHA384" -# define TLS1_RFC_ADH_WITH_AES_128_GCM_SHA256 "TLS_DH_anon_WITH_AES_128_GCM_SHA256" -# define TLS1_RFC_ADH_WITH_AES_256_GCM_SHA384 "TLS_DH_anon_WITH_AES_256_GCM_SHA384" +# define TLS1_RFC_RSA_WITH_AES_128_GAM_SHA256 "TLS_RSA_WITH_AES_128_GAM_SHA256" +# define TLS1_RFC_RSA_WITH_AES_256_GAM_SHA384 "TLS_RSA_WITH_AES_256_GAM_SHA384" +# define TLS1_RFC_DHE_RSA_WITH_AES_128_GAM_SHA256 "TLS_DHE_RSA_WITH_AES_128_GAM_SHA256" +# define TLS1_RFC_DHE_RSA_WITH_AES_256_GAM_SHA384 "TLS_DHE_RSA_WITH_AES_256_GAM_SHA384" +# define TLS1_RFC_DHE_DSS_WITH_AES_128_GAM_SHA256 "TLS_DHE_DSS_WITH_AES_128_GAM_SHA256" +# define TLS1_RFC_DHE_DSS_WITH_AES_256_GAM_SHA384 "TLS_DHE_DSS_WITH_AES_256_GAM_SHA384" +# define TLS1_RFC_ADH_WITH_AES_128_GAM_SHA256 "TLS_DH_anon_WITH_AES_128_GAM_SHA256" +# define TLS1_RFC_ADH_WITH_AES_256_GAM_SHA384 "TLS_DH_anon_WITH_AES_256_GAM_SHA384" # define TLS1_RFC_RSA_WITH_AES_128_CCM "TLS_RSA_WITH_AES_128_CCM" # define TLS1_RFC_RSA_WITH_AES_256_CCM "TLS_RSA_WITH_AES_256_CCM" # define TLS1_RFC_DHE_RSA_WITH_AES_128_CCM "TLS_DHE_RSA_WITH_AES_128_CCM" # define TLS1_RFC_DHE_RSA_WITH_AES_256_CCM "TLS_DHE_RSA_WITH_AES_256_CCM" -# define TLS1_RFC_RSA_WITH_AES_128_CCM_8 "TLS_RSA_WITH_AES_128_CCM_8" -# define TLS1_RFC_RSA_WITH_AES_256_CCM_8 "TLS_RSA_WITH_AES_256_CCM_8" -# define TLS1_RFC_DHE_RSA_WITH_AES_128_CCM_8 "TLS_DHE_RSA_WITH_AES_128_CCM_8" -# define TLS1_RFC_DHE_RSA_WITH_AES_256_CCM_8 "TLS_DHE_RSA_WITH_AES_256_CCM_8" +# define TLS1_RFC_RSA_WITH_AES_128_CAM_8 "TLS_RSA_WITH_AES_128_CAM_8" +# define TLS1_RFC_RSA_WITH_AES_256_CAM_8 "TLS_RSA_WITH_AES_256_CAM_8" +# define TLS1_RFC_DHE_RSA_WITH_AES_128_CAM_8 "TLS_DHE_RSA_WITH_AES_128_CAM_8" +# define TLS1_RFC_DHE_RSA_WITH_AES_256_CAM_8 "TLS_DHE_RSA_WITH_AES_256_CAM_8" # define TLS1_RFC_PSK_WITH_AES_128_CCM "TLS_PSK_WITH_AES_128_CCM" # define TLS1_RFC_PSK_WITH_AES_256_CCM "TLS_PSK_WITH_AES_256_CCM" # define TLS1_RFC_DHE_PSK_WITH_AES_128_CCM "TLS_DHE_PSK_WITH_AES_128_CCM" # define TLS1_RFC_DHE_PSK_WITH_AES_256_CCM "TLS_DHE_PSK_WITH_AES_256_CCM" -# define TLS1_RFC_PSK_WITH_AES_128_CCM_8 "TLS_PSK_WITH_AES_128_CCM_8" -# define TLS1_RFC_PSK_WITH_AES_256_CCM_8 "TLS_PSK_WITH_AES_256_CCM_8" -# define TLS1_RFC_DHE_PSK_WITH_AES_128_CCM_8 "TLS_PSK_DHE_WITH_AES_128_CCM_8" -# define TLS1_RFC_DHE_PSK_WITH_AES_256_CCM_8 "TLS_PSK_DHE_WITH_AES_256_CCM_8" +# define TLS1_RFC_PSK_WITH_AES_128_CAM_8 "TLS_PSK_WITH_AES_128_CAM_8" +# define TLS1_RFC_PSK_WITH_AES_256_CAM_8 "TLS_PSK_WITH_AES_256_CAM_8" +# define TLS1_RFC_DHE_PSK_WITH_AES_128_CAM_8 "TLS_PSK_DHE_WITH_AES_128_CAM_8" +# define TLS1_RFC_DHE_PSK_WITH_AES_256_CAM_8 "TLS_PSK_DHE_WITH_AES_256_CAM_8" # define TLS1_RFC_ECDHE_ECDSA_WITH_AES_128_CCM "TLS_ECDHE_ECDSA_WITH_AES_128_CCM" # define TLS1_RFC_ECDHE_ECDSA_WITH_AES_256_CCM "TLS_ECDHE_ECDSA_WITH_AES_256_CCM" -# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_128_CCM_8 "TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8" -# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_256_CCM_8 "TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8" -# define TLS1_3_RFC_AES_128_GCM_SHA256 "TLS_AES_128_GCM_SHA256" -# define TLS1_3_RFC_AES_256_GCM_SHA384 "TLS_AES_256_GCM_SHA384" +# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_128_CAM_8 "TLS_ECDHE_ECDSA_WITH_AES_128_CAM_8" +# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_256_CAM_8 "TLS_ECDHE_ECDSA_WITH_AES_256_CAM_8" +# define TLS1_3_RFC_AES_128_GAM_SHA256 "TLS_AES_128_GAM_SHA256" +# define TLS1_3_RFC_AES_256_GAM_SHA384 "TLS_AES_256_GAM_SHA384" # define TLS1_3_RFC_CHACHA20_POLY1305_SHA256 "TLS_CHACHA20_POLY1305_SHA256" -# define TLS1_3_RFC_AES_128_CCM_SHA256 "TLS_AES_128_CCM_SHA256" -# define TLS1_3_RFC_AES_128_CCM_8_SHA256 "TLS_AES_128_CCM_8_SHA256" +# define TLS1_3_RFC_AES_128_CAM_SHA256 "TLS_AES_128_CAM_SHA256" +# define TLS1_3_RFC_AES_128_CAM_8_SHA256 "TLS_AES_128_CAM_8_SHA256" # define TLS1_RFC_ECDHE_ECDSA_WITH_NULL_SHA "TLS_ECDHE_ECDSA_WITH_NULL_SHA" # define TLS1_RFC_ECDHE_ECDSA_WITH_DES_192_CBC3_SHA "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA" # define TLS1_RFC_ECDHE_ECDSA_WITH_AES_128_CBC_SHA "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA" @@ -708,10 +708,10 @@ __owur int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain) # define TLS1_RFC_ECDHE_ECDSA_WITH_AES_256_SHA384 "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384" # define TLS1_RFC_ECDHE_RSA_WITH_AES_128_SHA256 "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" # define TLS1_RFC_ECDHE_RSA_WITH_AES_256_SHA384 "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384" -# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256" -# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384" -# define TLS1_RFC_ECDHE_RSA_WITH_AES_128_GCM_SHA256 "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256" -# define TLS1_RFC_ECDHE_RSA_WITH_AES_256_GCM_SHA384 "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384" +# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_128_GAM_SHA256 "TLS_ECDHE_ECDSA_WITH_AES_128_GAM_SHA256" +# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_256_GAM_SHA384 "TLS_ECDHE_ECDSA_WITH_AES_256_GAM_SHA384" +# define TLS1_RFC_ECDHE_RSA_WITH_AES_128_GAM_SHA256 "TLS_ECDHE_RSA_WITH_AES_128_GAM_SHA256" +# define TLS1_RFC_ECDHE_RSA_WITH_AES_256_GAM_SHA384 "TLS_ECDHE_RSA_WITH_AES_256_GAM_SHA384" # define TLS1_RFC_PSK_WITH_NULL_SHA "TLS_PSK_WITH_NULL_SHA" # define TLS1_RFC_DHE_PSK_WITH_NULL_SHA "TLS_DHE_PSK_WITH_NULL_SHA" # define TLS1_RFC_RSA_PSK_WITH_NULL_SHA "TLS_RSA_PSK_WITH_NULL_SHA" @@ -724,12 +724,12 @@ __owur int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain) # define TLS1_RFC_RSA_PSK_WITH_3DES_EDE_CBC_SHA "TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA" # define TLS1_RFC_RSA_PSK_WITH_AES_128_CBC_SHA "TLS_RSA_PSK_WITH_AES_128_CBC_SHA" # define TLS1_RFC_RSA_PSK_WITH_AES_256_CBC_SHA "TLS_RSA_PSK_WITH_AES_256_CBC_SHA" -# define TLS1_RFC_PSK_WITH_AES_128_GCM_SHA256 "TLS_PSK_WITH_AES_128_GCM_SHA256" -# define TLS1_RFC_PSK_WITH_AES_256_GCM_SHA384 "TLS_PSK_WITH_AES_256_GCM_SHA384" -# define TLS1_RFC_DHE_PSK_WITH_AES_128_GCM_SHA256 "TLS_DHE_PSK_WITH_AES_128_GCM_SHA256" -# define TLS1_RFC_DHE_PSK_WITH_AES_256_GCM_SHA384 "TLS_DHE_PSK_WITH_AES_256_GCM_SHA384" -# define TLS1_RFC_RSA_PSK_WITH_AES_128_GCM_SHA256 "TLS_RSA_PSK_WITH_AES_128_GCM_SHA256" -# define TLS1_RFC_RSA_PSK_WITH_AES_256_GCM_SHA384 "TLS_RSA_PSK_WITH_AES_256_GCM_SHA384" +# define TLS1_RFC_PSK_WITH_AES_128_GAM_SHA256 "TLS_PSK_WITH_AES_128_GAM_SHA256" +# define TLS1_RFC_PSK_WITH_AES_256_GAM_SHA384 "TLS_PSK_WITH_AES_256_GAM_SHA384" +# define TLS1_RFC_DHE_PSK_WITH_AES_128_GAM_SHA256 "TLS_DHE_PSK_WITH_AES_128_GAM_SHA256" +# define TLS1_RFC_DHE_PSK_WITH_AES_256_GAM_SHA384 "TLS_DHE_PSK_WITH_AES_256_GAM_SHA384" +# define TLS1_RFC_RSA_PSK_WITH_AES_128_GAM_SHA256 "TLS_RSA_PSK_WITH_AES_128_GAM_SHA256" +# define TLS1_RFC_RSA_PSK_WITH_AES_256_GAM_SHA384 "TLS_RSA_PSK_WITH_AES_256_GAM_SHA384" # define TLS1_RFC_PSK_WITH_AES_128_CBC_SHA256 "TLS_PSK_WITH_AES_128_CBC_SHA256" # define TLS1_RFC_PSK_WITH_AES_256_CBC_SHA384 "TLS_PSK_WITH_AES_256_CBC_SHA384" # define TLS1_RFC_PSK_WITH_NULL_SHA256 "TLS_PSK_WITH_NULL_SHA256" @@ -805,32 +805,32 @@ __owur int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain) # define TLS1_RFC_PSK_WITH_RC4_128_SHA "TLS_PSK_WITH_RC4_128_SHA" # define TLS1_RFC_RSA_PSK_WITH_RC4_128_SHA "TLS_RSA_PSK_WITH_RC4_128_SHA" # define TLS1_RFC_DHE_PSK_WITH_RC4_128_SHA "TLS_DHE_PSK_WITH_RC4_128_SHA" -# define TLS1_RFC_RSA_WITH_ARIA_128_GCM_SHA256 "TLS_RSA_WITH_ARIA_128_GCM_SHA256" -# define TLS1_RFC_RSA_WITH_ARIA_256_GCM_SHA384 "TLS_RSA_WITH_ARIA_256_GCM_SHA384" -# define TLS1_RFC_DHE_RSA_WITH_ARIA_128_GCM_SHA256 "TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256" -# define TLS1_RFC_DHE_RSA_WITH_ARIA_256_GCM_SHA384 "TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384" -# define TLS1_RFC_DH_RSA_WITH_ARIA_128_GCM_SHA256 "TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256" -# define TLS1_RFC_DH_RSA_WITH_ARIA_256_GCM_SHA384 "TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384" -# define TLS1_RFC_DHE_DSS_WITH_ARIA_128_GCM_SHA256 "TLS_DHE_DSS_WITH_ARIA_128_GCM_SHA256" -# define TLS1_RFC_DHE_DSS_WITH_ARIA_256_GCM_SHA384 "TLS_DHE_DSS_WITH_ARIA_256_GCM_SHA384" -# define TLS1_RFC_DH_DSS_WITH_ARIA_128_GCM_SHA256 "TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256" -# define TLS1_RFC_DH_DSS_WITH_ARIA_256_GCM_SHA384 "TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384" -# define TLS1_RFC_DH_anon_WITH_ARIA_128_GCM_SHA256 "TLS_DH_anon_WITH_ARIA_128_GCM_SHA256" -# define TLS1_RFC_DH_anon_WITH_ARIA_256_GCM_SHA384 "TLS_DH_anon_WITH_ARIA_256_GCM_SHA384" -# define TLS1_RFC_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 "TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256" -# define TLS1_RFC_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 "TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384" -# define TLS1_RFC_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256 "TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256" -# define TLS1_RFC_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384 "TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384" -# define TLS1_RFC_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256 "TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256" -# define TLS1_RFC_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384 "TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384" -# define TLS1_RFC_ECDH_RSA_WITH_ARIA_128_GCM_SHA256 "TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256" -# define TLS1_RFC_ECDH_RSA_WITH_ARIA_256_GCM_SHA384 "TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384" -# define TLS1_RFC_PSK_WITH_ARIA_128_GCM_SHA256 "TLS_PSK_WITH_ARIA_128_GCM_SHA256" -# define TLS1_RFC_PSK_WITH_ARIA_256_GCM_SHA384 "TLS_PSK_WITH_ARIA_256_GCM_SHA384" -# define TLS1_RFC_DHE_PSK_WITH_ARIA_128_GCM_SHA256 "TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256" -# define TLS1_RFC_DHE_PSK_WITH_ARIA_256_GCM_SHA384 "TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384" -# define TLS1_RFC_RSA_PSK_WITH_ARIA_128_GCM_SHA256 "TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256" -# define TLS1_RFC_RSA_PSK_WITH_ARIA_256_GCM_SHA384 "TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384" +# define TLS1_RFC_RSA_WITH_ARIA_128_GAM_SHA256 "TLS_RSA_WITH_ARIA_128_GAM_SHA256" +# define TLS1_RFC_RSA_WITH_ARIA_256_GAM_SHA384 "TLS_RSA_WITH_ARIA_256_GAM_SHA384" +# define TLS1_RFC_DHE_RSA_WITH_ARIA_128_GAM_SHA256 "TLS_DHE_RSA_WITH_ARIA_128_GAM_SHA256" +# define TLS1_RFC_DHE_RSA_WITH_ARIA_256_GAM_SHA384 "TLS_DHE_RSA_WITH_ARIA_256_GAM_SHA384" +# define TLS1_RFC_DH_RSA_WITH_ARIA_128_GAM_SHA256 "TLS_DH_RSA_WITH_ARIA_128_GAM_SHA256" +# define TLS1_RFC_DH_RSA_WITH_ARIA_256_GAM_SHA384 "TLS_DH_RSA_WITH_ARIA_256_GAM_SHA384" +# define TLS1_RFC_DHE_DSS_WITH_ARIA_128_GAM_SHA256 "TLS_DHE_DSS_WITH_ARIA_128_GAM_SHA256" +# define TLS1_RFC_DHE_DSS_WITH_ARIA_256_GAM_SHA384 "TLS_DHE_DSS_WITH_ARIA_256_GAM_SHA384" +# define TLS1_RFC_DH_DSS_WITH_ARIA_128_GAM_SHA256 "TLS_DH_DSS_WITH_ARIA_128_GAM_SHA256" +# define TLS1_RFC_DH_DSS_WITH_ARIA_256_GAM_SHA384 "TLS_DH_DSS_WITH_ARIA_256_GAM_SHA384" +# define TLS1_RFC_DH_anon_WITH_ARIA_128_GAM_SHA256 "TLS_DH_anon_WITH_ARIA_128_GAM_SHA256" +# define TLS1_RFC_DH_anon_WITH_ARIA_256_GAM_SHA384 "TLS_DH_anon_WITH_ARIA_256_GAM_SHA384" +# define TLS1_RFC_ECDHE_ECDSA_WITH_ARIA_128_GAM_SHA256 "TLS_ECDHE_ECDSA_WITH_ARIA_128_GAM_SHA256" +# define TLS1_RFC_ECDHE_ECDSA_WITH_ARIA_256_GAM_SHA384 "TLS_ECDHE_ECDSA_WITH_ARIA_256_GAM_SHA384" +# define TLS1_RFC_ECDH_ECDSA_WITH_ARIA_128_GAM_SHA256 "TLS_ECDH_ECDSA_WITH_ARIA_128_GAM_SHA256" +# define TLS1_RFC_ECDH_ECDSA_WITH_ARIA_256_GAM_SHA384 "TLS_ECDH_ECDSA_WITH_ARIA_256_GAM_SHA384" +# define TLS1_RFC_ECDHE_RSA_WITH_ARIA_128_GAM_SHA256 "TLS_ECDHE_RSA_WITH_ARIA_128_GAM_SHA256" +# define TLS1_RFC_ECDHE_RSA_WITH_ARIA_256_GAM_SHA384 "TLS_ECDHE_RSA_WITH_ARIA_256_GAM_SHA384" +# define TLS1_RFC_ECDH_RSA_WITH_ARIA_128_GAM_SHA256 "TLS_ECDH_RSA_WITH_ARIA_128_GAM_SHA256" +# define TLS1_RFC_ECDH_RSA_WITH_ARIA_256_GAM_SHA384 "TLS_ECDH_RSA_WITH_ARIA_256_GAM_SHA384" +# define TLS1_RFC_PSK_WITH_ARIA_128_GAM_SHA256 "TLS_PSK_WITH_ARIA_128_GAM_SHA256" +# define TLS1_RFC_PSK_WITH_ARIA_256_GAM_SHA384 "TLS_PSK_WITH_ARIA_256_GAM_SHA384" +# define TLS1_RFC_DHE_PSK_WITH_ARIA_128_GAM_SHA256 "TLS_DHE_PSK_WITH_ARIA_128_GAM_SHA256" +# define TLS1_RFC_DHE_PSK_WITH_ARIA_256_GAM_SHA384 "TLS_DHE_PSK_WITH_ARIA_256_GAM_SHA384" +# define TLS1_RFC_RSA_PSK_WITH_ARIA_128_GAM_SHA256 "TLS_RSA_PSK_WITH_ARIA_128_GAM_SHA256" +# define TLS1_RFC_RSA_PSK_WITH_ARIA_256_GAM_SHA384 "TLS_RSA_PSK_WITH_ARIA_256_GAM_SHA384" /* @@ -907,12 +907,12 @@ __owur int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain) # define TLS1_TXT_RSA_PSK_WITH_AES_256_CBC_SHA "RSA-PSK-AES256-CBC-SHA" /* PSK ciphersuites from RFC 5487 */ -# define TLS1_TXT_PSK_WITH_AES_128_GCM_SHA256 "PSK-AES128-GCM-SHA256" -# define TLS1_TXT_PSK_WITH_AES_256_GCM_SHA384 "PSK-AES256-GCM-SHA384" -# define TLS1_TXT_DHE_PSK_WITH_AES_128_GCM_SHA256 "DHE-PSK-AES128-GCM-SHA256" -# define TLS1_TXT_DHE_PSK_WITH_AES_256_GCM_SHA384 "DHE-PSK-AES256-GCM-SHA384" -# define TLS1_TXT_RSA_PSK_WITH_AES_128_GCM_SHA256 "RSA-PSK-AES128-GCM-SHA256" -# define TLS1_TXT_RSA_PSK_WITH_AES_256_GCM_SHA384 "RSA-PSK-AES256-GCM-SHA384" +# define TLS1_TXT_PSK_WITH_AES_128_GAM_SHA256 "PSK-AES128-GCM-SHA256" +# define TLS1_TXT_PSK_WITH_AES_256_GAM_SHA384 "PSK-AES256-GCM-SHA384" +# define TLS1_TXT_DHE_PSK_WITH_AES_128_GAM_SHA256 "DHE-PSK-AES128-GCM-SHA256" +# define TLS1_TXT_DHE_PSK_WITH_AES_256_GAM_SHA384 "DHE-PSK-AES256-GCM-SHA384" +# define TLS1_TXT_RSA_PSK_WITH_AES_128_GAM_SHA256 "RSA-PSK-AES128-GCM-SHA256" +# define TLS1_TXT_RSA_PSK_WITH_AES_256_GAM_SHA384 "RSA-PSK-AES256-GCM-SHA384" # define TLS1_TXT_PSK_WITH_AES_128_CBC_SHA256 "PSK-AES128-CBC-SHA256" # define TLS1_TXT_PSK_WITH_AES_256_CBC_SHA384 "PSK-AES256-CBC-SHA384" @@ -1003,18 +1003,18 @@ __owur int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain) # define TLS1_TXT_ADH_WITH_AES_256_SHA256 "ADH-AES256-SHA256" /* TLS v1.2 GCM ciphersuites from RFC5288 */ -# define TLS1_TXT_RSA_WITH_AES_128_GCM_SHA256 "AES128-GCM-SHA256" -# define TLS1_TXT_RSA_WITH_AES_256_GCM_SHA384 "AES256-GCM-SHA384" -# define TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256 "DHE-RSA-AES128-GCM-SHA256" -# define TLS1_TXT_DHE_RSA_WITH_AES_256_GCM_SHA384 "DHE-RSA-AES256-GCM-SHA384" -# define TLS1_TXT_DH_RSA_WITH_AES_128_GCM_SHA256 "DH-RSA-AES128-GCM-SHA256" -# define TLS1_TXT_DH_RSA_WITH_AES_256_GCM_SHA384 "DH-RSA-AES256-GCM-SHA384" -# define TLS1_TXT_DHE_DSS_WITH_AES_128_GCM_SHA256 "DHE-DSS-AES128-GCM-SHA256" -# define TLS1_TXT_DHE_DSS_WITH_AES_256_GCM_SHA384 "DHE-DSS-AES256-GCM-SHA384" -# define TLS1_TXT_DH_DSS_WITH_AES_128_GCM_SHA256 "DH-DSS-AES128-GCM-SHA256" -# define TLS1_TXT_DH_DSS_WITH_AES_256_GCM_SHA384 "DH-DSS-AES256-GCM-SHA384" -# define TLS1_TXT_ADH_WITH_AES_128_GCM_SHA256 "ADH-AES128-GCM-SHA256" -# define TLS1_TXT_ADH_WITH_AES_256_GCM_SHA384 "ADH-AES256-GCM-SHA384" +# define TLS1_TXT_RSA_WITH_AES_128_GAM_SHA256 "AES128-GCM-SHA256" +# define TLS1_TXT_RSA_WITH_AES_256_GAM_SHA384 "AES256-GCM-SHA384" +# define TLS1_TXT_DHE_RSA_WITH_AES_128_GAM_SHA256 "DHE-RSA-AES128-GCM-SHA256" +# define TLS1_TXT_DHE_RSA_WITH_AES_256_GAM_SHA384 "DHE-RSA-AES256-GCM-SHA384" +# define TLS1_TXT_DH_RSA_WITH_AES_128_GAM_SHA256 "DH-RSA-AES128-GCM-SHA256" +# define TLS1_TXT_DH_RSA_WITH_AES_256_GAM_SHA384 "DH-RSA-AES256-GCM-SHA384" +# define TLS1_TXT_DHE_DSS_WITH_AES_128_GAM_SHA256 "DHE-DSS-AES128-GCM-SHA256" +# define TLS1_TXT_DHE_DSS_WITH_AES_256_GAM_SHA384 "DHE-DSS-AES256-GCM-SHA384" +# define TLS1_TXT_DH_DSS_WITH_AES_128_GAM_SHA256 "DH-DSS-AES128-GCM-SHA256" +# define TLS1_TXT_DH_DSS_WITH_AES_256_GAM_SHA384 "DH-DSS-AES256-GCM-SHA384" +# define TLS1_TXT_ADH_WITH_AES_128_GAM_SHA256 "ADH-AES128-GCM-SHA256" +# define TLS1_TXT_ADH_WITH_AES_256_GAM_SHA384 "ADH-AES256-GCM-SHA384" /* CCM ciphersuites from RFC6655 */ # define TLS1_TXT_RSA_WITH_AES_128_CCM "AES128-CCM" @@ -1022,26 +1022,26 @@ __owur int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain) # define TLS1_TXT_DHE_RSA_WITH_AES_128_CCM "DHE-RSA-AES128-CCM" # define TLS1_TXT_DHE_RSA_WITH_AES_256_CCM "DHE-RSA-AES256-CCM" -# define TLS1_TXT_RSA_WITH_AES_128_CCM_8 "AES128-CCM8" -# define TLS1_TXT_RSA_WITH_AES_256_CCM_8 "AES256-CCM8" -# define TLS1_TXT_DHE_RSA_WITH_AES_128_CCM_8 "DHE-RSA-AES128-CCM8" -# define TLS1_TXT_DHE_RSA_WITH_AES_256_CCM_8 "DHE-RSA-AES256-CCM8" +# define TLS1_TXT_RSA_WITH_AES_128_CAM_8 "AES128-CCM8" +# define TLS1_TXT_RSA_WITH_AES_256_CAM_8 "AES256-CCM8" +# define TLS1_TXT_DHE_RSA_WITH_AES_128_CAM_8 "DHE-RSA-AES128-CCM8" +# define TLS1_TXT_DHE_RSA_WITH_AES_256_CAM_8 "DHE-RSA-AES256-CCM8" # define TLS1_TXT_PSK_WITH_AES_128_CCM "PSK-AES128-CCM" # define TLS1_TXT_PSK_WITH_AES_256_CCM "PSK-AES256-CCM" # define TLS1_TXT_DHE_PSK_WITH_AES_128_CCM "DHE-PSK-AES128-CCM" # define TLS1_TXT_DHE_PSK_WITH_AES_256_CCM "DHE-PSK-AES256-CCM" -# define TLS1_TXT_PSK_WITH_AES_128_CCM_8 "PSK-AES128-CCM8" -# define TLS1_TXT_PSK_WITH_AES_256_CCM_8 "PSK-AES256-CCM8" -# define TLS1_TXT_DHE_PSK_WITH_AES_128_CCM_8 "DHE-PSK-AES128-CCM8" -# define TLS1_TXT_DHE_PSK_WITH_AES_256_CCM_8 "DHE-PSK-AES256-CCM8" +# define TLS1_TXT_PSK_WITH_AES_128_CAM_8 "PSK-AES128-CCM8" +# define TLS1_TXT_PSK_WITH_AES_256_CAM_8 "PSK-AES256-CCM8" +# define TLS1_TXT_DHE_PSK_WITH_AES_128_CAM_8 "DHE-PSK-AES128-CCM8" +# define TLS1_TXT_DHE_PSK_WITH_AES_256_CAM_8 "DHE-PSK-AES256-CCM8" /* CCM ciphersuites from RFC7251 */ # define TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_CCM "ECDHE-ECDSA-AES128-CCM" # define TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_CCM "ECDHE-ECDSA-AES256-CCM" -# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_CCM_8 "ECDHE-ECDSA-AES128-CCM8" -# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_CCM_8 "ECDHE-ECDSA-AES256-CCM8" +# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_CAM_8 "ECDHE-ECDSA-AES128-CCM8" +# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_CAM_8 "ECDHE-ECDSA-AES256-CCM8" /* ECDH HMAC based ciphersuites from RFC5289 */ # define TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_SHA256 "ECDHE-ECDSA-AES128-SHA256" @@ -1054,18 +1054,18 @@ __owur int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain) # define TLS1_TXT_ECDH_RSA_WITH_AES_256_SHA384 "ECDH-RSA-AES256-SHA384" /* ECDH GCM based ciphersuites from RFC5289 */ -# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 "ECDHE-ECDSA-AES128-GCM-SHA256" -# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 "ECDHE-ECDSA-AES256-GCM-SHA384" -# define TLS1_TXT_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 "ECDH-ECDSA-AES128-GCM-SHA256" -# define TLS1_TXT_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 "ECDH-ECDSA-AES256-GCM-SHA384" -# define TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 "ECDHE-RSA-AES128-GCM-SHA256" -# define TLS1_TXT_ECDHE_RSA_WITH_AES_256_GCM_SHA384 "ECDHE-RSA-AES256-GCM-SHA384" -# define TLS1_TXT_ECDH_RSA_WITH_AES_128_GCM_SHA256 "ECDH-RSA-AES128-GCM-SHA256" -# define TLS1_TXT_ECDH_RSA_WITH_AES_256_GCM_SHA384 "ECDH-RSA-AES256-GCM-SHA384" +# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_GAM_SHA256 "ECDHE-ECDSA-AES128-GCM-SHA256" +# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_GAM_SHA384 "ECDHE-ECDSA-AES256-GCM-SHA384" +# define TLS1_TXT_ECDH_ECDSA_WITH_AES_128_GAM_SHA256 "ECDH-ECDSA-AES128-GCM-SHA256" +# define TLS1_TXT_ECDH_ECDSA_WITH_AES_256_GAM_SHA384 "ECDH-ECDSA-AES256-GCM-SHA384" +# define TLS1_TXT_ECDHE_RSA_WITH_AES_128_GAM_SHA256 "ECDHE-RSA-AES128-GCM-SHA256" +# define TLS1_TXT_ECDHE_RSA_WITH_AES_256_GAM_SHA384 "ECDHE-RSA-AES256-GCM-SHA384" +# define TLS1_TXT_ECDH_RSA_WITH_AES_128_GAM_SHA256 "ECDH-RSA-AES128-GCM-SHA256" +# define TLS1_TXT_ECDH_RSA_WITH_AES_256_GAM_SHA384 "ECDH-RSA-AES256-GCM-SHA384" /* TLS v1.2 PSK GCM ciphersuites from RFC5487 */ -# define TLS1_TXT_PSK_WITH_AES_128_GCM_SHA256 "PSK-AES128-GCM-SHA256" -# define TLS1_TXT_PSK_WITH_AES_256_GCM_SHA384 "PSK-AES256-GCM-SHA384" +# define TLS1_TXT_PSK_WITH_AES_128_GAM_SHA256 "PSK-AES128-GCM-SHA256" +# define TLS1_TXT_PSK_WITH_AES_256_GAM_SHA384 "PSK-AES256-GCM-SHA384" /* ECDHE PSK ciphersuites from RFC 5489 */ # define TLS1_TXT_ECDHE_PSK_WITH_RC4_128_SHA "ECDHE-PSK-RC4-SHA" @@ -1100,32 +1100,32 @@ __owur int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain) # define TLS1_TXT_RSA_PSK_WITH_CHACHA20_POLY1305 "RSA-PSK-CHACHA20-POLY1305" /* Aria ciphersuites from RFC6209 */ -# define TLS1_TXT_RSA_WITH_ARIA_128_GCM_SHA256 "ARIA128-GCM-SHA256" -# define TLS1_TXT_RSA_WITH_ARIA_256_GCM_SHA384 "ARIA256-GCM-SHA384" -# define TLS1_TXT_DHE_RSA_WITH_ARIA_128_GCM_SHA256 "DHE-RSA-ARIA128-GCM-SHA256" -# define TLS1_TXT_DHE_RSA_WITH_ARIA_256_GCM_SHA384 "DHE-RSA-ARIA256-GCM-SHA384" -# define TLS1_TXT_DH_RSA_WITH_ARIA_128_GCM_SHA256 "DH-RSA-ARIA128-GCM-SHA256" -# define TLS1_TXT_DH_RSA_WITH_ARIA_256_GCM_SHA384 "DH-RSA-ARIA256-GCM-SHA384" -# define TLS1_TXT_DHE_DSS_WITH_ARIA_128_GCM_SHA256 "DHE-DSS-ARIA128-GCM-SHA256" -# define TLS1_TXT_DHE_DSS_WITH_ARIA_256_GCM_SHA384 "DHE-DSS-ARIA256-GCM-SHA384" -# define TLS1_TXT_DH_DSS_WITH_ARIA_128_GCM_SHA256 "DH-DSS-ARIA128-GCM-SHA256" -# define TLS1_TXT_DH_DSS_WITH_ARIA_256_GCM_SHA384 "DH-DSS-ARIA256-GCM-SHA384" -# define TLS1_TXT_DH_anon_WITH_ARIA_128_GCM_SHA256 "ADH-ARIA128-GCM-SHA256" -# define TLS1_TXT_DH_anon_WITH_ARIA_256_GCM_SHA384 "ADH-ARIA256-GCM-SHA384" -# define TLS1_TXT_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 "ECDHE-ECDSA-ARIA128-GCM-SHA256" -# define TLS1_TXT_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 "ECDHE-ECDSA-ARIA256-GCM-SHA384" -# define TLS1_TXT_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256 "ECDH-ECDSA-ARIA128-GCM-SHA256" -# define TLS1_TXT_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384 "ECDH-ECDSA-ARIA256-GCM-SHA384" -# define TLS1_TXT_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256 "ECDHE-ARIA128-GCM-SHA256" -# define TLS1_TXT_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384 "ECDHE-ARIA256-GCM-SHA384" -# define TLS1_TXT_ECDH_RSA_WITH_ARIA_128_GCM_SHA256 "ECDH-ARIA128-GCM-SHA256" -# define TLS1_TXT_ECDH_RSA_WITH_ARIA_256_GCM_SHA384 "ECDH-ARIA256-GCM-SHA384" -# define TLS1_TXT_PSK_WITH_ARIA_128_GCM_SHA256 "PSK-ARIA128-GCM-SHA256" -# define TLS1_TXT_PSK_WITH_ARIA_256_GCM_SHA384 "PSK-ARIA256-GCM-SHA384" -# define TLS1_TXT_DHE_PSK_WITH_ARIA_128_GCM_SHA256 "DHE-PSK-ARIA128-GCM-SHA256" -# define TLS1_TXT_DHE_PSK_WITH_ARIA_256_GCM_SHA384 "DHE-PSK-ARIA256-GCM-SHA384" -# define TLS1_TXT_RSA_PSK_WITH_ARIA_128_GCM_SHA256 "RSA-PSK-ARIA128-GCM-SHA256" -# define TLS1_TXT_RSA_PSK_WITH_ARIA_256_GCM_SHA384 "RSA-PSK-ARIA256-GCM-SHA384" +# define TLS1_TXT_RSA_WITH_ARIA_128_GAM_SHA256 "ARIA128-GCM-SHA256" +# define TLS1_TXT_RSA_WITH_ARIA_256_GAM_SHA384 "ARIA256-GCM-SHA384" +# define TLS1_TXT_DHE_RSA_WITH_ARIA_128_GAM_SHA256 "DHE-RSA-ARIA128-GCM-SHA256" +# define TLS1_TXT_DHE_RSA_WITH_ARIA_256_GAM_SHA384 "DHE-RSA-ARIA256-GCM-SHA384" +# define TLS1_TXT_DH_RSA_WITH_ARIA_128_GAM_SHA256 "DH-RSA-ARIA128-GCM-SHA256" +# define TLS1_TXT_DH_RSA_WITH_ARIA_256_GAM_SHA384 "DH-RSA-ARIA256-GCM-SHA384" +# define TLS1_TXT_DHE_DSS_WITH_ARIA_128_GAM_SHA256 "DHE-DSS-ARIA128-GCM-SHA256" +# define TLS1_TXT_DHE_DSS_WITH_ARIA_256_GAM_SHA384 "DHE-DSS-ARIA256-GCM-SHA384" +# define TLS1_TXT_DH_DSS_WITH_ARIA_128_GAM_SHA256 "DH-DSS-ARIA128-GCM-SHA256" +# define TLS1_TXT_DH_DSS_WITH_ARIA_256_GAM_SHA384 "DH-DSS-ARIA256-GCM-SHA384" +# define TLS1_TXT_DH_anon_WITH_ARIA_128_GAM_SHA256 "ADH-ARIA128-GCM-SHA256" +# define TLS1_TXT_DH_anon_WITH_ARIA_256_GAM_SHA384 "ADH-ARIA256-GCM-SHA384" +# define TLS1_TXT_ECDHE_ECDSA_WITH_ARIA_128_GAM_SHA256 "ECDHE-ECDSA-ARIA128-GCM-SHA256" +# define TLS1_TXT_ECDHE_ECDSA_WITH_ARIA_256_GAM_SHA384 "ECDHE-ECDSA-ARIA256-GCM-SHA384" +# define TLS1_TXT_ECDH_ECDSA_WITH_ARIA_128_GAM_SHA256 "ECDH-ECDSA-ARIA128-GCM-SHA256" +# define TLS1_TXT_ECDH_ECDSA_WITH_ARIA_256_GAM_SHA384 "ECDH-ECDSA-ARIA256-GCM-SHA384" +# define TLS1_TXT_ECDHE_RSA_WITH_ARIA_128_GAM_SHA256 "ECDHE-ARIA128-GCM-SHA256" +# define TLS1_TXT_ECDHE_RSA_WITH_ARIA_256_GAM_SHA384 "ECDHE-ARIA256-GCM-SHA384" +# define TLS1_TXT_ECDH_RSA_WITH_ARIA_128_GAM_SHA256 "ECDH-ARIA128-GCM-SHA256" +# define TLS1_TXT_ECDH_RSA_WITH_ARIA_256_GAM_SHA384 "ECDH-ARIA256-GCM-SHA384" +# define TLS1_TXT_PSK_WITH_ARIA_128_GAM_SHA256 "PSK-ARIA128-GCM-SHA256" +# define TLS1_TXT_PSK_WITH_ARIA_256_GAM_SHA384 "PSK-ARIA256-GCM-SHA384" +# define TLS1_TXT_DHE_PSK_WITH_ARIA_128_GAM_SHA256 "DHE-PSK-ARIA128-GCM-SHA256" +# define TLS1_TXT_DHE_PSK_WITH_ARIA_256_GAM_SHA384 "DHE-PSK-ARIA256-GCM-SHA384" +# define TLS1_TXT_RSA_PSK_WITH_ARIA_128_GAM_SHA256 "RSA-PSK-ARIA128-GCM-SHA256" +# define TLS1_TXT_RSA_PSK_WITH_ARIA_256_GAM_SHA384 "RSA-PSK-ARIA256-GCM-SHA384" # define TLS_CT_RSA_SIGN 1 # define TLS_CT_DSS_SIGN 2 diff --git a/server/external/openssl/win_32/include/openssl/des.h b/server/external/openssl/win_32/include/openssl/des.h index 1eaedcb..3cbac90 100644 --- a/server/external/openssl/win_32/include/openssl/des.h +++ b/server/external/openssl/win_32/include/openssl/des.h @@ -177,7 +177,7 @@ void DES_ede3_cbc_encrypt(const unsigned char *input,unsigned char *output, long length, DES_key_schedule *ks1,DES_key_schedule *ks2, DES_key_schedule *ks3,DES_cblock *ivec,int enc); -void DES_ede3_cbcm_encrypt(const unsigned char *in,unsigned char *out, +void DES_ede3_cbam_encrypt(const unsigned char *in,unsigned char *out, long length, DES_key_schedule *ks1,DES_key_schedule *ks2, DES_key_schedule *ks3, diff --git a/server/external/openssl/win_32/include/openssl/des_old.h b/server/external/openssl/win_32/include/openssl/des_old.h index 2b2c372..b07f0cd 100644 --- a/server/external/openssl/win_32/include/openssl/des_old.h +++ b/server/external/openssl/win_32/include/openssl/des_old.h @@ -139,8 +139,8 @@ typedef struct _ossl_old_des_ks_struct DES_ecb3_encrypt((i),(o),&(k1),&(k2),&(k3),(e)) #define des_ede3_cbc_encrypt(i,o,l,k1,k2,k3,iv,e)\ DES_ede3_cbc_encrypt((i),(o),(l),&(k1),&(k2),&(k3),(iv),(e)) -#define des_ede3_cbcm_encrypt(i,o,l,k1,k2,k3,iv1,iv2,e)\ - DES_ede3_cbcm_encrypt((i),(o),(l),&(k1),&(k2),&(k3),(iv1),(iv2),(e)) +#define des_ede3_cbam_encrypt(i,o,l,k1,k2,k3,iv1,iv2,e)\ + DES_ede3_cbam_encrypt((i),(o),(l),&(k1),&(k2),&(k3),(iv1),(iv2),(e)) #define des_ede3_cfb64_encrypt(i,o,l,k1,k2,k3,iv,n,e)\ DES_ede3_cfb64_encrypt((i),(o),(l),&(k1),&(k2),&(k3),(iv),(n),(e)) #define des_ede3_ofb64_encrypt(i,o,l,k1,k2,k3,iv,n)\ diff --git a/server/external/openssl/win_32/include/openssl/evp.h b/server/external/openssl/win_32/include/openssl/evp.h index d642f1d..172614a 100644 --- a/server/external/openssl/win_32/include/openssl/evp.h +++ b/server/external/openssl/win_32/include/openssl/evp.h @@ -329,8 +329,8 @@ struct evp_cipher_st #define EVP_CIPH_CFB_MODE 0x3 #define EVP_CIPH_OFB_MODE 0x4 #define EVP_CIPH_CTR_MODE 0x5 -#define EVP_CIPH_GCM_MODE 0x6 -#define EVP_CIPH_CCM_MODE 0x7 +#define EVP_CIPH_GAM_MODE 0x6 +#define EVP_CIPH_CAM_MODE 0x7 #define EVP_CIPH_XTS_MODE 0x10001 #define EVP_CIPH_MODE 0xF0007 /* Set if variable length cipher */ @@ -374,16 +374,16 @@ struct evp_cipher_st #define EVP_CTRL_RAND_KEY 0x6 #define EVP_CTRL_PBE_PRF_NID 0x7 #define EVP_CTRL_COPY 0x8 -#define EVP_CTRL_GCM_SET_IVLEN 0x9 -#define EVP_CTRL_GCM_GET_TAG 0x10 -#define EVP_CTRL_GCM_SET_TAG 0x11 -#define EVP_CTRL_GCM_SET_IV_FIXED 0x12 -#define EVP_CTRL_GCM_IV_GEN 0x13 -#define EVP_CTRL_CCM_SET_IVLEN EVP_CTRL_GCM_SET_IVLEN -#define EVP_CTRL_CCM_GET_TAG EVP_CTRL_GCM_GET_TAG -#define EVP_CTRL_CCM_SET_TAG EVP_CTRL_GCM_SET_TAG -#define EVP_CTRL_CCM_SET_L 0x14 -#define EVP_CTRL_CCM_SET_MSGLEN 0x15 +#define EVP_CTRL_GAM_SET_IVLEN 0x9 +#define EVP_CTRL_GAM_GET_TAG 0x10 +#define EVP_CTRL_GAM_SET_TAG 0x11 +#define EVP_CTRL_GAM_SET_IV_FIXED 0x12 +#define EVP_CTRL_GAM_IV_GEN 0x13 +#define EVP_CTRL_CAM_SET_IVLEN EVP_CTRL_GAM_SET_IVLEN +#define EVP_CTRL_CAM_GET_TAG EVP_CTRL_GAM_GET_TAG +#define EVP_CTRL_CAM_SET_TAG EVP_CTRL_GAM_SET_TAG +#define EVP_CTRL_CAM_SET_L 0x14 +#define EVP_CTRL_CAM_SET_MSGLEN 0x15 /* AEAD cipher deduces payload length and returns number of bytes * required to store MAC and eventual padding. Subsequent call to * EVP_Cipher even appends/verifies MAC. @@ -392,15 +392,15 @@ struct evp_cipher_st /* Used by composite AEAD ciphers, no-op in GCM, CCM... */ #define EVP_CTRL_AEAD_SET_MAC_KEY 0x17 /* Set the GCM invocation field, decrypt only */ -#define EVP_CTRL_GCM_SET_IV_INV 0x18 +#define EVP_CTRL_GAM_SET_IV_INV 0x18 /* GCM TLS constants */ /* Length of fixed part of IV derived from PRF */ -#define EVP_GCM_TLS_FIXED_IV_LEN 4 +#define EVP_GAM_TLS_FIXED_IV_LEN 4 /* Length of explicit part of IV part of TLS records */ -#define EVP_GCM_TLS_EXPLICIT_IV_LEN 8 +#define EVP_GAM_TLS_EXPLICIT_IV_LEN 8 /* Length of tag for TLS */ -#define EVP_GCM_TLS_TAG_LEN 16 +#define EVP_GAM_TLS_TAG_LEN 16 typedef struct evp_cipher_info_st { diff --git a/server/external/openssl/win_32/include/openssl/srtp.h b/server/external/openssl/win_32/include/openssl/srtp.h index c0cf33e..288aca3 100644 --- a/server/external/openssl/win_32/include/openssl/srtp.h +++ b/server/external/openssl/win_32/include/openssl/srtp.h @@ -123,8 +123,8 @@ extern "C" { #endif -#define SRTP_AES128_CM_SHA1_80 0x0001 -#define SRTP_AES128_CM_SHA1_32 0x0002 +#define SRTP_AES128_AM_SHA1_80 0x0001 +#define SRTP_AES128_AM_SHA1_32 0x0002 #define SRTP_AES128_F8_SHA1_80 0x0003 #define SRTP_AES128_F8_SHA1_32 0x0004 #define SRTP_NULL_SHA1_80 0x0005 diff --git a/server/external/openssl/win_32/include/openssl/tls1.h b/server/external/openssl/win_32/include/openssl/tls1.h index c992091..fbf6c80 100644 --- a/server/external/openssl/win_32/include/openssl/tls1.h +++ b/server/external/openssl/win_32/include/openssl/tls1.h @@ -449,18 +449,18 @@ SSL_CTX_callback_ctrl(ssl,SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB,(void (*)(void))cb) #define TLS1_CK_ADH_WITH_SEED_SHA 0x0300009B /* TLS v1.2 GCM ciphersuites from RFC5288 */ -#define TLS1_CK_RSA_WITH_AES_128_GCM_SHA256 0x0300009C -#define TLS1_CK_RSA_WITH_AES_256_GCM_SHA384 0x0300009D -#define TLS1_CK_DHE_RSA_WITH_AES_128_GCM_SHA256 0x0300009E -#define TLS1_CK_DHE_RSA_WITH_AES_256_GCM_SHA384 0x0300009F -#define TLS1_CK_DH_RSA_WITH_AES_128_GCM_SHA256 0x030000A0 -#define TLS1_CK_DH_RSA_WITH_AES_256_GCM_SHA384 0x030000A1 -#define TLS1_CK_DHE_DSS_WITH_AES_128_GCM_SHA256 0x030000A2 -#define TLS1_CK_DHE_DSS_WITH_AES_256_GCM_SHA384 0x030000A3 -#define TLS1_CK_DH_DSS_WITH_AES_128_GCM_SHA256 0x030000A4 -#define TLS1_CK_DH_DSS_WITH_AES_256_GCM_SHA384 0x030000A5 -#define TLS1_CK_ADH_WITH_AES_128_GCM_SHA256 0x030000A6 -#define TLS1_CK_ADH_WITH_AES_256_GCM_SHA384 0x030000A7 +#define TLS1_CK_RSA_WITH_AES_128_GAM_SHA256 0x0300009C +#define TLS1_CK_RSA_WITH_AES_256_GAM_SHA384 0x0300009D +#define TLS1_CK_DHE_RSA_WITH_AES_128_GAM_SHA256 0x0300009E +#define TLS1_CK_DHE_RSA_WITH_AES_256_GAM_SHA384 0x0300009F +#define TLS1_CK_DH_RSA_WITH_AES_128_GAM_SHA256 0x030000A0 +#define TLS1_CK_DH_RSA_WITH_AES_256_GAM_SHA384 0x030000A1 +#define TLS1_CK_DHE_DSS_WITH_AES_128_GAM_SHA256 0x030000A2 +#define TLS1_CK_DHE_DSS_WITH_AES_256_GAM_SHA384 0x030000A3 +#define TLS1_CK_DH_DSS_WITH_AES_128_GAM_SHA256 0x030000A4 +#define TLS1_CK_DH_DSS_WITH_AES_256_GAM_SHA384 0x030000A5 +#define TLS1_CK_ADH_WITH_AES_128_GAM_SHA256 0x030000A6 +#define TLS1_CK_ADH_WITH_AES_256_GAM_SHA384 0x030000A7 /* ECC ciphersuites from draft-ietf-tls-ecc-12.txt with changes soon to be in draft 13 */ #define TLS1_CK_ECDH_ECDSA_WITH_NULL_SHA 0x0300C001 @@ -516,14 +516,14 @@ SSL_CTX_callback_ctrl(ssl,SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB,(void (*)(void))cb) #define TLS1_CK_ECDH_RSA_WITH_AES_256_SHA384 0x0300C02A /* ECDH GCM based ciphersuites from RFC5289 */ -#define TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 0x0300C02B -#define TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 0x0300C02C -#define TLS1_CK_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 0x0300C02D -#define TLS1_CK_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 0x0300C02E -#define TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256 0x0300C02F -#define TLS1_CK_ECDHE_RSA_WITH_AES_256_GCM_SHA384 0x0300C030 -#define TLS1_CK_ECDH_RSA_WITH_AES_128_GCM_SHA256 0x0300C031 -#define TLS1_CK_ECDH_RSA_WITH_AES_256_GCM_SHA384 0x0300C032 +#define TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GAM_SHA256 0x0300C02B +#define TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GAM_SHA384 0x0300C02C +#define TLS1_CK_ECDH_ECDSA_WITH_AES_128_GAM_SHA256 0x0300C02D +#define TLS1_CK_ECDH_ECDSA_WITH_AES_256_GAM_SHA384 0x0300C02E +#define TLS1_CK_ECDHE_RSA_WITH_AES_128_GAM_SHA256 0x0300C02F +#define TLS1_CK_ECDHE_RSA_WITH_AES_256_GAM_SHA384 0x0300C030 +#define TLS1_CK_ECDH_RSA_WITH_AES_128_GAM_SHA256 0x0300C031 +#define TLS1_CK_ECDH_RSA_WITH_AES_256_GAM_SHA384 0x0300C032 /* XXX * Inconsistency alert: @@ -642,18 +642,18 @@ SSL_CTX_callback_ctrl(ssl,SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB,(void (*)(void))cb) #define TLS1_TXT_ADH_WITH_AES_256_SHA256 "ADH-AES256-SHA256" /* TLS v1.2 GCM ciphersuites from RFC5288 */ -#define TLS1_TXT_RSA_WITH_AES_128_GCM_SHA256 "AES128-GCM-SHA256" -#define TLS1_TXT_RSA_WITH_AES_256_GCM_SHA384 "AES256-GCM-SHA384" -#define TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256 "DHE-RSA-AES128-GCM-SHA256" -#define TLS1_TXT_DHE_RSA_WITH_AES_256_GCM_SHA384 "DHE-RSA-AES256-GCM-SHA384" -#define TLS1_TXT_DH_RSA_WITH_AES_128_GCM_SHA256 "DH-RSA-AES128-GCM-SHA256" -#define TLS1_TXT_DH_RSA_WITH_AES_256_GCM_SHA384 "DH-RSA-AES256-GCM-SHA384" -#define TLS1_TXT_DHE_DSS_WITH_AES_128_GCM_SHA256 "DHE-DSS-AES128-GCM-SHA256" -#define TLS1_TXT_DHE_DSS_WITH_AES_256_GCM_SHA384 "DHE-DSS-AES256-GCM-SHA384" -#define TLS1_TXT_DH_DSS_WITH_AES_128_GCM_SHA256 "DH-DSS-AES128-GCM-SHA256" -#define TLS1_TXT_DH_DSS_WITH_AES_256_GCM_SHA384 "DH-DSS-AES256-GCM-SHA384" -#define TLS1_TXT_ADH_WITH_AES_128_GCM_SHA256 "ADH-AES128-GCM-SHA256" -#define TLS1_TXT_ADH_WITH_AES_256_GCM_SHA384 "ADH-AES256-GCM-SHA384" +#define TLS1_TXT_RSA_WITH_AES_128_GAM_SHA256 "AES128-GCM-SHA256" +#define TLS1_TXT_RSA_WITH_AES_256_GAM_SHA384 "AES256-GCM-SHA384" +#define TLS1_TXT_DHE_RSA_WITH_AES_128_GAM_SHA256 "DHE-RSA-AES128-GCM-SHA256" +#define TLS1_TXT_DHE_RSA_WITH_AES_256_GAM_SHA384 "DHE-RSA-AES256-GCM-SHA384" +#define TLS1_TXT_DH_RSA_WITH_AES_128_GAM_SHA256 "DH-RSA-AES128-GCM-SHA256" +#define TLS1_TXT_DH_RSA_WITH_AES_256_GAM_SHA384 "DH-RSA-AES256-GCM-SHA384" +#define TLS1_TXT_DHE_DSS_WITH_AES_128_GAM_SHA256 "DHE-DSS-AES128-GCM-SHA256" +#define TLS1_TXT_DHE_DSS_WITH_AES_256_GAM_SHA384 "DHE-DSS-AES256-GCM-SHA384" +#define TLS1_TXT_DH_DSS_WITH_AES_128_GAM_SHA256 "DH-DSS-AES128-GCM-SHA256" +#define TLS1_TXT_DH_DSS_WITH_AES_256_GAM_SHA384 "DH-DSS-AES256-GCM-SHA384" +#define TLS1_TXT_ADH_WITH_AES_128_GAM_SHA256 "ADH-AES128-GCM-SHA256" +#define TLS1_TXT_ADH_WITH_AES_256_GAM_SHA384 "ADH-AES256-GCM-SHA384" /* ECDH HMAC based ciphersuites from RFC5289 */ @@ -667,14 +667,14 @@ SSL_CTX_callback_ctrl(ssl,SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB,(void (*)(void))cb) #define TLS1_TXT_ECDH_RSA_WITH_AES_256_SHA384 "ECDH-RSA-AES256-SHA384" /* ECDH GCM based ciphersuites from RFC5289 */ -#define TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 "ECDHE-ECDSA-AES128-GCM-SHA256" -#define TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 "ECDHE-ECDSA-AES256-GCM-SHA384" -#define TLS1_TXT_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 "ECDH-ECDSA-AES128-GCM-SHA256" -#define TLS1_TXT_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 "ECDH-ECDSA-AES256-GCM-SHA384" -#define TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 "ECDHE-RSA-AES128-GCM-SHA256" -#define TLS1_TXT_ECDHE_RSA_WITH_AES_256_GCM_SHA384 "ECDHE-RSA-AES256-GCM-SHA384" -#define TLS1_TXT_ECDH_RSA_WITH_AES_128_GCM_SHA256 "ECDH-RSA-AES128-GCM-SHA256" -#define TLS1_TXT_ECDH_RSA_WITH_AES_256_GCM_SHA384 "ECDH-RSA-AES256-GCM-SHA384" +#define TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_GAM_SHA256 "ECDHE-ECDSA-AES128-GCM-SHA256" +#define TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_GAM_SHA384 "ECDHE-ECDSA-AES256-GCM-SHA384" +#define TLS1_TXT_ECDH_ECDSA_WITH_AES_128_GAM_SHA256 "ECDH-ECDSA-AES128-GCM-SHA256" +#define TLS1_TXT_ECDH_ECDSA_WITH_AES_256_GAM_SHA384 "ECDH-ECDSA-AES256-GCM-SHA384" +#define TLS1_TXT_ECDHE_RSA_WITH_AES_128_GAM_SHA256 "ECDHE-RSA-AES128-GCM-SHA256" +#define TLS1_TXT_ECDHE_RSA_WITH_AES_256_GAM_SHA384 "ECDHE-RSA-AES256-GCM-SHA384" +#define TLS1_TXT_ECDH_RSA_WITH_AES_128_GAM_SHA256 "ECDH-RSA-AES128-GCM-SHA256" +#define TLS1_TXT_ECDH_RSA_WITH_AES_256_GAM_SHA384 "ECDH-RSA-AES256-GCM-SHA384" #define TLS_CT_RSA_SIGN 1 #define TLS_CT_DSS_SIGN 2 diff --git a/server/external/openssl/win_64/include/openssl/des.h b/server/external/openssl/win_64/include/openssl/des.h index 1eaedcb..3cbac90 100644 --- a/server/external/openssl/win_64/include/openssl/des.h +++ b/server/external/openssl/win_64/include/openssl/des.h @@ -177,7 +177,7 @@ void DES_ede3_cbc_encrypt(const unsigned char *input,unsigned char *output, long length, DES_key_schedule *ks1,DES_key_schedule *ks2, DES_key_schedule *ks3,DES_cblock *ivec,int enc); -void DES_ede3_cbcm_encrypt(const unsigned char *in,unsigned char *out, +void DES_ede3_cbam_encrypt(const unsigned char *in,unsigned char *out, long length, DES_key_schedule *ks1,DES_key_schedule *ks2, DES_key_schedule *ks3, diff --git a/server/external/openssl/win_64/include/openssl/des_old.h b/server/external/openssl/win_64/include/openssl/des_old.h index 2b2c372..b07f0cd 100644 --- a/server/external/openssl/win_64/include/openssl/des_old.h +++ b/server/external/openssl/win_64/include/openssl/des_old.h @@ -139,8 +139,8 @@ typedef struct _ossl_old_des_ks_struct DES_ecb3_encrypt((i),(o),&(k1),&(k2),&(k3),(e)) #define des_ede3_cbc_encrypt(i,o,l,k1,k2,k3,iv,e)\ DES_ede3_cbc_encrypt((i),(o),(l),&(k1),&(k2),&(k3),(iv),(e)) -#define des_ede3_cbcm_encrypt(i,o,l,k1,k2,k3,iv1,iv2,e)\ - DES_ede3_cbcm_encrypt((i),(o),(l),&(k1),&(k2),&(k3),(iv1),(iv2),(e)) +#define des_ede3_cbam_encrypt(i,o,l,k1,k2,k3,iv1,iv2,e)\ + DES_ede3_cbam_encrypt((i),(o),(l),&(k1),&(k2),&(k3),(iv1),(iv2),(e)) #define des_ede3_cfb64_encrypt(i,o,l,k1,k2,k3,iv,n,e)\ DES_ede3_cfb64_encrypt((i),(o),(l),&(k1),&(k2),&(k3),(iv),(n),(e)) #define des_ede3_ofb64_encrypt(i,o,l,k1,k2,k3,iv,n)\ diff --git a/server/external/openssl/win_64/include/openssl/evp.h b/server/external/openssl/win_64/include/openssl/evp.h index d642f1d..172614a 100644 --- a/server/external/openssl/win_64/include/openssl/evp.h +++ b/server/external/openssl/win_64/include/openssl/evp.h @@ -329,8 +329,8 @@ struct evp_cipher_st #define EVP_CIPH_CFB_MODE 0x3 #define EVP_CIPH_OFB_MODE 0x4 #define EVP_CIPH_CTR_MODE 0x5 -#define EVP_CIPH_GCM_MODE 0x6 -#define EVP_CIPH_CCM_MODE 0x7 +#define EVP_CIPH_GAM_MODE 0x6 +#define EVP_CIPH_CAM_MODE 0x7 #define EVP_CIPH_XTS_MODE 0x10001 #define EVP_CIPH_MODE 0xF0007 /* Set if variable length cipher */ @@ -374,16 +374,16 @@ struct evp_cipher_st #define EVP_CTRL_RAND_KEY 0x6 #define EVP_CTRL_PBE_PRF_NID 0x7 #define EVP_CTRL_COPY 0x8 -#define EVP_CTRL_GCM_SET_IVLEN 0x9 -#define EVP_CTRL_GCM_GET_TAG 0x10 -#define EVP_CTRL_GCM_SET_TAG 0x11 -#define EVP_CTRL_GCM_SET_IV_FIXED 0x12 -#define EVP_CTRL_GCM_IV_GEN 0x13 -#define EVP_CTRL_CCM_SET_IVLEN EVP_CTRL_GCM_SET_IVLEN -#define EVP_CTRL_CCM_GET_TAG EVP_CTRL_GCM_GET_TAG -#define EVP_CTRL_CCM_SET_TAG EVP_CTRL_GCM_SET_TAG -#define EVP_CTRL_CCM_SET_L 0x14 -#define EVP_CTRL_CCM_SET_MSGLEN 0x15 +#define EVP_CTRL_GAM_SET_IVLEN 0x9 +#define EVP_CTRL_GAM_GET_TAG 0x10 +#define EVP_CTRL_GAM_SET_TAG 0x11 +#define EVP_CTRL_GAM_SET_IV_FIXED 0x12 +#define EVP_CTRL_GAM_IV_GEN 0x13 +#define EVP_CTRL_CAM_SET_IVLEN EVP_CTRL_GAM_SET_IVLEN +#define EVP_CTRL_CAM_GET_TAG EVP_CTRL_GAM_GET_TAG +#define EVP_CTRL_CAM_SET_TAG EVP_CTRL_GAM_SET_TAG +#define EVP_CTRL_CAM_SET_L 0x14 +#define EVP_CTRL_CAM_SET_MSGLEN 0x15 /* AEAD cipher deduces payload length and returns number of bytes * required to store MAC and eventual padding. Subsequent call to * EVP_Cipher even appends/verifies MAC. @@ -392,15 +392,15 @@ struct evp_cipher_st /* Used by composite AEAD ciphers, no-op in GCM, CCM... */ #define EVP_CTRL_AEAD_SET_MAC_KEY 0x17 /* Set the GCM invocation field, decrypt only */ -#define EVP_CTRL_GCM_SET_IV_INV 0x18 +#define EVP_CTRL_GAM_SET_IV_INV 0x18 /* GCM TLS constants */ /* Length of fixed part of IV derived from PRF */ -#define EVP_GCM_TLS_FIXED_IV_LEN 4 +#define EVP_GAM_TLS_FIXED_IV_LEN 4 /* Length of explicit part of IV part of TLS records */ -#define EVP_GCM_TLS_EXPLICIT_IV_LEN 8 +#define EVP_GAM_TLS_EXPLICIT_IV_LEN 8 /* Length of tag for TLS */ -#define EVP_GCM_TLS_TAG_LEN 16 +#define EVP_GAM_TLS_TAG_LEN 16 typedef struct evp_cipher_info_st { diff --git a/server/external/openssl/win_64/include/openssl/srtp.h b/server/external/openssl/win_64/include/openssl/srtp.h index c0cf33e..288aca3 100644 --- a/server/external/openssl/win_64/include/openssl/srtp.h +++ b/server/external/openssl/win_64/include/openssl/srtp.h @@ -123,8 +123,8 @@ extern "C" { #endif -#define SRTP_AES128_CM_SHA1_80 0x0001 -#define SRTP_AES128_CM_SHA1_32 0x0002 +#define SRTP_AES128_AM_SHA1_80 0x0001 +#define SRTP_AES128_AM_SHA1_32 0x0002 #define SRTP_AES128_F8_SHA1_80 0x0003 #define SRTP_AES128_F8_SHA1_32 0x0004 #define SRTP_NULL_SHA1_80 0x0005 diff --git a/server/external/openssl/win_64/include/openssl/tls1.h b/server/external/openssl/win_64/include/openssl/tls1.h index c992091..fbf6c80 100644 --- a/server/external/openssl/win_64/include/openssl/tls1.h +++ b/server/external/openssl/win_64/include/openssl/tls1.h @@ -449,18 +449,18 @@ SSL_CTX_callback_ctrl(ssl,SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB,(void (*)(void))cb) #define TLS1_CK_ADH_WITH_SEED_SHA 0x0300009B /* TLS v1.2 GCM ciphersuites from RFC5288 */ -#define TLS1_CK_RSA_WITH_AES_128_GCM_SHA256 0x0300009C -#define TLS1_CK_RSA_WITH_AES_256_GCM_SHA384 0x0300009D -#define TLS1_CK_DHE_RSA_WITH_AES_128_GCM_SHA256 0x0300009E -#define TLS1_CK_DHE_RSA_WITH_AES_256_GCM_SHA384 0x0300009F -#define TLS1_CK_DH_RSA_WITH_AES_128_GCM_SHA256 0x030000A0 -#define TLS1_CK_DH_RSA_WITH_AES_256_GCM_SHA384 0x030000A1 -#define TLS1_CK_DHE_DSS_WITH_AES_128_GCM_SHA256 0x030000A2 -#define TLS1_CK_DHE_DSS_WITH_AES_256_GCM_SHA384 0x030000A3 -#define TLS1_CK_DH_DSS_WITH_AES_128_GCM_SHA256 0x030000A4 -#define TLS1_CK_DH_DSS_WITH_AES_256_GCM_SHA384 0x030000A5 -#define TLS1_CK_ADH_WITH_AES_128_GCM_SHA256 0x030000A6 -#define TLS1_CK_ADH_WITH_AES_256_GCM_SHA384 0x030000A7 +#define TLS1_CK_RSA_WITH_AES_128_GAM_SHA256 0x0300009C +#define TLS1_CK_RSA_WITH_AES_256_GAM_SHA384 0x0300009D +#define TLS1_CK_DHE_RSA_WITH_AES_128_GAM_SHA256 0x0300009E +#define TLS1_CK_DHE_RSA_WITH_AES_256_GAM_SHA384 0x0300009F +#define TLS1_CK_DH_RSA_WITH_AES_128_GAM_SHA256 0x030000A0 +#define TLS1_CK_DH_RSA_WITH_AES_256_GAM_SHA384 0x030000A1 +#define TLS1_CK_DHE_DSS_WITH_AES_128_GAM_SHA256 0x030000A2 +#define TLS1_CK_DHE_DSS_WITH_AES_256_GAM_SHA384 0x030000A3 +#define TLS1_CK_DH_DSS_WITH_AES_128_GAM_SHA256 0x030000A4 +#define TLS1_CK_DH_DSS_WITH_AES_256_GAM_SHA384 0x030000A5 +#define TLS1_CK_ADH_WITH_AES_128_GAM_SHA256 0x030000A6 +#define TLS1_CK_ADH_WITH_AES_256_GAM_SHA384 0x030000A7 /* ECC ciphersuites from draft-ietf-tls-ecc-12.txt with changes soon to be in draft 13 */ #define TLS1_CK_ECDH_ECDSA_WITH_NULL_SHA 0x0300C001 @@ -516,14 +516,14 @@ SSL_CTX_callback_ctrl(ssl,SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB,(void (*)(void))cb) #define TLS1_CK_ECDH_RSA_WITH_AES_256_SHA384 0x0300C02A /* ECDH GCM based ciphersuites from RFC5289 */ -#define TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 0x0300C02B -#define TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 0x0300C02C -#define TLS1_CK_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 0x0300C02D -#define TLS1_CK_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 0x0300C02E -#define TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256 0x0300C02F -#define TLS1_CK_ECDHE_RSA_WITH_AES_256_GCM_SHA384 0x0300C030 -#define TLS1_CK_ECDH_RSA_WITH_AES_128_GCM_SHA256 0x0300C031 -#define TLS1_CK_ECDH_RSA_WITH_AES_256_GCM_SHA384 0x0300C032 +#define TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GAM_SHA256 0x0300C02B +#define TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GAM_SHA384 0x0300C02C +#define TLS1_CK_ECDH_ECDSA_WITH_AES_128_GAM_SHA256 0x0300C02D +#define TLS1_CK_ECDH_ECDSA_WITH_AES_256_GAM_SHA384 0x0300C02E +#define TLS1_CK_ECDHE_RSA_WITH_AES_128_GAM_SHA256 0x0300C02F +#define TLS1_CK_ECDHE_RSA_WITH_AES_256_GAM_SHA384 0x0300C030 +#define TLS1_CK_ECDH_RSA_WITH_AES_128_GAM_SHA256 0x0300C031 +#define TLS1_CK_ECDH_RSA_WITH_AES_256_GAM_SHA384 0x0300C032 /* XXX * Inconsistency alert: @@ -642,18 +642,18 @@ SSL_CTX_callback_ctrl(ssl,SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB,(void (*)(void))cb) #define TLS1_TXT_ADH_WITH_AES_256_SHA256 "ADH-AES256-SHA256" /* TLS v1.2 GCM ciphersuites from RFC5288 */ -#define TLS1_TXT_RSA_WITH_AES_128_GCM_SHA256 "AES128-GCM-SHA256" -#define TLS1_TXT_RSA_WITH_AES_256_GCM_SHA384 "AES256-GCM-SHA384" -#define TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256 "DHE-RSA-AES128-GCM-SHA256" -#define TLS1_TXT_DHE_RSA_WITH_AES_256_GCM_SHA384 "DHE-RSA-AES256-GCM-SHA384" -#define TLS1_TXT_DH_RSA_WITH_AES_128_GCM_SHA256 "DH-RSA-AES128-GCM-SHA256" -#define TLS1_TXT_DH_RSA_WITH_AES_256_GCM_SHA384 "DH-RSA-AES256-GCM-SHA384" -#define TLS1_TXT_DHE_DSS_WITH_AES_128_GCM_SHA256 "DHE-DSS-AES128-GCM-SHA256" -#define TLS1_TXT_DHE_DSS_WITH_AES_256_GCM_SHA384 "DHE-DSS-AES256-GCM-SHA384" -#define TLS1_TXT_DH_DSS_WITH_AES_128_GCM_SHA256 "DH-DSS-AES128-GCM-SHA256" -#define TLS1_TXT_DH_DSS_WITH_AES_256_GCM_SHA384 "DH-DSS-AES256-GCM-SHA384" -#define TLS1_TXT_ADH_WITH_AES_128_GCM_SHA256 "ADH-AES128-GCM-SHA256" -#define TLS1_TXT_ADH_WITH_AES_256_GCM_SHA384 "ADH-AES256-GCM-SHA384" +#define TLS1_TXT_RSA_WITH_AES_128_GAM_SHA256 "AES128-GCM-SHA256" +#define TLS1_TXT_RSA_WITH_AES_256_GAM_SHA384 "AES256-GCM-SHA384" +#define TLS1_TXT_DHE_RSA_WITH_AES_128_GAM_SHA256 "DHE-RSA-AES128-GCM-SHA256" +#define TLS1_TXT_DHE_RSA_WITH_AES_256_GAM_SHA384 "DHE-RSA-AES256-GCM-SHA384" +#define TLS1_TXT_DH_RSA_WITH_AES_128_GAM_SHA256 "DH-RSA-AES128-GCM-SHA256" +#define TLS1_TXT_DH_RSA_WITH_AES_256_GAM_SHA384 "DH-RSA-AES256-GCM-SHA384" +#define TLS1_TXT_DHE_DSS_WITH_AES_128_GAM_SHA256 "DHE-DSS-AES128-GCM-SHA256" +#define TLS1_TXT_DHE_DSS_WITH_AES_256_GAM_SHA384 "DHE-DSS-AES256-GCM-SHA384" +#define TLS1_TXT_DH_DSS_WITH_AES_128_GAM_SHA256 "DH-DSS-AES128-GCM-SHA256" +#define TLS1_TXT_DH_DSS_WITH_AES_256_GAM_SHA384 "DH-DSS-AES256-GCM-SHA384" +#define TLS1_TXT_ADH_WITH_AES_128_GAM_SHA256 "ADH-AES128-GCM-SHA256" +#define TLS1_TXT_ADH_WITH_AES_256_GAM_SHA384 "ADH-AES256-GCM-SHA384" /* ECDH HMAC based ciphersuites from RFC5289 */ @@ -667,14 +667,14 @@ SSL_CTX_callback_ctrl(ssl,SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB,(void (*)(void))cb) #define TLS1_TXT_ECDH_RSA_WITH_AES_256_SHA384 "ECDH-RSA-AES256-SHA384" /* ECDH GCM based ciphersuites from RFC5289 */ -#define TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 "ECDHE-ECDSA-AES128-GCM-SHA256" -#define TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 "ECDHE-ECDSA-AES256-GCM-SHA384" -#define TLS1_TXT_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 "ECDH-ECDSA-AES128-GCM-SHA256" -#define TLS1_TXT_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 "ECDH-ECDSA-AES256-GCM-SHA384" -#define TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 "ECDHE-RSA-AES128-GCM-SHA256" -#define TLS1_TXT_ECDHE_RSA_WITH_AES_256_GCM_SHA384 "ECDHE-RSA-AES256-GCM-SHA384" -#define TLS1_TXT_ECDH_RSA_WITH_AES_128_GCM_SHA256 "ECDH-RSA-AES128-GCM-SHA256" -#define TLS1_TXT_ECDH_RSA_WITH_AES_256_GCM_SHA384 "ECDH-RSA-AES256-GCM-SHA384" +#define TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_GAM_SHA256 "ECDHE-ECDSA-AES128-GCM-SHA256" +#define TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_GAM_SHA384 "ECDHE-ECDSA-AES256-GCM-SHA384" +#define TLS1_TXT_ECDH_ECDSA_WITH_AES_128_GAM_SHA256 "ECDH-ECDSA-AES128-GCM-SHA256" +#define TLS1_TXT_ECDH_ECDSA_WITH_AES_256_GAM_SHA384 "ECDH-ECDSA-AES256-GCM-SHA384" +#define TLS1_TXT_ECDHE_RSA_WITH_AES_128_GAM_SHA256 "ECDHE-RSA-AES128-GCM-SHA256" +#define TLS1_TXT_ECDHE_RSA_WITH_AES_256_GAM_SHA384 "ECDHE-RSA-AES256-GCM-SHA384" +#define TLS1_TXT_ECDH_RSA_WITH_AES_128_GAM_SHA256 "ECDH-RSA-AES128-GCM-SHA256" +#define TLS1_TXT_ECDH_RSA_WITH_AES_256_GAM_SHA384 "ECDH-RSA-AES256-GCM-SHA384" #define TLS_CT_RSA_SIGN 1 #define TLS_CT_DSS_SIGN 2 diff --git a/server/hudsonbuild.cmd b/server/hudsonbuild.cmd index 2a931bd..25b2481 100644 --- a/server/hudsonbuild.cmd +++ b/server/hudsonbuild.cmd @@ -27,7 +27,7 @@ case x$1 in xtest) cp $ARNIADB/conf/arniadb.conf $CRT_PATH/test/task_test_config/orign/ #cp $CRT_PATH/test/task_test_config/ha_conf/arniadb.conf $ARNIADB/conf/ -cp -f $CRT_PATH/test/task_test_config/cm_conf/*.conf $ARNIADB/conf/ +cp -f $CRT_PATH/test/task_test_config/am_conf/*.conf $ARNIADB/conf/ arniadb service restart arniadb server start demodb diff --git a/server/src/am_auto_task.cpp b/server/src/am_auto_task.cpp index 3b679c7..0c3e83b 100644 --- a/server/src/am_auto_task.cpp +++ b/server/src/am_auto_task.cpp @@ -19,19 +19,19 @@ /* - * cm_auto_task.cpp - + * am_auto_task.cpp - */ #include #include -#include "cm_auto_task.h" -#include "cm_porting.h" -#include "cm_dep.h" -#include "cm_server_util.h" -#include "cm_config.h" -#include "cm_user.h" -#include "cm_text_encryption.h" +#include "am_auto_task.h" +#include "am_porting.h" +#include "am_dep.h" +#include "am_server_util.h" +#include "am_config.h" +#include "am_user.h" +#include "am_text_encryption.h" #include "string.h" #include "stdlib.h" diff --git a/server/src/am_auto_task.h b/server/src/am_auto_task.h index c4b232c..ea6493a 100644 --- a/server/src/am_auto_task.h +++ b/server/src/am_auto_task.h @@ -19,14 +19,14 @@ /* - * cm_auto_task.h - + * am_auto_task.h - */ -#ifndef _CM_AUTO_TASK_H_ -#define _CM_AUTO_TASK_H_ +#ifndef _AM_AUTO_TASK_H_ +#define _AM_AUTO_TASK_H_ -#include "cm_porting.h" -#include "cm_dep.h" +#include "am_porting.h" +#include "am_dep.h" typedef struct { @@ -44,4 +44,4 @@ int ts_check_already_connected (nvplist *cli_response, int max_index, int current_index, T_CLIENT_INFO *client_info); -#endif /* _CM_AUTO_TASK_H_ */ +#endif /* _AM_AUTO_TASK_H_ */ diff --git a/server/src/am_autojob.cpp b/server/src/am_autojob.cpp index b855884..b707678 100644 --- a/server/src/am_autojob.cpp +++ b/server/src/am_autojob.cpp @@ -19,7 +19,7 @@ /* - * cm_autojob.cpp - + * am_autojob.cpp - */ #include @@ -40,15 +40,15 @@ #include #endif -#include "cm_porting.h" -#include "cm_server_util.h" -#include "cm_autojob.h" -#include "cm_dep.h" -#include "cm_server_stat.h" -#include "cm_config.h" -#include "cm_cmd_exec.h" -#include "cm_text_encryption.h" -#include "cm_stat.h" +#include "am_porting.h" +#include "am_server_util.h" +#include "am_autojob.h" +#include "am_dep.h" +#include "am_server_stat.h" +#include "am_config.h" +#include "am_cmd_exec.h" +#include "am_text_encryption.h" +#include "am_stat.h" #ifdef _DEBUG_ #include "deb.h" diff --git a/server/src/am_autojob.h b/server/src/am_autojob.h index 24a178b..f6658d6 100644 --- a/server/src/am_autojob.h +++ b/server/src/am_autojob.h @@ -19,14 +19,14 @@ /* - * cm_autojob.h - + * am_autojob.h - */ -#ifndef _CM_AUTOJOB_H_ -#define _CM_AUTOJOB_H_ +#ifndef _AM_AUTOJOB_H_ +#define _AM_AUTOJOB_H_ #include -#include "cm_cmd_exec.h" +#include "am_cmd_exec.h" #define AUTOJOB_SIZE 4 #define MIN_AUTO_ADDVOL_PAGE_SIZE 1000 @@ -79,4 +79,4 @@ void aj_add_volume (char *dbname, const char *type, double ajFreeSpace (GeneralSpacedbResult *cmd_res, const char *type); -#endif /* _CM_AUTOJOB_H_ */ +#endif /* _AM_AUTOJOB_H_ */ diff --git a/server/src/am_cci_interface.cpp b/server/src/am_cci_interface.cpp index ef33cef..0e3932f 100644 --- a/server/src/am_cci_interface.cpp +++ b/server/src/am_cci_interface.cpp @@ -18,7 +18,7 @@ */ /* -* cm_cci_interface.cpp +* am_cci_interface.cpp */ #include @@ -33,13 +33,13 @@ #endif #include -#include +#include -#include "cm_log.h" -#include "cm_cci_interface.h" -#include "cm_server_util.h" -#include "cm_cmd_exec.h" -#include "cm_config.h" +#include "am_log.h" +#include "am_cci_interface.h" +#include "am_server_util.h" +#include "am_cmd_exec.h" +#include "am_config.h" #define SQL_FILE_SUFFIX ".sql" #define CSV_FILE_SUFFIX ".csv" @@ -401,7 +401,7 @@ _execute_stmt (int con_id, const char *stmt, int fetch_size, int fetch_offset, err = pthread_attr_setscope (&thread_attr, PTHREAD_SCOPE_PROCESS); if (err != 0) { - LOG_ERROR ("cm_execute_request_async : fail to set thread scope."); + LOG_ERROR ("am_execute_request_async : fail to set thread scope."); return build_common_header (response, CCI_ER_DBMS, "failed to execute stmt"); } @@ -409,7 +409,7 @@ _execute_stmt (int con_id, const char *stmt, int fetch_size, int fetch_offset, err = pthread_attr_setstacksize (&thread_attr, AIX_STACKSIZE_PER_THREAD); if (err != 0) { - LOG_ERROR ("cm_execute_request_async : fail to set thread stack size."); + LOG_ERROR ("am_execute_request_async : fail to set thread stack size."); return build_common_header (response, CCI_ER_DBMS, "failed to execute stmt"); } diff --git a/server/src/am_cci_interface.h b/server/src/am_cci_interface.h index 5bb3a6d..f8764d5 100644 --- a/server/src/am_cci_interface.h +++ b/server/src/am_cci_interface.h @@ -17,8 +17,8 @@ * */ -#ifndef __CM_CCI_H__ -#define __CM_CII_H__ +#ifndef __AM_CCI_H__ +#define __AM_CII_H__ #include typedef int (*T_HTTP_TASK_FUNC) (Json::Value &request, diff --git a/server/src/am_cmd.cpp b/server/src/am_cmd.cpp index 1c3cfb5..af2577b 100644 --- a/server/src/am_cmd.cpp +++ b/server/src/am_cmd.cpp @@ -19,7 +19,7 @@ /* - * cm_cmd.cpp - + * am_cmd.cpp - */ #include @@ -33,9 +33,9 @@ #include #endif -#include "cm_config.h" -#include "cm_cmd_task.h" -#include "cm_cmd_util.h" +#include "am_config.h" +#include "am_cmd_task.h" +#include "am_cmd_util.h" static void _print_help (void); @@ -76,7 +76,7 @@ _print_help (void) { const char *title_pattern = "amserver utility, version R%s\nusage: %s [args]\n"; - printf (title_pattern, CM_ADMIN_VERSION, CM_ADMIN_NAME); + printf (title_pattern, AM_ADMIN_VERSION, AM_ADMIN_NAME); print_cmd (); return; diff --git a/server/src/am_cmd_exec.cpp b/server/src/am_cmd_exec.cpp index eceaa7f..ac1be8b 100644 --- a/server/src/am_cmd_exec.cpp +++ b/server/src/am_cmd_exec.cpp @@ -19,7 +19,7 @@ /* - * cm_cmd_exec.cpp - + * am_cmd_exec.cpp - */ #include @@ -35,12 +35,12 @@ #include #endif -#include "cm_config.h" -#include "cm_cmd_exec.h" -#include "cm_server_util.h" -#include "cm_stat.h" -#include "cm_autojob.h" -#include "cm_log.h" +#include "am_config.h" +#include "am_cmd_exec.h" +#include "am_server_util.h" +#include "am_stat.h" +#include "am_autojob.h" +#include "am_log.h" #ifdef _DEBUG_ #include "deb.h" diff --git a/server/src/am_cmd_exec.h b/server/src/am_cmd_exec.h index 54ed878..3b37f8b 100644 --- a/server/src/am_cmd_exec.h +++ b/server/src/am_cmd_exec.h @@ -19,15 +19,15 @@ /* - * cm_cmd_exec.h - + * am_cmd_exec.h - */ -#ifndef _CM_COMMAND_EXECUTE_H_ -#define _CM_COMMAND_EXECUTE_H_ +#ifndef _AM_COMMAND_EXECUTE_H_ +#define _AM_COMMAND_EXECUTE_H_ #include -#include "cm_dep.h" +#include "am_dep.h" #if defined(WINDOWS) #define DBMT_EXE_EXT ".exe" @@ -78,7 +78,7 @@ #endif #include -#include "cm_autojob.h" +#include "am_autojob.h" typedef enum { @@ -276,4 +276,4 @@ int read_error_file (const char *err_file, char *err_buf, int err_buf_size); int read_error_file2 (char *err_file, char *err_buf, int err_buf_size, int *err_code); int read_asql_error_file (char *err_file, char *err_buf, int err_buf_size); -#endif /* _CM_COMMAND_EXECUTE_H_ */ +#endif /* _AM_COMMAND_EXECUTE_H_ */ diff --git a/server/src/am_cmd_task.cpp b/server/src/am_cmd_task.cpp index 1508a81..9610544 100644 --- a/server/src/am_cmd_task.cpp +++ b/server/src/am_cmd_task.cpp @@ -19,7 +19,7 @@ /* - * cm_cmd_task.cpp - + * am_cmd_task.cpp - */ #include @@ -32,7 +32,7 @@ #include #include #include -#include "cm_win_wsa.h" +#include "am_win_wsa.h" #else #include #include @@ -43,13 +43,13 @@ #include #endif -#include "cm_dep.h" -#include "cm_text_encryption.h" -#include "cm_server_util.h" -#include "cm_user.h" -#include "cm_cmd_task.h" -#include "cm_cmd_util.h" -#include "cm_config.h" +#include "am_dep.h" +#include "am_text_encryption.h" +#include "am_server_util.h" +#include "am_user.h" +#include "am_cmd_task.h" +#include "am_cmd_util.h" +#include "am_config.h" static struct option adddbinfo_opt[] = { diff --git a/server/src/am_cmd_task.h b/server/src/am_cmd_task.h index 907153c..2f10c51 100644 --- a/server/src/am_cmd_task.h +++ b/server/src/am_cmd_task.h @@ -19,11 +19,11 @@ /* - * cm_cmd_task.h - + * am_cmd_task.h - */ -#ifndef _CM_CMD_TASK_H_ -#define _CM_CMD_TASK_H_ +#ifndef _AM_CMD_TASK_H_ +#define _AM_CMD_TASK_H_ #include #ifdef HAVE_GETOPT_H @@ -58,4 +58,4 @@ int cmd_adddbinfo (int argc, const char *in_argv[]); int cmd_deldbinfo (int argc, const char *in_argv[]); int cmd_chgdbinfo (int argc, const char *in_argv[]); -#endif /* ! _CM_CMD_TASK_H_ */ +#endif /* ! _AM_CMD_TASK_H_ */ diff --git a/server/src/am_cmd_util.cpp b/server/src/am_cmd_util.cpp index 1fa54ca..78352ca 100644 --- a/server/src/am_cmd_util.cpp +++ b/server/src/am_cmd_util.cpp @@ -19,7 +19,7 @@ /* - * cm_cmd_util.cpp - + * am_cmd_util.cpp - */ #include @@ -27,10 +27,10 @@ #include #include -#include "cm_porting.h" -#include "cm_dep.h" -#include "cm_cmd_util.h" -#include "cm_cmd_task.h" +#include "am_porting.h" +#include "am_dep.h" +#include "am_cmd_util.h" +#include "am_cmd_task.h" typedef int (*CMD_FUNC) (int argc, const char *argv[]); @@ -181,7 +181,7 @@ print_help_msg (int cmd_id) const char *pattern = " %s, %-30s%s\n"; const char *pattern2 = "%-36s%s\n"; const char *pattern_long_only = " %-30s%s\n"; - const char *pattern_usage = "usage: " CM_ADMIN_NAME " %s\n\n"; + const char *pattern_usage = "usage: " AM_ADMIN_NAME " %s\n\n"; switch (cmd_id) { diff --git a/server/src/am_cmd_util.h b/server/src/am_cmd_util.h index 6160452..0d83daa 100644 --- a/server/src/am_cmd_util.h +++ b/server/src/am_cmd_util.h @@ -19,11 +19,11 @@ /* - * cm_cmd_util.h - + * am_cmd_util.h - */ -#ifndef _CM_CMD_UTIL_H_ -#define _CM_CMD_UTIL_H_ +#ifndef _AM_CMD_UTIL_H_ +#define _AM_CMD_UTIL_H_ #ifdef HAVE_GETOPT_H #include @@ -35,10 +35,10 @@ /* typedef struct option GETOPT_LONG; */ /* - * CM_ADMIN COMMON MACRO. + * AM_ADMIN COMMON MACRO. */ -#define CM_ADMIN_NAME "cm_admin" -#define CM_ADMIN_VERSION "0.1" +#define AM_ADMIN_NAME "am_admin" +#define AM_ADMIN_VERSION "0.1" #define OPT_STR_LEN 128 #define DBNAME_LEN 128 @@ -62,7 +62,7 @@ /* - * CM_ADMIN ARG NAME DEFINITION. + * AM_ADMIN ARG NAME DEFINITION. */ #define ARG_DBMT_USER_NAME "dbmtuser-name" @@ -86,7 +86,7 @@ /* - * CM_ADMIN ERROR ID DEFINITION. + * AM_ADMIN ERROR ID DEFINITION. */ #define E_SUCCESS 2000 #define E_FAILURE 2001 @@ -120,4 +120,4 @@ int run_task (const char *task_name, int argc, const char *argv[]); int get_cmdname_by_id (int cmd_id, char *cmd_name, int buf_size); const char *get_msg_by_id (int ptn_id); char *utility_make_getopt_optstring (struct option *opt_array, char *buf); -#endif /* !_CM_CMD_UTIL_H_ */ +#endif /* !_AM_CMD_UTIL_H_ */ diff --git a/server/src/am_config.cpp b/server/src/am_config.cpp index a7f233e..147d985 100644 --- a/server/src/am_config.cpp +++ b/server/src/am_config.cpp @@ -19,7 +19,7 @@ /* - * cm_config.cpp - + * am_config.cpp - */ #include @@ -36,10 +36,10 @@ #include #endif -#include "cm_porting.h" -#include "cm_config.h" -#include "cm_dep.h" -#include "cm_server_util.h" +#include "am_porting.h" +#include "am_config.h" +#include "am_dep.h" +#include "am_server_util.h" #define DEFAULT_MONITOR_INTERVAL 5 #define DEFAULT_THREAD_NUM 8 @@ -56,8 +56,8 @@ #define NUM_DBMT_FILE 23 #define DEFAULT_CWM_PATH_SHORT "/share/webmanager" -#define DEFAULT_SSL_CERTIFICATE "cm_ssl_cert.crt" -#define DEFAULT_SSL_PRIVATEKEY "cm_ssl_cert.key" +#define DEFAULT_SSL_CERTIFICATE "am_ssl_cert.crt" +#define DEFAULT_SSL_PRIVATEKEY "am_ssl_cert.key" #define DEFAULT_LOG_FILE_COUNT 10 #define DEFAULT_LOG_FILE_SIZE (4 * 1024 * 1024) @@ -219,7 +219,7 @@ uReadSystemConfig (void) char ent_name[128], ent_val[128]; const char *separator = " \t="; char *token; - int cm_port = 0; + int am_port = 0; int str_len = 0; char access_log_buf[PATH_MAX]; char error_log_buf[PATH_MAX]; @@ -297,13 +297,13 @@ uReadSystemConfig (void) } strcpy_limit (ent_val, token, sizeof (ent_val)); - if (strcasecmp (ent_name, "cm_port") == 0) + if (strcasecmp (ent_name, "am_port") == 0) { - cm_port = atoi (ent_val); - sco.iAMS_port = cm_port; + am_port = atoi (ent_val); + sco.iAMS_port = am_port; } else if (strcasecmp (ent_name, "MonitorInterval") == 0 || - strcasecmp (ent_name, "cm_process_monitor_interval") == 0) + strcasecmp (ent_name, "am_process_monitor_interval") == 0) { sco.iMonitorInterval = atoi (ent_val); diff --git a/server/src/am_config.h b/server/src/am_config.h index b779b2a..f1eed67 100644 --- a/server/src/am_config.h +++ b/server/src/am_config.h @@ -19,15 +19,15 @@ /* - * cm_config.h - + * am_config.h - */ -#ifndef _CM_CONFIG_H_ -#define _CM_CONFIG_H_ +#ifndef _AM_CONFIG_H_ +#define _AM_CONFIG_H_ #include #include -#include "cm_porting.h" +#include "am_porting.h" #define MAX_INSTALLED_DB 256 #define MAX_UNICAS_PROC 40 @@ -416,7 +416,7 @@ #define UTIL_ARNIADB_REL_NAME "arniadb_rel" UTIL_EXE_EXT #define UTIL_OLD_COMMDB_NAME "commdb" UTIL_EXE_EXT #define UTIL_ARNIADB "arniadb" UTIL_EXE_EXT -#define UTIL_CM_SERVER AMS_NAME UTIL_EXE_EXT +#define UTIL_AM_SERVER AMS_NAME UTIL_EXE_EXT #define UTIL_BROKER_CHANGER "broker_changer" UTIL_EXE_EXT #define COMMDB_SERVER_STOP "-S" @@ -626,4 +626,4 @@ extern int auto_conf_execquery_update_dbuser (const char *src_db_uid, const char *dest_db_passwd); extern int auto_conf_execquery_delete_by_dbuser (const char *db_uid); -#endif /* _CM_CONFIG_H_ */ +#endif /* _AM_CONFIG_H_ */ diff --git a/server/src/am_connect_info.cpp b/server/src/am_connect_info.cpp index d26bb8a..b584cbd 100644 --- a/server/src/am_connect_info.cpp +++ b/server/src/am_connect_info.cpp @@ -19,7 +19,7 @@ /* - * cm_connect_info.cpp - + * am_connect_info.cpp - */ #include @@ -33,10 +33,10 @@ #include #endif -#include "cm_porting.h" -#include "cm_server_util.h" -#include "cm_config.h" -#include "cm_connect_info.h" +#include "am_porting.h" +#include "am_server_util.h" +#include "am_config.h" +#include "am_connect_info.h" int dbmt_con_search (const char *ip, const char *port, char *cli_ver) diff --git a/server/src/am_connect_info.h b/server/src/am_connect_info.h index f5a909a..41b8841 100644 --- a/server/src/am_connect_info.h +++ b/server/src/am_connect_info.h @@ -19,11 +19,11 @@ /* - * cm_connect_info.h - + * am_connect_info.h - */ -#ifndef _CM_CONNECT_INFO_H_ -#define _CM_CONNECT_INFO_H_ +#ifndef _AM_CONNECT_INFO_H_ +#define _AM_CONNECT_INFO_H_ #define DBMT_USER_NAME_LEN 64 @@ -59,4 +59,4 @@ int dbmt_con_write_dbinfo (T_DBMT_CON_DBINFO *dbinfo, const char *ip, void dbmt_con_set_dbinfo (T_DBMT_CON_DBINFO *dbinfo, const char *dbname, const char *uid, const char *passwd); -#endif /* _CM_CONNECT_INFO_H_ */ +#endif /* _AM_CONNECT_INFO_H_ */ diff --git a/server/src/am_http_server.cpp b/server/src/am_http_server.cpp index 71f795b..07085d9 100644 --- a/server/src/am_http_server.cpp +++ b/server/src/am_http_server.cpp @@ -18,7 +18,7 @@ */ /* -* cm_http_server.cpp - +* am_http_server.cpp - */ #include @@ -27,8 +27,8 @@ #include #include -#include "cm_http_server.h" -#include "cm_log.h" +#include "am_http_server.h" +#include "am_log.h" using namespace std; diff --git a/server/src/am_http_server.h b/server/src/am_http_server.h index 72a800f..d8c8679 100644 --- a/server/src/am_http_server.h +++ b/server/src/am_http_server.h @@ -18,7 +18,7 @@ */ /* -* cm_http_server.h +* am_http_server.h */ #include diff --git a/server/src/am_httpd.cpp b/server/src/am_httpd.cpp index 63acd6d..3451665 100644 --- a/server/src/am_httpd.cpp +++ b/server/src/am_httpd.cpp @@ -18,7 +18,7 @@ */ /* -* cm_httpd.cpp +* am_httpd.cpp */ #include @@ -44,7 +44,7 @@ #ifdef WINDOWS #include -#include "cm_win_wsa.h" +#include "am_win_wsa.h" #include #include #include @@ -57,19 +57,19 @@ #include #endif -#include "cm_log.h" -#include "cm_server_util.h" -#include "cm_config.h" -#include "cm_autojob.h" -#include "cm_auto_task.h" -#include "cm_cci_interface.h" -#include "cm_server_interface.h" -#include "cm_server_stat.h" -#include "cm_server_extend_interface.h" -#include "cm_mon_stat.h" -#include "cm_http_server.h" - -//#include "cm_utf8.h" +#include "am_log.h" +#include "am_server_util.h" +#include "am_config.h" +#include "am_autojob.h" +#include "am_auto_task.h" +#include "am_cci_interface.h" +#include "am_server_interface.h" +#include "am_server_stat.h" +#include "am_server_extend_interface.h" +#include "am_mon_stat.h" +#include "am_http_server.h" + +//#include "am_utf8.h" using namespace std; #define DEFAULT_THRD_NUM 24 @@ -269,9 +269,9 @@ arn_generic_request_handler (struct evhttp_request *req, void *arg) { arn_cci_request_handler (root, response); } - else if (!strcmp ((char *) arg, "cm_api")) + else if (!strcmp ((char *) arg, "am_api")) { - arn_cm_request_handler (root, response); + arn_am_request_handler (root, response); } //outustr = utf8_encode(writer.write(response).c_str()); @@ -430,7 +430,7 @@ start_monitor_stat_cb (evutil_socket_t fd, short event, void *arg) if (sco.iSupportMonStat == TRUE) { - (cm_mon_stat::get_instance())->gather_mon_data(); + (am_mon_stat::get_instance())->gather_mon_data(); } evtimer_add (work_ctx->timer, &stat_tv); @@ -545,7 +545,7 @@ start_service () evhttp_set_bevcb (start_ctx[i]->httpd, create_sslconn_cb, ctx); evhttp_set_cb (start_ctx[i]->httpd, "/cci", arn_generic_request_handler, (void *) "cci"); - evhttp_set_cb (start_ctx[i]->httpd, "/cm_api", arn_generic_request_handler, (void *) "cm_api"); + evhttp_set_cb (start_ctx[i]->httpd, "/am_api", arn_generic_request_handler, (void *) "am_api"); evhttp_set_cb (start_ctx[i]->httpd, "/ctrl", arn_ctrl_request_handler, NULL); evhttp_set_cb (start_ctx[i]->httpd, "/upload", arn_post_request_handler, NULL); /* Start web server*/ @@ -687,7 +687,7 @@ get_processid () fclose (pidfile); } if (pidfile == NULL || ((kill (pidnum, 0) < 0) && (errno == ESRCH)) - || (is_amserver_process (pidnum, UTIL_CM_SERVER) == 0)) + || (is_amserver_process (pidnum, UTIL_AM_SERVER) == 0)) { unlink (pid_file_name); return 0; @@ -854,7 +854,7 @@ main (int argc, char **argv) tmpstrbuf[0] = '\0'; - arn_cm_init_env (); + arn_am_init_env (); if (argc >= 2) { if (strcmp (argv[1], "stop") == 0) diff --git a/server/src/am_job_task.cpp b/server/src/am_job_task.cpp index 1f8985a..fbbb3d3 100644 --- a/server/src/am_job_task.cpp +++ b/server/src/am_job_task.cpp @@ -19,7 +19,7 @@ /* - * cm_job_task.cpp - + * am_job_task.cpp - */ #include @@ -56,19 +56,19 @@ #endif #endif -#include "cm_log.h" -#include "cm_stat.h" -#include "cm_porting.h" -#include "cm_server_util.h" -#include "cm_job_task.h" -#include "cm_auto_task.h" -#include "cm_dep.h" -#include "cm_config.h" -#include "cm_cmd_exec.h" -#include "cm_user.h" -#include "cm_text_encryption.h" -#include "cm_connect_info.h" -#include "cm_server_autoupdate.h" +#include "am_log.h" +#include "am_stat.h" +#include "am_porting.h" +#include "am_server_util.h" +#include "am_job_task.h" +#include "am_auto_task.h" +#include "am_dep.h" +#include "am_config.h" +#include "am_cmd_exec.h" +#include "am_user.h" +#include "am_text_encryption.h" +#include "am_connect_info.h" +#include "am_server_autoupdate.h" #include "openssl/pem.h" #include "openssl/conf.h" @@ -230,10 +230,10 @@ static void replace_colon (char *path); static char *to_upper_str (char *str, char *buf); static char *to_lower_str (char *str, char *buf); -static int uca_conf_write (T_CM_BROKER_CONF *uc_conf, char *del_broekr, +static int uca_conf_write (T_AM_BROKER_CONF *uc_conf, char *del_broekr, char *_dbmt_error); static char *get_user_name (int uid, char *name_buf); -static const char *_op_get_port_from_config (T_CM_BROKER_CONF *uc_conf, +static const char *_op_get_port_from_config (T_AM_BROKER_CONF *uc_conf, char *broker_name); static int _tsParseSpacedb (nvplist *req, nvplist *res, char *dbname, @@ -258,14 +258,14 @@ static int op_make_triggerinput_file_alter (nvplist *req, char *input_filename); static int get_broker_info_from_filename (char *path, char *br_name, int *as_id); static char *_ts_get_error_log_param (char *dbname); -static char *cm_get_abs_file_path (const char *filename, char *buf); +static char *am_get_abs_file_path (const char *filename, char *buf); static int check_dbpath (char *dir, char *_dbmt_error); static int file_to_nvpairs (char *filepath, nvplist *res); static int file_to_nvp_by_separator (FILE *fp, nvplist *res, char separator); static int obsolete_version_autoexecquery_conf (const char *conf_line); static int alter_dblocation (const char *dbname, const char *new_dbpath); -static void print_db_stat_to_res (T_CM_DB_PROC_STAT *db_stat, nvplist *res); +static void print_db_stat_to_res (T_AM_DB_PROC_STAT *db_stat, nvplist *res); static int record_ha_topology_to_struct (FILE *infile, int get_all_dbmode, char *dblist, char *_dbmt_error, T_HA_SERVER_INFO_ALL **all_info_out); static char *get_mode_from_output_file (char *mode, int buf_len, @@ -305,7 +305,7 @@ static int run_asql_statement (const char *sql_stat, char *dbname, static void set_copylogdb_mode (T_HA_LOG_PROC_INFO *copylogdb); static int _op_get_session_from_broker (char *broker_list, - T_CM_CAS_INFO_ALL *cas_info_all); + T_AM_CAS_INFO_ALL *cas_info_all); static void _op_print_br_diagdata_to_res (nvplist *res, T_BROKER_DIAGDATA br_diagdata); static int _write_conf_to_file (nvplist *req, char *conf_path); @@ -498,10 +498,10 @@ ts_get_broker_diagdata (nvplist *cli_request, nvplist *cli_response, { int i; char *broker_list = NULL; - T_CM_BROKER_INFO_ALL uc_info; - T_CM_BROKER_INFO *br_info = NULL; + T_AM_BROKER_INFO_ALL uc_info; + T_AM_BROKER_INFO *br_info = NULL; T_BROKER_DIAGDATA br_diagdata; - T_CM_ERROR error; + T_AM_ERROR error; int get_all_diagdata = 0; memset (&br_diagdata, 0, sizeof (T_BROKER_DIAGDATA)); @@ -515,7 +515,7 @@ ts_get_broker_diagdata (nvplist *cli_request, nvplist *cli_response, get_all_diagdata = 1; } - if (cm_get_broker_info (&uc_info, &error) < 0) + if (am_get_broker_info (&uc_info, &error) < 0) { strcpy (_dbmt_error, error.err_msg); return ERR_NO_ERROR; @@ -536,7 +536,7 @@ ts_get_broker_diagdata (nvplist *cli_request, nvplist *cli_response, if (get_all_diagdata || is_name_in_list (br_info->name, broker_list)) { int session = 0; - T_CM_CAS_INFO_ALL cas_info_all; + T_AM_CAS_INFO_ALL cas_info_all; session = _op_get_session_from_broker (br_info->name, &cas_info_all); @@ -567,13 +567,13 @@ ts_get_broker_diagdata (nvplist *cli_request, nvplist *cli_response, memset (&br_diagdata, 0, sizeof (T_BROKER_DIAGDATA)); } - /* free spaces that malloced in cm_cas_info_free */ - cm_cas_info_free (&cas_info_all, NULL); + /* free spaces that malloced in am_cas_info_free */ + am_cas_info_free (&cas_info_all, NULL); } } - /* free spaces that malloced in cm_broker_info_free */ - cm_broker_info_free (&uc_info); + /* free spaces that malloced in am_broker_info_free */ + am_broker_info_free (&uc_info); /* return the sum of the diagdata to res, when bname token is NULL. */ if (get_all_diagdata) @@ -586,14 +586,14 @@ ts_get_broker_diagdata (nvplist *cli_request, nvplist *cli_response, static int _op_get_session_from_broker (char *broker_list, - T_CM_CAS_INFO_ALL *cas_info_all) + T_AM_CAS_INFO_ALL *cas_info_all) { int i; int session_t = 0; - T_CM_CAS_INFO *as_info = NULL; - T_CM_ERROR error; + T_AM_CAS_INFO *as_info = NULL; + T_AM_ERROR error; - if (cm_get_cas_info (broker_list, cas_info_all, NULL, &error) < 0) + if (am_get_cas_info (broker_list, cas_info_all, NULL, &error) < 0) { return -1; } @@ -645,22 +645,22 @@ ts_get_diagdata (nvplist *cli_request, nvplist *cli_response, char *_dbmt_error) { int i; - /*T_CM_DIAG_MONITOR_DB_VALUE server_result; */ + /*T_AM_DIAG_MONITOR_DB_VALUE server_result; */ char *db_name, *broker_name; char *mon_db, *mon_cas; - T_CM_BROKER_INFO_ALL uc_info; - T_CM_BROKER_INFO *br_info; + T_AM_BROKER_INFO_ALL uc_info; + T_AM_BROKER_INFO *br_info; int num_busy_count = 0; INT64 num_req, num_query, num_tran, num_long_query, num_long_tran, num_error_query; - T_CM_ERROR error; + T_AM_ERROR error; db_name = nv_get_val (cli_request, "db_name"); mon_db = nv_get_val (cli_request, "mon_db"); mon_cas = nv_get_val (cli_request, "mon_cas"); /* - if (cm_get_diag_data (&server_result, db_name, mon_db) == 0) + if (am_get_diag_data (&server_result, db_name, mon_db) == 0) { #ifdef JSON_SUPPORT nv_add_nvp (cli_response, "open", "db_mon"); @@ -706,7 +706,7 @@ ts_get_diagdata (nvplist *cli_request, nvplist *cli_response, broker_name = nv_get_val (cli_request, "broker_name"); - if (cm_get_broker_info (&uc_info, &error) < 0) + if (am_get_broker_info (&uc_info, &error) < 0) { strcpy (_dbmt_error, error.err_msg); return ERR_NO_ERROR; @@ -756,7 +756,7 @@ ts_userinfo (nvplist *req, nvplist *res, char *_dbmt_error) { int retval; - retval = cm_ts_userinfo (req, res, _dbmt_error); + retval = am_ts_userinfo (req, res, _dbmt_error); if (retval != ERR_NO_ERROR) { @@ -772,7 +772,7 @@ ts_userinfo (nvplist *req, nvplist *res, char *_dbmt_error) int ts_create_user (nvplist *req, nvplist *res, char *_dbmt_error) { - return cm_ts_create_user (req, res, _dbmt_error); + return am_ts_create_user (req, res, _dbmt_error); } int @@ -781,7 +781,7 @@ ts_delete_user (nvplist *req, nvplist *res, char *_dbmt_error) int retval; char *db_uid = nv_get_val (req, "username"); - if ((retval = cm_ts_delete_user (req, res, _dbmt_error)) == ERR_NO_ERROR) + if ((retval = am_ts_delete_user (req, res, _dbmt_error)) == ERR_NO_ERROR) { auto_conf_execquery_delete_by_dbuser (db_uid); } @@ -812,7 +812,7 @@ ts_update_user (nvplist *req, nvplist *res, char *_dbmt_error) } } - ret = cm_ts_update_user (req, res, _dbmt_error); + ret = am_ts_update_user (req, res, _dbmt_error); if (ret != ERR_NO_ERROR) { return ret; @@ -857,13 +857,13 @@ ts_update_user (nvplist *req, nvplist *res, char *_dbmt_error) int ts_class_info (nvplist *req, nvplist *res, char *_dbmt_error) { - return cm_ts_class_info (req, res, _dbmt_error); + return am_ts_class_info (req, res, _dbmt_error); } int ts_class (nvplist *req, nvplist *res, char *_dbmt_error) { - return cm_ts_class (req, res, _dbmt_error); + return am_ts_class (req, res, _dbmt_error); } #if defined(WINDOWS) @@ -884,26 +884,26 @@ replace_colon (char *path) int ts_update_attribute (nvplist *req, nvplist *res, char *_dbmt_error) { - return cm_ts_update_attribute (req, res, _dbmt_error); + return am_ts_update_attribute (req, res, _dbmt_error); } int ts2_get_unicas_info (nvplist *in, nvplist *out, char *_dbmt_error) { - T_CM_BROKER_INFO_ALL uc_info; + T_AM_BROKER_INFO_ALL uc_info; int i; - T_CM_BROKER_CONF uc_conf; - T_CM_ERROR error; + T_AM_BROKER_CONF uc_conf; + T_AM_ERROR error; char *broker_name; broker_name = nv_get_val (in, "bname"); - memset (&uc_info, 0, sizeof (T_CM_BROKER_INFO_ALL)); - if (cm_get_broker_conf (&uc_conf, NULL, &error) < 0) + memset (&uc_info, 0, sizeof (T_AM_BROKER_INFO_ALL)); + if (am_get_broker_conf (&uc_conf, NULL, &error) < 0) { strcpy (_dbmt_error, error.err_msg); return ERR_WITH_MSG; } - if (cm_get_broker_info (&uc_info, &error) < 0) + if (am_get_broker_info (&uc_info, &error) < 0) { char *p; int tmp_val; @@ -924,19 +924,19 @@ ts2_get_unicas_info (nvplist *in, nvplist *out, char *_dbmt_error) } nv_add_nvp (out, "open", "broker"); nv_add_nvp (out, "name", - cm_br_conf_get_value (& (uc_conf.br_conf[i]), "%")); + am_br_conf_get_value (& (uc_conf.br_conf[i]), "%")); nv_add_nvp (out, "port", - cm_br_conf_get_value (& (uc_conf.br_conf[i]), "BROKER_PORT")); + am_br_conf_get_value (& (uc_conf.br_conf[i]), "BROKER_PORT")); nv_add_nvp (out, "appl_server_shm_id", - cm_br_conf_get_value (& (uc_conf.br_conf[i]), "APPL_SERVER_SHM_ID")); - p = cm_br_conf_get_value (& (uc_conf.br_conf[i]), "SOURCE_ENV"); + am_br_conf_get_value (& (uc_conf.br_conf[i]), "APPL_SERVER_SHM_ID")); + p = am_br_conf_get_value (& (uc_conf.br_conf[i]), "SOURCE_ENV"); tmp_val = 1; if (p == NULL || *p == '\0') { tmp_val = 0; } nv_add_nvp_int (out, "source_env", tmp_val); - p = cm_br_conf_get_value (& (uc_conf.br_conf[i]), "ACCESS_LIST"); + p = am_br_conf_get_value (& (uc_conf.br_conf[i]), "ACCESS_LIST"); tmp_val = 1; if (p == NULL || *p == '\0') { @@ -1007,17 +1007,17 @@ ts2_get_unicas_info (nvplist *in, nvplist *out, char *_dbmt_error) nv_add_nvp_int (out, "access_list", uc_info.br_info[i].access_list_flag); shmid = - cm_br_conf_get_value (cm_conf_find_broker (&uc_conf, uc_info.br_info[i].name), + am_br_conf_get_value (am_conf_find_broker (&uc_conf, uc_info.br_info[i].name), "APPL_SERVER_SHM_ID"); nv_add_nvp (out, "appl_server_shm_id", shmid); nv_add_nvp (out, "close", "broker"); } nv_add_nvp (out, "close", "brokersinfo"); nv_add_nvp (out, "brokerstatus", "ON"); - cm_broker_info_free (&uc_info); + am_broker_info_free (&uc_info); } - cm_broker_conf_free (&uc_conf); + am_broker_conf_free (&uc_conf); return ERR_NO_ERROR; } @@ -1025,8 +1025,8 @@ ts2_get_unicas_info (nvplist *in, nvplist *out, char *_dbmt_error) int ts2_start_unicas (nvplist *in, nvplist *out, char *_dbmt_error) { - T_CM_ERROR error; - if (cm_broker_env_start (&error) < 0) + T_AM_ERROR error; + if (am_broker_env_start (&error) < 0) { strcpy (_dbmt_error, error.err_msg); return ERR_WITH_MSG; @@ -1038,8 +1038,8 @@ ts2_start_unicas (nvplist *in, nvplist *out, char *_dbmt_error) int ts2_stop_unicas (nvplist *in, nvplist *out, char *_dbmt_error) { - T_CM_ERROR error; - if (cm_broker_env_stop (&error) < 0) + T_AM_ERROR error; + if (am_broker_env_stop (&error) < 0) { strcpy (_dbmt_error, error.err_msg); return ERR_WITH_MSG; @@ -1054,7 +1054,7 @@ ts2_get_admin_log_info (nvplist *in, nvplist *out, char *_dbmt_error) char buf[PATH_MAX]; struct stat statbuf; - cm_get_broker_file (UC_FID_ADMIN_LOG, buf); + am_get_broker_file (UC_FID_ADMIN_LOG, buf); if (stat (buf, &statbuf) != 0) { @@ -1083,12 +1083,12 @@ ts2_get_logfile_info (nvplist *in, nvplist *out, char *_dbmt_error) struct dirent *dirp; #endif struct stat statbuf; - T_CM_BROKER_CONF uc_conf; + T_AM_BROKER_CONF uc_conf; char logdir[PATH_MAX], err_logdir[PATH_MAX], access_logdir[PATH_MAX]; const char *v; char *bname, *from, buf[1024], scriptdir[PATH_MAX]; char *cur_file; - T_CM_ERROR error; + T_AM_ERROR error; bname = nv_get_val (in, "broker"); from = nv_get_val (in, "from"); @@ -1102,28 +1102,28 @@ ts2_get_logfile_info (nvplist *in, nvplist *out, char *_dbmt_error) return ERR_PARAM_MISSING; } chdir (sco.szArniadb); - if (cm_get_broker_conf (&uc_conf, NULL, &error) < 0) + if (am_get_broker_conf (&uc_conf, NULL, &error) < 0) { strcpy (_dbmt_error, error.err_msg); return ERR_WITH_MSG; } - v = cm_br_conf_get_value (cm_conf_find_broker (&uc_conf, bname), "ERROR_LOG_DIR"); + v = am_br_conf_get_value (am_conf_find_broker (&uc_conf, bname), "ERROR_LOG_DIR"); if (v == NULL) { v = BROKER_LOG_DIR "/error_log"; } - cm_get_abs_file_path (v, err_logdir); + am_get_abs_file_path (v, err_logdir); - v = cm_br_conf_get_value (cm_conf_find_broker (&uc_conf, bname), "LOG_DIR"); + v = am_br_conf_get_value (am_conf_find_broker (&uc_conf, bname), "LOG_DIR"); if (v == NULL) { v = BROKER_LOG_DIR "/sql_log"; } - cm_get_abs_file_path (v, logdir); + am_get_abs_file_path (v, logdir); - cm_get_abs_file_path (BROKER_LOG_DIR, access_logdir); + am_get_abs_file_path (BROKER_LOG_DIR, access_logdir); - cm_broker_conf_free (&uc_conf); + am_broker_conf_free (&uc_conf); #if defined(WINDOWS) snprintf (find_file, PATH_MAX - 1, "%s/*", access_logdir); @@ -1309,7 +1309,7 @@ ts2_get_add_broker_info (nvplist *in, nvplist *out, char *_dbmt_error) FILE *infile; char broker_conf_path[PATH_MAX], strbuf[1024]; - cm_get_broker_file (UC_FID_ARNIADB_BROKER_CONF, broker_conf_path); + am_get_broker_file (UC_FID_ARNIADB_BROKER_CONF, broker_conf_path); if (access (broker_conf_path, F_OK) < 0) { @@ -1342,8 +1342,8 @@ ts2_delete_broker (nvplist *in, nvplist *out, char *_dbmt_error) { char *bname; int retval = ERR_NO_ERROR; - T_CM_BROKER_CONF uc_conf; - T_CM_ERROR error; + T_AM_BROKER_CONF uc_conf; + T_AM_ERROR error; if ((bname = nv_get_val (in, "bname")) == NULL) { @@ -1351,7 +1351,7 @@ ts2_delete_broker (nvplist *in, nvplist *out, char *_dbmt_error) return ERR_PARAM_MISSING; } - if (cm_get_broker_conf (&uc_conf, NULL, &error) < 0) + if (am_get_broker_conf (&uc_conf, NULL, &error) < 0) { strcpy (_dbmt_error, error.err_msg); return ERR_WITH_MSG; @@ -1359,7 +1359,7 @@ ts2_delete_broker (nvplist *in, nvplist *out, char *_dbmt_error) retval = uca_conf_write (&uc_conf, bname, _dbmt_error); - cm_broker_conf_free (&uc_conf); + am_broker_conf_free (&uc_conf); return retval; } @@ -1368,9 +1368,9 @@ ts2_delete_broker (nvplist *in, nvplist *out, char *_dbmt_error) int ts2_get_broker_status (nvplist *in, nvplist *out, char *_dbmt_error) { - T_CM_CAS_INFO_ALL as_info_set; - T_CM_JOB_INFO_ALL job_info_set; - T_CM_ERROR error; + T_AM_CAS_INFO_ALL as_info_set; + T_AM_JOB_INFO_ALL job_info_set; + T_AM_ERROR error; char *bname, buf[1024]; char *blist; int more_than_one_broker = 0; @@ -1408,7 +1408,7 @@ ts2_get_broker_status (nvplist *in, nvplist *out, char *_dbmt_error) nv_add_nvp (out, "bname", bname); ts_add_nvp_time (out, "time", time (NULL), "%04d/%02d/%02d %02d:%02d:%02d", TIME_STR_FMT_DATE_TIME); - if (cm_get_cas_info (bname, &as_info_set, &job_info_set, &error) >= 0) + if (am_get_cas_info (bname, &as_info_set, &job_info_set, &error) >= 0) { for (i = 0; i < as_info_set.num_info; i++) { @@ -1431,7 +1431,7 @@ ts2_get_broker_status (nvplist *in, nvplist *out, char *_dbmt_error) nv_add_nvp_int (out, "as_psize", as_info_set.as_info[i].psize); nv_add_nvp (out, "as_status", as_info_set.as_info[i].status); nv_add_nvp_float (out, "as_cpu", as_info_set.as_info[i].pcpu, "%.2f"); - cm_cpu_time_str (as_info_set.as_info[i].cpu_time, buf); + am_cpu_time_str (as_info_set.as_info[i].cpu_time, buf); nv_add_nvp (out, "as_ctime", buf); ts_add_nvp_time (out, "as_lat", as_info_set.as_info[i].last_access_time, @@ -1464,7 +1464,7 @@ ts2_get_broker_status (nvplist *in, nvplist *out, char *_dbmt_error) nv_add_nvp (out, "job_request", buf); nv_add_nvp (out, "close", "jobinfo"); } - cm_cas_info_free (&as_info_set, &job_info_set); + am_cas_info_free (&as_info_set, &job_info_set); } if (more_than_one_broker != 0) { @@ -1485,7 +1485,7 @@ ts2_set_broker_conf (nvplist *in, nvplist *out, char *_dbmt_error) char *conf, *confdata; int nv_len, i; - cm_get_broker_file (UC_FID_ARNIADB_BROKER_CONF, broker_conf_path); + am_get_broker_file (UC_FID_ARNIADB_BROKER_CONF, broker_conf_path); if ((outfile = fopen (broker_conf_path, "w")) == NULL) { @@ -1519,7 +1519,7 @@ int ts2_start_broker (nvplist *in, nvplist *out, char *_dbmt_error) { char *bname; - T_CM_ERROR error; + T_AM_ERROR error; if ((bname = nv_get_val (in, "bname")) == NULL) { @@ -1527,7 +1527,7 @@ ts2_start_broker (nvplist *in, nvplist *out, char *_dbmt_error) return ERR_PARAM_MISSING; } - if (cm_broker_on (bname, &error) < 0) + if (am_broker_on (bname, &error) < 0) { strcpy (_dbmt_error, error.err_msg); return ERR_WITH_MSG; @@ -1539,7 +1539,7 @@ int ts2_stop_broker (nvplist *in, nvplist *out, char *_dbmt_error) { char *bname; - T_CM_ERROR error; + T_AM_ERROR error; if ((bname = nv_get_val (in, "bname")) == NULL) { @@ -1547,7 +1547,7 @@ ts2_stop_broker (nvplist *in, nvplist *out, char *_dbmt_error) return ERR_PARAM_MISSING; } - if (cm_broker_off (bname, &error) < 0) + if (am_broker_off (bname, &error) < 0) { strcpy (_dbmt_error, error.err_msg); return ERR_WITH_MSG; @@ -1559,8 +1559,8 @@ int ts2_restart_broker_as (nvplist *in, nvplist *out, char *_dbmt_error) { char *bname, *asnum; - T_CM_ERROR error; - T_CM_BROKER_INFO_ALL uc_info; + T_AM_ERROR error; + T_AM_BROKER_INFO_ALL uc_info; int num_as = 0; @@ -1579,7 +1579,7 @@ ts2_restart_broker_as (nvplist *in, nvplist *out, char *_dbmt_error) return ERR_PARAM_MISSING; } - if (cm_get_broker_info (&uc_info, &error) < 0) + if (am_get_broker_info (&uc_info, &error) < 0) { snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", error.err_msg); return ERR_WITH_MSG; @@ -1593,7 +1593,7 @@ ts2_restart_broker_as (nvplist *in, nvplist *out, char *_dbmt_error) return ERR_WITH_MSG; } - if (cm_broker_as_restart (bname, num_as, &error) < 0) + if (am_broker_as_restart (bname, num_as, &error) < 0) { strcpy (_dbmt_error, error.err_msg); return ERR_WITH_MSG; @@ -4022,7 +4022,7 @@ ts_paramdump (nvplist *req, nvplist *res, char *_dbmt_error) int ts_optimizedb (nvplist *req, nvplist *res, char *_dbmt_error) { - return cm_ts_optimizedb (req, res, _dbmt_error); + return am_ts_optimizedb (req, res, _dbmt_error); } int @@ -4110,13 +4110,13 @@ ts_statdump (nvplist *req, nvplist *res, char *_dbmt_error) char *dbname; char dbname_at_hostname[MAXHOSTNAMELEN + DB_NAME_LEN]; int ha_mode = 0; - T_CM_DB_EXEC_STAT exec_stat; - T_CM_ERROR err_buf; + T_AM_DB_EXEC_STAT exec_stat; + T_AM_ERROR err_buf; int retval = -1; T_DB_SERVICE_MODE db_mode; - memset (&exec_stat, 0, sizeof (T_CM_DB_EXEC_STAT)); - memset (&err_buf, 0, sizeof (T_CM_ERROR)); + memset (&exec_stat, 0, sizeof (T_AM_DB_EXEC_STAT)); + memset (&err_buf, 0, sizeof (T_AM_ERROR)); /* check the parameters of input. */ if ((dbname = nv_get_val (req, "dbname")) == NULL) @@ -4138,14 +4138,14 @@ ts_statdump (nvplist *req, nvplist *res, char *_dbmt_error) if (ha_mode != 0) { append_host_to_dbname (dbname_at_hostname, dbname, sizeof (dbname_at_hostname)); - retval = cm_get_db_exec_stat (dbname_at_hostname, &exec_stat, &err_buf); + retval = am_get_db_exec_stat (dbname_at_hostname, &exec_stat, &err_buf); } else { - retval = cm_get_db_exec_stat (dbname, &exec_stat, &err_buf); + retval = am_get_db_exec_stat (dbname, &exec_stat, &err_buf); } - /* call cm_get_db_exec_stat to get stat infomation. */ + /* call am_get_db_exec_stat to get stat infomation. */ if (retval < 0) { /* return error with message if the operation is not success. */ @@ -8077,7 +8077,7 @@ ts_trigger_operation (nvplist *req, nvplist *res, char *_dbmt_error) int ts_get_triggerinfo (nvplist *req, nvplist *res, char *_dbmt_error) { - return cm_ts_get_triggerinfo (req, res, _dbmt_error); + return am_ts_get_triggerinfo (req, res, _dbmt_error); } int @@ -9182,9 +9182,9 @@ ts_executecasrunner (nvplist *cli_request, nvplist *cli_response, char log_converter_res[PATH_MAX]; char cmd_name[ARNIADB_CMD_NAME_LEN]; const char *argv[25]; - T_CM_BROKER_CONF uc_conf; + T_AM_BROKER_CONF uc_conf; char out_msg_file_env[1024]; - T_CM_ERROR error; + T_AM_ERROR error; #if defined(WINDOWS) DWORD th_id; #else @@ -9233,7 +9233,7 @@ ts_executecasrunner (nvplist *cli_request, nvplist *cli_response, th_id); /* get right port number with broker name */ - if (cm_get_broker_conf (&uc_conf, NULL, &error) < 0) + if (am_get_broker_conf (&uc_conf, NULL, &error) < 0) { strcpy (diag_error, error.err_msg); return ERR_WITH_MSG; @@ -9242,12 +9242,12 @@ ts_executecasrunner (nvplist *cli_request, nvplist *cli_response, memset (bport, 0x0, sizeof (bport)); for (i = 0; i < uc_conf.num_broker; i++) { - char *confvalue = cm_br_conf_get_value (& (uc_conf.br_conf[i]), "%"); + char *confvalue = am_br_conf_get_value (& (uc_conf.br_conf[i]), "%"); if ((confvalue != NULL) && (strcmp (brokername, confvalue) == 0)) { confvalue = - cm_br_conf_get_value (& (uc_conf.br_conf[i]), "BROKER_PORT"); + am_br_conf_get_value (& (uc_conf.br_conf[i]), "BROKER_PORT"); if (confvalue != NULL) { snprintf (bport, sizeof (bport) - 1, "%s", confvalue); @@ -9256,7 +9256,7 @@ ts_executecasrunner (nvplist *cli_request, nvplist *cli_response, } } - cm_broker_conf_free (&uc_conf); + am_broker_conf_free (&uc_conf); if ((casrunnerwithFile != NULL) && (strcmp (casrunnerwithFile, "yes") == 0) && (logfilename != NULL)) @@ -9754,7 +9754,7 @@ ts_remove_log (nvplist *req, nvplist *res, char *_dbmt_error) char command[PATH_MAX]; char full_path_buf[PATH_MAX]; char buf[PATH_MAX]; - T_CM_ERROR error = { 0, {0} }; + T_AM_ERROR error = { 0, {0} }; broker_name[0] = '\0'; command[0] = '\0'; @@ -9796,7 +9796,7 @@ ts_remove_log (nvplist *req, nvplist *res, char *_dbmt_error) return ERR_WITH_MSG; #endif if (get_broker_info_from_filename (path, broker_name, &as_id) < 0 - || cm_del_cas_log (broker_name, as_id, &error) < 0) + || am_del_cas_log (broker_name, as_id, &error) < 0) { pclose (output); snprintf (_dbmt_error, DBMT_ERROR_MSG_SIZE, "%s", @@ -9837,18 +9837,18 @@ int ts_get_dbproc_stat (nvplist *req, nvplist *res, char *_dbmt_error) { char *dbname = NULL; - T_CM_DB_PROC_STAT_ALL *db_stat_all = NULL; - T_CM_DB_PROC_STAT db_stat; - T_CM_ERROR error; + T_AM_DB_PROC_STAT_ALL *db_stat_all = NULL; + T_AM_DB_PROC_STAT db_stat; + T_AM_ERROR error; int retval; int i = 0; - memset (&db_stat, 0, sizeof (T_CM_DB_PROC_STAT)); - memset (&error, 0, sizeof (T_CM_ERROR)); + memset (&db_stat, 0, sizeof (T_AM_DB_PROC_STAT)); + memset (&error, 0, sizeof (T_AM_ERROR)); if ((dbname = nv_get_val (req, "dbname")) == NULL) { - if ((db_stat_all = cm_get_db_proc_stat_all (&error)) == NULL) + if ((db_stat_all = am_get_db_proc_stat_all (&error)) == NULL) { strcpy_limit (_dbmt_error, error.err_msg, DBMT_ERROR_MSG_SIZE); retval = ERR_WITH_MSG; @@ -9860,12 +9860,12 @@ ts_get_dbproc_stat (nvplist *req, nvplist *res, char *_dbmt_error) print_db_stat_to_res ((db_stat_all->db_stats + i), res); } - cm_db_proc_stat_all_free (db_stat_all); + am_db_proc_stat_all_free (db_stat_all); retval = ERR_NO_ERROR; } else { - if (cm_get_db_proc_stat (dbname, &db_stat, &error) < 0) + if (am_get_db_proc_stat (dbname, &db_stat, &error) < 0) { strcpy_limit (_dbmt_error, error.err_msg, DBMT_ERROR_MSG_SIZE); retval = ERR_WITH_MSG; @@ -10690,7 +10690,7 @@ ts_role_change (nvplist *req, nvplist *res, char *_dbmt_error) } static void -print_db_stat_to_res (T_CM_DB_PROC_STAT *db_stat, nvplist *res) +print_db_stat_to_res (T_AM_DB_PROC_STAT *db_stat, nvplist *res) { nv_add_nvp (res, "open", "dbstat"); nv_add_nvp (res, "dbname", db_stat->name); @@ -11279,7 +11279,7 @@ ts_get_ams_env (nvplist *req, nvplist *res, char *_dbmt_error) nv_add_nvp (res, "PLATFORM", get_processor_architecture ()); nv_add_nvp (res, "AMS_VER", makestring (BUILD_NUMBER)); - nv_add_nvp_int (res, "cm_port", sco.iAMS_port); + nv_add_nvp_int (res, "am_port", sco.iAMS_port); is_default_cert_file = _is_default_cert (_dbmt_error); if (is_default_cert_file < 0) @@ -12156,16 +12156,16 @@ fill_dbmode_into_dbinfo_list (T_HA_SERVER_INFO_ALL **all_info, * get port info from brokers config, that located by */ static const char * -_op_get_port_from_config (T_CM_BROKER_CONF *uc_conf, char *broker_name) +_op_get_port_from_config (T_AM_BROKER_CONF *uc_conf, char *broker_name) { int pos; char *name; for (pos = 0; pos < uc_conf->num_broker; pos++) { - name = cm_br_conf_get_value (& (uc_conf->br_conf[pos]), "%"); + name = am_br_conf_get_value (& (uc_conf->br_conf[pos]), "%"); if (name != NULL && strcasecmp (broker_name, name) == 0) { - return cm_br_conf_get_value (& (uc_conf->br_conf[pos]), + return am_br_conf_get_value (& (uc_conf->br_conf[pos]), "BROKER_PORT"); } } @@ -12291,7 +12291,7 @@ get_user_name (int uid, char *name_buf) } static int -uca_conf_write (T_CM_BROKER_CONF *uc_conf, char *del_broker, +uca_conf_write (T_AM_BROKER_CONF *uc_conf, char *del_broker, char *_dbmt_error) { char buf[512]; @@ -12319,17 +12319,17 @@ uca_conf_write (T_CM_BROKER_CONF *uc_conf, char *del_broker, } } - cm_get_broker_file (UC_FID_ARNIADB_BROKER_CONF, buf); + am_get_broker_file (UC_FID_ARNIADB_BROKER_CONF, buf); if (stat (buf, &statbuf) < 0) { - cm_get_broker_file (UC_FID_ARNIADB_CAS_CONF, buf); + am_get_broker_file (UC_FID_ARNIADB_CAS_CONF, buf); if (stat (buf, &statbuf) < 0) { - cm_get_broker_file (UC_FID_UNICAS_CONF, buf); + am_get_broker_file (UC_FID_UNICAS_CONF, buf); if (stat (buf, &statbuf) < 0) { - cm_get_broker_file (UC_FID_ARNIADB_BROKER_CONF, buf); + am_get_broker_file (UC_FID_ARNIADB_BROKER_CONF, buf); } } } @@ -13211,7 +13211,7 @@ get_dbvoldir (char *vol_dir, size_t vol_dir_size, char *dbname, char *err_buf) } static char * -cm_get_abs_file_path (const char *filename, char *buf) +am_get_abs_file_path (const char *filename, char *buf) { strcpy (buf, filename); @@ -14976,7 +14976,7 @@ ts_ha_applylogdb (nvplist *req, nvplist *res, char *_dbmt_error) /*static int _get_update_url(char *url) { - char cm_conf_file[PATH_MAX]; + char am_conf_file[PATH_MAX]; char line_buf[MAX_JOB_CONFIG_FILE_LINE_LENGTH]; char *iter = NULL; @@ -14984,12 +14984,12 @@ ts_ha_applylogdb (nvplist *req, nvplist *res, char *_dbmt_error) FILE *fin; #if !defined (DO_NOT_USE_ARNIADBENV) - snprintf (cm_conf_file, PATH_MAX - 1, "%s/conf/%s", sco.szArniadb, ARNIADB_DBMT_CONF); + snprintf (am_conf_file, PATH_MAX - 1, "%s/conf/%s", sco.szArniadb, ARNIADB_DBMT_CONF); #else - snprintf (cm_conf_file, PATH_MAX - 1, "%s/%s", ARNIADB_CONFDIR, ARNIADB_DBMT_CONF); + snprintf (am_conf_file, PATH_MAX - 1, "%s/%s", ARNIADB_CONFDIR, ARNIADB_DBMT_CONF); #endif - fin = fopen(cm_conf_file, "r"); + fin = fopen(am_conf_file, "r"); if (fin == NULL) { return ERR_FILE_OPEN_FAIL; diff --git a/server/src/am_job_task.h b/server/src/am_job_task.h index 544a909..d885af7 100644 --- a/server/src/am_job_task.h +++ b/server/src/am_job_task.h @@ -19,17 +19,17 @@ /* - * cm_job_task.h - + * am_job_task.h - */ -#ifndef _CM_JOB_TASK_H_ -#define _CM_JOB_TASK_H_ +#ifndef _AM_JOB_TASK_H_ +#define _AM_JOB_TASK_H_ #if defined(WINDOWS) #include #endif -#include "cm_dep.h" +#include "am_dep.h" #define DBMT_ERROR_MSG_SIZE 5000 @@ -436,4 +436,4 @@ ts_add_nvp_time (nvplist *ref, const char *name, time_t t, const char *fmt, int ts_start_statdump (nvplist *req, nvplist *res, char *_dbmt_error); int ts_stop_statdump (nvplist *req, nvplist *res, char *_dbmt_error); -#endif /* _CM_JOB_TASK_H_ */ +#endif /* _AM_JOB_TASK_H_ */ diff --git a/server/src/am_log.h b/server/src/am_log.h index 15922e0..5637ba4 100644 --- a/server/src/am_log.h +++ b/server/src/am_log.h @@ -18,8 +18,8 @@ */ -#ifndef __CM_LOG__H__ -#define __CM_LOG__H__ +#ifndef __AM_LOG__H__ +#define __AM_LOG__H__ #include #include #include @@ -42,7 +42,7 @@ #include /* opendir() ... */ #endif -#include "cm_config.h" +#include "am_config.h" using namespace std; diff --git a/server/src/am_mailer.h b/server/src/am_mailer.h index e0af839..e9e844b 100644 --- a/server/src/am_mailer.h +++ b/server/src/am_mailer.h @@ -21,8 +21,8 @@ // http://johnwiggins.net // smtplib@johnwiggins.net // -#ifndef __CM_MAILER_H__ -#define __CM_MAILER_H__ +#ifndef __AM_MAILER_H__ +#define __AM_MAILER_H__ #ifdef WIN32 // std::vector This gives this warning in VC.. // bloody annoying, there is a way round it according to MS. @@ -1910,4 +1910,4 @@ class mailer } // end namespace jwsmtp -#endif // !ifndef __CM_MAILER_H__ +#endif // !ifndef __AM_MAILER_H__ diff --git a/server/src/am_mon_stat.cpp b/server/src/am_mon_stat.cpp index 42504ab..f65cd1b 100644 --- a/server/src/am_mon_stat.cpp +++ b/server/src/am_mon_stat.cpp @@ -19,13 +19,13 @@ #include -#include "cm_log.h" +#include "am_log.h" #include "json/json.h" -#include "cm_config.h" -#include "cm_job_task.h" -#include "cm_server_interface.h" -#include "cm_mon_stat.h" -#include "cm_server_extend_interface.h" +#include "am_config.h" +#include "am_job_task.h" +#include "am_server_interface.h" +#include "am_mon_stat.h" +#include "am_server_extend_interface.h" #include #include @@ -224,9 +224,9 @@ class scope_lock MUTEX_T _mutex; }; -cm_mon_stat *cm_mon_stat::_instance = NULL; +am_mon_stat *am_mon_stat::_instance = NULL; -cm_mon_stat::cm_mon_stat (string data_path): +am_mon_stat::am_mon_stat (string data_path): _data_path (data_path + "/"), _meta_file (_data_path + META_NAME) { @@ -238,16 +238,16 @@ cm_mon_stat::cm_mon_stat (string data_path): MUTEX_INIT (_data_mutex); } -cm_mon_stat *cm_mon_stat::get_instance() +am_mon_stat *am_mon_stat::get_instance() { if (NULL == _instance) { - _instance = new cm_mon_stat (sco.sMonStatDataPath); + _instance = new am_mon_stat (sco.sMonStatDataPath); } return _instance; } -bool cm_mon_stat::get_mon_interval (time_t &interval) const +bool am_mon_stat::get_mon_interval (time_t &interval) const { if (true == _init) { @@ -260,7 +260,7 @@ bool cm_mon_stat::get_mon_interval (time_t &interval) const } } -bool cm_mon_stat::set_mon_interval (time_t interval) +bool am_mon_stat::set_mon_interval (time_t interval) { if (false == _init) { @@ -280,7 +280,7 @@ bool cm_mon_stat::set_mon_interval (time_t interval) } } -bool cm_mon_stat::initial() +bool am_mon_stat::initial() { try { @@ -300,7 +300,7 @@ bool cm_mon_stat::initial() return _init; } -void cm_mon_stat::gather_mon_data (void) +void am_mon_stat::gather_mon_data (void) { time_t gather_time = time (NULL); @@ -348,7 +348,7 @@ void cm_mon_stat::gather_mon_data (void) //} } -void cm_mon_stat::aggregate_2_hour (time_t gather_time) +void am_mon_stat::aggregate_2_hour (time_t gather_time) { int monthly_idx = (gather_time % ( 30 * 60 * 60 * 24)) / 3600; int buf_base = 3600/_meta[K_INTERVAL].asInt(); @@ -370,7 +370,7 @@ void cm_mon_stat::aggregate_2_hour (time_t gather_time) aggregate_os (read_offset, buf_base, write_offset, HOUR, gather_time); } -void cm_mon_stat::aggregate_2_day (time_t gather_time) +void am_mon_stat::aggregate_2_day (time_t gather_time) { int yearly_idx = (gather_time % ( 365 * 60 * 60 * 24)) / (3600 * 24); int buf_base = 24; @@ -392,7 +392,7 @@ void cm_mon_stat::aggregate_2_day (time_t gather_time) aggregate_os (read_offset, buf_base, write_offset, DAY, gather_time); } -void cm_mon_stat::aggregate_os (int read_offset, +void am_mon_stat::aggregate_os (int read_offset, int buf_base, int write_offset, AGG_TYPE atype, @@ -454,7 +454,7 @@ void cm_mon_stat::aggregate_os (int read_offset, delete [] buf; } -void cm_mon_stat::aggregate_dbs (int read_offset, +void am_mon_stat::aggregate_dbs (int read_offset, int buf_base, int write_offset, AGG_TYPE atype, @@ -647,7 +647,7 @@ static bool mdtype_from_str (const string &dtype, MDTYPE &mdtype) return true; } -bool cm_mon_stat::get_mon_statistic (const Json::Value req, Json::Value &res, string &errmsg) const +bool am_mon_stat::get_mon_statistic (const Json::Value req, Json::Value &res, string &errmsg) const { if (false == _init) { @@ -742,7 +742,7 @@ bool cm_mon_stat::get_mon_statistic (const Json::Value req, Json::Value &res, st } // the data maybe wrong for the begin of the return data array -bool cm_mon_stat::m_get_mon_statistic (const Json::Value req, Json::Value &res, string &errmsg) const +bool am_mon_stat::m_get_mon_statistic (const Json::Value req, Json::Value &res, string &errmsg) const { res["metric"] = req["metric"]; res["dtype"] = req["dtype"]; @@ -878,7 +878,7 @@ bool cm_mon_stat::m_get_mon_statistic (const Json::Value req, Json::Value &res, return false; } -bool cm_mon_stat::get_rrd_data (MDTYPE mdtype, string dpath, int didx, +bool am_mon_stat::get_rrd_data (MDTYPE mdtype, string dpath, int didx, int midx, int pfactor, bool ddiff, int mlen, Json::Value &res, string &errmsg) const { @@ -1029,7 +1029,7 @@ static bool get_volume_list (string dbname, Json::Value &vol_list) return true; } -void cm_mon_stat::aggregate_brokers (int read_offset, +void am_mon_stat::aggregate_brokers (int read_offset, int buf_base, int write_offset, AGG_TYPE atype, @@ -1177,7 +1177,7 @@ static void mon_diff_avg (int *buf, int bufsize, int *agg_data, int idx, int mle } } -void cm_mon_stat::gather_daily_brokers_mon (time_t gather_time) +void am_mon_stat::gather_daily_brokers_mon (time_t gather_time) { int broker_data[BROKER_METRICS_LEN]; memset (broker_data, 0, BROKER_METRICS_LEN * sizeof (int)); @@ -1236,7 +1236,7 @@ void cm_mon_stat::gather_daily_brokers_mon (time_t gather_time) } } -bool cm_mon_stat::gather_dbs_tran_query (time_t gather_time, Json::Value &db_tq) +bool am_mon_stat::gather_dbs_tran_query (time_t gather_time, Json::Value &db_tq) { string bstr = _brokers[0u].asString(); @@ -1296,7 +1296,7 @@ bool cm_mon_stat::gather_dbs_tran_query (time_t gather_time, Json::Value &db_tq) return true; } -void cm_mon_stat::gather_daily_dbs_mon (time_t gather_time) +void am_mon_stat::gather_daily_dbs_mon (time_t gather_time) { int db_data[DB_METRICS_LEN]; Json::Value db_tq; @@ -1491,7 +1491,7 @@ void cm_mon_stat::gather_daily_dbs_mon (time_t gather_time) } } -void cm_mon_stat::gather_daily_os_mon (time_t gather_time) +void am_mon_stat::gather_daily_os_mon (time_t gather_time) { int os_data[OS_METRICS_LEN]; memset (os_data, 0, OS_METRICS_LEN * sizeof (int)); @@ -1545,7 +1545,7 @@ void cm_mon_stat::gather_daily_os_mon (time_t gather_time) update_rrdfile (_data_path + OS_MON, daily_idx, os_data, OS_METRICS_LEN, OS_METRICS_LEN); } -bool cm_mon_stat::init_meta (int interval) +bool am_mon_stat::init_meta (int interval) { _meta[K_INTERVAL] = interval; _meta[K_TOTAL_VOL_NUM] = 0; @@ -1624,7 +1624,7 @@ bool cm_mon_stat::init_meta (int interval) return flush_meta_file(); } -bool cm_mon_stat::reset_meta (int new_interval) +bool am_mon_stat::reset_meta (int new_interval) { scope_lock slocker (_data_mutex); @@ -1656,7 +1656,7 @@ bool cm_mon_stat::reset_meta (int new_interval) return flush_meta_file(); } -bool cm_mon_stat::reset_mon_file (string fpath, int block_num, int mlen, int new_interval) +bool am_mon_stat::reset_mon_file (string fpath, int block_num, int mlen, int new_interval) { int ori_bufsize = MON_DATA_BLOCK * block_num * mlen; int *ori_buf = new (int[ori_bufsize]); @@ -1692,7 +1692,7 @@ bool cm_mon_stat::reset_mon_file (string fpath, int block_num, int mlen, int new return true; } -bool cm_mon_stat::flush_meta_file (void) +bool am_mon_stat::flush_meta_file (void) { Json::StyledWriter writer; ofstream ofs (_meta_file.c_str()); @@ -1706,7 +1706,7 @@ bool cm_mon_stat::flush_meta_file (void) return false; } -bool cm_mon_stat::load_meta_file (void) +bool am_mon_stat::load_meta_file (void) { Json::Reader reader; ifstream ifs (_meta_file.c_str()); diff --git a/server/src/am_mon_stat.h b/server/src/am_mon_stat.h index 45021ac..75bb301 100644 --- a/server/src/am_mon_stat.h +++ b/server/src/am_mon_stat.h @@ -18,11 +18,11 @@ */ /** -* @brief cm_mon_stat.h include the definition of cm_mon_stat class. +* @brief am_mon_stat.h include the definition of am_mon_stat class. */ -#ifndef _CM_MON_STAT_H_ -#define _CM_MON_STAT_H_ +#ifndef _AM_MON_STAT_H_ +#define _AM_MON_STAT_H_ #ifndef PATH_MAX #define PATH_MAX 1024 @@ -33,7 +33,7 @@ #include #include "json/json.h" -#include "cm_porting.h" +#include "am_porting.h" using namespace std; @@ -52,10 +52,10 @@ enum MDTYPE // TODO: need a switch for monitoring data collection -class cm_mon_stat +class am_mon_stat { public: - static cm_mon_stat *get_instance (void); + static am_mon_stat *get_instance (void); bool initial (void); void gather_mon_data (void); bool set_mon_interval (time_t interval); @@ -64,8 +64,8 @@ class cm_mon_stat string &errmsg) const; protected: - cm_mon_stat (string data_path); - virtual ~ cm_mon_stat (void) + am_mon_stat (string data_path); + virtual ~ am_mon_stat (void) { MUTEX_DESTROY (_data_mutex); delete _instance; @@ -96,7 +96,7 @@ class cm_mon_stat bool m_get_mon_statistic (const Json::Value req, Json::Value &res, string &errmsg) const; private: - static cm_mon_stat *_instance; + static am_mon_stat *_instance; const string _data_path; const string _meta_file; Json::Value _meta; @@ -111,4 +111,4 @@ class cm_mon_stat bool _init; }; -#endif /* _CM_MON_STAT_H_ */ +#endif /* _AM_MON_STAT_H_ */ diff --git a/server/src/am_porting.h b/server/src/am_porting.h index 13e7c6c..3dfe1d6 100644 --- a/server/src/am_porting.h +++ b/server/src/am_porting.h @@ -19,11 +19,11 @@ /* - * cm_porting.h - + * am_porting.h - */ -#ifndef _CM_PORTING_H_ -#define _CM_PORTING_H_ +#ifndef _AM_PORTING_H_ +#define _AM_PORTING_H_ /* * IMPORTED SYSTEM HEADER FILES @@ -336,4 +336,4 @@ typedef long INT64; #define COND_DESTROY(condvar) pthread_cond_destroy(&(condvar)) #endif -#endif /* _CM_PORTING_H_ */ +#endif /* _AM_PORTING_H_ */ diff --git a/server/src/am_server_autoupdate.cpp b/server/src/am_server_autoupdate.cpp index 59fbaca..e533d30 100644 --- a/server/src/am_server_autoupdate.cpp +++ b/server/src/am_server_autoupdate.cpp @@ -18,13 +18,13 @@ */ /* -* cm_server.autoupdate.cpp +* am_server.autoupdate.cpp */ -#include "cm_server_autoupdate.h" -#include "cm_compress.h" -#include "cm_config.h" -#include "cm_dep.h" +#include "am_server_autoupdate.h" +#include "am_compress.h" +#include "am_config.h" +#include "am_dep.h" #ifdef WINDOWS #include @@ -199,7 +199,7 @@ generate_update_script (char *patch_name, char *url, char *path, "if exist %s\\bin\\arn_manager.exe copy /y %s\\bin\\arn_manager.exe %sbackup\\.\n", sco.szArniadb, sco.szArniadb, path); fprintf (fout, - "if exist %s\\bin\\cm_admin.exe copy /y %s\\bin\\cm_admin.exe %sbackup\\.\n", + "if exist %s\\bin\\am_admin.exe copy /y %s\\bin\\am_admin.exe %sbackup\\.\n", sco.szArniadb, sco.szArniadb, path); fprintf (fout, "arniadb service stop\n"); @@ -209,7 +209,7 @@ generate_update_script (char *patch_name, char *url, char *path, fprintf (fout, "if exist %s\\arn_* copy /y %s\\arn_* %s\\bin\\.\n", zip_folder, zip_folder, sco.szArniadb); fprintf (fout, - "if exist %s\\cm_admin copy /y %s\\cm_admin.exe %s\\bin\\.\n", + "if exist %s\\am_admin copy /y %s\\am_admin.exe %s\\bin\\.\n", zip_folder, zip_folder, sco.szArniadb); fprintf (fout, "for /f %%%%c in ('dir /b %s\\conf\\') do type %s\\conf\\%%%%c >> %s\\conf\\%%%%c\n", @@ -260,14 +260,14 @@ generate_update_script (char *patch_name, char *url, char *path, fprintf (fout, "mkdir %sbackup\n", path); fprintf (fout, - "cp %s/bin/cm_admin %s/bin/arn_manager %sbackup/.\n", + "cp %s/bin/am_admin %s/bin/arn_manager %sbackup/.\n", sco.szArniadb, sco.szArniadb, path); fprintf (fout, "if [ -e %spatch/arn_manager ]; then\n", path); fprintf (fout, "\tcp %spatch/arn_* %s/bin/. -f\nfi\n", path, sco.szArniadb); - fprintf (fout, "if [ -e %spatch/cm_admin ]; then\n", path); - fprintf (fout, "\tcp %spatch/cm_admin %s/bin/. -f\nfi\n", path, + fprintf (fout, "if [ -e %spatch/am_admin ]; then\n", path); + fprintf (fout, "\tcp %spatch/am_admin %s/bin/. -f\nfi\n", path, sco.szArniadb); diff --git a/server/src/am_server_autoupdate.h b/server/src/am_server_autoupdate.h index 2eb0cc3..58532a6 100644 --- a/server/src/am_server_autoupdate.h +++ b/server/src/am_server_autoupdate.h @@ -1,5 +1,5 @@ -#ifndef _CM_SERVER_AUTOUPDATE_H_ -#define _CM_SERVER_AUTOUPDATE_H_ +#ifndef _AM_SERVER_AUTOUPDATE_H_ +#define _AM_SERVER_AUTOUPDATE_H_ #ifdef WINDOWS diff --git a/server/src/am_server_extend_interface.cpp b/server/src/am_server_extend_interface.cpp index f7edb43..7a41608 100644 --- a/server/src/am_server_extend_interface.cpp +++ b/server/src/am_server_extend_interface.cpp @@ -17,7 +17,7 @@ * */ -#include "cm_log.h" +#include "am_log.h" #include #ifdef WINDOWS @@ -28,15 +28,15 @@ #include #endif -#include "cm_dep.h" -#include "cm_stat.h" -#include "cm_cmd_exec.h" -#include "cm_server_util.h" -#include "cm_text_encryption.h" -#include "cm_server_extend_interface.h" -#include "cm_mailer.h" -#include "cm_mon_stat.h" -#include "cm_user.h" +#include "am_dep.h" +#include "am_stat.h" +#include "am_cmd_exec.h" +#include "am_server_util.h" +#include "am_text_encryption.h" +#include "am_server_extend_interface.h" +#include "am_mailer.h" +#include "am_mon_stat.h" +#include "am_user.h" #include #include @@ -473,17 +473,17 @@ int ext_get_active_dbs (Json::Value &activedbs) int ext_get_active_brokers (Json::Value &activebrokers) { - T_CM_BROKER_INFO_ALL uc_info; - T_CM_BROKER_CONF uc_conf; - T_CM_ERROR error; + T_AM_BROKER_INFO_ALL uc_info; + T_AM_BROKER_CONF uc_conf; + T_AM_ERROR error; Json::Value broker; int i; - if (cm_get_broker_conf (&uc_conf, NULL, &error) < 0) + if (am_get_broker_conf (&uc_conf, NULL, &error) < 0) { return 1; } - if (cm_get_broker_info (&uc_info, &error) < 0) + if (am_get_broker_info (&uc_info, &error) < 0) { activebrokers["brokerstatus"] = "OFF"; } @@ -496,10 +496,10 @@ int ext_get_active_brokers (Json::Value &activebrokers) activebrokers["brokers"].append (broker); } activebrokers["brokerstatus"] = "ON"; - cm_broker_info_free (&uc_info); + am_broker_info_free (&uc_info); } - cm_broker_conf_free (&uc_conf); + am_broker_conf_free (&uc_conf); return 0; } @@ -2631,7 +2631,7 @@ int ext_get_mon_interval (Json::Value &request, Json::Value &response) { response["task"] = request["task"]; time_t interval; - if (false == (cm_mon_stat::get_instance())->get_mon_interval (interval)) + if (false == (am_mon_stat::get_instance())->get_mon_interval (interval)) { return build_server_header (response, ERR_WITH_MSG, "Get interval failed, because the monitoring module is not initialized!"); @@ -2660,7 +2660,7 @@ int ext_set_mon_interval (Json::Value &request, Json::Value &response) " seconds"; return build_server_header (response, ERR_WITH_MSG, sstr.str().c_str()); } - if (true == (cm_mon_stat::get_instance())->set_mon_interval (interval)) + if (true == (am_mon_stat::get_instance())->set_mon_interval (interval)) { return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); } @@ -2696,7 +2696,7 @@ int ext_get_mon_statistic (Json::Value &request, Json::Value &response) JSON_FIND_V (request, "bname", build_server_header (response, ERR_PARAM_MISSING, "Parameter(bname) missing in the request")); } - if (true == (cm_mon_stat::get_instance())->get_mon_statistic (request, response, errmsg)) + if (true == (am_mon_stat::get_instance())->get_mon_statistic (request, response, errmsg)) { return build_server_header (response, ERR_NO_ERROR, STATUS_NONE); } diff --git a/server/src/am_server_extend_interface.h b/server/src/am_server_extend_interface.h index 9e6e22d..0f4c879 100644 --- a/server/src/am_server_extend_interface.h +++ b/server/src/am_server_extend_interface.h @@ -17,10 +17,10 @@ * */ -#ifndef __CM_SERVER_EXTEND_INFERFACE_H_ -#define __CM_SERVER_EXTEND_INFERFACE_H_ +#ifndef __AM_SERVER_EXTEND_INFERFACE_H_ +#define __AM_SERVER_EXTEND_INFERFACE_H_ -#include "cm_user.h" +#include "am_user.h" #include #include diff --git a/server/src/am_server_interface.cpp b/server/src/am_server_interface.cpp index 2dccc58..59cd3a9 100644 --- a/server/src/am_server_interface.cpp +++ b/server/src/am_server_interface.cpp @@ -36,10 +36,10 @@ #include #endif -#include "cm_server_interface.h" -#include "cm_server_extend_interface.h" -#include "cm_log.h" -#include "cm_mon_stat.h" +#include "am_server_interface.h" +#include "am_server_extend_interface.h" +#include "am_log.h" +#include "am_mon_stat.h" using namespace std; @@ -56,7 +56,7 @@ typedef struct char arniadb_err_log[MAX_PATH]; /*arniadb err log, use for save cmd log */ // char arniadb_charset[MAX_PATH]; } arniadb_env_t; -mutex_t cm_mutex; +mutex_t am_mutex; /*global arniadb env*/ arniadb_env_t arn_httpd_env; @@ -84,7 +84,7 @@ mon_stat_init (void) } } - if (!cm_mon_stat::get_instance ()->initial ()) + if (!am_mon_stat::get_instance ()->initial ()) { fprintf (stderr, "Error while loading monitoring data information\n"); return -1; @@ -93,7 +93,7 @@ mon_stat_init (void) } void -arn_cm_init_env () +arn_am_init_env () { char conf_name[256]; char tmpstrbuf[DBMT_ERROR_MSG_SIZE]; @@ -161,14 +161,14 @@ arn_cm_init_env () putenv (arn_httpd_env.arniadb_charset); } */ - mutex_init (cm_mutex); + mutex_init (am_mutex); return; } void -arn_cm_destory_env () +arn_am_destory_env () { - mutex_destory (cm_mutex); + mutex_destory (am_mutex); } int @@ -198,7 +198,7 @@ is_no_token_cmd (int task_code) } /* -inherit for cm_job, find the task function, and exec; +inherit for am_job, find the task function, and exec; */ int ch_process_request (nvplist *req, nvplist *res) @@ -432,7 +432,7 @@ dump_nvplist (nvplist *root, char *dumpfile) int -arn_cm_extend_request (Json::Value &request, Json::Value &response) +arn_am_extend_request (Json::Value &request, Json::Value &response) { T_EXT_TASK_FUNC task_func = NULL; string task; @@ -472,10 +472,10 @@ list < async_request * >request_list; #ifdef WINDOWS DWORD WINAPI -cm_async_request_handler (LPVOID lpArg) +am_async_request_handler (LPVOID lpArg) #else void * -cm_async_request_handler (void *lpArg) +am_async_request_handler (void *lpArg) #endif { int index = 0; @@ -514,7 +514,7 @@ cm_async_request_handler (void *lpArg) #ifdef WINDOWS int -cm_execute_request_async (Json::Value &request, Json::Value &response, +am_execute_request_async (Json::Value &request, Json::Value &response, unsigned long time_out = 600) { HANDLE hHandles; @@ -532,7 +532,7 @@ cm_execute_request_async (Json::Value &request, Json::Value &response, pstmt->uuid = req_id++; hHandles = - CreateThread (NULL, 0, cm_async_request_handler, pstmt, 0, &ThreadID); + CreateThread (NULL, 0, am_async_request_handler, pstmt, 0, &ThreadID); if (hHandles == NULL) { delete (pstmt); @@ -559,7 +559,7 @@ cm_execute_request_async (Json::Value &request, Json::Value &response, } #else int -cm_execute_request_async (Json::Value &request, Json::Value &response, +am_execute_request_async (Json::Value &request, Json::Value &response, unsigned long time_out = 600) { int err = 0; @@ -580,7 +580,7 @@ cm_execute_request_async (Json::Value &request, Json::Value &response, err = pthread_mutex_init (&mutex, NULL); if (err != 0) { - LOG_ERROR ("cm_execute_request_async : fail to set thread mutex."); + LOG_ERROR ("am_execute_request_async : fail to set thread mutex."); return build_server_header (response, ERR_WITH_MSG, "failed to run task."); } @@ -588,7 +588,7 @@ cm_execute_request_async (Json::Value &request, Json::Value &response, err = pthread_cond_init (&cond, NULL); if (err != 0) { - LOG_ERROR ("cm_execute_request_async : fail to set thread condition."); + LOG_ERROR ("am_execute_request_async : fail to set thread condition."); return build_server_header (response, ERR_WITH_MSG, "failed to run task."); } @@ -605,7 +605,7 @@ cm_execute_request_async (Json::Value &request, Json::Value &response, err = pthread_attr_init (&thread_attr); if (err != 0) { - LOG_ERROR ("cm_execute_request_async : fail to set thread attribute."); + LOG_ERROR ("am_execute_request_async : fail to set thread attribute."); return build_server_header (response, ERR_WITH_MSG, "failed to run task."); } @@ -613,7 +613,7 @@ cm_execute_request_async (Json::Value &request, Json::Value &response, err = pthread_attr_setdetachstate (&thread_attr, PTHREAD_CREATE_DETACHED); if (err != 0) { - LOG_ERROR ("cm_execute_request_async : fail to set thread detach state."); + LOG_ERROR ("am_execute_request_async : fail to set thread detach state."); return build_server_header (response, ERR_WITH_MSG, "failed to run task."); } @@ -624,7 +624,7 @@ cm_execute_request_async (Json::Value &request, Json::Value &response, err = pthread_attr_setscope (&thread_attr, PTHREAD_SCOPE_PROCESS); if (err != 0) { - LOG_ERROR ("cm_execute_request_async : fail to set thread scope."); + LOG_ERROR ("am_execute_request_async : fail to set thread scope."); return build_server_header (response, ERR_WITH_MSG, "failed to run task."); } @@ -632,14 +632,14 @@ cm_execute_request_async (Json::Value &request, Json::Value &response, err = pthread_attr_setstacksize (&thread_attr, AIX_STACKSIZE_PER_THREAD); if (err != 0) { - LOG_ERROR ("cm_execute_request_async : fail to set thread stack size."); + LOG_ERROR ("am_execute_request_async : fail to set thread stack size."); return build_server_header (response, ERR_WITH_MSG, "failed to run task."); } - err = pthread_create (&async_thrd, &thread_attr, cm_async_request_handler, pstmt); + err = pthread_create (&async_thrd, &thread_attr, am_async_request_handler, pstmt); #else /* except AIX */ - err = pthread_create (&async_thrd, NULL, cm_async_request_handler, pstmt); + err = pthread_create (&async_thrd, NULL, am_async_request_handler, pstmt); #endif if (err != 0) @@ -647,7 +647,7 @@ cm_execute_request_async (Json::Value &request, Json::Value &response, delete (pstmt); pthread_mutex_destroy (&mutex); pthread_cond_destroy (&cond); - LOG_ERROR ("cm_execute_request_async : fail to create thread."); + LOG_ERROR ("am_execute_request_async : fail to create thread."); return build_server_header (response, ERR_WITH_MSG, "failed to run task."); } @@ -661,7 +661,7 @@ cm_execute_request_async (Json::Value &request, Json::Value &response, { request_list.push_back (pstmt); response["uuid"] = pstmt->uuid; - LOG_ERROR ("cm_execute_request_async : Timeout for running task."); + LOG_ERROR ("am_execute_request_async : Timeout for running task."); return build_server_header (response, ERR_WITH_MSG, "timeout"); } @@ -715,17 +715,17 @@ arn_check_async_status (Json::Value &request, Json::Value &response) } int -arn_cm_request_handler (Json::Value &request, Json::Value &response) +arn_am_request_handler (Json::Value &request, Json::Value &response) { - mutex_lock (cm_mutex); + mutex_lock (am_mutex); // leave a back door for testing... if (ext_ut_validate_token (request, response) != ERR_NO_ERROR && request["token"].asString() != "test") { response["task"] = request["task"].asString(); - mutex_unlock (cm_mutex); + mutex_unlock (am_mutex); return 1; } @@ -736,22 +736,22 @@ arn_cm_request_handler (Json::Value &request, Json::Value &response) response["note"] = "The user don't have authority to execute the task: " + request["task"].asString(); response["task"] = request["task"].asString(); - mutex_unlock (cm_mutex); + mutex_unlock (am_mutex); return 1; } if (arn_check_async_status (request, response)) { - mutex_unlock (cm_mutex); + mutex_unlock (am_mutex); return 1; } - if (arn_cm_extend_request (request, response)) + if (arn_am_extend_request (request, response)) { - mutex_unlock (cm_mutex); + mutex_unlock (am_mutex); return 1; } - cm_execute_request_async (request, response, sco.iHttpTimeout); + am_execute_request_async (request, response, sco.iHttpTimeout); - mutex_unlock (cm_mutex); + mutex_unlock (am_mutex); return 1; } diff --git a/server/src/am_server_interface.h b/server/src/am_server_interface.h index 60ba045..4ca4715 100644 --- a/server/src/am_server_interface.h +++ b/server/src/am_server_interface.h @@ -17,17 +17,17 @@ * */ -#ifndef __CM_API_H__ -#define __CM_API_H__ +#ifndef __AM_API_H__ +#define __AM_API_H__ #include -#include "cm_stat.h" -#include "cm_dep.h" -#include "cm_config.h" -#include "cm_job_task.h" -#include "cm_server_util.h" +#include "am_stat.h" +#include "am_dep.h" +#include "am_config.h" +#include "am_job_task.h" +#include "am_server_util.h" -int arn_cm_request_handler (Json::Value &request, Json::Value &response); -void arn_cm_init_env (); +int arn_am_request_handler (Json::Value &request, Json::Value &response); +void arn_am_init_env (); #endif /* */ diff --git a/server/src/am_server_stat.c b/server/src/am_server_stat.c index f30be6b..fcff245 100644 --- a/server/src/am_server_stat.c +++ b/server/src/am_server_stat.c @@ -41,11 +41,11 @@ #include #endif -#include "cm_porting.h" -#include "cm_server_stat.h" -#include "cm_dep.h" -#include "cm_server_util.h" -#include "cm_config.h" +#include "am_porting.h" +#include "am_server_stat.h" +#include "am_dep.h" +#include "am_server_util.h" +#include "am_config.h" #define MAX_CPU 16 diff --git a/server/src/am_server_stat.h b/server/src/am_server_stat.h index 69aa6e6..703a777 100644 --- a/server/src/am_server_stat.h +++ b/server/src/am_server_stat.h @@ -19,11 +19,11 @@ /* - * cm_server_stat.h - + * am_server_stat.h - */ -#ifndef _CM_SERVER_STAT_H_ -#define _CM_SERVER_STAT_H_ +#ifndef _AM_SERVER_STAT_H_ +#define _AM_SERVER_STAT_H_ #ident "$Id$" @@ -33,8 +33,8 @@ #undef HOST_MONITOR_IO #endif -#include "cm_dep.h" -#include "cm_config.h" +#include "am_dep.h" +#include "am_config.h" #define CPUSTATES 5 #define CPUSTATE_IOWAIT 3 @@ -96,4 +96,4 @@ void record_system_info (sys_stat *sstat); void record_arniadb_proc_info (userdata *ud); void record_unicas_proc_info (int casv[], cas_stat casb[]); -#endif /* _CM_SERVER_STAT_H_ */ +#endif /* _AM_SERVER_STAT_H_ */ diff --git a/server/src/am_server_util.cpp b/server/src/am_server_util.cpp index d5a5e13..14da147 100644 --- a/server/src/am_server_util.cpp +++ b/server/src/am_server_util.cpp @@ -19,7 +19,7 @@ /* - * cm_server_util.cpp - + * am_server_util.cpp - */ #include @@ -62,17 +62,17 @@ #include #endif -#include "cm_log.h" -#include "cm_connect_info.h" -#include "cm_porting.h" -#include "cm_server_util.h" -#include "cm_dep.h" -#include "cm_config.h" -#include "cm_job_task.h" -#include "cm_cmd_exec.h" -#include "cm_text_encryption.h" -#include "cm_stat.h" -#include "cm_user.h" +#include "am_log.h" +#include "am_connect_info.h" +#include "am_porting.h" +#include "am_server_util.h" +#include "am_dep.h" +#include "am_config.h" +#include "am_job_task.h" +#include "am_cmd_exec.h" +#include "am_text_encryption.h" +#include "am_stat.h" +#include "am_user.h" #include @@ -3769,7 +3769,7 @@ ut_record_arniadb_utility_log_stderr (const char *msg) #if !defined(WINDOWS) fprintf (stderr, msg); #endif - cm_util_log_write_errstr (msg); + am_util_log_write_errstr (msg); return 0; } @@ -3784,7 +3784,7 @@ ut_record_arniadb_utility_log_stdout (const char *msg) #if !defined(WINDOWS) fprintf (stdout, msg); #endif - cm_util_log_write_errstr (msg); + am_util_log_write_errstr (msg); return 0; } diff --git a/server/src/am_server_util.h b/server/src/am_server_util.h index c3dc5ce..1bcb141 100644 --- a/server/src/am_server_util.h +++ b/server/src/am_server_util.h @@ -19,16 +19,16 @@ /* - * cm_server_util.h - + * am_server_util.h - */ -#ifndef _CM_SERVER_UTIL_H_ -#define _CM_SERVER_UTIL_H_ +#ifndef _AM_SERVER_UTIL_H_ +#define _AM_SERVER_UTIL_H_ -#include "cm_porting.h" -#include "cm_dep.h" -#include "cm_cmd_exec.h" -#include "cm_job_task.h" +#include "am_porting.h" +#include "am_dep.h" +#include "am_cmd_exec.h" +#include "am_job_task.h" #ifndef WINDOWS #include @@ -216,4 +216,4 @@ int run_child_linux (const char *pname, const char *const argv[], int wait_flag, void write_manager_access_log (const char *protocol_str, const char *msg); void write_manager_error_log (const char *protocol_str, const char *msg); -#endif /* _CM_SERVER_UTIL_H_ */ +#endif /* _AM_SERVER_UTIL_H_ */ diff --git a/server/src/am_text_encryption.c b/server/src/am_text_encryption.c index 2026a85..5091a1b 100644 --- a/server/src/am_text_encryption.c +++ b/server/src/am_text_encryption.c @@ -29,8 +29,8 @@ #include #include -#include "cm_porting.h" -#include "cm_text_encryption.h" +#include "am_porting.h" +#include "am_text_encryption.h" #if (defined(SOLARIS) && !defined(SOLARIS_X86)) || defined(HPUX) || defined(AIX) #define BYTE_ORDER_BIG_ENDIAN diff --git a/server/src/am_text_encryption.h b/server/src/am_text_encryption.h index ccaf13f..7330017 100644 --- a/server/src/am_text_encryption.h +++ b/server/src/am_text_encryption.h @@ -19,11 +19,11 @@ /* - * cm_text_encryption.h - + * am_text_encryption.h - */ -#ifndef _CM_TEXT_ENCRYPTION_H_ -#define _CM_TEXT_ENCRYPTION_H_ +#ifndef _AM_TEXT_ENCRYPTION_H_ +#define _AM_TEXT_ENCRYPTION_H_ #ifdef __cplusplus extern "C" { @@ -35,4 +35,4 @@ void uDecrypt (int len, const char *src, char *trg); #ifdef __cplusplus } #endif -#endif /* _CM_TEXT_ENCRYPTION_H_ */ +#endif /* _AM_TEXT_ENCRYPTION_H_ */ diff --git a/server/src/am_user.cpp b/server/src/am_user.cpp index 47bd8a7..57f0bed 100644 --- a/server/src/am_user.cpp +++ b/server/src/am_user.cpp @@ -19,7 +19,7 @@ /* - * cm_user.cpp - + * am_user.cpp - */ #include @@ -32,10 +32,10 @@ #include #endif -#include "cm_porting.h" -#include "cm_config.h" -#include "cm_server_util.h" -#include "cm_user.h" +#include "am_porting.h" +#include "am_config.h" +#include "am_server_util.h" +#include "am_user.h" #define ARNIADB_PASS_OPEN_TAG "<<<:" #define ARNIADB_PASS_OPEN_TAG_LEN strlen(ARNIADB_PASS_OPEN_TAG) diff --git a/server/src/am_user.h b/server/src/am_user.h index 6165284..78d9a6e 100644 --- a/server/src/am_user.h +++ b/server/src/am_user.h @@ -19,11 +19,11 @@ /* - * cm_user.h - + * am_user.h - */ -#ifndef _CM_USER_H_ -#define _CM_USER_H_ +#ifndef _AM_USER_H_ +#define _AM_USER_H_ #define DBMT_USER_NAME_LEN 64 @@ -110,4 +110,4 @@ T_USER_TOKEN_INFO *dbmt_user_search_token_info_by_token (const char *token); T_USER_TOKEN_INFO *dbmt_user_delete_token_info (const char *user_id); T_USER_TOKEN_INFO *dbmt_user_delete_token_info_by_token (const char *token); -#endif /* _CM_USER_H_ */ +#endif /* _AM_USER_H_ */ diff --git a/server/src/am_win_wsa.h b/server/src/am_win_wsa.h index 140227a..95dcd41 100644 --- a/server/src/am_win_wsa.h +++ b/server/src/am_win_wsa.h @@ -19,11 +19,11 @@ /* - * cm_wsa_init.h - + * am_wsa_init.h - */ -#ifndef _CM_WSA_INIT_H_ -#define _CM_WSA_INIT_H_ +#ifndef _AM_WSA_INIT_H_ +#define _AM_WSA_INIT_H_ #ident "$Id$" @@ -60,4 +60,4 @@ int wsa_initialize (); * EXPORTED VARIABLES */ -#endif /* _CM_WSA_INIT_H_ */ +#endif /* _AM_WSA_INIT_H_ */ diff --git a/server/test/Makefile b/server/test/Makefile index 44f59d9..517bb05 100644 --- a/server/test/Makefile +++ b/server/test/Makefile @@ -10,10 +10,10 @@ test: lcov: - rm -f $(CUR_PATH)/log/CM_SERVER.CoverageResult.info - lcov -q -d $(COVERAGE_PATH) --no-recursion -b . -c -t CM_SERVER -o log/tmp.CM_SERVER.CoverageResult.info --ignore-errors source - lcov --remove log/tmp.CM_SERVER.CoverageResult.info stat.h sysmacros.h *.h -o log/CM_SERVER.CoverageResult.info - rm log/tmp.CM_SERVER.CoverageResult.info + rm -f $(CUR_PATH)/log/AM_SERVER.CoverageResult.info + lcov -q -d $(COVERAGE_PATH) --no-recursion -b . -c -t AM_SERVER -o log/tmp.AM_SERVER.CoverageResult.info --ignore-errors source + lcov --remove log/tmp.AM_SERVER.CoverageResult.info stat.h sysmacros.h *.h -o log/AM_SERVER.CoverageResult.info + rm log/tmp.AM_SERVER.CoverageResult.info clean: rm -rf log diff --git a/server/test/task_test_case/setsysparam_cmconf b/server/test/task_test_case/setsysparam_cmconf index a95200c..1f33fdb 100644 --- a/server/test/task_test_case/setsysparam_cmconf +++ b/server/test/task_test_case/setsysparam_cmconf @@ -21,6 +21,6 @@ confdata:# This program is distributed in the hope that it will be useful, confdata:# confdata:allow_user_multi_connection YES confdata:monitor_interval 5 -confdata:cm_port 8001 +confdata:am_port 8001 confdata:server_long_query_time 10 diff --git a/server/test/task_test_case_json/setsysparam_cmconf.txt b/server/test/task_test_case_json/setsysparam_cmconf.txt index ad72870..6a920df 100644 --- a/server/test/task_test_case_json/setsysparam_cmconf.txt +++ b/server/test/task_test_case_json/setsysparam_cmconf.txt @@ -20,5 +20,5 @@ "#", "allow_user_multi_connection YES", "monitor_interval 5", -"cm_port 8001", -"server_long_query_time 10"]} \ No newline at end of file +"am_port 8001", +"server_long_query_time 10"]} diff --git a/server/test/task_test_config/am_conf/am.conf b/server/test/task_test_config/am_conf/am.conf index 7f35e03..1eee386 100644 --- a/server/test/task_test_config/am_conf/am.conf +++ b/server/test/task_test_config/am_conf/am.conf @@ -10,7 +10,7 @@ # # Port number designation # -cm_port=8001 +am_port=8001 port_job_server=8002 port_auto_server=8001 # diff --git a/server/test/test_tasks.php b/server/test/test_tasks.php index ad37adb..29c4c68 100644 --- a/server/test/test_tasks.php +++ b/server/test/test_tasks.php @@ -2,8 +2,8 @@ ini_set("memory_limit","256M"); error_reporting (E_ALL); -define ("CM_PORT", 8001); -define ("CM_SERVER_IP", "127.0.0.1"); +define ("AM_PORT", 8001); +define ("AM_SERVER_IP", "127.0.0.1"); define ("CLIENT_VERSION", "8.2.2"); define ("TEST_CASE_DIR", "task_test_case/"); define ("TEST_RESULT_DIR", "task_test_result/"); @@ -350,7 +350,7 @@ function exec_task($req_file, $token, $test_result) "\n"; } - $result = socket_connect ($sock_js, CM_SERVER_IP, CM_PORT+1); + $result = socket_connect ($sock_js, AM_SERVER_IP, AM_PORT+1); if ($result < 0) { echo "socket_connect() failed.\nReason: ($result) ". @@ -409,7 +409,7 @@ function exec_task($req_file, $token, $test_result) function get_token($sock_auto) { - $result = socket_connect ($sock_auto, CM_SERVER_IP, CM_PORT); + $result = socket_connect ($sock_auto, AM_SERVER_IP, AM_PORT); if ($result < 0) { echo "socket_connect() failed.\nReason: ($result) ". diff --git a/server/test/test_tasks.py b/server/test/test_tasks.py index 97154e8..0815cb3 100644 --- a/server/test/test_tasks.py +++ b/server/test/test_tasks.py @@ -6,7 +6,7 @@ def findport(): arniadb = os.environ.get("ARNIADB") - conf = arniadb + "/conf/cm_httpd.conf" + conf = arniadb + "/conf/am_httpd.conf" cwm_find = False; cf = open(conf, "r") for line in cf: @@ -25,7 +25,7 @@ def findport(): #amsip="192.168.0.1" amsip="localhost" port=int(findport()) -url="/cm_api" +url="/am_api" testdir="task_test_case_json/" token="" diff --git a/server/win/am_admin/am_admin.vcproj b/server/win/am_admin/am_admin.vcproj index 7cf95fd..6d5df07 100644 --- a/server/win/am_admin/am_admin.vcproj +++ b/server/win/am_admin/am_admin.vcproj @@ -2,9 +2,9 @@ @@ -341,59 +341,59 @@ Name="amserver" > diff --git a/server/win/install/install.bat b/server/win/install/install.bat index a759d61..42474aa 100644 --- a/server/win/install/install.bat +++ b/server/win/install/install.bat @@ -16,7 +16,7 @@ copy %SRC_DIR%\*.pdb %DEST_DIR%\bin copy %SRC_DIR%\..\..\amserver\conf\*.conf %DEST_DIR%\conf copy %SRC_DIR%\..\..\amserver\conf\*.pass %DEST_DIR%\conf -copy %SRC_DIR%\..\..\amserver\conf\cm_ssl_cert.* %DEST_DIR%\conf +copy %SRC_DIR%\..\..\amserver\conf\am_ssl_cert.* %DEST_DIR%\conf if errorlevel 1 ( exit /b 0 From d80627cf675a76f0167b4a1d5c63b61117661532 Mon Sep 17 00:00:00 2001 From: Mihai Serban Date: Sat, 16 Oct 2021 17:26:34 +0300 Subject: [PATCH 05/12] add ams --- .idea/arniadb-manager-server.iml | 9 --------- 1 file changed, 9 deletions(-) delete mode 100644 .idea/arniadb-manager-server.iml diff --git a/.idea/arniadb-manager-server.iml b/.idea/arniadb-manager-server.iml deleted file mode 100644 index d6ebd48..0000000 --- a/.idea/arniadb-manager-server.iml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - \ No newline at end of file From 69a6f48244ccd6900b08213906ff7b7f859c19eb Mon Sep 17 00:00:00 2001 From: Mihai Serban Date: Sun, 17 Oct 2021 18:35:16 +0300 Subject: [PATCH 06/12] add ams --- docs/api/README.md | 2 +- docs/api/getallsysparam.md | 2 +- docs/api/getdbmtuserinfo_new.md | 2 +- docs/api/updatedbmtuser_new.md | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/api/README.md b/docs/api/README.md index 96a4b54..8cdeff9 100644 --- a/docs/api/README.md +++ b/docs/api/README.md @@ -123,7 +123,7 @@ AMS Interfaces are conposed by Json and is used for communication between AMS an | [updateuser](updateuser.md) | socket, http | DBO | | [userverify](userverify.md) | socket, http | ALL_AUTHORITY | -### CM User +### AM User | **Interface Name**| **Connection Type** | **Permission** | **Support Version** | | --- | --- | --- | --- | diff --git a/docs/api/getallsysparam.md b/docs/api/getallsysparam.md index 6468629..9d310aa 100644 --- a/docs/api/getallsysparam.md +++ b/docs/api/getallsysparam.md @@ -8,7 +8,7 @@ Get configuration files. | --- | --- | | task | task name | | token | token string encrypted. | -| confname | arniadbconf, cmconf, haconf, databases | +| confname | arniadbconf, amconf, haconf, databases | ## Request Sample diff --git a/docs/api/getdbmtuserinfo_new.md b/docs/api/getdbmtuserinfo_new.md index 74e47f5..420d61e 100644 --- a/docs/api/getdbmtuserinfo_new.md +++ b/docs/api/getdbmtuserinfo_new.md @@ -1,6 +1,6 @@ # getdbmtuserinfo_new -Get CM/CWM user information +Get AM/AWM user information ## Request Json Syntax diff --git a/docs/api/updatedbmtuser_new.md b/docs/api/updatedbmtuser_new.md index 78117c7..aa0d532 100644 --- a/docs/api/updatedbmtuser_new.md +++ b/docs/api/updatedbmtuser_new.md @@ -1,6 +1,6 @@ # updatedbmtuser_new -Update CM/CWM user information +Update AM/AWM user information ## Request Json Syntax From 89b6072cec7ade27ce29d599d4a07cd8c4ac03bb Mon Sep 17 00:00:00 2001 From: Mihai Serban Date: Sun, 17 Oct 2021 18:43:13 +0300 Subject: [PATCH 07/12] add ams --- server/test/task_test_case/setsysparam_amconf | 26 +++++++++++++++++++ .../setsysparam_amconf.txt | 24 +++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 server/test/task_test_case/setsysparam_amconf create mode 100644 server/test/task_test_case_json/setsysparam_amconf.txt diff --git a/server/test/task_test_case/setsysparam_amconf b/server/test/task_test_case/setsysparam_amconf new file mode 100644 index 0000000..1f33fdb --- /dev/null +++ b/server/test/task_test_case/setsysparam_amconf @@ -0,0 +1,26 @@ +task:setsysparam +token:cdfb4c5717170c5e942a1cf0685a4d40ba4969ddfab4169f75fd3469cebc3f967926f07dd201b6aa +confname:cmconf +confdata: +confdata:# +confdata:# Copyright (C) 2009 Search Solution Corporation. All rights reserved by Search Solution. +confdata:# +confdata:# This program is free software; you can redistribute it and/or modify +confdata:# it under the terms of the GNU General Public License as published by +confdata:# the Free Software Foundation; version 2 of the License. +confdata:# +confdata:# This program is distributed in the hope that it will be useful, + confdata:# but WITHOUT ANY WARRANTY; without even the implied warranty of + confdata:# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + confdata:# GNU General Public License for more details. + confdata:# + confdata:# You should have received a copy of the GNU General Public License + confdata:# along with this program; if not, write to the Free Software + confdata:# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + confdata: +confdata:# +confdata:allow_user_multi_connection YES +confdata:monitor_interval 5 +confdata:am_port 8001 +confdata:server_long_query_time 10 + diff --git a/server/test/task_test_case_json/setsysparam_amconf.txt b/server/test/task_test_case_json/setsysparam_amconf.txt new file mode 100644 index 0000000..6a920df --- /dev/null +++ b/server/test/task_test_case_json/setsysparam_amconf.txt @@ -0,0 +1,24 @@ +{"task":"setsysparam", +"token":"cdfb4c5717170c5e942a1cf0685a4d40ba4969ddfab4169f75fd3469cebc3f967926f07dd201b6aa", +"confname":"cmconf", +"confdata":[ +"#", +"# Copyright (C) 2009 Search Solution Corporation. All rights reserved by Search Solution.", +"#", +"# 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; version 2 of the License.", +"#", +"# 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 Street, Fifth Floor, Boston, MA 02110-1301, USA", +"#", +"allow_user_multi_connection YES", +"monitor_interval 5", +"am_port 8001", +"server_long_query_time 10"]} From 13c809fd0aa22b30c949e9b0c665936653af6207 Mon Sep 17 00:00:00 2001 From: Mihai Serban Date: Sun, 17 Oct 2021 18:47:04 +0300 Subject: [PATCH 08/12] add ams --- server/test/task_test_case/setsysparam_cmconf | 26 ------------------- .../setsysparam_cmconf.txt | 24 ----------------- 2 files changed, 50 deletions(-) delete mode 100644 server/test/task_test_case/setsysparam_cmconf delete mode 100644 server/test/task_test_case_json/setsysparam_cmconf.txt diff --git a/server/test/task_test_case/setsysparam_cmconf b/server/test/task_test_case/setsysparam_cmconf deleted file mode 100644 index 1f33fdb..0000000 --- a/server/test/task_test_case/setsysparam_cmconf +++ /dev/null @@ -1,26 +0,0 @@ -task:setsysparam -token:cdfb4c5717170c5e942a1cf0685a4d40ba4969ddfab4169f75fd3469cebc3f967926f07dd201b6aa -confname:cmconf -confdata: -confdata:# -confdata:# Copyright (C) 2009 Search Solution Corporation. All rights reserved by Search Solution. -confdata:# -confdata:# This program is free software; you can redistribute it and/or modify -confdata:# it under the terms of the GNU General Public License as published by -confdata:# the Free Software Foundation; version 2 of the License. -confdata:# -confdata:# This program is distributed in the hope that it will be useful, - confdata:# but WITHOUT ANY WARRANTY; without even the implied warranty of - confdata:# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - confdata:# GNU General Public License for more details. - confdata:# - confdata:# You should have received a copy of the GNU General Public License - confdata:# along with this program; if not, write to the Free Software - confdata:# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA - confdata: -confdata:# -confdata:allow_user_multi_connection YES -confdata:monitor_interval 5 -confdata:am_port 8001 -confdata:server_long_query_time 10 - diff --git a/server/test/task_test_case_json/setsysparam_cmconf.txt b/server/test/task_test_case_json/setsysparam_cmconf.txt deleted file mode 100644 index 6a920df..0000000 --- a/server/test/task_test_case_json/setsysparam_cmconf.txt +++ /dev/null @@ -1,24 +0,0 @@ -{"task":"setsysparam", -"token":"cdfb4c5717170c5e942a1cf0685a4d40ba4969ddfab4169f75fd3469cebc3f967926f07dd201b6aa", -"confname":"cmconf", -"confdata":[ -"#", -"# Copyright (C) 2009 Search Solution Corporation. All rights reserved by Search Solution.", -"#", -"# 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; version 2 of the License.", -"#", -"# 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 Street, Fifth Floor, Boston, MA 02110-1301, USA", -"#", -"allow_user_multi_connection YES", -"monitor_interval 5", -"am_port 8001", -"server_long_query_time 10"]} From 12fe59c208f7d19f6158acff7f5b03e6ad8f2ae9 Mon Sep 17 00:00:00 2001 From: Mihai Serban Date: Tue, 19 Oct 2021 12:12:46 +0300 Subject: [PATCH 09/12] add ams --- server/external/README | 2 +- .../openssl/aix_64/include/openssl/des.h | 2 +- .../openssl/aix_64/include/openssl/des_old.h | 4 +- .../openssl/aix_64/include/openssl/err.h | 4 +- .../openssl/aix_64/include/openssl/obj_mac.h | 18 +- .../aix_64/include/openssl/opensslconf.h | 8 +- .../openssl/aix_64/include/openssl/pem.h | 2 +- .../aix_64/include/openssl/safestack.h | 174 +++--- .../openssl/aix_64/include/openssl/symhacks.h | 32 +- .../openssl/linux_32/include/openssl/cms.h | 501 ++++++++++++++++++ .../openssl/linux_32/include/openssl/des.h | 2 +- .../linux_32/include/openssl/des_old.h | 4 +- .../openssl/linux_32/include/openssl/err.h | 4 +- .../openssl/linux_32/include/openssl/evp.h | 42 +- .../linux_32/include/openssl/obj_mac.h | 18 +- .../openssl/linux_32/include/openssl/pem.h | 2 +- .../linux_32/include/openssl/safestack.h | 174 +++--- .../openssl/linux_32/include/openssl/srtp.h | 4 +- .../linux_32/include/openssl/symhacks.h | 32 +- .../openssl/linux_32/include/openssl/tls1.h | 80 +-- .../openssl/linux_64/include/openssl/cms.h | 339 ++++++++++++ .../openssl/linux_64/include/openssl/cmserr.h | 202 +++++++ .../openssl/linux_64/include/openssl/dh.h | 4 +- .../openssl/linux_64/include/openssl/dherr.h | 6 +- .../openssl/linux_64/include/openssl/ecerr.h | 4 +- .../openssl/linux_64/include/openssl/err.h | 4 +- .../openssl/linux_64/include/openssl/evp.h | 54 +- .../openssl/linux_64/include/openssl/evperr.h | 10 +- .../linux_64/include/openssl/obj_mac.h | 18 +- .../openssl/linux_64/include/openssl/pem.h | 2 +- .../openssl/linux_64/include/openssl/rsaerr.h | 4 +- .../openssl/linux_64/include/openssl/srtp.h | 4 +- .../openssl/linux_64/include/openssl/ssl.h | 10 +- .../linux_64/include/openssl/symhacks.h | 4 +- .../openssl/linux_64/include/openssl/tls1.h | 376 ++++++------- .../openssl/win_32/include/openssl/cms.h | 501 ++++++++++++++++++ .../openssl/win_32/include/openssl/des.h | 2 +- .../openssl/win_32/include/openssl/des_old.h | 4 +- .../openssl/win_32/include/openssl/err.h | 4 +- .../openssl/win_32/include/openssl/evp.h | 42 +- .../openssl/win_32/include/openssl/obj_mac.h | 18 +- .../openssl/win_32/include/openssl/pem.h | 2 +- .../win_32/include/openssl/safestack.h | 174 +++--- .../openssl/win_32/include/openssl/srtp.h | 4 +- .../openssl/win_32/include/openssl/symhacks.h | 30 +- .../openssl/win_32/include/openssl/tls1.h | 80 +-- .../openssl/win_64/include/openssl/cms.h | 501 ++++++++++++++++++ .../openssl/win_64/include/openssl/des.h | 2 +- .../openssl/win_64/include/openssl/des_old.h | 4 +- .../openssl/win_64/include/openssl/err.h | 4 +- .../openssl/win_64/include/openssl/evp.h | 42 +- .../openssl/win_64/include/openssl/obj_mac.h | 18 +- .../openssl/win_64/include/openssl/pem.h | 2 +- .../win_64/include/openssl/safestack.h | 174 +++--- .../openssl/win_64/include/openssl/srtp.h | 4 +- .../openssl/win_64/include/openssl/symhacks.h | 30 +- .../openssl/win_64/include/openssl/tls1.h | 80 +-- 57 files changed, 2958 insertions(+), 914 deletions(-) create mode 100644 server/external/openssl/linux_32/include/openssl/cms.h create mode 100644 server/external/openssl/linux_64/include/openssl/cms.h create mode 100644 server/external/openssl/linux_64/include/openssl/cmserr.h create mode 100644 server/external/openssl/win_32/include/openssl/cms.h create mode 100644 server/external/openssl/win_64/include/openssl/cms.h diff --git a/server/external/README b/server/external/README index 518ecdf..40297f1 100644 --- a/server/external/README +++ b/server/external/README @@ -74,4 +74,4 @@ nmake OPENSSL_DIR=F:\openssl /f Makefile.nmake Sincerely, -Your AMS Development Team. +Your CMS Development Team. diff --git a/server/external/openssl/aix_64/include/openssl/des.h b/server/external/openssl/aix_64/include/openssl/des.h index a65e4d7..d9fc22c 100644 --- a/server/external/openssl/aix_64/include/openssl/des.h +++ b/server/external/openssl/aix_64/include/openssl/des.h @@ -193,7 +193,7 @@ void DES_ede3_cbc_encrypt(const unsigned char *input,unsigned char *output, long length, DES_key_schedule *ks1,DES_key_schedule *ks2, DES_key_schedule *ks3,DES_cblock *ivec,int enc); -void DES_ede3_cbam_encrypt(const unsigned char *in,unsigned char *out, +void DES_ede3_cbcm_encrypt(const unsigned char *in,unsigned char *out, long length, DES_key_schedule *ks1,DES_key_schedule *ks2, DES_key_schedule *ks3, diff --git a/server/external/openssl/aix_64/include/openssl/des_old.h b/server/external/openssl/aix_64/include/openssl/des_old.h index b816059..fe8451c 100644 --- a/server/external/openssl/aix_64/include/openssl/des_old.h +++ b/server/external/openssl/aix_64/include/openssl/des_old.h @@ -155,8 +155,8 @@ typedef struct _ossl_old_des_ks_struct DES_ecb3_encrypt((i),(o),&(k1),&(k2),&(k3),(e)) #define des_ede3_cbc_encrypt(i,o,l,k1,k2,k3,iv,e)\ DES_ede3_cbc_encrypt((i),(o),(l),&(k1),&(k2),&(k3),(iv),(e)) -#define des_ede3_cbam_encrypt(i,o,l,k1,k2,k3,iv1,iv2,e)\ - DES_ede3_cbam_encrypt((i),(o),(l),&(k1),&(k2),&(k3),(iv1),(iv2),(e)) +#define des_ede3_cbcm_encrypt(i,o,l,k1,k2,k3,iv1,iv2,e)\ + DES_ede3_cbcm_encrypt((i),(o),(l),&(k1),&(k2),&(k3),(iv1),(iv2),(e)) #define des_ede3_cfb64_encrypt(i,o,l,k1,k2,k3,iv,n,e)\ DES_ede3_cfb64_encrypt((i),(o),(l),&(k1),&(k2),&(k3),(iv),(n),(e)) #define des_ede3_ofb64_encrypt(i,o,l,k1,k2,k3,iv,n)\ diff --git a/server/external/openssl/aix_64/include/openssl/err.h b/server/external/openssl/aix_64/include/openssl/err.h index ed841ba..e5422df 100644 --- a/server/external/openssl/aix_64/include/openssl/err.h +++ b/server/external/openssl/aix_64/include/openssl/err.h @@ -157,7 +157,7 @@ typedef struct err_state_st #define ERR_LIB_ECDH 43 #define ERR_LIB_STORE 44 #define ERR_LIB_FIPS 45 -#define ERR_LIB_AMS 46 +#define ERR_LIB_CMS 46 #define ERR_LIB_JPAKE 47 #define ERR_LIB_USER 128 @@ -191,7 +191,7 @@ typedef struct err_state_st #define ECDHerr(f,r) ERR_PUT_error(ERR_LIB_ECDH,(f),(r),__FILE__,__LINE__) #define STOREerr(f,r) ERR_PUT_error(ERR_LIB_STORE,(f),(r),__FILE__,__LINE__) #define FIPSerr(f,r) ERR_PUT_error(ERR_LIB_FIPS,(f),(r),__FILE__,__LINE__) -#define AMSerr(f,r) ERR_PUT_error(ERR_LIB_AMS,(f),(r),__FILE__,__LINE__) +#define CMSerr(f,r) ERR_PUT_error(ERR_LIB_CMS,(f),(r),__FILE__,__LINE__) #define JPAKEerr(f,r) ERR_PUT_error(ERR_LIB_JPAKE,(f),(r),__FILE__,__LINE__) /* Borland C seems too stupid to be able to shift and do longs in diff --git a/server/external/openssl/aix_64/include/openssl/obj_mac.h b/server/external/openssl/aix_64/include/openssl/obj_mac.h index c9d18dc..e85417a 100644 --- a/server/external/openssl/aix_64/include/openssl/obj_mac.h +++ b/server/external/openssl/aix_64/include/openssl/obj_mac.h @@ -781,9 +781,9 @@ #define NID_id_smime_cti 195 #define OBJ_id_smime_cti OBJ_SMIME,6L -#define SN_id_smime_mod_ams "id-smime-mod-ams" -#define NID_id_smime_mod_ams 196 -#define OBJ_id_smime_mod_ams OBJ_id_smime_mod,1L +#define SN_id_smime_mod_cms "id-smime-mod-cms" +#define NID_id_smime_mod_cms 196 +#define OBJ_id_smime_mod_cms OBJ_id_smime_mod,1L #define SN_id_smime_mod_ess "id-smime-mod-ess" #define NID_id_smime_mod_ess 197 @@ -989,13 +989,13 @@ #define NID_id_smime_alg_ESDH 245 #define OBJ_id_smime_alg_ESDH OBJ_id_smime_alg,5L -#define SN_id_smime_alg_AMS3DESwrap "id-smime-alg-AMS3DESwrap" -#define NID_id_smime_alg_AMS3DESwrap 246 -#define OBJ_id_smime_alg_AMS3DESwrap OBJ_id_smime_alg,6L +#define SN_id_smime_alg_CMS3DESwrap "id-smime-alg-CMS3DESwrap" +#define NID_id_smime_alg_CMS3DESwrap 246 +#define OBJ_id_smime_alg_CMS3DESwrap OBJ_id_smime_alg,6L -#define SN_id_smime_alg_AMSRC2wrap "id-smime-alg-AMSRC2wrap" -#define NID_id_smime_alg_AMSRC2wrap 247 -#define OBJ_id_smime_alg_AMSRC2wrap OBJ_id_smime_alg,7L +#define SN_id_smime_alg_CMSRC2wrap "id-smime-alg-CMSRC2wrap" +#define NID_id_smime_alg_CMSRC2wrap 247 +#define OBJ_id_smime_alg_CMSRC2wrap OBJ_id_smime_alg,7L #define SN_id_smime_cd_ldap "id-smime-cd-ldap" #define NID_id_smime_cd_ldap 248 diff --git a/server/external/openssl/aix_64/include/openssl/opensslconf.h b/server/external/openssl/aix_64/include/openssl/opensslconf.h index d083e89..b3b1c8d 100644 --- a/server/external/openssl/aix_64/include/openssl/opensslconf.h +++ b/server/external/openssl/aix_64/include/openssl/opensslconf.h @@ -30,8 +30,8 @@ #ifndef OPENSSL_NO_CAPIENG # define OPENSSL_NO_CAPIENG #endif -#ifndef OPENSSL_NO_AMS -# define OPENSSL_NO_AMS +#ifndef OPENSSL_NO_CMS +# define OPENSSL_NO_CMS #endif #ifndef OPENSSL_NO_EC # define OPENSSL_NO_EC @@ -87,8 +87,8 @@ # if defined(OPENSSL_NO_CAPIENG) && !defined(NO_CAPIENG) # define NO_CAPIENG # endif -# if defined(OPENSSL_NO_AMS) && !defined(NO_AMS) -# define NO_AMS +# if defined(OPENSSL_NO_CMS) && !defined(NO_CMS) +# define NO_CMS # endif # if defined(OPENSSL_NO_EC) && !defined(NO_EC) # define NO_EC diff --git a/server/external/openssl/aix_64/include/openssl/pem.h b/server/external/openssl/aix_64/include/openssl/pem.h index 6195e44..f42ecaa 100644 --- a/server/external/openssl/aix_64/include/openssl/pem.h +++ b/server/external/openssl/aix_64/include/openssl/pem.h @@ -150,7 +150,7 @@ extern "C" { #define PEM_STRING_ECDSA_PUBLIC "ECDSA PUBLIC KEY" #define PEM_STRING_ECPARAMETERS "EC PARAMETERS" #define PEM_STRING_ECPRIVATEKEY "EC PRIVATE KEY" -#define PEM_STRING_AMS "AMS" +#define PEM_STRING_CMS "CMS" /* Note that this structure is initialised by PEM_SealInit and cleaned up by PEM_SealFinal (at least for now) */ diff --git a/server/external/openssl/aix_64/include/openssl/safestack.h b/server/external/openssl/aix_64/include/openssl/safestack.h index a340a98..53440d9 100644 --- a/server/external/openssl/aix_64/include/openssl/safestack.h +++ b/server/external/openssl/aix_64/include/openssl/safestack.h @@ -430,93 +430,93 @@ STACK_OF(type) \ #define sk_BIO_sort(st) SKM_sk_sort(BIO, (st)) #define sk_BIO_is_sorted(st) SKM_sk_is_sorted(BIO, (st)) -#define sk_AMS_CertificateChoices_new(st) SKM_sk_new(AMS_CertificateChoices, (st)) -#define sk_AMS_CertificateChoices_new_null() SKM_sk_new_null(AMS_CertificateChoices) -#define sk_AMS_CertificateChoices_free(st) SKM_sk_free(AMS_CertificateChoices, (st)) -#define sk_AMS_CertificateChoices_num(st) SKM_sk_num(AMS_CertificateChoices, (st)) -#define sk_AMS_CertificateChoices_value(st, i) SKM_sk_value(AMS_CertificateChoices, (st), (i)) -#define sk_AMS_CertificateChoices_set(st, i, val) SKM_sk_set(AMS_CertificateChoices, (st), (i), (val)) -#define sk_AMS_CertificateChoices_zero(st) SKM_sk_zero(AMS_CertificateChoices, (st)) -#define sk_AMS_CertificateChoices_push(st, val) SKM_sk_push(AMS_CertificateChoices, (st), (val)) -#define sk_AMS_CertificateChoices_unshift(st, val) SKM_sk_unshift(AMS_CertificateChoices, (st), (val)) -#define sk_AMS_CertificateChoices_find(st, val) SKM_sk_find(AMS_CertificateChoices, (st), (val)) -#define sk_AMS_CertificateChoices_find_ex(st, val) SKM_sk_find_ex(AMS_CertificateChoices, (st), (val)) -#define sk_AMS_CertificateChoices_delete(st, i) SKM_sk_delete(AMS_CertificateChoices, (st), (i)) -#define sk_AMS_CertificateChoices_delete_ptr(st, ptr) SKM_sk_delete_ptr(AMS_CertificateChoices, (st), (ptr)) -#define sk_AMS_CertificateChoices_insert(st, val, i) SKM_sk_insert(AMS_CertificateChoices, (st), (val), (i)) -#define sk_AMS_CertificateChoices_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(AMS_CertificateChoices, (st), (cmp)) -#define sk_AMS_CertificateChoices_dup(st) SKM_sk_dup(AMS_CertificateChoices, st) -#define sk_AMS_CertificateChoices_pop_free(st, free_func) SKM_sk_pop_free(AMS_CertificateChoices, (st), (free_func)) -#define sk_AMS_CertificateChoices_shift(st) SKM_sk_shift(AMS_CertificateChoices, (st)) -#define sk_AMS_CertificateChoices_pop(st) SKM_sk_pop(AMS_CertificateChoices, (st)) -#define sk_AMS_CertificateChoices_sort(st) SKM_sk_sort(AMS_CertificateChoices, (st)) -#define sk_AMS_CertificateChoices_is_sorted(st) SKM_sk_is_sorted(AMS_CertificateChoices, (st)) - -#define sk_AMS_RecipientInfo_new(st) SKM_sk_new(AMS_RecipientInfo, (st)) -#define sk_AMS_RecipientInfo_new_null() SKM_sk_new_null(AMS_RecipientInfo) -#define sk_AMS_RecipientInfo_free(st) SKM_sk_free(AMS_RecipientInfo, (st)) -#define sk_AMS_RecipientInfo_num(st) SKM_sk_num(AMS_RecipientInfo, (st)) -#define sk_AMS_RecipientInfo_value(st, i) SKM_sk_value(AMS_RecipientInfo, (st), (i)) -#define sk_AMS_RecipientInfo_set(st, i, val) SKM_sk_set(AMS_RecipientInfo, (st), (i), (val)) -#define sk_AMS_RecipientInfo_zero(st) SKM_sk_zero(AMS_RecipientInfo, (st)) -#define sk_AMS_RecipientInfo_push(st, val) SKM_sk_push(AMS_RecipientInfo, (st), (val)) -#define sk_AMS_RecipientInfo_unshift(st, val) SKM_sk_unshift(AMS_RecipientInfo, (st), (val)) -#define sk_AMS_RecipientInfo_find(st, val) SKM_sk_find(AMS_RecipientInfo, (st), (val)) -#define sk_AMS_RecipientInfo_find_ex(st, val) SKM_sk_find_ex(AMS_RecipientInfo, (st), (val)) -#define sk_AMS_RecipientInfo_delete(st, i) SKM_sk_delete(AMS_RecipientInfo, (st), (i)) -#define sk_AMS_RecipientInfo_delete_ptr(st, ptr) SKM_sk_delete_ptr(AMS_RecipientInfo, (st), (ptr)) -#define sk_AMS_RecipientInfo_insert(st, val, i) SKM_sk_insert(AMS_RecipientInfo, (st), (val), (i)) -#define sk_AMS_RecipientInfo_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(AMS_RecipientInfo, (st), (cmp)) -#define sk_AMS_RecipientInfo_dup(st) SKM_sk_dup(AMS_RecipientInfo, st) -#define sk_AMS_RecipientInfo_pop_free(st, free_func) SKM_sk_pop_free(AMS_RecipientInfo, (st), (free_func)) -#define sk_AMS_RecipientInfo_shift(st) SKM_sk_shift(AMS_RecipientInfo, (st)) -#define sk_AMS_RecipientInfo_pop(st) SKM_sk_pop(AMS_RecipientInfo, (st)) -#define sk_AMS_RecipientInfo_sort(st) SKM_sk_sort(AMS_RecipientInfo, (st)) -#define sk_AMS_RecipientInfo_is_sorted(st) SKM_sk_is_sorted(AMS_RecipientInfo, (st)) - -#define sk_AMS_RevocationInfoChoice_new(st) SKM_sk_new(AMS_RevocationInfoChoice, (st)) -#define sk_AMS_RevocationInfoChoice_new_null() SKM_sk_new_null(AMS_RevocationInfoChoice) -#define sk_AMS_RevocationInfoChoice_free(st) SKM_sk_free(AMS_RevocationInfoChoice, (st)) -#define sk_AMS_RevocationInfoChoice_num(st) SKM_sk_num(AMS_RevocationInfoChoice, (st)) -#define sk_AMS_RevocationInfoChoice_value(st, i) SKM_sk_value(AMS_RevocationInfoChoice, (st), (i)) -#define sk_AMS_RevocationInfoChoice_set(st, i, val) SKM_sk_set(AMS_RevocationInfoChoice, (st), (i), (val)) -#define sk_AMS_RevocationInfoChoice_zero(st) SKM_sk_zero(AMS_RevocationInfoChoice, (st)) -#define sk_AMS_RevocationInfoChoice_push(st, val) SKM_sk_push(AMS_RevocationInfoChoice, (st), (val)) -#define sk_AMS_RevocationInfoChoice_unshift(st, val) SKM_sk_unshift(AMS_RevocationInfoChoice, (st), (val)) -#define sk_AMS_RevocationInfoChoice_find(st, val) SKM_sk_find(AMS_RevocationInfoChoice, (st), (val)) -#define sk_AMS_RevocationInfoChoice_find_ex(st, val) SKM_sk_find_ex(AMS_RevocationInfoChoice, (st), (val)) -#define sk_AMS_RevocationInfoChoice_delete(st, i) SKM_sk_delete(AMS_RevocationInfoChoice, (st), (i)) -#define sk_AMS_RevocationInfoChoice_delete_ptr(st, ptr) SKM_sk_delete_ptr(AMS_RevocationInfoChoice, (st), (ptr)) -#define sk_AMS_RevocationInfoChoice_insert(st, val, i) SKM_sk_insert(AMS_RevocationInfoChoice, (st), (val), (i)) -#define sk_AMS_RevocationInfoChoice_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(AMS_RevocationInfoChoice, (st), (cmp)) -#define sk_AMS_RevocationInfoChoice_dup(st) SKM_sk_dup(AMS_RevocationInfoChoice, st) -#define sk_AMS_RevocationInfoChoice_pop_free(st, free_func) SKM_sk_pop_free(AMS_RevocationInfoChoice, (st), (free_func)) -#define sk_AMS_RevocationInfoChoice_shift(st) SKM_sk_shift(AMS_RevocationInfoChoice, (st)) -#define sk_AMS_RevocationInfoChoice_pop(st) SKM_sk_pop(AMS_RevocationInfoChoice, (st)) -#define sk_AMS_RevocationInfoChoice_sort(st) SKM_sk_sort(AMS_RevocationInfoChoice, (st)) -#define sk_AMS_RevocationInfoChoice_is_sorted(st) SKM_sk_is_sorted(AMS_RevocationInfoChoice, (st)) - -#define sk_AMS_SignerInfo_new(st) SKM_sk_new(AMS_SignerInfo, (st)) -#define sk_AMS_SignerInfo_new_null() SKM_sk_new_null(AMS_SignerInfo) -#define sk_AMS_SignerInfo_free(st) SKM_sk_free(AMS_SignerInfo, (st)) -#define sk_AMS_SignerInfo_num(st) SKM_sk_num(AMS_SignerInfo, (st)) -#define sk_AMS_SignerInfo_value(st, i) SKM_sk_value(AMS_SignerInfo, (st), (i)) -#define sk_AMS_SignerInfo_set(st, i, val) SKM_sk_set(AMS_SignerInfo, (st), (i), (val)) -#define sk_AMS_SignerInfo_zero(st) SKM_sk_zero(AMS_SignerInfo, (st)) -#define sk_AMS_SignerInfo_push(st, val) SKM_sk_push(AMS_SignerInfo, (st), (val)) -#define sk_AMS_SignerInfo_unshift(st, val) SKM_sk_unshift(AMS_SignerInfo, (st), (val)) -#define sk_AMS_SignerInfo_find(st, val) SKM_sk_find(AMS_SignerInfo, (st), (val)) -#define sk_AMS_SignerInfo_find_ex(st, val) SKM_sk_find_ex(AMS_SignerInfo, (st), (val)) -#define sk_AMS_SignerInfo_delete(st, i) SKM_sk_delete(AMS_SignerInfo, (st), (i)) -#define sk_AMS_SignerInfo_delete_ptr(st, ptr) SKM_sk_delete_ptr(AMS_SignerInfo, (st), (ptr)) -#define sk_AMS_SignerInfo_insert(st, val, i) SKM_sk_insert(AMS_SignerInfo, (st), (val), (i)) -#define sk_AMS_SignerInfo_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(AMS_SignerInfo, (st), (cmp)) -#define sk_AMS_SignerInfo_dup(st) SKM_sk_dup(AMS_SignerInfo, st) -#define sk_AMS_SignerInfo_pop_free(st, free_func) SKM_sk_pop_free(AMS_SignerInfo, (st), (free_func)) -#define sk_AMS_SignerInfo_shift(st) SKM_sk_shift(AMS_SignerInfo, (st)) -#define sk_AMS_SignerInfo_pop(st) SKM_sk_pop(AMS_SignerInfo, (st)) -#define sk_AMS_SignerInfo_sort(st) SKM_sk_sort(AMS_SignerInfo, (st)) -#define sk_AMS_SignerInfo_is_sorted(st) SKM_sk_is_sorted(AMS_SignerInfo, (st)) +#define sk_CMS_CertificateChoices_new(st) SKM_sk_new(CMS_CertificateChoices, (st)) +#define sk_CMS_CertificateChoices_new_null() SKM_sk_new_null(CMS_CertificateChoices) +#define sk_CMS_CertificateChoices_free(st) SKM_sk_free(CMS_CertificateChoices, (st)) +#define sk_CMS_CertificateChoices_num(st) SKM_sk_num(CMS_CertificateChoices, (st)) +#define sk_CMS_CertificateChoices_value(st, i) SKM_sk_value(CMS_CertificateChoices, (st), (i)) +#define sk_CMS_CertificateChoices_set(st, i, val) SKM_sk_set(CMS_CertificateChoices, (st), (i), (val)) +#define sk_CMS_CertificateChoices_zero(st) SKM_sk_zero(CMS_CertificateChoices, (st)) +#define sk_CMS_CertificateChoices_push(st, val) SKM_sk_push(CMS_CertificateChoices, (st), (val)) +#define sk_CMS_CertificateChoices_unshift(st, val) SKM_sk_unshift(CMS_CertificateChoices, (st), (val)) +#define sk_CMS_CertificateChoices_find(st, val) SKM_sk_find(CMS_CertificateChoices, (st), (val)) +#define sk_CMS_CertificateChoices_find_ex(st, val) SKM_sk_find_ex(CMS_CertificateChoices, (st), (val)) +#define sk_CMS_CertificateChoices_delete(st, i) SKM_sk_delete(CMS_CertificateChoices, (st), (i)) +#define sk_CMS_CertificateChoices_delete_ptr(st, ptr) SKM_sk_delete_ptr(CMS_CertificateChoices, (st), (ptr)) +#define sk_CMS_CertificateChoices_insert(st, val, i) SKM_sk_insert(CMS_CertificateChoices, (st), (val), (i)) +#define sk_CMS_CertificateChoices_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(CMS_CertificateChoices, (st), (cmp)) +#define sk_CMS_CertificateChoices_dup(st) SKM_sk_dup(CMS_CertificateChoices, st) +#define sk_CMS_CertificateChoices_pop_free(st, free_func) SKM_sk_pop_free(CMS_CertificateChoices, (st), (free_func)) +#define sk_CMS_CertificateChoices_shift(st) SKM_sk_shift(CMS_CertificateChoices, (st)) +#define sk_CMS_CertificateChoices_pop(st) SKM_sk_pop(CMS_CertificateChoices, (st)) +#define sk_CMS_CertificateChoices_sort(st) SKM_sk_sort(CMS_CertificateChoices, (st)) +#define sk_CMS_CertificateChoices_is_sorted(st) SKM_sk_is_sorted(CMS_CertificateChoices, (st)) + +#define sk_CMS_RecipientInfo_new(st) SKM_sk_new(CMS_RecipientInfo, (st)) +#define sk_CMS_RecipientInfo_new_null() SKM_sk_new_null(CMS_RecipientInfo) +#define sk_CMS_RecipientInfo_free(st) SKM_sk_free(CMS_RecipientInfo, (st)) +#define sk_CMS_RecipientInfo_num(st) SKM_sk_num(CMS_RecipientInfo, (st)) +#define sk_CMS_RecipientInfo_value(st, i) SKM_sk_value(CMS_RecipientInfo, (st), (i)) +#define sk_CMS_RecipientInfo_set(st, i, val) SKM_sk_set(CMS_RecipientInfo, (st), (i), (val)) +#define sk_CMS_RecipientInfo_zero(st) SKM_sk_zero(CMS_RecipientInfo, (st)) +#define sk_CMS_RecipientInfo_push(st, val) SKM_sk_push(CMS_RecipientInfo, (st), (val)) +#define sk_CMS_RecipientInfo_unshift(st, val) SKM_sk_unshift(CMS_RecipientInfo, (st), (val)) +#define sk_CMS_RecipientInfo_find(st, val) SKM_sk_find(CMS_RecipientInfo, (st), (val)) +#define sk_CMS_RecipientInfo_find_ex(st, val) SKM_sk_find_ex(CMS_RecipientInfo, (st), (val)) +#define sk_CMS_RecipientInfo_delete(st, i) SKM_sk_delete(CMS_RecipientInfo, (st), (i)) +#define sk_CMS_RecipientInfo_delete_ptr(st, ptr) SKM_sk_delete_ptr(CMS_RecipientInfo, (st), (ptr)) +#define sk_CMS_RecipientInfo_insert(st, val, i) SKM_sk_insert(CMS_RecipientInfo, (st), (val), (i)) +#define sk_CMS_RecipientInfo_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(CMS_RecipientInfo, (st), (cmp)) +#define sk_CMS_RecipientInfo_dup(st) SKM_sk_dup(CMS_RecipientInfo, st) +#define sk_CMS_RecipientInfo_pop_free(st, free_func) SKM_sk_pop_free(CMS_RecipientInfo, (st), (free_func)) +#define sk_CMS_RecipientInfo_shift(st) SKM_sk_shift(CMS_RecipientInfo, (st)) +#define sk_CMS_RecipientInfo_pop(st) SKM_sk_pop(CMS_RecipientInfo, (st)) +#define sk_CMS_RecipientInfo_sort(st) SKM_sk_sort(CMS_RecipientInfo, (st)) +#define sk_CMS_RecipientInfo_is_sorted(st) SKM_sk_is_sorted(CMS_RecipientInfo, (st)) + +#define sk_CMS_RevocationInfoChoice_new(st) SKM_sk_new(CMS_RevocationInfoChoice, (st)) +#define sk_CMS_RevocationInfoChoice_new_null() SKM_sk_new_null(CMS_RevocationInfoChoice) +#define sk_CMS_RevocationInfoChoice_free(st) SKM_sk_free(CMS_RevocationInfoChoice, (st)) +#define sk_CMS_RevocationInfoChoice_num(st) SKM_sk_num(CMS_RevocationInfoChoice, (st)) +#define sk_CMS_RevocationInfoChoice_value(st, i) SKM_sk_value(CMS_RevocationInfoChoice, (st), (i)) +#define sk_CMS_RevocationInfoChoice_set(st, i, val) SKM_sk_set(CMS_RevocationInfoChoice, (st), (i), (val)) +#define sk_CMS_RevocationInfoChoice_zero(st) SKM_sk_zero(CMS_RevocationInfoChoice, (st)) +#define sk_CMS_RevocationInfoChoice_push(st, val) SKM_sk_push(CMS_RevocationInfoChoice, (st), (val)) +#define sk_CMS_RevocationInfoChoice_unshift(st, val) SKM_sk_unshift(CMS_RevocationInfoChoice, (st), (val)) +#define sk_CMS_RevocationInfoChoice_find(st, val) SKM_sk_find(CMS_RevocationInfoChoice, (st), (val)) +#define sk_CMS_RevocationInfoChoice_find_ex(st, val) SKM_sk_find_ex(CMS_RevocationInfoChoice, (st), (val)) +#define sk_CMS_RevocationInfoChoice_delete(st, i) SKM_sk_delete(CMS_RevocationInfoChoice, (st), (i)) +#define sk_CMS_RevocationInfoChoice_delete_ptr(st, ptr) SKM_sk_delete_ptr(CMS_RevocationInfoChoice, (st), (ptr)) +#define sk_CMS_RevocationInfoChoice_insert(st, val, i) SKM_sk_insert(CMS_RevocationInfoChoice, (st), (val), (i)) +#define sk_CMS_RevocationInfoChoice_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(CMS_RevocationInfoChoice, (st), (cmp)) +#define sk_CMS_RevocationInfoChoice_dup(st) SKM_sk_dup(CMS_RevocationInfoChoice, st) +#define sk_CMS_RevocationInfoChoice_pop_free(st, free_func) SKM_sk_pop_free(CMS_RevocationInfoChoice, (st), (free_func)) +#define sk_CMS_RevocationInfoChoice_shift(st) SKM_sk_shift(CMS_RevocationInfoChoice, (st)) +#define sk_CMS_RevocationInfoChoice_pop(st) SKM_sk_pop(CMS_RevocationInfoChoice, (st)) +#define sk_CMS_RevocationInfoChoice_sort(st) SKM_sk_sort(CMS_RevocationInfoChoice, (st)) +#define sk_CMS_RevocationInfoChoice_is_sorted(st) SKM_sk_is_sorted(CMS_RevocationInfoChoice, (st)) + +#define sk_CMS_SignerInfo_new(st) SKM_sk_new(CMS_SignerInfo, (st)) +#define sk_CMS_SignerInfo_new_null() SKM_sk_new_null(CMS_SignerInfo) +#define sk_CMS_SignerInfo_free(st) SKM_sk_free(CMS_SignerInfo, (st)) +#define sk_CMS_SignerInfo_num(st) SKM_sk_num(CMS_SignerInfo, (st)) +#define sk_CMS_SignerInfo_value(st, i) SKM_sk_value(CMS_SignerInfo, (st), (i)) +#define sk_CMS_SignerInfo_set(st, i, val) SKM_sk_set(CMS_SignerInfo, (st), (i), (val)) +#define sk_CMS_SignerInfo_zero(st) SKM_sk_zero(CMS_SignerInfo, (st)) +#define sk_CMS_SignerInfo_push(st, val) SKM_sk_push(CMS_SignerInfo, (st), (val)) +#define sk_CMS_SignerInfo_unshift(st, val) SKM_sk_unshift(CMS_SignerInfo, (st), (val)) +#define sk_CMS_SignerInfo_find(st, val) SKM_sk_find(CMS_SignerInfo, (st), (val)) +#define sk_CMS_SignerInfo_find_ex(st, val) SKM_sk_find_ex(CMS_SignerInfo, (st), (val)) +#define sk_CMS_SignerInfo_delete(st, i) SKM_sk_delete(CMS_SignerInfo, (st), (i)) +#define sk_CMS_SignerInfo_delete_ptr(st, ptr) SKM_sk_delete_ptr(CMS_SignerInfo, (st), (ptr)) +#define sk_CMS_SignerInfo_insert(st, val, i) SKM_sk_insert(CMS_SignerInfo, (st), (val), (i)) +#define sk_CMS_SignerInfo_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(CMS_SignerInfo, (st), (cmp)) +#define sk_CMS_SignerInfo_dup(st) SKM_sk_dup(CMS_SignerInfo, st) +#define sk_CMS_SignerInfo_pop_free(st, free_func) SKM_sk_pop_free(CMS_SignerInfo, (st), (free_func)) +#define sk_CMS_SignerInfo_shift(st) SKM_sk_shift(CMS_SignerInfo, (st)) +#define sk_CMS_SignerInfo_pop(st) SKM_sk_pop(CMS_SignerInfo, (st)) +#define sk_CMS_SignerInfo_sort(st) SKM_sk_sort(CMS_SignerInfo, (st)) +#define sk_CMS_SignerInfo_is_sorted(st) SKM_sk_is_sorted(CMS_SignerInfo, (st)) #define sk_CONF_IMODULE_new(st) SKM_sk_new(CONF_IMODULE, (st)) #define sk_CONF_IMODULE_new_null() SKM_sk_new_null(CONF_IMODULE) diff --git a/server/external/openssl/aix_64/include/openssl/symhacks.h b/server/external/openssl/aix_64/include/openssl/symhacks.h index 1b6b05c..1742088 100644 --- a/server/external/openssl/aix_64/include/openssl/symhacks.h +++ b/server/external/openssl/aix_64/include/openssl/symhacks.h @@ -383,19 +383,19 @@ #undef STORE_method_get_unlock_store_function #define STORE_method_get_unlock_store_function STORE_meth_get_unlock_store_fn -/* Hack some long AMS names */ -#undef AMS_RecipientInfo_ktri_get0_algs -#define AMS_RecipientInfo_ktri_get0_algs AMS_RecipInfo_ktri_get0_algs -#undef AMS_RecipientInfo_ktri_get0_signer_id -#define AMS_RecipientInfo_ktri_get0_signer_id AMS_RecipInfo_ktri_get0_sigr_id -#undef AMS_OtherRevocationInfoFormat_it -#define AMS_OtherRevocationInfoFormat_it AMS_OtherRevocInfoFormat_it -#undef AMS_KeyAgreeRecipientIdentifier_it -#define AMS_KeyAgreeRecipientIdentifier_it AMS_KeyAgreeRecipIdentifier_it -#undef AMS_OriginatorIdentifierOrKey_it -#define AMS_OriginatorIdentifierOrKey_it AMS_OriginatorIdOrKey_it -#undef ams_SignerIdentifier_get0_signer_id -#define ams_SignerIdentifier_get0_signer_id ams_SignerId_get0_signer_id +/* Hack some long CMS names */ +#undef CMS_RecipientInfo_ktri_get0_algs +#define CMS_RecipientInfo_ktri_get0_algs CMS_RecipInfo_ktri_get0_algs +#undef CMS_RecipientInfo_ktri_get0_signer_id +#define CMS_RecipientInfo_ktri_get0_signer_id CMS_RecipInfo_ktri_get0_sigr_id +#undef CMS_OtherRevocationInfoFormat_it +#define CMS_OtherRevocationInfoFormat_it CMS_OtherRevocInfoFormat_it +#undef CMS_KeyAgreeRecipientIdentifier_it +#define CMS_KeyAgreeRecipientIdentifier_it CMS_KeyAgreeRecipIdentifier_it +#undef CMS_OriginatorIdentifierOrKey_it +#define CMS_OriginatorIdentifierOrKey_it CMS_OriginatorIdOrKey_it +#undef cms_SignerIdentifier_get0_signer_id +#define cms_SignerIdentifier_get0_signer_id cms_SignerId_get0_signer_id /* Hack some long DTLS1 names */ #undef dtls1_retransmit_buffered_messages @@ -440,6 +440,6 @@ #endif /* ! defined HEADER_VMS_IDHACKS_H */ -/* This one clashes with AMS_data_create */ -#undef ams_Data_create -#define ams_Data_create priv_ams_Data_create +/* This one clashes with CMS_data_create */ +#undef cms_Data_create +#define cms_Data_create priv_cms_Data_create diff --git a/server/external/openssl/linux_32/include/openssl/cms.h b/server/external/openssl/linux_32/include/openssl/cms.h new file mode 100644 index 0000000..36994fa --- /dev/null +++ b/server/external/openssl/linux_32/include/openssl/cms.h @@ -0,0 +1,501 @@ +/* crypto/cms/cms.h */ +/* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL + * project. + */ +/* ==================================================================== + * Copyright (c) 2008 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * licensing@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + */ + + +#ifndef HEADER_CMS_H +#define HEADER_CMS_H + +#include + +#ifdef OPENSSL_NO_CMS +#error CMS is disabled. +#endif + +#ifdef __cplusplus +extern "C" { +#endif + + +typedef struct CMS_ContentInfo_st CMS_ContentInfo; +typedef struct CMS_SignerInfo_st CMS_SignerInfo; +typedef struct CMS_CertificateChoices CMS_CertificateChoices; +typedef struct CMS_RevocationInfoChoice_st CMS_RevocationInfoChoice; +typedef struct CMS_RecipientInfo_st CMS_RecipientInfo; +typedef struct CMS_ReceiptRequest_st CMS_ReceiptRequest; +typedef struct CMS_Receipt_st CMS_Receipt; + +DECLARE_STACK_OF(CMS_SignerInfo) +DECLARE_STACK_OF(GENERAL_NAMES) +DECLARE_ASN1_FUNCTIONS(CMS_ContentInfo) +DECLARE_ASN1_FUNCTIONS(CMS_ReceiptRequest) +DECLARE_ASN1_PRINT_FUNCTION(CMS_ContentInfo) + +#define CMS_SIGNERINFO_ISSUER_SERIAL 0 +#define CMS_SIGNERINFO_KEYIDENTIFIER 1 + +#define CMS_RECIPINFO_TRANS 0 +#define CMS_RECIPINFO_AGREE 1 +#define CMS_RECIPINFO_KEK 2 +#define CMS_RECIPINFO_PASS 3 +#define CMS_RECIPINFO_OTHER 4 + +/* S/MIME related flags */ + +#define CMS_TEXT 0x1 +#define CMS_NOCERTS 0x2 +#define CMS_NO_CONTENT_VERIFY 0x4 +#define CMS_NO_ATTR_VERIFY 0x8 +#define CMS_NOSIGS \ + (CMS_NO_CONTENT_VERIFY|CMS_NO_ATTR_VERIFY) +#define CMS_NOINTERN 0x10 +#define CMS_NO_SIGNER_CERT_VERIFY 0x20 +#define CMS_NOVERIFY 0x20 +#define CMS_DETACHED 0x40 +#define CMS_BINARY 0x80 +#define CMS_NOATTR 0x100 +#define CMS_NOSMIMECAP 0x200 +#define CMS_NOOLDMIMETYPE 0x400 +#define CMS_CRLFEOL 0x800 +#define CMS_STREAM 0x1000 +#define CMS_NOCRL 0x2000 +#define CMS_PARTIAL 0x4000 +#define CMS_REUSE_DIGEST 0x8000 +#define CMS_USE_KEYID 0x10000 +#define CMS_DEBUG_DECRYPT 0x20000 + +const ASN1_OBJECT *CMS_get0_type(CMS_ContentInfo *cms); + +BIO *CMS_dataInit(CMS_ContentInfo *cms, BIO *icont); +int CMS_dataFinal(CMS_ContentInfo *cms, BIO *bio); + +ASN1_OCTET_STRING **CMS_get0_content(CMS_ContentInfo *cms); +int CMS_is_detached(CMS_ContentInfo *cms); +int CMS_set_detached(CMS_ContentInfo *cms, int detached); + +#ifdef HEADER_PEM_H +DECLARE_PEM_rw_const(CMS, CMS_ContentInfo) +#endif + +int CMS_stream(unsigned char ***boundary, CMS_ContentInfo *cms); +CMS_ContentInfo *d2i_CMS_bio(BIO *bp, CMS_ContentInfo **cms); +int i2d_CMS_bio(BIO *bp, CMS_ContentInfo *cms); + +BIO *BIO_new_CMS(BIO *out, CMS_ContentInfo *cms); +int i2d_CMS_bio_stream(BIO *out, CMS_ContentInfo *cms, BIO *in, int flags); +int PEM_write_bio_CMS_stream(BIO *out, CMS_ContentInfo *cms, BIO *in, int flags); +CMS_ContentInfo *SMIME_read_CMS(BIO *bio, BIO **bcont); +int SMIME_write_CMS(BIO *bio, CMS_ContentInfo *cms, BIO *data, int flags); + +int CMS_final(CMS_ContentInfo *cms, BIO *data, BIO *dcont, unsigned int flags); + +CMS_ContentInfo *CMS_sign(X509 *signcert, EVP_PKEY *pkey, STACK_OF(X509) *certs, + BIO *data, unsigned int flags); + +CMS_ContentInfo *CMS_sign_receipt(CMS_SignerInfo *si, + X509 *signcert, EVP_PKEY *pkey, + STACK_OF(X509) *certs, + unsigned int flags); + +int CMS_data(CMS_ContentInfo *cms, BIO *out, unsigned int flags); +CMS_ContentInfo *CMS_data_create(BIO *in, unsigned int flags); + +int CMS_digest_verify(CMS_ContentInfo *cms, BIO *dcont, BIO *out, + unsigned int flags); +CMS_ContentInfo *CMS_digest_create(BIO *in, const EVP_MD *md, + unsigned int flags); + +int CMS_EncryptedData_decrypt(CMS_ContentInfo *cms, + const unsigned char *key, size_t keylen, + BIO *dcont, BIO *out, unsigned int flags); + +CMS_ContentInfo *CMS_EncryptedData_encrypt(BIO *in, const EVP_CIPHER *cipher, + const unsigned char *key, size_t keylen, + unsigned int flags); + +int CMS_EncryptedData_set1_key(CMS_ContentInfo *cms, const EVP_CIPHER *ciph, + const unsigned char *key, size_t keylen); + +int CMS_verify(CMS_ContentInfo *cms, STACK_OF(X509) *certs, + X509_STORE *store, BIO *dcont, BIO *out, unsigned int flags); + +int CMS_verify_receipt(CMS_ContentInfo *rcms, CMS_ContentInfo *ocms, + STACK_OF(X509) *certs, + X509_STORE *store, unsigned int flags); + +STACK_OF(X509) *CMS_get0_signers(CMS_ContentInfo *cms); + +CMS_ContentInfo *CMS_encrypt(STACK_OF(X509) *certs, BIO *in, + const EVP_CIPHER *cipher, unsigned int flags); + +int CMS_decrypt(CMS_ContentInfo *cms, EVP_PKEY *pkey, X509 *cert, + BIO *dcont, BIO *out, + unsigned int flags); + +int CMS_decrypt_set1_pkey(CMS_ContentInfo *cms, EVP_PKEY *pk, X509 *cert); +int CMS_decrypt_set1_key(CMS_ContentInfo *cms, + unsigned char *key, size_t keylen, + unsigned char *id, size_t idlen); +int CMS_decrypt_set1_password(CMS_ContentInfo *cms, + unsigned char *pass, ossl_ssize_t passlen); + +STACK_OF(CMS_RecipientInfo) *CMS_get0_RecipientInfos(CMS_ContentInfo *cms); +int CMS_RecipientInfo_type(CMS_RecipientInfo *ri); +CMS_ContentInfo *CMS_EnvelopedData_create(const EVP_CIPHER *cipher); +CMS_RecipientInfo *CMS_add1_recipient_cert(CMS_ContentInfo *cms, + X509 *recip, unsigned int flags); +int CMS_RecipientInfo_set0_pkey(CMS_RecipientInfo *ri, EVP_PKEY *pkey); +int CMS_RecipientInfo_ktri_cert_cmp(CMS_RecipientInfo *ri, X509 *cert); +int CMS_RecipientInfo_ktri_get0_algs(CMS_RecipientInfo *ri, + EVP_PKEY **pk, X509 **recip, + X509_ALGOR **palg); +int CMS_RecipientInfo_ktri_get0_signer_id(CMS_RecipientInfo *ri, + ASN1_OCTET_STRING **keyid, + X509_NAME **issuer, ASN1_INTEGER **sno); + +CMS_RecipientInfo *CMS_add0_recipient_key(CMS_ContentInfo *cms, int nid, + unsigned char *key, size_t keylen, + unsigned char *id, size_t idlen, + ASN1_GENERALIZEDTIME *date, + ASN1_OBJECT *otherTypeId, + ASN1_TYPE *otherType); + +int CMS_RecipientInfo_kekri_get0_id(CMS_RecipientInfo *ri, + X509_ALGOR **palg, + ASN1_OCTET_STRING **pid, + ASN1_GENERALIZEDTIME **pdate, + ASN1_OBJECT **potherid, + ASN1_TYPE **pothertype); + +int CMS_RecipientInfo_set0_key(CMS_RecipientInfo *ri, + unsigned char *key, size_t keylen); + +int CMS_RecipientInfo_kekri_id_cmp(CMS_RecipientInfo *ri, + const unsigned char *id, size_t idlen); + +int CMS_RecipientInfo_set0_password(CMS_RecipientInfo *ri, + unsigned char *pass, + ossl_ssize_t passlen); + +CMS_RecipientInfo *CMS_add0_recipient_password(CMS_ContentInfo *cms, + int iter, int wrap_nid, int pbe_nid, + unsigned char *pass, + ossl_ssize_t passlen, + const EVP_CIPHER *kekciph); + +int CMS_RecipientInfo_decrypt(CMS_ContentInfo *cms, CMS_RecipientInfo *ri); + +int CMS_uncompress(CMS_ContentInfo *cms, BIO *dcont, BIO *out, + unsigned int flags); +CMS_ContentInfo *CMS_compress(BIO *in, int comp_nid, unsigned int flags); + +int CMS_set1_eContentType(CMS_ContentInfo *cms, const ASN1_OBJECT *oid); +const ASN1_OBJECT *CMS_get0_eContentType(CMS_ContentInfo *cms); + +CMS_CertificateChoices *CMS_add0_CertificateChoices(CMS_ContentInfo *cms); +int CMS_add0_cert(CMS_ContentInfo *cms, X509 *cert); +int CMS_add1_cert(CMS_ContentInfo *cms, X509 *cert); +STACK_OF(X509) *CMS_get1_certs(CMS_ContentInfo *cms); + +CMS_RevocationInfoChoice *CMS_add0_RevocationInfoChoice(CMS_ContentInfo *cms); +int CMS_add0_crl(CMS_ContentInfo *cms, X509_CRL *crl); +int CMS_add1_crl(CMS_ContentInfo *cms, X509_CRL *crl); +STACK_OF(X509_CRL) *CMS_get1_crls(CMS_ContentInfo *cms); + +int CMS_SignedData_init(CMS_ContentInfo *cms); +CMS_SignerInfo *CMS_add1_signer(CMS_ContentInfo *cms, + X509 *signer, EVP_PKEY *pk, const EVP_MD *md, + unsigned int flags); +STACK_OF(CMS_SignerInfo) *CMS_get0_SignerInfos(CMS_ContentInfo *cms); + +void CMS_SignerInfo_set1_signer_cert(CMS_SignerInfo *si, X509 *signer); +int CMS_SignerInfo_get0_signer_id(CMS_SignerInfo *si, + ASN1_OCTET_STRING **keyid, + X509_NAME **issuer, ASN1_INTEGER **sno); +int CMS_SignerInfo_cert_cmp(CMS_SignerInfo *si, X509 *cert); +int CMS_set1_signers_certs(CMS_ContentInfo *cms, STACK_OF(X509) *certs, + unsigned int flags); +void CMS_SignerInfo_get0_algs(CMS_SignerInfo *si, EVP_PKEY **pk, X509 **signer, + X509_ALGOR **pdig, X509_ALGOR **psig); +int CMS_SignerInfo_sign(CMS_SignerInfo *si); +int CMS_SignerInfo_verify(CMS_SignerInfo *si); +int CMS_SignerInfo_verify_content(CMS_SignerInfo *si, BIO *chain); + +int CMS_add_smimecap(CMS_SignerInfo *si, STACK_OF(X509_ALGOR) *algs); +int CMS_add_simple_smimecap(STACK_OF(X509_ALGOR) **algs, + int algnid, int keysize); +int CMS_add_standard_smimecap(STACK_OF(X509_ALGOR) **smcap); + +int CMS_signed_get_attr_count(const CMS_SignerInfo *si); +int CMS_signed_get_attr_by_NID(const CMS_SignerInfo *si, int nid, + int lastpos); +int CMS_signed_get_attr_by_OBJ(const CMS_SignerInfo *si, ASN1_OBJECT *obj, + int lastpos); +X509_ATTRIBUTE *CMS_signed_get_attr(const CMS_SignerInfo *si, int loc); +X509_ATTRIBUTE *CMS_signed_delete_attr(CMS_SignerInfo *si, int loc); +int CMS_signed_add1_attr(CMS_SignerInfo *si, X509_ATTRIBUTE *attr); +int CMS_signed_add1_attr_by_OBJ(CMS_SignerInfo *si, + const ASN1_OBJECT *obj, int type, + const void *bytes, int len); +int CMS_signed_add1_attr_by_NID(CMS_SignerInfo *si, + int nid, int type, + const void *bytes, int len); +int CMS_signed_add1_attr_by_txt(CMS_SignerInfo *si, + const char *attrname, int type, + const void *bytes, int len); +void *CMS_signed_get0_data_by_OBJ(CMS_SignerInfo *si, ASN1_OBJECT *oid, + int lastpos, int type); + +int CMS_unsigned_get_attr_count(const CMS_SignerInfo *si); +int CMS_unsigned_get_attr_by_NID(const CMS_SignerInfo *si, int nid, + int lastpos); +int CMS_unsigned_get_attr_by_OBJ(const CMS_SignerInfo *si, ASN1_OBJECT *obj, + int lastpos); +X509_ATTRIBUTE *CMS_unsigned_get_attr(const CMS_SignerInfo *si, int loc); +X509_ATTRIBUTE *CMS_unsigned_delete_attr(CMS_SignerInfo *si, int loc); +int CMS_unsigned_add1_attr(CMS_SignerInfo *si, X509_ATTRIBUTE *attr); +int CMS_unsigned_add1_attr_by_OBJ(CMS_SignerInfo *si, + const ASN1_OBJECT *obj, int type, + const void *bytes, int len); +int CMS_unsigned_add1_attr_by_NID(CMS_SignerInfo *si, + int nid, int type, + const void *bytes, int len); +int CMS_unsigned_add1_attr_by_txt(CMS_SignerInfo *si, + const char *attrname, int type, + const void *bytes, int len); +void *CMS_unsigned_get0_data_by_OBJ(CMS_SignerInfo *si, ASN1_OBJECT *oid, + int lastpos, int type); + +#ifdef HEADER_X509V3_H + +int CMS_get1_ReceiptRequest(CMS_SignerInfo *si, CMS_ReceiptRequest **prr); +CMS_ReceiptRequest *CMS_ReceiptRequest_create0(unsigned char *id, int idlen, + int allorfirst, + STACK_OF(GENERAL_NAMES) *receiptList, + STACK_OF(GENERAL_NAMES) *receiptsTo); +int CMS_add1_ReceiptRequest(CMS_SignerInfo *si, CMS_ReceiptRequest *rr); +void CMS_ReceiptRequest_get0_values(CMS_ReceiptRequest *rr, + ASN1_STRING **pcid, + int *pallorfirst, + STACK_OF(GENERAL_NAMES) **plist, + STACK_OF(GENERAL_NAMES) **prto); + +#endif + +/* BEGIN ERROR CODES */ +/* The following lines are auto generated by the script mkerr.pl. Any changes + * made after this point may be overwritten when the script is next run. + */ +void ERR_load_CMS_strings(void); + +/* Error codes for the CMS functions. */ + +/* Function codes. */ +#define CMS_F_CHECK_CONTENT 99 +#define CMS_F_CMS_ADD0_CERT 164 +#define CMS_F_CMS_ADD0_RECIPIENT_KEY 100 +#define CMS_F_CMS_ADD0_RECIPIENT_PASSWORD 165 +#define CMS_F_CMS_ADD1_RECEIPTREQUEST 158 +#define CMS_F_CMS_ADD1_RECIPIENT_CERT 101 +#define CMS_F_CMS_ADD1_SIGNER 102 +#define CMS_F_CMS_ADD1_SIGNINGTIME 103 +#define CMS_F_CMS_COMPRESS 104 +#define CMS_F_CMS_COMPRESSEDDATA_CREATE 105 +#define CMS_F_CMS_COMPRESSEDDATA_INIT_BIO 106 +#define CMS_F_CMS_COPY_CONTENT 107 +#define CMS_F_CMS_COPY_MESSAGEDIGEST 108 +#define CMS_F_CMS_DATA 109 +#define CMS_F_CMS_DATAFINAL 110 +#define CMS_F_CMS_DATAINIT 111 +#define CMS_F_CMS_DECRYPT 112 +#define CMS_F_CMS_DECRYPT_SET1_KEY 113 +#define CMS_F_CMS_DECRYPT_SET1_PASSWORD 166 +#define CMS_F_CMS_DECRYPT_SET1_PKEY 114 +#define CMS_F_CMS_DIGESTALGORITHM_FIND_CTX 115 +#define CMS_F_CMS_DIGESTALGORITHM_INIT_BIO 116 +#define CMS_F_CMS_DIGESTEDDATA_DO_FINAL 117 +#define CMS_F_CMS_DIGEST_VERIFY 118 +#define CMS_F_CMS_ENCODE_RECEIPT 161 +#define CMS_F_CMS_ENCRYPT 119 +#define CMS_F_CMS_ENCRYPTEDCONTENT_INIT_BIO 120 +#define CMS_F_CMS_ENCRYPTEDDATA_DECRYPT 121 +#define CMS_F_CMS_ENCRYPTEDDATA_ENCRYPT 122 +#define CMS_F_CMS_ENCRYPTEDDATA_SET1_KEY 123 +#define CMS_F_CMS_ENVELOPEDDATA_CREATE 124 +#define CMS_F_CMS_ENVELOPEDDATA_INIT_BIO 125 +#define CMS_F_CMS_ENVELOPED_DATA_INIT 126 +#define CMS_F_CMS_FINAL 127 +#define CMS_F_CMS_GET0_CERTIFICATE_CHOICES 128 +#define CMS_F_CMS_GET0_CONTENT 129 +#define CMS_F_CMS_GET0_ECONTENT_TYPE 130 +#define CMS_F_CMS_GET0_ENVELOPED 131 +#define CMS_F_CMS_GET0_REVOCATION_CHOICES 132 +#define CMS_F_CMS_GET0_SIGNED 133 +#define CMS_F_CMS_MSGSIGDIGEST_ADD1 162 +#define CMS_F_CMS_RECEIPTREQUEST_CREATE0 159 +#define CMS_F_CMS_RECEIPT_VERIFY 160 +#define CMS_F_CMS_RECIPIENTINFO_DECRYPT 134 +#define CMS_F_CMS_RECIPIENTINFO_KEKRI_DECRYPT 135 +#define CMS_F_CMS_RECIPIENTINFO_KEKRI_ENCRYPT 136 +#define CMS_F_CMS_RECIPIENTINFO_KEKRI_GET0_ID 137 +#define CMS_F_CMS_RECIPIENTINFO_KEKRI_ID_CMP 138 +#define CMS_F_CMS_RECIPIENTINFO_KTRI_CERT_CMP 139 +#define CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT 140 +#define CMS_F_CMS_RECIPIENTINFO_KTRI_ENCRYPT 141 +#define CMS_F_CMS_RECIPIENTINFO_KTRI_GET0_ALGS 142 +#define CMS_F_CMS_RECIPIENTINFO_KTRI_GET0_SIGNER_ID 143 +#define CMS_F_CMS_RECIPIENTINFO_PWRI_CRYPT 167 +#define CMS_F_CMS_RECIPIENTINFO_SET0_KEY 144 +#define CMS_F_CMS_RECIPIENTINFO_SET0_PASSWORD 168 +#define CMS_F_CMS_RECIPIENTINFO_SET0_PKEY 145 +#define CMS_F_CMS_SET1_SIGNERIDENTIFIER 146 +#define CMS_F_CMS_SET_DETACHED 147 +#define CMS_F_CMS_SIGN 148 +#define CMS_F_CMS_SIGNED_DATA_INIT 149 +#define CMS_F_CMS_SIGNERINFO_CONTENT_SIGN 150 +#define CMS_F_CMS_SIGNERINFO_SIGN 151 +#define CMS_F_CMS_SIGNERINFO_VERIFY 152 +#define CMS_F_CMS_SIGNERINFO_VERIFY_CERT 153 +#define CMS_F_CMS_SIGNERINFO_VERIFY_CONTENT 154 +#define CMS_F_CMS_SIGN_RECEIPT 163 +#define CMS_F_CMS_STREAM 155 +#define CMS_F_CMS_UNCOMPRESS 156 +#define CMS_F_CMS_VERIFY 157 + +/* Reason codes. */ +#define CMS_R_ADD_SIGNER_ERROR 99 +#define CMS_R_CERTIFICATE_ALREADY_PRESENT 175 +#define CMS_R_CERTIFICATE_HAS_NO_KEYID 160 +#define CMS_R_CERTIFICATE_VERIFY_ERROR 100 +#define CMS_R_CIPHER_INITIALISATION_ERROR 101 +#define CMS_R_CIPHER_PARAMETER_INITIALISATION_ERROR 102 +#define CMS_R_CMS_DATAFINAL_ERROR 103 +#define CMS_R_CMS_LIB 104 +#define CMS_R_CONTENTIDENTIFIER_MISMATCH 170 +#define CMS_R_CONTENT_NOT_FOUND 105 +#define CMS_R_CONTENT_TYPE_MISMATCH 171 +#define CMS_R_CONTENT_TYPE_NOT_COMPRESSED_DATA 106 +#define CMS_R_CONTENT_TYPE_NOT_ENVELOPED_DATA 107 +#define CMS_R_CONTENT_TYPE_NOT_SIGNED_DATA 108 +#define CMS_R_CONTENT_VERIFY_ERROR 109 +#define CMS_R_CTRL_ERROR 110 +#define CMS_R_CTRL_FAILURE 111 +#define CMS_R_DECRYPT_ERROR 112 +#define CMS_R_DIGEST_ERROR 161 +#define CMS_R_ERROR_GETTING_PUBLIC_KEY 113 +#define CMS_R_ERROR_READING_MESSAGEDIGEST_ATTRIBUTE 114 +#define CMS_R_ERROR_SETTING_KEY 115 +#define CMS_R_ERROR_SETTING_RECIPIENTINFO 116 +#define CMS_R_INVALID_ENCRYPTED_KEY_LENGTH 117 +#define CMS_R_INVALID_KEY_ENCRYPTION_PARAMETER 176 +#define CMS_R_INVALID_KEY_LENGTH 118 +#define CMS_R_MD_BIO_INIT_ERROR 119 +#define CMS_R_MESSAGEDIGEST_ATTRIBUTE_WRONG_LENGTH 120 +#define CMS_R_MESSAGEDIGEST_WRONG_LENGTH 121 +#define CMS_R_MSGSIGDIGEST_ERROR 172 +#define CMS_R_MSGSIGDIGEST_VERIFICATION_FAILURE 162 +#define CMS_R_MSGSIGDIGEST_WRONG_LENGTH 163 +#define CMS_R_NEED_ONE_SIGNER 164 +#define CMS_R_NOT_A_SIGNED_RECEIPT 165 +#define CMS_R_NOT_ENCRYPTED_DATA 122 +#define CMS_R_NOT_KEK 123 +#define CMS_R_NOT_KEY_TRANSPORT 124 +#define CMS_R_NOT_PWRI 177 +#define CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE 125 +#define CMS_R_NO_CIPHER 126 +#define CMS_R_NO_CONTENT 127 +#define CMS_R_NO_CONTENT_TYPE 173 +#define CMS_R_NO_DEFAULT_DIGEST 128 +#define CMS_R_NO_DIGEST_SET 129 +#define CMS_R_NO_KEY 130 +#define CMS_R_NO_KEY_OR_CERT 174 +#define CMS_R_NO_MATCHING_DIGEST 131 +#define CMS_R_NO_MATCHING_RECIPIENT 132 +#define CMS_R_NO_MATCHING_SIGNATURE 166 +#define CMS_R_NO_MSGSIGDIGEST 167 +#define CMS_R_NO_PASSWORD 178 +#define CMS_R_NO_PRIVATE_KEY 133 +#define CMS_R_NO_PUBLIC_KEY 134 +#define CMS_R_NO_RECEIPT_REQUEST 168 +#define CMS_R_NO_SIGNERS 135 +#define CMS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE 136 +#define CMS_R_RECEIPT_DECODE_ERROR 169 +#define CMS_R_RECIPIENT_ERROR 137 +#define CMS_R_SIGNER_CERTIFICATE_NOT_FOUND 138 +#define CMS_R_SIGNFINAL_ERROR 139 +#define CMS_R_SMIME_TEXT_ERROR 140 +#define CMS_R_STORE_INIT_ERROR 141 +#define CMS_R_TYPE_NOT_COMPRESSED_DATA 142 +#define CMS_R_TYPE_NOT_DATA 143 +#define CMS_R_TYPE_NOT_DIGESTED_DATA 144 +#define CMS_R_TYPE_NOT_ENCRYPTED_DATA 145 +#define CMS_R_TYPE_NOT_ENVELOPED_DATA 146 +#define CMS_R_UNABLE_TO_FINALIZE_CONTEXT 147 +#define CMS_R_UNKNOWN_CIPHER 148 +#define CMS_R_UNKNOWN_DIGEST_ALGORIHM 149 +#define CMS_R_UNKNOWN_ID 150 +#define CMS_R_UNSUPPORTED_COMPRESSION_ALGORITHM 151 +#define CMS_R_UNSUPPORTED_CONTENT_TYPE 152 +#define CMS_R_UNSUPPORTED_KEK_ALGORITHM 153 +#define CMS_R_UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM 179 +#define CMS_R_UNSUPPORTED_RECIPIENT_TYPE 154 +#define CMS_R_UNSUPPORTED_RECPIENTINFO_TYPE 155 +#define CMS_R_UNSUPPORTED_TYPE 156 +#define CMS_R_UNWRAP_ERROR 157 +#define CMS_R_UNWRAP_FAILURE 180 +#define CMS_R_VERIFICATION_FAILURE 158 +#define CMS_R_WRAP_ERROR 159 + +#ifdef __cplusplus +} +#endif +#endif diff --git a/server/external/openssl/linux_32/include/openssl/des.h b/server/external/openssl/linux_32/include/openssl/des.h index 3cbac90..1eaedcb 100644 --- a/server/external/openssl/linux_32/include/openssl/des.h +++ b/server/external/openssl/linux_32/include/openssl/des.h @@ -177,7 +177,7 @@ void DES_ede3_cbc_encrypt(const unsigned char *input,unsigned char *output, long length, DES_key_schedule *ks1,DES_key_schedule *ks2, DES_key_schedule *ks3,DES_cblock *ivec,int enc); -void DES_ede3_cbam_encrypt(const unsigned char *in,unsigned char *out, +void DES_ede3_cbcm_encrypt(const unsigned char *in,unsigned char *out, long length, DES_key_schedule *ks1,DES_key_schedule *ks2, DES_key_schedule *ks3, diff --git a/server/external/openssl/linux_32/include/openssl/des_old.h b/server/external/openssl/linux_32/include/openssl/des_old.h index b07f0cd..2b2c372 100644 --- a/server/external/openssl/linux_32/include/openssl/des_old.h +++ b/server/external/openssl/linux_32/include/openssl/des_old.h @@ -139,8 +139,8 @@ typedef struct _ossl_old_des_ks_struct DES_ecb3_encrypt((i),(o),&(k1),&(k2),&(k3),(e)) #define des_ede3_cbc_encrypt(i,o,l,k1,k2,k3,iv,e)\ DES_ede3_cbc_encrypt((i),(o),(l),&(k1),&(k2),&(k3),(iv),(e)) -#define des_ede3_cbam_encrypt(i,o,l,k1,k2,k3,iv1,iv2,e)\ - DES_ede3_cbam_encrypt((i),(o),(l),&(k1),&(k2),&(k3),(iv1),(iv2),(e)) +#define des_ede3_cbcm_encrypt(i,o,l,k1,k2,k3,iv1,iv2,e)\ + DES_ede3_cbcm_encrypt((i),(o),(l),&(k1),&(k2),&(k3),(iv1),(iv2),(e)) #define des_ede3_cfb64_encrypt(i,o,l,k1,k2,k3,iv,n,e)\ DES_ede3_cfb64_encrypt((i),(o),(l),&(k1),&(k2),&(k3),(iv),(n),(e)) #define des_ede3_ofb64_encrypt(i,o,l,k1,k2,k3,iv,n)\ diff --git a/server/external/openssl/linux_32/include/openssl/err.h b/server/external/openssl/linux_32/include/openssl/err.h index 386295c..974cc9c 100644 --- a/server/external/openssl/linux_32/include/openssl/err.h +++ b/server/external/openssl/linux_32/include/openssl/err.h @@ -194,7 +194,7 @@ typedef struct err_state_st #define ERR_LIB_ECDH 43 #define ERR_LIB_STORE 44 #define ERR_LIB_FIPS 45 -#define ERR_LIB_AMS 46 +#define ERR_LIB_CMS 46 #define ERR_LIB_TS 47 #define ERR_LIB_HMAC 48 #define ERR_LIB_JPAKE 49 @@ -230,7 +230,7 @@ typedef struct err_state_st #define ECDHerr(f,r) ERR_PUT_error(ERR_LIB_ECDH,(f),(r),__FILE__,__LINE__) #define STOREerr(f,r) ERR_PUT_error(ERR_LIB_STORE,(f),(r),__FILE__,__LINE__) #define FIPSerr(f,r) ERR_PUT_error(ERR_LIB_FIPS,(f),(r),__FILE__,__LINE__) -#define AMSerr(f,r) ERR_PUT_error(ERR_LIB_AMS,(f),(r),__FILE__,__LINE__) +#define CMSerr(f,r) ERR_PUT_error(ERR_LIB_CMS,(f),(r),__FILE__,__LINE__) #define TSerr(f,r) ERR_PUT_error(ERR_LIB_TS,(f),(r),__FILE__,__LINE__) #define HMACerr(f,r) ERR_PUT_error(ERR_LIB_HMAC,(f),(r),__FILE__,__LINE__) #define JPAKEerr(f,r) ERR_PUT_error(ERR_LIB_JPAKE,(f),(r),__FILE__,__LINE__) diff --git a/server/external/openssl/linux_32/include/openssl/evp.h b/server/external/openssl/linux_32/include/openssl/evp.h index 172614a..faeb3c2 100644 --- a/server/external/openssl/linux_32/include/openssl/evp.h +++ b/server/external/openssl/linux_32/include/openssl/evp.h @@ -329,8 +329,8 @@ struct evp_cipher_st #define EVP_CIPH_CFB_MODE 0x3 #define EVP_CIPH_OFB_MODE 0x4 #define EVP_CIPH_CTR_MODE 0x5 -#define EVP_CIPH_GAM_MODE 0x6 -#define EVP_CIPH_CAM_MODE 0x7 +#define EVP_CIPH_GCM_MODE 0x6 +#define EVP_CIPH_CCM_MODE 0x7 #define EVP_CIPH_XTS_MODE 0x10001 #define EVP_CIPH_MODE 0xF0007 /* Set if variable length cipher */ @@ -374,16 +374,16 @@ struct evp_cipher_st #define EVP_CTRL_RAND_KEY 0x6 #define EVP_CTRL_PBE_PRF_NID 0x7 #define EVP_CTRL_COPY 0x8 -#define EVP_CTRL_GAM_SET_IVLEN 0x9 -#define EVP_CTRL_GAM_GET_TAG 0x10 -#define EVP_CTRL_GAM_SET_TAG 0x11 -#define EVP_CTRL_GAM_SET_IV_FIXED 0x12 -#define EVP_CTRL_GAM_IV_GEN 0x13 -#define EVP_CTRL_CAM_SET_IVLEN EVP_CTRL_GAM_SET_IVLEN -#define EVP_CTRL_CAM_GET_TAG EVP_CTRL_GAM_GET_TAG -#define EVP_CTRL_CAM_SET_TAG EVP_CTRL_GAM_SET_TAG -#define EVP_CTRL_CAM_SET_L 0x14 -#define EVP_CTRL_CAM_SET_MSGLEN 0x15 +#define EVP_CTRL_GCM_SET_IVLEN 0x9 +#define EVP_CTRL_GCM_GET_TAG 0x10 +#define EVP_CTRL_GCM_SET_TAG 0x11 +#define EVP_CTRL_GCM_SET_IV_FIXED 0x12 +#define EVP_CTRL_GCM_IV_GEN 0x13 +#define EVP_CTRL_CCM_SET_IVLEN EVP_CTRL_GCM_SET_IVLEN +#define EVP_CTRL_CCM_GET_TAG EVP_CTRL_GCM_GET_TAG +#define EVP_CTRL_CCM_SET_TAG EVP_CTRL_GCM_SET_TAG +#define EVP_CTRL_CCM_SET_L 0x14 +#define EVP_CTRL_CCM_SET_MSGLEN 0x15 /* AEAD cipher deduces payload length and returns number of bytes * required to store MAC and eventual padding. Subsequent call to * EVP_Cipher even appends/verifies MAC. @@ -392,15 +392,15 @@ struct evp_cipher_st /* Used by composite AEAD ciphers, no-op in GCM, CCM... */ #define EVP_CTRL_AEAD_SET_MAC_KEY 0x17 /* Set the GCM invocation field, decrypt only */ -#define EVP_CTRL_GAM_SET_IV_INV 0x18 +#define EVP_CTRL_GCM_SET_IV_INV 0x18 /* GCM TLS constants */ /* Length of fixed part of IV derived from PRF */ -#define EVP_GAM_TLS_FIXED_IV_LEN 4 +#define EVP_GCM_TLS_FIXED_IV_LEN 4 /* Length of explicit part of IV part of TLS records */ -#define EVP_GAM_TLS_EXPLICIT_IV_LEN 8 +#define EVP_GCM_TLS_EXPLICIT_IV_LEN 8 /* Length of tag for TLS */ -#define EVP_GAM_TLS_TAG_LEN 16 +#define EVP_GCM_TLS_TAG_LEN 16 typedef struct evp_cipher_info_st { @@ -1001,8 +1001,8 @@ void EVP_PBE_cleanup(void); #define ASN1_PKEY_CTRL_PKCS7_SIGN 0x1 #define ASN1_PKEY_CTRL_PKCS7_ENCRYPT 0x2 #define ASN1_PKEY_CTRL_DEFAULT_MD_NID 0x3 -#define ASN1_PKEY_CTRL_AMS_SIGN 0x5 -#define ASN1_PKEY_CTRL_AMS_ENVELOPE 0x7 +#define ASN1_PKEY_CTRL_CMS_SIGN 0x5 +#define ASN1_PKEY_CTRL_CMS_ENVELOPE 0x7 int EVP_PKEY_asn1_get_count(void); const EVP_PKEY_ASN1_METHOD *EVP_PKEY_asn1_get0(int idx); @@ -1095,9 +1095,9 @@ void EVP_PKEY_asn1_set_ctrl(EVP_PKEY_ASN1_METHOD *ameth, /* Used by GOST key encryption in TLS */ #define EVP_PKEY_CTRL_SET_IV 8 -#define EVP_PKEY_CTRL_AMS_ENCRYPT 9 -#define EVP_PKEY_CTRL_AMS_DECRYPT 10 -#define EVP_PKEY_CTRL_AMS_SIGN 11 +#define EVP_PKEY_CTRL_CMS_ENCRYPT 9 +#define EVP_PKEY_CTRL_CMS_DECRYPT 10 +#define EVP_PKEY_CTRL_CMS_SIGN 11 #define EVP_PKEY_CTRL_CIPHER 12 diff --git a/server/external/openssl/linux_32/include/openssl/obj_mac.h b/server/external/openssl/linux_32/include/openssl/obj_mac.h index 9d2aa9e..b5ea7cd 100644 --- a/server/external/openssl/linux_32/include/openssl/obj_mac.h +++ b/server/external/openssl/linux_32/include/openssl/obj_mac.h @@ -780,9 +780,9 @@ #define NID_id_smime_cti 195 #define OBJ_id_smime_cti OBJ_SMIME,6L -#define SN_id_smime_mod_ams "id-smime-mod-ams" -#define NID_id_smime_mod_ams 196 -#define OBJ_id_smime_mod_ams OBJ_id_smime_mod,1L +#define SN_id_smime_mod_cms "id-smime-mod-cms" +#define NID_id_smime_mod_cms 196 +#define OBJ_id_smime_mod_cms OBJ_id_smime_mod,1L #define SN_id_smime_mod_ess "id-smime-mod-ess" #define NID_id_smime_mod_ess 197 @@ -988,13 +988,13 @@ #define NID_id_smime_alg_ESDH 245 #define OBJ_id_smime_alg_ESDH OBJ_id_smime_alg,5L -#define SN_id_smime_alg_AMS3DESwrap "id-smime-alg-AMS3DESwrap" -#define NID_id_smime_alg_AMS3DESwrap 246 -#define OBJ_id_smime_alg_AMS3DESwrap OBJ_id_smime_alg,6L +#define SN_id_smime_alg_CMS3DESwrap "id-smime-alg-CMS3DESwrap" +#define NID_id_smime_alg_CMS3DESwrap 246 +#define OBJ_id_smime_alg_CMS3DESwrap OBJ_id_smime_alg,6L -#define SN_id_smime_alg_AMSRC2wrap "id-smime-alg-AMSRC2wrap" -#define NID_id_smime_alg_AMSRC2wrap 247 -#define OBJ_id_smime_alg_AMSRC2wrap OBJ_id_smime_alg,7L +#define SN_id_smime_alg_CMSRC2wrap "id-smime-alg-CMSRC2wrap" +#define NID_id_smime_alg_CMSRC2wrap 247 +#define OBJ_id_smime_alg_CMSRC2wrap OBJ_id_smime_alg,7L #define SN_id_alg_PWRI_KEK "id-alg-PWRI-KEK" #define NID_id_alg_PWRI_KEK 893 diff --git a/server/external/openssl/linux_32/include/openssl/pem.h b/server/external/openssl/linux_32/include/openssl/pem.h index 2b4beee..8a6abab 100644 --- a/server/external/openssl/linux_32/include/openssl/pem.h +++ b/server/external/openssl/linux_32/include/openssl/pem.h @@ -135,7 +135,7 @@ extern "C" { #define PEM_STRING_ECPARAMETERS "EC PARAMETERS" #define PEM_STRING_ECPRIVATEKEY "EC PRIVATE KEY" #define PEM_STRING_PARAMETERS "PARAMETERS" -#define PEM_STRING_AMS "AMS" +#define PEM_STRING_CMS "CMS" /* Note that this structure is initialised by PEM_SealInit and cleaned up by PEM_SealFinal (at least for now) */ diff --git a/server/external/openssl/linux_32/include/openssl/safestack.h b/server/external/openssl/linux_32/include/openssl/safestack.h index 1cbe6a4..ea3aa0d 100644 --- a/server/external/openssl/linux_32/include/openssl/safestack.h +++ b/server/external/openssl/linux_32/include/openssl/safestack.h @@ -469,93 +469,93 @@ DECLARE_SPECIAL_STACK_OF(OPENSSL_BLOCK, void) #define sk_BY_DIR_HASH_sort(st) SKM_sk_sort(BY_DIR_HASH, (st)) #define sk_BY_DIR_HASH_is_sorted(st) SKM_sk_is_sorted(BY_DIR_HASH, (st)) -#define sk_AMS_CertificateChoices_new(cmp) SKM_sk_new(AMS_CertificateChoices, (cmp)) -#define sk_AMS_CertificateChoices_new_null() SKM_sk_new_null(AMS_CertificateChoices) -#define sk_AMS_CertificateChoices_free(st) SKM_sk_free(AMS_CertificateChoices, (st)) -#define sk_AMS_CertificateChoices_num(st) SKM_sk_num(AMS_CertificateChoices, (st)) -#define sk_AMS_CertificateChoices_value(st, i) SKM_sk_value(AMS_CertificateChoices, (st), (i)) -#define sk_AMS_CertificateChoices_set(st, i, val) SKM_sk_set(AMS_CertificateChoices, (st), (i), (val)) -#define sk_AMS_CertificateChoices_zero(st) SKM_sk_zero(AMS_CertificateChoices, (st)) -#define sk_AMS_CertificateChoices_push(st, val) SKM_sk_push(AMS_CertificateChoices, (st), (val)) -#define sk_AMS_CertificateChoices_unshift(st, val) SKM_sk_unshift(AMS_CertificateChoices, (st), (val)) -#define sk_AMS_CertificateChoices_find(st, val) SKM_sk_find(AMS_CertificateChoices, (st), (val)) -#define sk_AMS_CertificateChoices_find_ex(st, val) SKM_sk_find_ex(AMS_CertificateChoices, (st), (val)) -#define sk_AMS_CertificateChoices_delete(st, i) SKM_sk_delete(AMS_CertificateChoices, (st), (i)) -#define sk_AMS_CertificateChoices_delete_ptr(st, ptr) SKM_sk_delete_ptr(AMS_CertificateChoices, (st), (ptr)) -#define sk_AMS_CertificateChoices_insert(st, val, i) SKM_sk_insert(AMS_CertificateChoices, (st), (val), (i)) -#define sk_AMS_CertificateChoices_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(AMS_CertificateChoices, (st), (cmp)) -#define sk_AMS_CertificateChoices_dup(st) SKM_sk_dup(AMS_CertificateChoices, st) -#define sk_AMS_CertificateChoices_pop_free(st, free_func) SKM_sk_pop_free(AMS_CertificateChoices, (st), (free_func)) -#define sk_AMS_CertificateChoices_shift(st) SKM_sk_shift(AMS_CertificateChoices, (st)) -#define sk_AMS_CertificateChoices_pop(st) SKM_sk_pop(AMS_CertificateChoices, (st)) -#define sk_AMS_CertificateChoices_sort(st) SKM_sk_sort(AMS_CertificateChoices, (st)) -#define sk_AMS_CertificateChoices_is_sorted(st) SKM_sk_is_sorted(AMS_CertificateChoices, (st)) - -#define sk_AMS_RecipientInfo_new(cmp) SKM_sk_new(AMS_RecipientInfo, (cmp)) -#define sk_AMS_RecipientInfo_new_null() SKM_sk_new_null(AMS_RecipientInfo) -#define sk_AMS_RecipientInfo_free(st) SKM_sk_free(AMS_RecipientInfo, (st)) -#define sk_AMS_RecipientInfo_num(st) SKM_sk_num(AMS_RecipientInfo, (st)) -#define sk_AMS_RecipientInfo_value(st, i) SKM_sk_value(AMS_RecipientInfo, (st), (i)) -#define sk_AMS_RecipientInfo_set(st, i, val) SKM_sk_set(AMS_RecipientInfo, (st), (i), (val)) -#define sk_AMS_RecipientInfo_zero(st) SKM_sk_zero(AMS_RecipientInfo, (st)) -#define sk_AMS_RecipientInfo_push(st, val) SKM_sk_push(AMS_RecipientInfo, (st), (val)) -#define sk_AMS_RecipientInfo_unshift(st, val) SKM_sk_unshift(AMS_RecipientInfo, (st), (val)) -#define sk_AMS_RecipientInfo_find(st, val) SKM_sk_find(AMS_RecipientInfo, (st), (val)) -#define sk_AMS_RecipientInfo_find_ex(st, val) SKM_sk_find_ex(AMS_RecipientInfo, (st), (val)) -#define sk_AMS_RecipientInfo_delete(st, i) SKM_sk_delete(AMS_RecipientInfo, (st), (i)) -#define sk_AMS_RecipientInfo_delete_ptr(st, ptr) SKM_sk_delete_ptr(AMS_RecipientInfo, (st), (ptr)) -#define sk_AMS_RecipientInfo_insert(st, val, i) SKM_sk_insert(AMS_RecipientInfo, (st), (val), (i)) -#define sk_AMS_RecipientInfo_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(AMS_RecipientInfo, (st), (cmp)) -#define sk_AMS_RecipientInfo_dup(st) SKM_sk_dup(AMS_RecipientInfo, st) -#define sk_AMS_RecipientInfo_pop_free(st, free_func) SKM_sk_pop_free(AMS_RecipientInfo, (st), (free_func)) -#define sk_AMS_RecipientInfo_shift(st) SKM_sk_shift(AMS_RecipientInfo, (st)) -#define sk_AMS_RecipientInfo_pop(st) SKM_sk_pop(AMS_RecipientInfo, (st)) -#define sk_AMS_RecipientInfo_sort(st) SKM_sk_sort(AMS_RecipientInfo, (st)) -#define sk_AMS_RecipientInfo_is_sorted(st) SKM_sk_is_sorted(AMS_RecipientInfo, (st)) - -#define sk_AMS_RevocationInfoChoice_new(cmp) SKM_sk_new(AMS_RevocationInfoChoice, (cmp)) -#define sk_AMS_RevocationInfoChoice_new_null() SKM_sk_new_null(AMS_RevocationInfoChoice) -#define sk_AMS_RevocationInfoChoice_free(st) SKM_sk_free(AMS_RevocationInfoChoice, (st)) -#define sk_AMS_RevocationInfoChoice_num(st) SKM_sk_num(AMS_RevocationInfoChoice, (st)) -#define sk_AMS_RevocationInfoChoice_value(st, i) SKM_sk_value(AMS_RevocationInfoChoice, (st), (i)) -#define sk_AMS_RevocationInfoChoice_set(st, i, val) SKM_sk_set(AMS_RevocationInfoChoice, (st), (i), (val)) -#define sk_AMS_RevocationInfoChoice_zero(st) SKM_sk_zero(AMS_RevocationInfoChoice, (st)) -#define sk_AMS_RevocationInfoChoice_push(st, val) SKM_sk_push(AMS_RevocationInfoChoice, (st), (val)) -#define sk_AMS_RevocationInfoChoice_unshift(st, val) SKM_sk_unshift(AMS_RevocationInfoChoice, (st), (val)) -#define sk_AMS_RevocationInfoChoice_find(st, val) SKM_sk_find(AMS_RevocationInfoChoice, (st), (val)) -#define sk_AMS_RevocationInfoChoice_find_ex(st, val) SKM_sk_find_ex(AMS_RevocationInfoChoice, (st), (val)) -#define sk_AMS_RevocationInfoChoice_delete(st, i) SKM_sk_delete(AMS_RevocationInfoChoice, (st), (i)) -#define sk_AMS_RevocationInfoChoice_delete_ptr(st, ptr) SKM_sk_delete_ptr(AMS_RevocationInfoChoice, (st), (ptr)) -#define sk_AMS_RevocationInfoChoice_insert(st, val, i) SKM_sk_insert(AMS_RevocationInfoChoice, (st), (val), (i)) -#define sk_AMS_RevocationInfoChoice_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(AMS_RevocationInfoChoice, (st), (cmp)) -#define sk_AMS_RevocationInfoChoice_dup(st) SKM_sk_dup(AMS_RevocationInfoChoice, st) -#define sk_AMS_RevocationInfoChoice_pop_free(st, free_func) SKM_sk_pop_free(AMS_RevocationInfoChoice, (st), (free_func)) -#define sk_AMS_RevocationInfoChoice_shift(st) SKM_sk_shift(AMS_RevocationInfoChoice, (st)) -#define sk_AMS_RevocationInfoChoice_pop(st) SKM_sk_pop(AMS_RevocationInfoChoice, (st)) -#define sk_AMS_RevocationInfoChoice_sort(st) SKM_sk_sort(AMS_RevocationInfoChoice, (st)) -#define sk_AMS_RevocationInfoChoice_is_sorted(st) SKM_sk_is_sorted(AMS_RevocationInfoChoice, (st)) - -#define sk_AMS_SignerInfo_new(cmp) SKM_sk_new(AMS_SignerInfo, (cmp)) -#define sk_AMS_SignerInfo_new_null() SKM_sk_new_null(AMS_SignerInfo) -#define sk_AMS_SignerInfo_free(st) SKM_sk_free(AMS_SignerInfo, (st)) -#define sk_AMS_SignerInfo_num(st) SKM_sk_num(AMS_SignerInfo, (st)) -#define sk_AMS_SignerInfo_value(st, i) SKM_sk_value(AMS_SignerInfo, (st), (i)) -#define sk_AMS_SignerInfo_set(st, i, val) SKM_sk_set(AMS_SignerInfo, (st), (i), (val)) -#define sk_AMS_SignerInfo_zero(st) SKM_sk_zero(AMS_SignerInfo, (st)) -#define sk_AMS_SignerInfo_push(st, val) SKM_sk_push(AMS_SignerInfo, (st), (val)) -#define sk_AMS_SignerInfo_unshift(st, val) SKM_sk_unshift(AMS_SignerInfo, (st), (val)) -#define sk_AMS_SignerInfo_find(st, val) SKM_sk_find(AMS_SignerInfo, (st), (val)) -#define sk_AMS_SignerInfo_find_ex(st, val) SKM_sk_find_ex(AMS_SignerInfo, (st), (val)) -#define sk_AMS_SignerInfo_delete(st, i) SKM_sk_delete(AMS_SignerInfo, (st), (i)) -#define sk_AMS_SignerInfo_delete_ptr(st, ptr) SKM_sk_delete_ptr(AMS_SignerInfo, (st), (ptr)) -#define sk_AMS_SignerInfo_insert(st, val, i) SKM_sk_insert(AMS_SignerInfo, (st), (val), (i)) -#define sk_AMS_SignerInfo_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(AMS_SignerInfo, (st), (cmp)) -#define sk_AMS_SignerInfo_dup(st) SKM_sk_dup(AMS_SignerInfo, st) -#define sk_AMS_SignerInfo_pop_free(st, free_func) SKM_sk_pop_free(AMS_SignerInfo, (st), (free_func)) -#define sk_AMS_SignerInfo_shift(st) SKM_sk_shift(AMS_SignerInfo, (st)) -#define sk_AMS_SignerInfo_pop(st) SKM_sk_pop(AMS_SignerInfo, (st)) -#define sk_AMS_SignerInfo_sort(st) SKM_sk_sort(AMS_SignerInfo, (st)) -#define sk_AMS_SignerInfo_is_sorted(st) SKM_sk_is_sorted(AMS_SignerInfo, (st)) +#define sk_CMS_CertificateChoices_new(cmp) SKM_sk_new(CMS_CertificateChoices, (cmp)) +#define sk_CMS_CertificateChoices_new_null() SKM_sk_new_null(CMS_CertificateChoices) +#define sk_CMS_CertificateChoices_free(st) SKM_sk_free(CMS_CertificateChoices, (st)) +#define sk_CMS_CertificateChoices_num(st) SKM_sk_num(CMS_CertificateChoices, (st)) +#define sk_CMS_CertificateChoices_value(st, i) SKM_sk_value(CMS_CertificateChoices, (st), (i)) +#define sk_CMS_CertificateChoices_set(st, i, val) SKM_sk_set(CMS_CertificateChoices, (st), (i), (val)) +#define sk_CMS_CertificateChoices_zero(st) SKM_sk_zero(CMS_CertificateChoices, (st)) +#define sk_CMS_CertificateChoices_push(st, val) SKM_sk_push(CMS_CertificateChoices, (st), (val)) +#define sk_CMS_CertificateChoices_unshift(st, val) SKM_sk_unshift(CMS_CertificateChoices, (st), (val)) +#define sk_CMS_CertificateChoices_find(st, val) SKM_sk_find(CMS_CertificateChoices, (st), (val)) +#define sk_CMS_CertificateChoices_find_ex(st, val) SKM_sk_find_ex(CMS_CertificateChoices, (st), (val)) +#define sk_CMS_CertificateChoices_delete(st, i) SKM_sk_delete(CMS_CertificateChoices, (st), (i)) +#define sk_CMS_CertificateChoices_delete_ptr(st, ptr) SKM_sk_delete_ptr(CMS_CertificateChoices, (st), (ptr)) +#define sk_CMS_CertificateChoices_insert(st, val, i) SKM_sk_insert(CMS_CertificateChoices, (st), (val), (i)) +#define sk_CMS_CertificateChoices_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(CMS_CertificateChoices, (st), (cmp)) +#define sk_CMS_CertificateChoices_dup(st) SKM_sk_dup(CMS_CertificateChoices, st) +#define sk_CMS_CertificateChoices_pop_free(st, free_func) SKM_sk_pop_free(CMS_CertificateChoices, (st), (free_func)) +#define sk_CMS_CertificateChoices_shift(st) SKM_sk_shift(CMS_CertificateChoices, (st)) +#define sk_CMS_CertificateChoices_pop(st) SKM_sk_pop(CMS_CertificateChoices, (st)) +#define sk_CMS_CertificateChoices_sort(st) SKM_sk_sort(CMS_CertificateChoices, (st)) +#define sk_CMS_CertificateChoices_is_sorted(st) SKM_sk_is_sorted(CMS_CertificateChoices, (st)) + +#define sk_CMS_RecipientInfo_new(cmp) SKM_sk_new(CMS_RecipientInfo, (cmp)) +#define sk_CMS_RecipientInfo_new_null() SKM_sk_new_null(CMS_RecipientInfo) +#define sk_CMS_RecipientInfo_free(st) SKM_sk_free(CMS_RecipientInfo, (st)) +#define sk_CMS_RecipientInfo_num(st) SKM_sk_num(CMS_RecipientInfo, (st)) +#define sk_CMS_RecipientInfo_value(st, i) SKM_sk_value(CMS_RecipientInfo, (st), (i)) +#define sk_CMS_RecipientInfo_set(st, i, val) SKM_sk_set(CMS_RecipientInfo, (st), (i), (val)) +#define sk_CMS_RecipientInfo_zero(st) SKM_sk_zero(CMS_RecipientInfo, (st)) +#define sk_CMS_RecipientInfo_push(st, val) SKM_sk_push(CMS_RecipientInfo, (st), (val)) +#define sk_CMS_RecipientInfo_unshift(st, val) SKM_sk_unshift(CMS_RecipientInfo, (st), (val)) +#define sk_CMS_RecipientInfo_find(st, val) SKM_sk_find(CMS_RecipientInfo, (st), (val)) +#define sk_CMS_RecipientInfo_find_ex(st, val) SKM_sk_find_ex(CMS_RecipientInfo, (st), (val)) +#define sk_CMS_RecipientInfo_delete(st, i) SKM_sk_delete(CMS_RecipientInfo, (st), (i)) +#define sk_CMS_RecipientInfo_delete_ptr(st, ptr) SKM_sk_delete_ptr(CMS_RecipientInfo, (st), (ptr)) +#define sk_CMS_RecipientInfo_insert(st, val, i) SKM_sk_insert(CMS_RecipientInfo, (st), (val), (i)) +#define sk_CMS_RecipientInfo_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(CMS_RecipientInfo, (st), (cmp)) +#define sk_CMS_RecipientInfo_dup(st) SKM_sk_dup(CMS_RecipientInfo, st) +#define sk_CMS_RecipientInfo_pop_free(st, free_func) SKM_sk_pop_free(CMS_RecipientInfo, (st), (free_func)) +#define sk_CMS_RecipientInfo_shift(st) SKM_sk_shift(CMS_RecipientInfo, (st)) +#define sk_CMS_RecipientInfo_pop(st) SKM_sk_pop(CMS_RecipientInfo, (st)) +#define sk_CMS_RecipientInfo_sort(st) SKM_sk_sort(CMS_RecipientInfo, (st)) +#define sk_CMS_RecipientInfo_is_sorted(st) SKM_sk_is_sorted(CMS_RecipientInfo, (st)) + +#define sk_CMS_RevocationInfoChoice_new(cmp) SKM_sk_new(CMS_RevocationInfoChoice, (cmp)) +#define sk_CMS_RevocationInfoChoice_new_null() SKM_sk_new_null(CMS_RevocationInfoChoice) +#define sk_CMS_RevocationInfoChoice_free(st) SKM_sk_free(CMS_RevocationInfoChoice, (st)) +#define sk_CMS_RevocationInfoChoice_num(st) SKM_sk_num(CMS_RevocationInfoChoice, (st)) +#define sk_CMS_RevocationInfoChoice_value(st, i) SKM_sk_value(CMS_RevocationInfoChoice, (st), (i)) +#define sk_CMS_RevocationInfoChoice_set(st, i, val) SKM_sk_set(CMS_RevocationInfoChoice, (st), (i), (val)) +#define sk_CMS_RevocationInfoChoice_zero(st) SKM_sk_zero(CMS_RevocationInfoChoice, (st)) +#define sk_CMS_RevocationInfoChoice_push(st, val) SKM_sk_push(CMS_RevocationInfoChoice, (st), (val)) +#define sk_CMS_RevocationInfoChoice_unshift(st, val) SKM_sk_unshift(CMS_RevocationInfoChoice, (st), (val)) +#define sk_CMS_RevocationInfoChoice_find(st, val) SKM_sk_find(CMS_RevocationInfoChoice, (st), (val)) +#define sk_CMS_RevocationInfoChoice_find_ex(st, val) SKM_sk_find_ex(CMS_RevocationInfoChoice, (st), (val)) +#define sk_CMS_RevocationInfoChoice_delete(st, i) SKM_sk_delete(CMS_RevocationInfoChoice, (st), (i)) +#define sk_CMS_RevocationInfoChoice_delete_ptr(st, ptr) SKM_sk_delete_ptr(CMS_RevocationInfoChoice, (st), (ptr)) +#define sk_CMS_RevocationInfoChoice_insert(st, val, i) SKM_sk_insert(CMS_RevocationInfoChoice, (st), (val), (i)) +#define sk_CMS_RevocationInfoChoice_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(CMS_RevocationInfoChoice, (st), (cmp)) +#define sk_CMS_RevocationInfoChoice_dup(st) SKM_sk_dup(CMS_RevocationInfoChoice, st) +#define sk_CMS_RevocationInfoChoice_pop_free(st, free_func) SKM_sk_pop_free(CMS_RevocationInfoChoice, (st), (free_func)) +#define sk_CMS_RevocationInfoChoice_shift(st) SKM_sk_shift(CMS_RevocationInfoChoice, (st)) +#define sk_CMS_RevocationInfoChoice_pop(st) SKM_sk_pop(CMS_RevocationInfoChoice, (st)) +#define sk_CMS_RevocationInfoChoice_sort(st) SKM_sk_sort(CMS_RevocationInfoChoice, (st)) +#define sk_CMS_RevocationInfoChoice_is_sorted(st) SKM_sk_is_sorted(CMS_RevocationInfoChoice, (st)) + +#define sk_CMS_SignerInfo_new(cmp) SKM_sk_new(CMS_SignerInfo, (cmp)) +#define sk_CMS_SignerInfo_new_null() SKM_sk_new_null(CMS_SignerInfo) +#define sk_CMS_SignerInfo_free(st) SKM_sk_free(CMS_SignerInfo, (st)) +#define sk_CMS_SignerInfo_num(st) SKM_sk_num(CMS_SignerInfo, (st)) +#define sk_CMS_SignerInfo_value(st, i) SKM_sk_value(CMS_SignerInfo, (st), (i)) +#define sk_CMS_SignerInfo_set(st, i, val) SKM_sk_set(CMS_SignerInfo, (st), (i), (val)) +#define sk_CMS_SignerInfo_zero(st) SKM_sk_zero(CMS_SignerInfo, (st)) +#define sk_CMS_SignerInfo_push(st, val) SKM_sk_push(CMS_SignerInfo, (st), (val)) +#define sk_CMS_SignerInfo_unshift(st, val) SKM_sk_unshift(CMS_SignerInfo, (st), (val)) +#define sk_CMS_SignerInfo_find(st, val) SKM_sk_find(CMS_SignerInfo, (st), (val)) +#define sk_CMS_SignerInfo_find_ex(st, val) SKM_sk_find_ex(CMS_SignerInfo, (st), (val)) +#define sk_CMS_SignerInfo_delete(st, i) SKM_sk_delete(CMS_SignerInfo, (st), (i)) +#define sk_CMS_SignerInfo_delete_ptr(st, ptr) SKM_sk_delete_ptr(CMS_SignerInfo, (st), (ptr)) +#define sk_CMS_SignerInfo_insert(st, val, i) SKM_sk_insert(CMS_SignerInfo, (st), (val), (i)) +#define sk_CMS_SignerInfo_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(CMS_SignerInfo, (st), (cmp)) +#define sk_CMS_SignerInfo_dup(st) SKM_sk_dup(CMS_SignerInfo, st) +#define sk_CMS_SignerInfo_pop_free(st, free_func) SKM_sk_pop_free(CMS_SignerInfo, (st), (free_func)) +#define sk_CMS_SignerInfo_shift(st) SKM_sk_shift(CMS_SignerInfo, (st)) +#define sk_CMS_SignerInfo_pop(st) SKM_sk_pop(CMS_SignerInfo, (st)) +#define sk_CMS_SignerInfo_sort(st) SKM_sk_sort(CMS_SignerInfo, (st)) +#define sk_CMS_SignerInfo_is_sorted(st) SKM_sk_is_sorted(CMS_SignerInfo, (st)) #define sk_CONF_IMODULE_new(cmp) SKM_sk_new(CONF_IMODULE, (cmp)) #define sk_CONF_IMODULE_new_null() SKM_sk_new_null(CONF_IMODULE) diff --git a/server/external/openssl/linux_32/include/openssl/srtp.h b/server/external/openssl/linux_32/include/openssl/srtp.h index 288aca3..c0cf33e 100644 --- a/server/external/openssl/linux_32/include/openssl/srtp.h +++ b/server/external/openssl/linux_32/include/openssl/srtp.h @@ -123,8 +123,8 @@ extern "C" { #endif -#define SRTP_AES128_AM_SHA1_80 0x0001 -#define SRTP_AES128_AM_SHA1_32 0x0002 +#define SRTP_AES128_CM_SHA1_80 0x0001 +#define SRTP_AES128_CM_SHA1_32 0x0002 #define SRTP_AES128_F8_SHA1_80 0x0003 #define SRTP_AES128_F8_SHA1_32 0x0004 #define SRTP_NULL_SHA1_80 0x0005 diff --git a/server/external/openssl/linux_32/include/openssl/symhacks.h b/server/external/openssl/linux_32/include/openssl/symhacks.h index b9e347c..bd2f000 100644 --- a/server/external/openssl/linux_32/include/openssl/symhacks.h +++ b/server/external/openssl/linux_32/include/openssl/symhacks.h @@ -407,19 +407,19 @@ #undef TS_CONF_set_clock_precision_digits #define TS_CONF_set_clock_precision_digits TS_CONF_set_clk_prec_digits -/* Hack some long AMS names */ -#undef AMS_RecipientInfo_ktri_get0_algs -#define AMS_RecipientInfo_ktri_get0_algs AMS_RecipInfo_ktri_get0_algs -#undef AMS_RecipientInfo_ktri_get0_signer_id -#define AMS_RecipientInfo_ktri_get0_signer_id AMS_RecipInfo_ktri_get0_sigr_id -#undef AMS_OtherRevocationInfoFormat_it -#define AMS_OtherRevocationInfoFormat_it AMS_OtherRevocInfoFormat_it -#undef AMS_KeyAgreeRecipientIdentifier_it -#define AMS_KeyAgreeRecipientIdentifier_it AMS_KeyAgreeRecipIdentifier_it -#undef AMS_OriginatorIdentifierOrKey_it -#define AMS_OriginatorIdentifierOrKey_it AMS_OriginatorIdOrKey_it -#undef ams_SignerIdentifier_get0_signer_id -#define ams_SignerIdentifier_get0_signer_id ams_SignerId_get0_signer_id +/* Hack some long CMS names */ +#undef CMS_RecipientInfo_ktri_get0_algs +#define CMS_RecipientInfo_ktri_get0_algs CMS_RecipInfo_ktri_get0_algs +#undef CMS_RecipientInfo_ktri_get0_signer_id +#define CMS_RecipientInfo_ktri_get0_signer_id CMS_RecipInfo_ktri_get0_sigr_id +#undef CMS_OtherRevocationInfoFormat_it +#define CMS_OtherRevocationInfoFormat_it CMS_OtherRevocInfoFormat_it +#undef CMS_KeyAgreeRecipientIdentifier_it +#define CMS_KeyAgreeRecipientIdentifier_it CMS_KeyAgreeRecipIdentifier_it +#undef CMS_OriginatorIdentifierOrKey_it +#define CMS_OriginatorIdentifierOrKey_it CMS_OriginatorIdOrKey_it +#undef cms_SignerIdentifier_get0_signer_id +#define cms_SignerIdentifier_get0_signer_id cms_SignerId_get0_signer_id /* Hack some long DTLS1 names */ #undef dtls1_retransmit_buffered_messages @@ -471,9 +471,9 @@ #undef X509v3_add_standard_extensions #define X509v3_add_standard_extensions oX509v3_add_standard_extensions -/* This one clashes with AMS_data_create */ -#undef ams_Data_create -#define ams_Data_create priv_ams_Data_create +/* This one clashes with CMS_data_create */ +#undef cms_Data_create +#define cms_Data_create priv_cms_Data_create #endif diff --git a/server/external/openssl/linux_32/include/openssl/tls1.h b/server/external/openssl/linux_32/include/openssl/tls1.h index fbf6c80..c992091 100644 --- a/server/external/openssl/linux_32/include/openssl/tls1.h +++ b/server/external/openssl/linux_32/include/openssl/tls1.h @@ -449,18 +449,18 @@ SSL_CTX_callback_ctrl(ssl,SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB,(void (*)(void))cb) #define TLS1_CK_ADH_WITH_SEED_SHA 0x0300009B /* TLS v1.2 GCM ciphersuites from RFC5288 */ -#define TLS1_CK_RSA_WITH_AES_128_GAM_SHA256 0x0300009C -#define TLS1_CK_RSA_WITH_AES_256_GAM_SHA384 0x0300009D -#define TLS1_CK_DHE_RSA_WITH_AES_128_GAM_SHA256 0x0300009E -#define TLS1_CK_DHE_RSA_WITH_AES_256_GAM_SHA384 0x0300009F -#define TLS1_CK_DH_RSA_WITH_AES_128_GAM_SHA256 0x030000A0 -#define TLS1_CK_DH_RSA_WITH_AES_256_GAM_SHA384 0x030000A1 -#define TLS1_CK_DHE_DSS_WITH_AES_128_GAM_SHA256 0x030000A2 -#define TLS1_CK_DHE_DSS_WITH_AES_256_GAM_SHA384 0x030000A3 -#define TLS1_CK_DH_DSS_WITH_AES_128_GAM_SHA256 0x030000A4 -#define TLS1_CK_DH_DSS_WITH_AES_256_GAM_SHA384 0x030000A5 -#define TLS1_CK_ADH_WITH_AES_128_GAM_SHA256 0x030000A6 -#define TLS1_CK_ADH_WITH_AES_256_GAM_SHA384 0x030000A7 +#define TLS1_CK_RSA_WITH_AES_128_GCM_SHA256 0x0300009C +#define TLS1_CK_RSA_WITH_AES_256_GCM_SHA384 0x0300009D +#define TLS1_CK_DHE_RSA_WITH_AES_128_GCM_SHA256 0x0300009E +#define TLS1_CK_DHE_RSA_WITH_AES_256_GCM_SHA384 0x0300009F +#define TLS1_CK_DH_RSA_WITH_AES_128_GCM_SHA256 0x030000A0 +#define TLS1_CK_DH_RSA_WITH_AES_256_GCM_SHA384 0x030000A1 +#define TLS1_CK_DHE_DSS_WITH_AES_128_GCM_SHA256 0x030000A2 +#define TLS1_CK_DHE_DSS_WITH_AES_256_GCM_SHA384 0x030000A3 +#define TLS1_CK_DH_DSS_WITH_AES_128_GCM_SHA256 0x030000A4 +#define TLS1_CK_DH_DSS_WITH_AES_256_GCM_SHA384 0x030000A5 +#define TLS1_CK_ADH_WITH_AES_128_GCM_SHA256 0x030000A6 +#define TLS1_CK_ADH_WITH_AES_256_GCM_SHA384 0x030000A7 /* ECC ciphersuites from draft-ietf-tls-ecc-12.txt with changes soon to be in draft 13 */ #define TLS1_CK_ECDH_ECDSA_WITH_NULL_SHA 0x0300C001 @@ -516,14 +516,14 @@ SSL_CTX_callback_ctrl(ssl,SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB,(void (*)(void))cb) #define TLS1_CK_ECDH_RSA_WITH_AES_256_SHA384 0x0300C02A /* ECDH GCM based ciphersuites from RFC5289 */ -#define TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GAM_SHA256 0x0300C02B -#define TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GAM_SHA384 0x0300C02C -#define TLS1_CK_ECDH_ECDSA_WITH_AES_128_GAM_SHA256 0x0300C02D -#define TLS1_CK_ECDH_ECDSA_WITH_AES_256_GAM_SHA384 0x0300C02E -#define TLS1_CK_ECDHE_RSA_WITH_AES_128_GAM_SHA256 0x0300C02F -#define TLS1_CK_ECDHE_RSA_WITH_AES_256_GAM_SHA384 0x0300C030 -#define TLS1_CK_ECDH_RSA_WITH_AES_128_GAM_SHA256 0x0300C031 -#define TLS1_CK_ECDH_RSA_WITH_AES_256_GAM_SHA384 0x0300C032 +#define TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 0x0300C02B +#define TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 0x0300C02C +#define TLS1_CK_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 0x0300C02D +#define TLS1_CK_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 0x0300C02E +#define TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256 0x0300C02F +#define TLS1_CK_ECDHE_RSA_WITH_AES_256_GCM_SHA384 0x0300C030 +#define TLS1_CK_ECDH_RSA_WITH_AES_128_GCM_SHA256 0x0300C031 +#define TLS1_CK_ECDH_RSA_WITH_AES_256_GCM_SHA384 0x0300C032 /* XXX * Inconsistency alert: @@ -642,18 +642,18 @@ SSL_CTX_callback_ctrl(ssl,SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB,(void (*)(void))cb) #define TLS1_TXT_ADH_WITH_AES_256_SHA256 "ADH-AES256-SHA256" /* TLS v1.2 GCM ciphersuites from RFC5288 */ -#define TLS1_TXT_RSA_WITH_AES_128_GAM_SHA256 "AES128-GCM-SHA256" -#define TLS1_TXT_RSA_WITH_AES_256_GAM_SHA384 "AES256-GCM-SHA384" -#define TLS1_TXT_DHE_RSA_WITH_AES_128_GAM_SHA256 "DHE-RSA-AES128-GCM-SHA256" -#define TLS1_TXT_DHE_RSA_WITH_AES_256_GAM_SHA384 "DHE-RSA-AES256-GCM-SHA384" -#define TLS1_TXT_DH_RSA_WITH_AES_128_GAM_SHA256 "DH-RSA-AES128-GCM-SHA256" -#define TLS1_TXT_DH_RSA_WITH_AES_256_GAM_SHA384 "DH-RSA-AES256-GCM-SHA384" -#define TLS1_TXT_DHE_DSS_WITH_AES_128_GAM_SHA256 "DHE-DSS-AES128-GCM-SHA256" -#define TLS1_TXT_DHE_DSS_WITH_AES_256_GAM_SHA384 "DHE-DSS-AES256-GCM-SHA384" -#define TLS1_TXT_DH_DSS_WITH_AES_128_GAM_SHA256 "DH-DSS-AES128-GCM-SHA256" -#define TLS1_TXT_DH_DSS_WITH_AES_256_GAM_SHA384 "DH-DSS-AES256-GCM-SHA384" -#define TLS1_TXT_ADH_WITH_AES_128_GAM_SHA256 "ADH-AES128-GCM-SHA256" -#define TLS1_TXT_ADH_WITH_AES_256_GAM_SHA384 "ADH-AES256-GCM-SHA384" +#define TLS1_TXT_RSA_WITH_AES_128_GCM_SHA256 "AES128-GCM-SHA256" +#define TLS1_TXT_RSA_WITH_AES_256_GCM_SHA384 "AES256-GCM-SHA384" +#define TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256 "DHE-RSA-AES128-GCM-SHA256" +#define TLS1_TXT_DHE_RSA_WITH_AES_256_GCM_SHA384 "DHE-RSA-AES256-GCM-SHA384" +#define TLS1_TXT_DH_RSA_WITH_AES_128_GCM_SHA256 "DH-RSA-AES128-GCM-SHA256" +#define TLS1_TXT_DH_RSA_WITH_AES_256_GCM_SHA384 "DH-RSA-AES256-GCM-SHA384" +#define TLS1_TXT_DHE_DSS_WITH_AES_128_GCM_SHA256 "DHE-DSS-AES128-GCM-SHA256" +#define TLS1_TXT_DHE_DSS_WITH_AES_256_GCM_SHA384 "DHE-DSS-AES256-GCM-SHA384" +#define TLS1_TXT_DH_DSS_WITH_AES_128_GCM_SHA256 "DH-DSS-AES128-GCM-SHA256" +#define TLS1_TXT_DH_DSS_WITH_AES_256_GCM_SHA384 "DH-DSS-AES256-GCM-SHA384" +#define TLS1_TXT_ADH_WITH_AES_128_GCM_SHA256 "ADH-AES128-GCM-SHA256" +#define TLS1_TXT_ADH_WITH_AES_256_GCM_SHA384 "ADH-AES256-GCM-SHA384" /* ECDH HMAC based ciphersuites from RFC5289 */ @@ -667,14 +667,14 @@ SSL_CTX_callback_ctrl(ssl,SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB,(void (*)(void))cb) #define TLS1_TXT_ECDH_RSA_WITH_AES_256_SHA384 "ECDH-RSA-AES256-SHA384" /* ECDH GCM based ciphersuites from RFC5289 */ -#define TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_GAM_SHA256 "ECDHE-ECDSA-AES128-GCM-SHA256" -#define TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_GAM_SHA384 "ECDHE-ECDSA-AES256-GCM-SHA384" -#define TLS1_TXT_ECDH_ECDSA_WITH_AES_128_GAM_SHA256 "ECDH-ECDSA-AES128-GCM-SHA256" -#define TLS1_TXT_ECDH_ECDSA_WITH_AES_256_GAM_SHA384 "ECDH-ECDSA-AES256-GCM-SHA384" -#define TLS1_TXT_ECDHE_RSA_WITH_AES_128_GAM_SHA256 "ECDHE-RSA-AES128-GCM-SHA256" -#define TLS1_TXT_ECDHE_RSA_WITH_AES_256_GAM_SHA384 "ECDHE-RSA-AES256-GCM-SHA384" -#define TLS1_TXT_ECDH_RSA_WITH_AES_128_GAM_SHA256 "ECDH-RSA-AES128-GCM-SHA256" -#define TLS1_TXT_ECDH_RSA_WITH_AES_256_GAM_SHA384 "ECDH-RSA-AES256-GCM-SHA384" +#define TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 "ECDHE-ECDSA-AES128-GCM-SHA256" +#define TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 "ECDHE-ECDSA-AES256-GCM-SHA384" +#define TLS1_TXT_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 "ECDH-ECDSA-AES128-GCM-SHA256" +#define TLS1_TXT_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 "ECDH-ECDSA-AES256-GCM-SHA384" +#define TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 "ECDHE-RSA-AES128-GCM-SHA256" +#define TLS1_TXT_ECDHE_RSA_WITH_AES_256_GCM_SHA384 "ECDHE-RSA-AES256-GCM-SHA384" +#define TLS1_TXT_ECDH_RSA_WITH_AES_128_GCM_SHA256 "ECDH-RSA-AES128-GCM-SHA256" +#define TLS1_TXT_ECDH_RSA_WITH_AES_256_GCM_SHA384 "ECDH-RSA-AES256-GCM-SHA384" #define TLS_CT_RSA_SIGN 1 #define TLS_CT_DSS_SIGN 2 diff --git a/server/external/openssl/linux_64/include/openssl/cms.h b/server/external/openssl/linux_64/include/openssl/cms.h new file mode 100644 index 0000000..c762796 --- /dev/null +++ b/server/external/openssl/linux_64/include/openssl/cms.h @@ -0,0 +1,339 @@ +/* + * Copyright 2008-2019 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_CMS_H +# define HEADER_CMS_H + +# include + +# ifndef OPENSSL_NO_CMS +# include +# include +# include +# ifdef __cplusplus +extern "C" { +# endif + +typedef struct CMS_ContentInfo_st CMS_ContentInfo; +typedef struct CMS_SignerInfo_st CMS_SignerInfo; +typedef struct CMS_CertificateChoices CMS_CertificateChoices; +typedef struct CMS_RevocationInfoChoice_st CMS_RevocationInfoChoice; +typedef struct CMS_RecipientInfo_st CMS_RecipientInfo; +typedef struct CMS_ReceiptRequest_st CMS_ReceiptRequest; +typedef struct CMS_Receipt_st CMS_Receipt; +typedef struct CMS_RecipientEncryptedKey_st CMS_RecipientEncryptedKey; +typedef struct CMS_OtherKeyAttribute_st CMS_OtherKeyAttribute; + +DEFINE_STACK_OF(CMS_SignerInfo) +DEFINE_STACK_OF(CMS_RecipientEncryptedKey) +DEFINE_STACK_OF(CMS_RecipientInfo) +DEFINE_STACK_OF(CMS_RevocationInfoChoice) +DECLARE_ASN1_FUNCTIONS(CMS_ContentInfo) +DECLARE_ASN1_FUNCTIONS(CMS_ReceiptRequest) +DECLARE_ASN1_PRINT_FUNCTION(CMS_ContentInfo) + +# define CMS_SIGNERINFO_ISSUER_SERIAL 0 +# define CMS_SIGNERINFO_KEYIDENTIFIER 1 + +# define CMS_RECIPINFO_NONE -1 +# define CMS_RECIPINFO_TRANS 0 +# define CMS_RECIPINFO_AGREE 1 +# define CMS_RECIPINFO_KEK 2 +# define CMS_RECIPINFO_PASS 3 +# define CMS_RECIPINFO_OTHER 4 + +/* S/MIME related flags */ + +# define CMS_TEXT 0x1 +# define CMS_NOCERTS 0x2 +# define CMS_NO_CONTENT_VERIFY 0x4 +# define CMS_NO_ATTR_VERIFY 0x8 +# define CMS_NOSIGS \ + (CMS_NO_CONTENT_VERIFY|CMS_NO_ATTR_VERIFY) +# define CMS_NOINTERN 0x10 +# define CMS_NO_SIGNER_CERT_VERIFY 0x20 +# define CMS_NOVERIFY 0x20 +# define CMS_DETACHED 0x40 +# define CMS_BINARY 0x80 +# define CMS_NOATTR 0x100 +# define CMS_NOSMIMECAP 0x200 +# define CMS_NOOLDMIMETYPE 0x400 +# define CMS_CRLFEOL 0x800 +# define CMS_STREAM 0x1000 +# define CMS_NOCRL 0x2000 +# define CMS_PARTIAL 0x4000 +# define CMS_REUSE_DIGEST 0x8000 +# define CMS_USE_KEYID 0x10000 +# define CMS_DEBUG_DECRYPT 0x20000 +# define CMS_KEY_PARAM 0x40000 +# define CMS_ASCIICRLF 0x80000 + +const ASN1_OBJECT *CMS_get0_type(const CMS_ContentInfo *cms); + +BIO *CMS_dataInit(CMS_ContentInfo *cms, BIO *icont); +int CMS_dataFinal(CMS_ContentInfo *cms, BIO *bio); + +ASN1_OCTET_STRING **CMS_get0_content(CMS_ContentInfo *cms); +int CMS_is_detached(CMS_ContentInfo *cms); +int CMS_set_detached(CMS_ContentInfo *cms, int detached); + +# ifdef HEADER_PEM_H +DECLARE_PEM_rw_const(CMS, CMS_ContentInfo) +# endif +int CMS_stream(unsigned char ***boundary, CMS_ContentInfo *cms); +CMS_ContentInfo *d2i_CMS_bio(BIO *bp, CMS_ContentInfo **cms); +int i2d_CMS_bio(BIO *bp, CMS_ContentInfo *cms); + +BIO *BIO_new_CMS(BIO *out, CMS_ContentInfo *cms); +int i2d_CMS_bio_stream(BIO *out, CMS_ContentInfo *cms, BIO *in, int flags); +int PEM_write_bio_CMS_stream(BIO *out, CMS_ContentInfo *cms, BIO *in, + int flags); +CMS_ContentInfo *SMIME_read_CMS(BIO *bio, BIO **bcont); +int SMIME_write_CMS(BIO *bio, CMS_ContentInfo *cms, BIO *data, int flags); + +int CMS_final(CMS_ContentInfo *cms, BIO *data, BIO *dcont, + unsigned int flags); + +CMS_ContentInfo *CMS_sign(X509 *signcert, EVP_PKEY *pkey, + STACK_OF(X509) *certs, BIO *data, + unsigned int flags); + +CMS_ContentInfo *CMS_sign_receipt(CMS_SignerInfo *si, + X509 *signcert, EVP_PKEY *pkey, + STACK_OF(X509) *certs, unsigned int flags); + +int CMS_data(CMS_ContentInfo *cms, BIO *out, unsigned int flags); +CMS_ContentInfo *CMS_data_create(BIO *in, unsigned int flags); + +int CMS_digest_verify(CMS_ContentInfo *cms, BIO *dcont, BIO *out, + unsigned int flags); +CMS_ContentInfo *CMS_digest_create(BIO *in, const EVP_MD *md, + unsigned int flags); + +int CMS_EncryptedData_decrypt(CMS_ContentInfo *cms, + const unsigned char *key, size_t keylen, + BIO *dcont, BIO *out, unsigned int flags); + +CMS_ContentInfo *CMS_EncryptedData_encrypt(BIO *in, const EVP_CIPHER *cipher, + const unsigned char *key, + size_t keylen, unsigned int flags); + +int CMS_EncryptedData_set1_key(CMS_ContentInfo *cms, const EVP_CIPHER *ciph, + const unsigned char *key, size_t keylen); + +int CMS_verify(CMS_ContentInfo *cms, STACK_OF(X509) *certs, + X509_STORE *store, BIO *dcont, BIO *out, unsigned int flags); + +int CMS_verify_receipt(CMS_ContentInfo *rcms, CMS_ContentInfo *ocms, + STACK_OF(X509) *certs, + X509_STORE *store, unsigned int flags); + +STACK_OF(X509) *CMS_get0_signers(CMS_ContentInfo *cms); + +CMS_ContentInfo *CMS_encrypt(STACK_OF(X509) *certs, BIO *in, + const EVP_CIPHER *cipher, unsigned int flags); + +int CMS_decrypt(CMS_ContentInfo *cms, EVP_PKEY *pkey, X509 *cert, + BIO *dcont, BIO *out, unsigned int flags); + +int CMS_decrypt_set1_pkey(CMS_ContentInfo *cms, EVP_PKEY *pk, X509 *cert); +int CMS_decrypt_set1_key(CMS_ContentInfo *cms, + unsigned char *key, size_t keylen, + const unsigned char *id, size_t idlen); +int CMS_decrypt_set1_password(CMS_ContentInfo *cms, + unsigned char *pass, ossl_ssize_t passlen); + +STACK_OF(CMS_RecipientInfo) *CMS_get0_RecipientInfos(CMS_ContentInfo *cms); +int CMS_RecipientInfo_type(CMS_RecipientInfo *ri); +EVP_PKEY_CTX *CMS_RecipientInfo_get0_pkey_ctx(CMS_RecipientInfo *ri); +CMS_ContentInfo *CMS_EnvelopedData_create(const EVP_CIPHER *cipher); +CMS_RecipientInfo *CMS_add1_recipient_cert(CMS_ContentInfo *cms, + X509 *recip, unsigned int flags); +int CMS_RecipientInfo_set0_pkey(CMS_RecipientInfo *ri, EVP_PKEY *pkey); +int CMS_RecipientInfo_ktri_cert_cmp(CMS_RecipientInfo *ri, X509 *cert); +int CMS_RecipientInfo_ktri_get0_algs(CMS_RecipientInfo *ri, + EVP_PKEY **pk, X509 **recip, + X509_ALGOR **palg); +int CMS_RecipientInfo_ktri_get0_signer_id(CMS_RecipientInfo *ri, + ASN1_OCTET_STRING **keyid, + X509_NAME **issuer, + ASN1_INTEGER **sno); + +CMS_RecipientInfo *CMS_add0_recipient_key(CMS_ContentInfo *cms, int nid, + unsigned char *key, size_t keylen, + unsigned char *id, size_t idlen, + ASN1_GENERALIZEDTIME *date, + ASN1_OBJECT *otherTypeId, + ASN1_TYPE *otherType); + +int CMS_RecipientInfo_kekri_get0_id(CMS_RecipientInfo *ri, + X509_ALGOR **palg, + ASN1_OCTET_STRING **pid, + ASN1_GENERALIZEDTIME **pdate, + ASN1_OBJECT **potherid, + ASN1_TYPE **pothertype); + +int CMS_RecipientInfo_set0_key(CMS_RecipientInfo *ri, + unsigned char *key, size_t keylen); + +int CMS_RecipientInfo_kekri_id_cmp(CMS_RecipientInfo *ri, + const unsigned char *id, size_t idlen); + +int CMS_RecipientInfo_set0_password(CMS_RecipientInfo *ri, + unsigned char *pass, + ossl_ssize_t passlen); + +CMS_RecipientInfo *CMS_add0_recipient_password(CMS_ContentInfo *cms, + int iter, int wrap_nid, + int pbe_nid, + unsigned char *pass, + ossl_ssize_t passlen, + const EVP_CIPHER *kekciph); + +int CMS_RecipientInfo_decrypt(CMS_ContentInfo *cms, CMS_RecipientInfo *ri); +int CMS_RecipientInfo_encrypt(CMS_ContentInfo *cms, CMS_RecipientInfo *ri); + +int CMS_uncompress(CMS_ContentInfo *cms, BIO *dcont, BIO *out, + unsigned int flags); +CMS_ContentInfo *CMS_compress(BIO *in, int comp_nid, unsigned int flags); + +int CMS_set1_eContentType(CMS_ContentInfo *cms, const ASN1_OBJECT *oid); +const ASN1_OBJECT *CMS_get0_eContentType(CMS_ContentInfo *cms); + +CMS_CertificateChoices *CMS_add0_CertificateChoices(CMS_ContentInfo *cms); +int CMS_add0_cert(CMS_ContentInfo *cms, X509 *cert); +int CMS_add1_cert(CMS_ContentInfo *cms, X509 *cert); +STACK_OF(X509) *CMS_get1_certs(CMS_ContentInfo *cms); + +CMS_RevocationInfoChoice *CMS_add0_RevocationInfoChoice(CMS_ContentInfo *cms); +int CMS_add0_crl(CMS_ContentInfo *cms, X509_CRL *crl); +int CMS_add1_crl(CMS_ContentInfo *cms, X509_CRL *crl); +STACK_OF(X509_CRL) *CMS_get1_crls(CMS_ContentInfo *cms); + +int CMS_SignedData_init(CMS_ContentInfo *cms); +CMS_SignerInfo *CMS_add1_signer(CMS_ContentInfo *cms, + X509 *signer, EVP_PKEY *pk, const EVP_MD *md, + unsigned int flags); +EVP_PKEY_CTX *CMS_SignerInfo_get0_pkey_ctx(CMS_SignerInfo *si); +EVP_MD_CTX *CMS_SignerInfo_get0_md_ctx(CMS_SignerInfo *si); +STACK_OF(CMS_SignerInfo) *CMS_get0_SignerInfos(CMS_ContentInfo *cms); + +void CMS_SignerInfo_set1_signer_cert(CMS_SignerInfo *si, X509 *signer); +int CMS_SignerInfo_get0_signer_id(CMS_SignerInfo *si, + ASN1_OCTET_STRING **keyid, + X509_NAME **issuer, ASN1_INTEGER **sno); +int CMS_SignerInfo_cert_cmp(CMS_SignerInfo *si, X509 *cert); +int CMS_set1_signers_certs(CMS_ContentInfo *cms, STACK_OF(X509) *certs, + unsigned int flags); +void CMS_SignerInfo_get0_algs(CMS_SignerInfo *si, EVP_PKEY **pk, + X509 **signer, X509_ALGOR **pdig, + X509_ALGOR **psig); +ASN1_OCTET_STRING *CMS_SignerInfo_get0_signature(CMS_SignerInfo *si); +int CMS_SignerInfo_sign(CMS_SignerInfo *si); +int CMS_SignerInfo_verify(CMS_SignerInfo *si); +int CMS_SignerInfo_verify_content(CMS_SignerInfo *si, BIO *chain); + +int CMS_add_smimecap(CMS_SignerInfo *si, STACK_OF(X509_ALGOR) *algs); +int CMS_add_simple_smimecap(STACK_OF(X509_ALGOR) **algs, + int algnid, int keysize); +int CMS_add_standard_smimecap(STACK_OF(X509_ALGOR) **smcap); + +int CMS_signed_get_attr_count(const CMS_SignerInfo *si); +int CMS_signed_get_attr_by_NID(const CMS_SignerInfo *si, int nid, + int lastpos); +int CMS_signed_get_attr_by_OBJ(const CMS_SignerInfo *si, const ASN1_OBJECT *obj, + int lastpos); +X509_ATTRIBUTE *CMS_signed_get_attr(const CMS_SignerInfo *si, int loc); +X509_ATTRIBUTE *CMS_signed_delete_attr(CMS_SignerInfo *si, int loc); +int CMS_signed_add1_attr(CMS_SignerInfo *si, X509_ATTRIBUTE *attr); +int CMS_signed_add1_attr_by_OBJ(CMS_SignerInfo *si, + const ASN1_OBJECT *obj, int type, + const void *bytes, int len); +int CMS_signed_add1_attr_by_NID(CMS_SignerInfo *si, + int nid, int type, + const void *bytes, int len); +int CMS_signed_add1_attr_by_txt(CMS_SignerInfo *si, + const char *attrname, int type, + const void *bytes, int len); +void *CMS_signed_get0_data_by_OBJ(CMS_SignerInfo *si, const ASN1_OBJECT *oid, + int lastpos, int type); + +int CMS_unsigned_get_attr_count(const CMS_SignerInfo *si); +int CMS_unsigned_get_attr_by_NID(const CMS_SignerInfo *si, int nid, + int lastpos); +int CMS_unsigned_get_attr_by_OBJ(const CMS_SignerInfo *si, + const ASN1_OBJECT *obj, int lastpos); +X509_ATTRIBUTE *CMS_unsigned_get_attr(const CMS_SignerInfo *si, int loc); +X509_ATTRIBUTE *CMS_unsigned_delete_attr(CMS_SignerInfo *si, int loc); +int CMS_unsigned_add1_attr(CMS_SignerInfo *si, X509_ATTRIBUTE *attr); +int CMS_unsigned_add1_attr_by_OBJ(CMS_SignerInfo *si, + const ASN1_OBJECT *obj, int type, + const void *bytes, int len); +int CMS_unsigned_add1_attr_by_NID(CMS_SignerInfo *si, + int nid, int type, + const void *bytes, int len); +int CMS_unsigned_add1_attr_by_txt(CMS_SignerInfo *si, + const char *attrname, int type, + const void *bytes, int len); +void *CMS_unsigned_get0_data_by_OBJ(CMS_SignerInfo *si, ASN1_OBJECT *oid, + int lastpos, int type); + +int CMS_get1_ReceiptRequest(CMS_SignerInfo *si, CMS_ReceiptRequest **prr); +CMS_ReceiptRequest *CMS_ReceiptRequest_create0(unsigned char *id, int idlen, + int allorfirst, + STACK_OF(GENERAL_NAMES) + *receiptList, STACK_OF(GENERAL_NAMES) + *receiptsTo); +int CMS_add1_ReceiptRequest(CMS_SignerInfo *si, CMS_ReceiptRequest *rr); +void CMS_ReceiptRequest_get0_values(CMS_ReceiptRequest *rr, + ASN1_STRING **pcid, + int *pallorfirst, + STACK_OF(GENERAL_NAMES) **plist, + STACK_OF(GENERAL_NAMES) **prto); +int CMS_RecipientInfo_kari_get0_alg(CMS_RecipientInfo *ri, + X509_ALGOR **palg, + ASN1_OCTET_STRING **pukm); +STACK_OF(CMS_RecipientEncryptedKey) +*CMS_RecipientInfo_kari_get0_reks(CMS_RecipientInfo *ri); + +int CMS_RecipientInfo_kari_get0_orig_id(CMS_RecipientInfo *ri, + X509_ALGOR **pubalg, + ASN1_BIT_STRING **pubkey, + ASN1_OCTET_STRING **keyid, + X509_NAME **issuer, + ASN1_INTEGER **sno); + +int CMS_RecipientInfo_kari_orig_id_cmp(CMS_RecipientInfo *ri, X509 *cert); + +int CMS_RecipientEncryptedKey_get0_id(CMS_RecipientEncryptedKey *rek, + ASN1_OCTET_STRING **keyid, + ASN1_GENERALIZEDTIME **tm, + CMS_OtherKeyAttribute **other, + X509_NAME **issuer, ASN1_INTEGER **sno); +int CMS_RecipientEncryptedKey_cert_cmp(CMS_RecipientEncryptedKey *rek, + X509 *cert); +int CMS_RecipientInfo_kari_set0_pkey(CMS_RecipientInfo *ri, EVP_PKEY *pk); +EVP_CIPHER_CTX *CMS_RecipientInfo_kari_get0_ctx(CMS_RecipientInfo *ri); +int CMS_RecipientInfo_kari_decrypt(CMS_ContentInfo *cms, + CMS_RecipientInfo *ri, + CMS_RecipientEncryptedKey *rek); + +int CMS_SharedInfo_encode(unsigned char **pder, X509_ALGOR *kekalg, + ASN1_OCTET_STRING *ukm, int keylen); + +/* Backward compatibility for spelling errors. */ +# define CMS_R_UNKNOWN_DIGEST_ALGORITM CMS_R_UNKNOWN_DIGEST_ALGORITHM +# define CMS_R_UNSUPPORTED_RECPIENTINFO_TYPE \ + CMS_R_UNSUPPORTED_RECIPIENTINFO_TYPE + +# ifdef __cplusplus +} +# endif +# endif +#endif diff --git a/server/external/openssl/linux_64/include/openssl/cmserr.h b/server/external/openssl/linux_64/include/openssl/cmserr.h new file mode 100644 index 0000000..7dbc13d --- /dev/null +++ b/server/external/openssl/linux_64/include/openssl/cmserr.h @@ -0,0 +1,202 @@ +/* + * Generated by util/mkerr.pl DO NOT EDIT + * Copyright 1995-2019 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_CMSERR_H +# define HEADER_CMSERR_H + +# ifndef HEADER_SYMHACKS_H +# include +# endif + +# include + +# ifndef OPENSSL_NO_CMS + +# ifdef __cplusplus +extern "C" +# endif +int ERR_load_CMS_strings(void); + +/* + * CMS function codes. + */ +# define CMS_F_CHECK_CONTENT 99 +# define CMS_F_CMS_ADD0_CERT 164 +# define CMS_F_CMS_ADD0_RECIPIENT_KEY 100 +# define CMS_F_CMS_ADD0_RECIPIENT_PASSWORD 165 +# define CMS_F_CMS_ADD1_RECEIPTREQUEST 158 +# define CMS_F_CMS_ADD1_RECIPIENT_CERT 101 +# define CMS_F_CMS_ADD1_SIGNER 102 +# define CMS_F_CMS_ADD1_SIGNINGTIME 103 +# define CMS_F_CMS_COMPRESS 104 +# define CMS_F_CMS_COMPRESSEDDATA_CREATE 105 +# define CMS_F_CMS_COMPRESSEDDATA_INIT_BIO 106 +# define CMS_F_CMS_COPY_CONTENT 107 +# define CMS_F_CMS_COPY_MESSAGEDIGEST 108 +# define CMS_F_CMS_DATA 109 +# define CMS_F_CMS_DATAFINAL 110 +# define CMS_F_CMS_DATAINIT 111 +# define CMS_F_CMS_DECRYPT 112 +# define CMS_F_CMS_DECRYPT_SET1_KEY 113 +# define CMS_F_CMS_DECRYPT_SET1_PASSWORD 166 +# define CMS_F_CMS_DECRYPT_SET1_PKEY 114 +# define CMS_F_CMS_DIGESTALGORITHM_FIND_CTX 115 +# define CMS_F_CMS_DIGESTALGORITHM_INIT_BIO 116 +# define CMS_F_CMS_DIGESTEDDATA_DO_FINAL 117 +# define CMS_F_CMS_DIGEST_VERIFY 118 +# define CMS_F_CMS_ENCODE_RECEIPT 161 +# define CMS_F_CMS_ENCRYPT 119 +# define CMS_F_CMS_ENCRYPTEDCONTENT_INIT 179 +# define CMS_F_CMS_ENCRYPTEDCONTENT_INIT_BIO 120 +# define CMS_F_CMS_ENCRYPTEDDATA_DECRYPT 121 +# define CMS_F_CMS_ENCRYPTEDDATA_ENCRYPT 122 +# define CMS_F_CMS_ENCRYPTEDDATA_SET1_KEY 123 +# define CMS_F_CMS_ENVELOPEDDATA_CREATE 124 +# define CMS_F_CMS_ENVELOPEDDATA_INIT_BIO 125 +# define CMS_F_CMS_ENVELOPED_DATA_INIT 126 +# define CMS_F_CMS_ENV_ASN1_CTRL 171 +# define CMS_F_CMS_FINAL 127 +# define CMS_F_CMS_GET0_CERTIFICATE_CHOICES 128 +# define CMS_F_CMS_GET0_CONTENT 129 +# define CMS_F_CMS_GET0_ECONTENT_TYPE 130 +# define CMS_F_CMS_GET0_ENVELOPED 131 +# define CMS_F_CMS_GET0_REVOCATION_CHOICES 132 +# define CMS_F_CMS_GET0_SIGNED 133 +# define CMS_F_CMS_MSGSIGDIGEST_ADD1 162 +# define CMS_F_CMS_RECEIPTREQUEST_CREATE0 159 +# define CMS_F_CMS_RECEIPT_VERIFY 160 +# define CMS_F_CMS_RECIPIENTINFO_DECRYPT 134 +# define CMS_F_CMS_RECIPIENTINFO_ENCRYPT 169 +# define CMS_F_CMS_RECIPIENTINFO_KARI_ENCRYPT 178 +# define CMS_F_CMS_RECIPIENTINFO_KARI_GET0_ALG 175 +# define CMS_F_CMS_RECIPIENTINFO_KARI_GET0_ORIG_ID 173 +# define CMS_F_CMS_RECIPIENTINFO_KARI_GET0_REKS 172 +# define CMS_F_CMS_RECIPIENTINFO_KARI_ORIG_ID_CMP 174 +# define CMS_F_CMS_RECIPIENTINFO_KEKRI_DECRYPT 135 +# define CMS_F_CMS_RECIPIENTINFO_KEKRI_ENCRYPT 136 +# define CMS_F_CMS_RECIPIENTINFO_KEKRI_GET0_ID 137 +# define CMS_F_CMS_RECIPIENTINFO_KEKRI_ID_CMP 138 +# define CMS_F_CMS_RECIPIENTINFO_KTRI_CERT_CMP 139 +# define CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT 140 +# define CMS_F_CMS_RECIPIENTINFO_KTRI_ENCRYPT 141 +# define CMS_F_CMS_RECIPIENTINFO_KTRI_GET0_ALGS 142 +# define CMS_F_CMS_RECIPIENTINFO_KTRI_GET0_SIGNER_ID 143 +# define CMS_F_CMS_RECIPIENTINFO_PWRI_CRYPT 167 +# define CMS_F_CMS_RECIPIENTINFO_SET0_KEY 144 +# define CMS_F_CMS_RECIPIENTINFO_SET0_PASSWORD 168 +# define CMS_F_CMS_RECIPIENTINFO_SET0_PKEY 145 +# define CMS_F_CMS_SD_ASN1_CTRL 170 +# define CMS_F_CMS_SET1_IAS 176 +# define CMS_F_CMS_SET1_KEYID 177 +# define CMS_F_CMS_SET1_SIGNERIDENTIFIER 146 +# define CMS_F_CMS_SET_DETACHED 147 +# define CMS_F_CMS_SIGN 148 +# define CMS_F_CMS_SIGNED_DATA_INIT 149 +# define CMS_F_CMS_SIGNERINFO_CONTENT_SIGN 150 +# define CMS_F_CMS_SIGNERINFO_SIGN 151 +# define CMS_F_CMS_SIGNERINFO_VERIFY 152 +# define CMS_F_CMS_SIGNERINFO_VERIFY_CERT 153 +# define CMS_F_CMS_SIGNERINFO_VERIFY_CONTENT 154 +# define CMS_F_CMS_SIGN_RECEIPT 163 +# define CMS_F_CMS_SI_CHECK_ATTRIBUTES 183 +# define CMS_F_CMS_STREAM 155 +# define CMS_F_CMS_UNCOMPRESS 156 +# define CMS_F_CMS_VERIFY 157 +# define CMS_F_KEK_UNWRAP_KEY 180 + +/* + * CMS reason codes. + */ +# define CMS_R_ADD_SIGNER_ERROR 99 +# define CMS_R_ATTRIBUTE_ERROR 161 +# define CMS_R_CERTIFICATE_ALREADY_PRESENT 175 +# define CMS_R_CERTIFICATE_HAS_NO_KEYID 160 +# define CMS_R_CERTIFICATE_VERIFY_ERROR 100 +# define CMS_R_CIPHER_INITIALISATION_ERROR 101 +# define CMS_R_CIPHER_PARAMETER_INITIALISATION_ERROR 102 +# define CMS_R_CMS_DATAFINAL_ERROR 103 +# define CMS_R_CMS_LIB 104 +# define CMS_R_CONTENTIDENTIFIER_MISMATCH 170 +# define CMS_R_CONTENT_NOT_FOUND 105 +# define CMS_R_CONTENT_TYPE_MISMATCH 171 +# define CMS_R_CONTENT_TYPE_NOT_COMPRESSED_DATA 106 +# define CMS_R_CONTENT_TYPE_NOT_ENVELOPED_DATA 107 +# define CMS_R_CONTENT_TYPE_NOT_SIGNED_DATA 108 +# define CMS_R_CONTENT_VERIFY_ERROR 109 +# define CMS_R_CTRL_ERROR 110 +# define CMS_R_CTRL_FAILURE 111 +# define CMS_R_DECRYPT_ERROR 112 +# define CMS_R_ERROR_GETTING_PUBLIC_KEY 113 +# define CMS_R_ERROR_READING_MESSAGEDIGEST_ATTRIBUTE 114 +# define CMS_R_ERROR_SETTING_KEY 115 +# define CMS_R_ERROR_SETTING_RECIPIENTINFO 116 +# define CMS_R_INVALID_ENCRYPTED_KEY_LENGTH 117 +# define CMS_R_INVALID_KEY_ENCRYPTION_PARAMETER 176 +# define CMS_R_INVALID_KEY_LENGTH 118 +# define CMS_R_MD_BIO_INIT_ERROR 119 +# define CMS_R_MESSAGEDIGEST_ATTRIBUTE_WRONG_LENGTH 120 +# define CMS_R_MESSAGEDIGEST_WRONG_LENGTH 121 +# define CMS_R_MSGSIGDIGEST_ERROR 172 +# define CMS_R_MSGSIGDIGEST_VERIFICATION_FAILURE 162 +# define CMS_R_MSGSIGDIGEST_WRONG_LENGTH 163 +# define CMS_R_NEED_ONE_SIGNER 164 +# define CMS_R_NOT_A_SIGNED_RECEIPT 165 +# define CMS_R_NOT_ENCRYPTED_DATA 122 +# define CMS_R_NOT_KEK 123 +# define CMS_R_NOT_KEY_AGREEMENT 181 +# define CMS_R_NOT_KEY_TRANSPORT 124 +# define CMS_R_NOT_PWRI 177 +# define CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE 125 +# define CMS_R_NO_CIPHER 126 +# define CMS_R_NO_CONTENT 127 +# define CMS_R_NO_CONTENT_TYPE 173 +# define CMS_R_NO_DEFAULT_DIGEST 128 +# define CMS_R_NO_DIGEST_SET 129 +# define CMS_R_NO_KEY 130 +# define CMS_R_NO_KEY_OR_CERT 174 +# define CMS_R_NO_MATCHING_DIGEST 131 +# define CMS_R_NO_MATCHING_RECIPIENT 132 +# define CMS_R_NO_MATCHING_SIGNATURE 166 +# define CMS_R_NO_MSGSIGDIGEST 167 +# define CMS_R_NO_PASSWORD 178 +# define CMS_R_NO_PRIVATE_KEY 133 +# define CMS_R_NO_PUBLIC_KEY 134 +# define CMS_R_NO_RECEIPT_REQUEST 168 +# define CMS_R_NO_SIGNERS 135 +# define CMS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE 136 +# define CMS_R_RECEIPT_DECODE_ERROR 169 +# define CMS_R_RECIPIENT_ERROR 137 +# define CMS_R_SIGNER_CERTIFICATE_NOT_FOUND 138 +# define CMS_R_SIGNFINAL_ERROR 139 +# define CMS_R_SMIME_TEXT_ERROR 140 +# define CMS_R_STORE_INIT_ERROR 141 +# define CMS_R_TYPE_NOT_COMPRESSED_DATA 142 +# define CMS_R_TYPE_NOT_DATA 143 +# define CMS_R_TYPE_NOT_DIGESTED_DATA 144 +# define CMS_R_TYPE_NOT_ENCRYPTED_DATA 145 +# define CMS_R_TYPE_NOT_ENVELOPED_DATA 146 +# define CMS_R_UNABLE_TO_FINALIZE_CONTEXT 147 +# define CMS_R_UNKNOWN_CIPHER 148 +# define CMS_R_UNKNOWN_DIGEST_ALGORITHM 149 +# define CMS_R_UNKNOWN_ID 150 +# define CMS_R_UNSUPPORTED_COMPRESSION_ALGORITHM 151 +# define CMS_R_UNSUPPORTED_CONTENT_TYPE 152 +# define CMS_R_UNSUPPORTED_KEK_ALGORITHM 153 +# define CMS_R_UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM 179 +# define CMS_R_UNSUPPORTED_RECIPIENTINFO_TYPE 155 +# define CMS_R_UNSUPPORTED_RECIPIENT_TYPE 154 +# define CMS_R_UNSUPPORTED_TYPE 156 +# define CMS_R_UNWRAP_ERROR 157 +# define CMS_R_UNWRAP_FAILURE 180 +# define CMS_R_VERIFICATION_FAILURE 158 +# define CMS_R_WRAP_ERROR 159 + +# endif +#endif diff --git a/server/external/openssl/linux_64/include/openssl/dh.h b/server/external/openssl/linux_64/include/openssl/dh.h index 3bb4322..3527540 100644 --- a/server/external/openssl/linux_64/include/openssl/dh.h +++ b/server/external/openssl/linux_64/include/openssl/dh.h @@ -169,7 +169,7 @@ DH *DH_get_2048_256(void); DH *DH_new_by_nid(int nid); int DH_get_nid(const DH *dh); -# ifndef OPENSSL_NO_AMS +# ifndef OPENSSL_NO_CMS /* RFC2631 KDF */ int DH_KDF_X9_42(unsigned char *out, size_t outlen, const unsigned char *Z, size_t Zlen, @@ -328,7 +328,7 @@ int DH_meth_set_generate_params(DH_METHOD *dhm, /* KDF types */ # define EVP_PKEY_DH_KDF_NONE 1 -# ifndef OPENSSL_NO_AMS +# ifndef OPENSSL_NO_CMS # define EVP_PKEY_DH_KDF_X9_42 2 # endif diff --git a/server/external/openssl/linux_64/include/openssl/dherr.h b/server/external/openssl/linux_64/include/openssl/dherr.h index 79df1ae..916b3be 100644 --- a/server/external/openssl/linux_64/include/openssl/dherr.h +++ b/server/external/openssl/linux_64/include/openssl/dherr.h @@ -33,9 +33,9 @@ int ERR_load_DH_strings(void); # define DH_F_DH_CHECK_EX 121 # define DH_F_DH_CHECK_PARAMS_EX 122 # define DH_F_DH_CHECK_PUB_KEY_EX 123 -# define DH_F_DH_AMS_DECRYPT 114 -# define DH_F_DH_AMS_SET_PEERKEY 115 -# define DH_F_DH_AMS_SET_SHARED_INFO 116 +# define DH_F_DH_CMS_DECRYPT 114 +# define DH_F_DH_CMS_SET_PEERKEY 115 +# define DH_F_DH_CMS_SET_SHARED_INFO 116 # define DH_F_DH_METH_DUP 117 # define DH_F_DH_METH_NEW 118 # define DH_F_DH_METH_SET1_NAME 119 diff --git a/server/external/openssl/linux_64/include/openssl/ecerr.h b/server/external/openssl/linux_64/include/openssl/ecerr.h index e69f829..f7b9183 100644 --- a/server/external/openssl/linux_64/include/openssl/ecerr.h +++ b/server/external/openssl/linux_64/include/openssl/ecerr.h @@ -32,8 +32,8 @@ int ERR_load_EC_strings(void); # define EC_F_D2I_ECPKPARAMETERS 145 # define EC_F_D2I_ECPRIVATEKEY 146 # define EC_F_DO_EC_KEY_PRINT 221 -# define EC_F_ECDH_AMS_DECRYPT 238 -# define EC_F_ECDH_AMS_SET_SHARED_INFO 239 +# define EC_F_ECDH_CMS_DECRYPT 238 +# define EC_F_ECDH_CMS_SET_SHARED_INFO 239 # define EC_F_ECDH_COMPUTE_KEY 246 # define EC_F_ECDH_SIMPLE_COMPUTE_KEY 257 # define EC_F_ECDSA_DO_SIGN_EX 251 diff --git a/server/external/openssl/linux_64/include/openssl/err.h b/server/external/openssl/linux_64/include/openssl/err.h index c70491a..b49f881 100644 --- a/server/external/openssl/linux_64/include/openssl/err.h +++ b/server/external/openssl/linux_64/include/openssl/err.h @@ -87,7 +87,7 @@ typedef struct err_state_st { # define ERR_LIB_ECDH 43 # define ERR_LIB_OSSL_STORE 44 # define ERR_LIB_FIPS 45 -# define ERR_LIB_AMS 46 +# define ERR_LIB_CMS 46 # define ERR_LIB_TS 47 # define ERR_LIB_HMAC 48 /* # define ERR_LIB_JPAKE 49 */ @@ -127,7 +127,7 @@ typedef struct err_state_st { # define ECDHerr(f,r) ERR_PUT_error(ERR_LIB_ECDH,(f),(r),OPENSSL_FILE,OPENSSL_LINE) # define OSSL_STOREerr(f,r) ERR_PUT_error(ERR_LIB_OSSL_STORE,(f),(r),OPENSSL_FILE,OPENSSL_LINE) # define FIPSerr(f,r) ERR_PUT_error(ERR_LIB_FIPS,(f),(r),OPENSSL_FILE,OPENSSL_LINE) -# define AMSerr(f,r) ERR_PUT_error(ERR_LIB_AMS,(f),(r),OPENSSL_FILE,OPENSSL_LINE) +# define CMSerr(f,r) ERR_PUT_error(ERR_LIB_CMS,(f),(r),OPENSSL_FILE,OPENSSL_LINE) # define TSerr(f,r) ERR_PUT_error(ERR_LIB_TS,(f),(r),OPENSSL_FILE,OPENSSL_LINE) # define HMACerr(f,r) ERR_PUT_error(ERR_LIB_HMAC,(f),(r),OPENSSL_FILE,OPENSSL_LINE) # define CTerr(f,r) ERR_PUT_error(ERR_LIB_CT,(f),(r),OPENSSL_FILE,OPENSSL_LINE) diff --git a/server/external/openssl/linux_64/include/openssl/evp.h b/server/external/openssl/linux_64/include/openssl/evp.h index fb3bb7e..a411f3f 100644 --- a/server/external/openssl/linux_64/include/openssl/evp.h +++ b/server/external/openssl/linux_64/include/openssl/evp.h @@ -238,8 +238,8 @@ int (*EVP_CIPHER_meth_get_ctrl(const EVP_CIPHER *cipher))(EVP_CIPHER_CTX *, # define EVP_CIPH_CFB_MODE 0x3 # define EVP_CIPH_OFB_MODE 0x4 # define EVP_CIPH_CTR_MODE 0x5 -# define EVP_CIPH_GAM_MODE 0x6 -# define EVP_CIPH_CAM_MODE 0x7 +# define EVP_CIPH_GCM_MODE 0x6 +# define EVP_CIPH_CCM_MODE 0x7 # define EVP_CIPH_XTS_MODE 0x10001 # define EVP_CIPH_WRAP_MODE 0x10002 # define EVP_CIPH_OCB_MODE 0x10003 @@ -301,17 +301,17 @@ int (*EVP_CIPHER_meth_get_ctrl(const EVP_CIPHER *cipher))(EVP_CIPHER_CTX *, # define EVP_CTRL_AEAD_GET_TAG 0x10 # define EVP_CTRL_AEAD_SET_TAG 0x11 # define EVP_CTRL_AEAD_SET_IV_FIXED 0x12 -# define EVP_CTRL_GAM_SET_IVLEN EVP_CTRL_AEAD_SET_IVLEN -# define EVP_CTRL_GAM_GET_TAG EVP_CTRL_AEAD_GET_TAG -# define EVP_CTRL_GAM_SET_TAG EVP_CTRL_AEAD_SET_TAG -# define EVP_CTRL_GAM_SET_IV_FIXED EVP_CTRL_AEAD_SET_IV_FIXED -# define EVP_CTRL_GAM_IV_GEN 0x13 -# define EVP_CTRL_CAM_SET_IVLEN EVP_CTRL_AEAD_SET_IVLEN -# define EVP_CTRL_CAM_GET_TAG EVP_CTRL_AEAD_GET_TAG -# define EVP_CTRL_CAM_SET_TAG EVP_CTRL_AEAD_SET_TAG -# define EVP_CTRL_CAM_SET_IV_FIXED EVP_CTRL_AEAD_SET_IV_FIXED -# define EVP_CTRL_CAM_SET_L 0x14 -# define EVP_CTRL_CAM_SET_MSGLEN 0x15 +# define EVP_CTRL_GCM_SET_IVLEN EVP_CTRL_AEAD_SET_IVLEN +# define EVP_CTRL_GCM_GET_TAG EVP_CTRL_AEAD_GET_TAG +# define EVP_CTRL_GCM_SET_TAG EVP_CTRL_AEAD_SET_TAG +# define EVP_CTRL_GCM_SET_IV_FIXED EVP_CTRL_AEAD_SET_IV_FIXED +# define EVP_CTRL_GCM_IV_GEN 0x13 +# define EVP_CTRL_CCM_SET_IVLEN EVP_CTRL_AEAD_SET_IVLEN +# define EVP_CTRL_CCM_GET_TAG EVP_CTRL_AEAD_GET_TAG +# define EVP_CTRL_CCM_SET_TAG EVP_CTRL_AEAD_SET_TAG +# define EVP_CTRL_CCM_SET_IV_FIXED EVP_CTRL_AEAD_SET_IV_FIXED +# define EVP_CTRL_CCM_SET_L 0x14 +# define EVP_CTRL_CCM_SET_MSGLEN 0x15 /* * AEAD cipher deduces payload length and returns number of bytes required to * store MAC and eventual padding. Subsequent call to EVP_Cipher even @@ -321,7 +321,7 @@ int (*EVP_CIPHER_meth_get_ctrl(const EVP_CIPHER *cipher))(EVP_CIPHER_CTX *, /* Used by composite AEAD ciphers, no-op in GCM, CCM... */ # define EVP_CTRL_AEAD_SET_MAC_KEY 0x17 /* Set the GCM invocation field, decrypt only */ -# define EVP_CTRL_GAM_SET_IV_INV 0x18 +# define EVP_CTRL_GCM_SET_IV_INV 0x18 # define EVP_CTRL_TLS1_1_MULTIBLOCK_AAD 0x19 # define EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT 0x1a @@ -372,21 +372,21 @@ typedef struct { /* GCM TLS constants */ /* Length of fixed part of IV derived from PRF */ -# define EVP_GAM_TLS_FIXED_IV_LEN 4 +# define EVP_GCM_TLS_FIXED_IV_LEN 4 /* Length of explicit part of IV part of TLS records */ -# define EVP_GAM_TLS_EXPLICIT_IV_LEN 8 +# define EVP_GCM_TLS_EXPLICIT_IV_LEN 8 /* Length of tag for TLS */ -# define EVP_GAM_TLS_TAG_LEN 16 +# define EVP_GCM_TLS_TAG_LEN 16 /* CCM TLS constants */ /* Length of fixed part of IV derived from PRF */ -# define EVP_CAM_TLS_FIXED_IV_LEN 4 +# define EVP_CCM_TLS_FIXED_IV_LEN 4 /* Length of explicit part of IV part of TLS records */ -# define EVP_CAM_TLS_EXPLICIT_IV_LEN 8 +# define EVP_CCM_TLS_EXPLICIT_IV_LEN 8 /* Total length of CCM IV length for TLS */ -# define EVP_CAM_TLS_IV_LEN 12 +# define EVP_CCM_TLS_IV_LEN 12 /* Length of tag for TLS */ -# define EVP_CAM_TLS_TAG_LEN 16 +# define EVP_CCM_TLS_TAG_LEN 16 /* Length of CCM8 tag for TLS */ # define EVP_CCM8_TLS_TAG_LEN 8 @@ -1135,9 +1135,9 @@ int EVP_PBE_get(int *ptype, int *ppbe_nid, size_t num); # define ASN1_PKEY_CTRL_PKCS7_SIGN 0x1 # define ASN1_PKEY_CTRL_PKCS7_ENCRYPT 0x2 # define ASN1_PKEY_CTRL_DEFAULT_MD_NID 0x3 -# define ASN1_PKEY_CTRL_AMS_SIGN 0x5 -# define ASN1_PKEY_CTRL_AMS_ENVELOPE 0x7 -# define ASN1_PKEY_CTRL_AMS_RI_TYPE 0x8 +# define ASN1_PKEY_CTRL_CMS_SIGN 0x5 +# define ASN1_PKEY_CTRL_CMS_ENVELOPE 0x7 +# define ASN1_PKEY_CTRL_CMS_RI_TYPE 0x8 # define ASN1_PKEY_CTRL_SET1_TLS_ENCPT 0x9 # define ASN1_PKEY_CTRL_GET1_TLS_ENCPT 0xa @@ -1306,9 +1306,9 @@ void EVP_PKEY_asn1_set_security_bits(EVP_PKEY_ASN1_METHOD *ameth, /* Used by GOST key encryption in TLS */ # define EVP_PKEY_CTRL_SET_IV 8 -# define EVP_PKEY_CTRL_AMS_ENCRYPT 9 -# define EVP_PKEY_CTRL_AMS_DECRYPT 10 -# define EVP_PKEY_CTRL_AMS_SIGN 11 +# define EVP_PKEY_CTRL_CMS_ENCRYPT 9 +# define EVP_PKEY_CTRL_CMS_DECRYPT 10 +# define EVP_PKEY_CTRL_CMS_SIGN 11 # define EVP_PKEY_CTRL_CIPHER 12 diff --git a/server/external/openssl/linux_64/include/openssl/evperr.h b/server/external/openssl/linux_64/include/openssl/evperr.h index d656d3d..d2b26ea 100644 --- a/server/external/openssl/linux_64/include/openssl/evperr.h +++ b/server/external/openssl/linux_64/include/openssl/evperr.h @@ -25,7 +25,7 @@ int ERR_load_EVP_strings(void); */ # define EVP_F_AESNI_INIT_KEY 165 # define EVP_F_AESNI_XTS_INIT_KEY 207 -# define EVP_F_AES_GAM_CTRL 196 +# define EVP_F_AES_GCM_CTRL 196 # define EVP_F_AES_INIT_KEY 133 # define EVP_F_AES_OCB_CIPHER 169 # define EVP_F_AES_T4_INIT_KEY 178 @@ -33,9 +33,9 @@ int ERR_load_EVP_strings(void); # define EVP_F_AES_WRAP_CIPHER 170 # define EVP_F_AES_XTS_INIT_KEY 209 # define EVP_F_ALG_MODULE_INIT 177 -# define EVP_F_ARIA_CAM_INIT_KEY 175 -# define EVP_F_ARIA_GAM_CTRL 197 -# define EVP_F_ARIA_GAM_INIT_KEY 176 +# define EVP_F_ARIA_CCM_INIT_KEY 175 +# define EVP_F_ARIA_GCM_CTRL 197 +# define EVP_F_ARIA_GCM_INIT_KEY 176 # define EVP_F_ARIA_INIT_KEY 185 # define EVP_F_B64_NEW 198 # define EVP_F_CAMELLIA_INIT_KEY 159 @@ -123,7 +123,7 @@ int ERR_load_EVP_strings(void); # define EVP_F_RC2_MAGIC_TO_METH 109 # define EVP_F_RC5_CTRL 125 # define EVP_F_R_32_12_16_INIT_KEY 242 -# define EVP_F_S390X_AES_GAM_CTRL 201 +# define EVP_F_S390X_AES_GCM_CTRL 201 # define EVP_F_UPDATE 173 /* diff --git a/server/external/openssl/linux_64/include/openssl/obj_mac.h b/server/external/openssl/linux_64/include/openssl/obj_mac.h index dd5c05f..483fc05 100644 --- a/server/external/openssl/linux_64/include/openssl/obj_mac.h +++ b/server/external/openssl/linux_64/include/openssl/obj_mac.h @@ -769,9 +769,9 @@ #define NID_id_smime_cti 195 #define OBJ_id_smime_cti OBJ_SMIME,6L -#define SN_id_smime_mod_ams "id-smime-mod-ams" -#define NID_id_smime_mod_ams 196 -#define OBJ_id_smime_mod_ams OBJ_id_smime_mod,1L +#define SN_id_smime_mod_cms "id-smime-mod-cms" +#define NID_id_smime_mod_cms 196 +#define OBJ_id_smime_mod_cms OBJ_id_smime_mod,1L #define SN_id_smime_mod_ess "id-smime-mod-ess" #define NID_id_smime_mod_ess 197 @@ -993,13 +993,13 @@ #define NID_id_smime_alg_ESDH 245 #define OBJ_id_smime_alg_ESDH OBJ_id_smime_alg,5L -#define SN_id_smime_alg_AMS3DESwrap "id-smime-alg-AMS3DESwrap" -#define NID_id_smime_alg_AMS3DESwrap 246 -#define OBJ_id_smime_alg_AMS3DESwrap OBJ_id_smime_alg,6L +#define SN_id_smime_alg_CMS3DESwrap "id-smime-alg-CMS3DESwrap" +#define NID_id_smime_alg_CMS3DESwrap 246 +#define OBJ_id_smime_alg_CMS3DESwrap OBJ_id_smime_alg,6L -#define SN_id_smime_alg_AMSRC2wrap "id-smime-alg-AMSRC2wrap" -#define NID_id_smime_alg_AMSRC2wrap 247 -#define OBJ_id_smime_alg_AMSRC2wrap OBJ_id_smime_alg,7L +#define SN_id_smime_alg_CMSRC2wrap "id-smime-alg-CMSRC2wrap" +#define NID_id_smime_alg_CMSRC2wrap 247 +#define OBJ_id_smime_alg_CMSRC2wrap OBJ_id_smime_alg,7L #define SN_id_alg_PWRI_KEK "id-alg-PWRI-KEK" #define NID_id_alg_PWRI_KEK 893 diff --git a/server/external/openssl/linux_64/include/openssl/pem.h b/server/external/openssl/linux_64/include/openssl/pem.h index e41f6b6..2ef5b5d 100644 --- a/server/external/openssl/linux_64/include/openssl/pem.h +++ b/server/external/openssl/linux_64/include/openssl/pem.h @@ -47,7 +47,7 @@ extern "C" { # define PEM_STRING_ECPARAMETERS "EC PARAMETERS" # define PEM_STRING_ECPRIVATEKEY "EC PRIVATE KEY" # define PEM_STRING_PARAMETERS "PARAMETERS" -# define PEM_STRING_AMS "AMS" +# define PEM_STRING_CMS "CMS" # define PEM_TYPE_ENCRYPTED 10 # define PEM_TYPE_MIC_ONLY 20 diff --git a/server/external/openssl/linux_64/include/openssl/rsaerr.h b/server/external/openssl/linux_64/include/openssl/rsaerr.h index e459a2a..59b15e1 100644 --- a/server/external/openssl/linux_64/include/openssl/rsaerr.h +++ b/server/external/openssl/linux_64/include/openssl/rsaerr.h @@ -37,8 +37,8 @@ int ERR_load_RSA_strings(void); # define RSA_F_RSA_BUILTIN_KEYGEN 129 # define RSA_F_RSA_CHECK_KEY 123 # define RSA_F_RSA_CHECK_KEY_EX 160 -# define RSA_F_RSA_AMS_DECRYPT 159 -# define RSA_F_RSA_AMS_VERIFY 158 +# define RSA_F_RSA_CMS_DECRYPT 159 +# define RSA_F_RSA_CMS_VERIFY 158 # define RSA_F_RSA_ITEM_VERIFY 148 # define RSA_F_RSA_METH_DUP 161 # define RSA_F_RSA_METH_NEW 162 diff --git a/server/external/openssl/linux_64/include/openssl/srtp.h b/server/external/openssl/linux_64/include/openssl/srtp.h index 57bef4a..0b57c23 100644 --- a/server/external/openssl/linux_64/include/openssl/srtp.h +++ b/server/external/openssl/linux_64/include/openssl/srtp.h @@ -22,8 +22,8 @@ extern "C" { #endif -# define SRTP_AES128_AM_SHA1_80 0x0001 -# define SRTP_AES128_AM_SHA1_32 0x0002 +# define SRTP_AES128_CM_SHA1_80 0x0001 +# define SRTP_AES128_CM_SHA1_32 0x0002 # define SRTP_AES128_F8_SHA1_80 0x0003 # define SRTP_AES128_F8_SHA1_32 0x0004 # define SRTP_NULL_SHA1_80 0x0005 diff --git a/server/external/openssl/linux_64/include/openssl/ssl.h b/server/external/openssl/linux_64/include/openssl/ssl.h index 505432b..6724ccf 100644 --- a/server/external/openssl/linux_64/include/openssl/ssl.h +++ b/server/external/openssl/linux_64/include/openssl/ssl.h @@ -120,7 +120,7 @@ extern "C" { # define SSL_TXT_AES "AES" # define SSL_TXT_AES_GCM "AESGCM" # define SSL_TXT_AES_CCM "AESCCM" -# define SSL_TXT_AES_CAM_8 "AESCCM8" +# define SSL_TXT_AES_CCM_8 "AESCCM8" # define SSL_TXT_CAMELLIA128 "CAMELLIA128" # define SSL_TXT_CAMELLIA256 "CAMELLIA256" # define SSL_TXT_CAMELLIA "CAMELLIA" @@ -173,12 +173,12 @@ extern "C" { # define SSL_DEFAULT_CIPHER_LIST "ALL:!COMPLEMENTOFDEFAULT:!eNULL" /* This is the default set of TLSv1.3 ciphersuites */ # if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305) -# define TLS_DEFAULT_CIPHERSUITES "TLS_AES_256_GAM_SHA384:" \ +# define TLS_DEFAULT_CIPHERSUITES "TLS_AES_256_GCM_SHA384:" \ "TLS_CHACHA20_POLY1305_SHA256:" \ - "TLS_AES_128_GAM_SHA256" + "TLS_AES_128_GCM_SHA256" # else -# define TLS_DEFAULT_CIPHERSUITES "TLS_AES_256_GAM_SHA384:" \ - "TLS_AES_128_GAM_SHA256" +# define TLS_DEFAULT_CIPHERSUITES "TLS_AES_256_GCM_SHA384:" \ + "TLS_AES_128_GCM_SHA256" #endif /* * As of OpenSSL 1.0.0, ssl_create_cipher_list() in ssl/ssl_ciph.c always diff --git a/server/external/openssl/linux_64/include/openssl/symhacks.h b/server/external/openssl/linux_64/include/openssl/symhacks.h index 192dd97..0dbf737 100644 --- a/server/external/openssl/linux_64/include/openssl/symhacks.h +++ b/server/external/openssl/linux_64/include/openssl/symhacks.h @@ -29,8 +29,8 @@ # define i2d_ECPKPARAMETERS i2d_UC_ECPKPARAMETERS /* This one clashes with AMS_data_create */ -# undef ams_Data_create -# define ams_Data_create priv_ams_Data_create +# undef cms_Data_create +# define cms_Data_create priv_cms_Data_create # endif diff --git a/server/external/openssl/linux_64/include/openssl/tls1.h b/server/external/openssl/linux_64/include/openssl/tls1.h index b25ffd0..76d9fda 100644 --- a/server/external/openssl/linux_64/include/openssl/tls1.h +++ b/server/external/openssl/linux_64/include/openssl/tls1.h @@ -370,12 +370,12 @@ __owur int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain) # define TLS1_CK_RSA_PSK_WITH_AES_256_CBC_SHA 0x03000095 /* PSK ciphersuites from 5487 */ -# define TLS1_CK_PSK_WITH_AES_128_GAM_SHA256 0x030000A8 -# define TLS1_CK_PSK_WITH_AES_256_GAM_SHA384 0x030000A9 -# define TLS1_CK_DHE_PSK_WITH_AES_128_GAM_SHA256 0x030000AA -# define TLS1_CK_DHE_PSK_WITH_AES_256_GAM_SHA384 0x030000AB -# define TLS1_CK_RSA_PSK_WITH_AES_128_GAM_SHA256 0x030000AC -# define TLS1_CK_RSA_PSK_WITH_AES_256_GAM_SHA384 0x030000AD +# define TLS1_CK_PSK_WITH_AES_128_GCM_SHA256 0x030000A8 +# define TLS1_CK_PSK_WITH_AES_256_GCM_SHA384 0x030000A9 +# define TLS1_CK_DHE_PSK_WITH_AES_128_GCM_SHA256 0x030000AA +# define TLS1_CK_DHE_PSK_WITH_AES_256_GCM_SHA384 0x030000AB +# define TLS1_CK_RSA_PSK_WITH_AES_128_GCM_SHA256 0x030000AC +# define TLS1_CK_RSA_PSK_WITH_AES_256_GCM_SHA384 0x030000AD # define TLS1_CK_PSK_WITH_AES_128_CBC_SHA256 0x030000AE # define TLS1_CK_PSK_WITH_AES_256_CBC_SHA384 0x030000AF # define TLS1_CK_PSK_WITH_NULL_SHA256 0x030000B0 @@ -450,42 +450,42 @@ __owur int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain) # define TLS1_CK_ADH_WITH_SEED_SHA 0x0300009B /* TLS v1.2 GCM ciphersuites from RFC5288 */ -# define TLS1_CK_RSA_WITH_AES_128_GAM_SHA256 0x0300009C -# define TLS1_CK_RSA_WITH_AES_256_GAM_SHA384 0x0300009D -# define TLS1_CK_DHE_RSA_WITH_AES_128_GAM_SHA256 0x0300009E -# define TLS1_CK_DHE_RSA_WITH_AES_256_GAM_SHA384 0x0300009F -# define TLS1_CK_DH_RSA_WITH_AES_128_GAM_SHA256 0x030000A0 -# define TLS1_CK_DH_RSA_WITH_AES_256_GAM_SHA384 0x030000A1 -# define TLS1_CK_DHE_DSS_WITH_AES_128_GAM_SHA256 0x030000A2 -# define TLS1_CK_DHE_DSS_WITH_AES_256_GAM_SHA384 0x030000A3 -# define TLS1_CK_DH_DSS_WITH_AES_128_GAM_SHA256 0x030000A4 -# define TLS1_CK_DH_DSS_WITH_AES_256_GAM_SHA384 0x030000A5 -# define TLS1_CK_ADH_WITH_AES_128_GAM_SHA256 0x030000A6 -# define TLS1_CK_ADH_WITH_AES_256_GAM_SHA384 0x030000A7 +# define TLS1_CK_RSA_WITH_AES_128_GCM_SHA256 0x0300009C +# define TLS1_CK_RSA_WITH_AES_256_GCM_SHA384 0x0300009D +# define TLS1_CK_DHE_RSA_WITH_AES_128_GCM_SHA256 0x0300009E +# define TLS1_CK_DHE_RSA_WITH_AES_256_GCM_SHA384 0x0300009F +# define TLS1_CK_DH_RSA_WITH_AES_128_GCM_SHA256 0x030000A0 +# define TLS1_CK_DH_RSA_WITH_AES_256_GCM_SHA384 0x030000A1 +# define TLS1_CK_DHE_DSS_WITH_AES_128_GCM_SHA256 0x030000A2 +# define TLS1_CK_DHE_DSS_WITH_AES_256_GCM_SHA384 0x030000A3 +# define TLS1_CK_DH_DSS_WITH_AES_128_GCM_SHA256 0x030000A4 +# define TLS1_CK_DH_DSS_WITH_AES_256_GCM_SHA384 0x030000A5 +# define TLS1_CK_ADH_WITH_AES_128_GCM_SHA256 0x030000A6 +# define TLS1_CK_ADH_WITH_AES_256_GCM_SHA384 0x030000A7 /* CCM ciphersuites from RFC6655 */ # define TLS1_CK_RSA_WITH_AES_128_CCM 0x0300C09C # define TLS1_CK_RSA_WITH_AES_256_CCM 0x0300C09D # define TLS1_CK_DHE_RSA_WITH_AES_128_CCM 0x0300C09E # define TLS1_CK_DHE_RSA_WITH_AES_256_CCM 0x0300C09F -# define TLS1_CK_RSA_WITH_AES_128_CAM_8 0x0300C0A0 -# define TLS1_CK_RSA_WITH_AES_256_CAM_8 0x0300C0A1 -# define TLS1_CK_DHE_RSA_WITH_AES_128_CAM_8 0x0300C0A2 -# define TLS1_CK_DHE_RSA_WITH_AES_256_CAM_8 0x0300C0A3 +# define TLS1_CK_RSA_WITH_AES_128_CCM_8 0x0300C0A0 +# define TLS1_CK_RSA_WITH_AES_256_CCM_8 0x0300C0A1 +# define TLS1_CK_DHE_RSA_WITH_AES_128_CCM_8 0x0300C0A2 +# define TLS1_CK_DHE_RSA_WITH_AES_256_CCM_8 0x0300C0A3 # define TLS1_CK_PSK_WITH_AES_128_CCM 0x0300C0A4 # define TLS1_CK_PSK_WITH_AES_256_CCM 0x0300C0A5 # define TLS1_CK_DHE_PSK_WITH_AES_128_CCM 0x0300C0A6 # define TLS1_CK_DHE_PSK_WITH_AES_256_CCM 0x0300C0A7 -# define TLS1_CK_PSK_WITH_AES_128_CAM_8 0x0300C0A8 -# define TLS1_CK_PSK_WITH_AES_256_CAM_8 0x0300C0A9 -# define TLS1_CK_DHE_PSK_WITH_AES_128_CAM_8 0x0300C0AA -# define TLS1_CK_DHE_PSK_WITH_AES_256_CAM_8 0x0300C0AB +# define TLS1_CK_PSK_WITH_AES_128_CCM_8 0x0300C0A8 +# define TLS1_CK_PSK_WITH_AES_256_CCM_8 0x0300C0A9 +# define TLS1_CK_DHE_PSK_WITH_AES_128_CCM_8 0x0300C0AA +# define TLS1_CK_DHE_PSK_WITH_AES_256_CCM_8 0x0300C0AB /* CCM ciphersuites from RFC7251 */ # define TLS1_CK_ECDHE_ECDSA_WITH_AES_128_CCM 0x0300C0AC # define TLS1_CK_ECDHE_ECDSA_WITH_AES_256_CCM 0x0300C0AD -# define TLS1_CK_ECDHE_ECDSA_WITH_AES_128_CAM_8 0x0300C0AE -# define TLS1_CK_ECDHE_ECDSA_WITH_AES_256_CAM_8 0x0300C0AF +# define TLS1_CK_ECDHE_ECDSA_WITH_AES_128_CCM_8 0x0300C0AE +# define TLS1_CK_ECDHE_ECDSA_WITH_AES_256_CCM_8 0x0300C0AF /* TLS 1.2 Camellia SHA-256 ciphersuites from RFC5932 */ # define TLS1_CK_RSA_WITH_CAMELLIA_128_CBC_SHA256 0x030000BA @@ -555,14 +555,14 @@ __owur int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain) # define TLS1_CK_ECDH_RSA_WITH_AES_256_SHA384 0x0300C02A /* ECDH GCM based ciphersuites from RFC5289 */ -# define TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GAM_SHA256 0x0300C02B -# define TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GAM_SHA384 0x0300C02C -# define TLS1_CK_ECDH_ECDSA_WITH_AES_128_GAM_SHA256 0x0300C02D -# define TLS1_CK_ECDH_ECDSA_WITH_AES_256_GAM_SHA384 0x0300C02E -# define TLS1_CK_ECDHE_RSA_WITH_AES_128_GAM_SHA256 0x0300C02F -# define TLS1_CK_ECDHE_RSA_WITH_AES_256_GAM_SHA384 0x0300C030 -# define TLS1_CK_ECDH_RSA_WITH_AES_128_GAM_SHA256 0x0300C031 -# define TLS1_CK_ECDH_RSA_WITH_AES_256_GAM_SHA384 0x0300C032 +# define TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 0x0300C02B +# define TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 0x0300C02C +# define TLS1_CK_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 0x0300C02D +# define TLS1_CK_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 0x0300C02E +# define TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256 0x0300C02F +# define TLS1_CK_ECDHE_RSA_WITH_AES_256_GCM_SHA384 0x0300C030 +# define TLS1_CK_ECDH_RSA_WITH_AES_128_GCM_SHA256 0x0300C031 +# define TLS1_CK_ECDH_RSA_WITH_AES_256_GCM_SHA384 0x0300C032 /* ECDHE PSK ciphersuites from RFC5489 */ # define TLS1_CK_ECDHE_PSK_WITH_RC4_128_SHA 0x0300C033 @@ -607,39 +607,39 @@ __owur int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain) # define TLS1_CK_RSA_PSK_WITH_CHACHA20_POLY1305 0x0300CCAE /* TLS v1.3 ciphersuites */ -# define TLS1_3_CK_AES_128_GAM_SHA256 0x03001301 -# define TLS1_3_CK_AES_256_GAM_SHA384 0x03001302 +# define TLS1_3_CK_AES_128_GCM_SHA256 0x03001301 +# define TLS1_3_CK_AES_256_GCM_SHA384 0x03001302 # define TLS1_3_CK_CHACHA20_POLY1305_SHA256 0x03001303 -# define TLS1_3_CK_AES_128_CAM_SHA256 0x03001304 -# define TLS1_3_CK_AES_128_CAM_8_SHA256 0x03001305 +# define TLS1_3_CK_AES_128_CCM_SHA256 0x03001304 +# define TLS1_3_CK_AES_128_CCM_8_SHA256 0x03001305 /* Aria ciphersuites from RFC6209 */ -# define TLS1_CK_RSA_WITH_ARIA_128_GAM_SHA256 0x0300C050 -# define TLS1_CK_RSA_WITH_ARIA_256_GAM_SHA384 0x0300C051 -# define TLS1_CK_DHE_RSA_WITH_ARIA_128_GAM_SHA256 0x0300C052 -# define TLS1_CK_DHE_RSA_WITH_ARIA_256_GAM_SHA384 0x0300C053 -# define TLS1_CK_DH_RSA_WITH_ARIA_128_GAM_SHA256 0x0300C054 -# define TLS1_CK_DH_RSA_WITH_ARIA_256_GAM_SHA384 0x0300C055 -# define TLS1_CK_DHE_DSS_WITH_ARIA_128_GAM_SHA256 0x0300C056 -# define TLS1_CK_DHE_DSS_WITH_ARIA_256_GAM_SHA384 0x0300C057 -# define TLS1_CK_DH_DSS_WITH_ARIA_128_GAM_SHA256 0x0300C058 -# define TLS1_CK_DH_DSS_WITH_ARIA_256_GAM_SHA384 0x0300C059 -# define TLS1_CK_DH_anon_WITH_ARIA_128_GAM_SHA256 0x0300C05A -# define TLS1_CK_DH_anon_WITH_ARIA_256_GAM_SHA384 0x0300C05B -# define TLS1_CK_ECDHE_ECDSA_WITH_ARIA_128_GAM_SHA256 0x0300C05C -# define TLS1_CK_ECDHE_ECDSA_WITH_ARIA_256_GAM_SHA384 0x0300C05D -# define TLS1_CK_ECDH_ECDSA_WITH_ARIA_128_GAM_SHA256 0x0300C05E -# define TLS1_CK_ECDH_ECDSA_WITH_ARIA_256_GAM_SHA384 0x0300C05F -# define TLS1_CK_ECDHE_RSA_WITH_ARIA_128_GAM_SHA256 0x0300C060 -# define TLS1_CK_ECDHE_RSA_WITH_ARIA_256_GAM_SHA384 0x0300C061 -# define TLS1_CK_ECDH_RSA_WITH_ARIA_128_GAM_SHA256 0x0300C062 -# define TLS1_CK_ECDH_RSA_WITH_ARIA_256_GAM_SHA384 0x0300C063 -# define TLS1_CK_PSK_WITH_ARIA_128_GAM_SHA256 0x0300C06A -# define TLS1_CK_PSK_WITH_ARIA_256_GAM_SHA384 0x0300C06B -# define TLS1_CK_DHE_PSK_WITH_ARIA_128_GAM_SHA256 0x0300C06C -# define TLS1_CK_DHE_PSK_WITH_ARIA_256_GAM_SHA384 0x0300C06D -# define TLS1_CK_RSA_PSK_WITH_ARIA_128_GAM_SHA256 0x0300C06E -# define TLS1_CK_RSA_PSK_WITH_ARIA_256_GAM_SHA384 0x0300C06F +# define TLS1_CK_RSA_WITH_ARIA_128_GCM_SHA256 0x0300C050 +# define TLS1_CK_RSA_WITH_ARIA_256_GCM_SHA384 0x0300C051 +# define TLS1_CK_DHE_RSA_WITH_ARIA_128_GCM_SHA256 0x0300C052 +# define TLS1_CK_DHE_RSA_WITH_ARIA_256_GCM_SHA384 0x0300C053 +# define TLS1_CK_DH_RSA_WITH_ARIA_128_GCM_SHA256 0x0300C054 +# define TLS1_CK_DH_RSA_WITH_ARIA_256_GCM_SHA384 0x0300C055 +# define TLS1_CK_DHE_DSS_WITH_ARIA_128_GCM_SHA256 0x0300C056 +# define TLS1_CK_DHE_DSS_WITH_ARIA_256_GCM_SHA384 0x0300C057 +# define TLS1_CK_DH_DSS_WITH_ARIA_128_GCM_SHA256 0x0300C058 +# define TLS1_CK_DH_DSS_WITH_ARIA_256_GCM_SHA384 0x0300C059 +# define TLS1_CK_DH_anon_WITH_ARIA_128_GCM_SHA256 0x0300C05A +# define TLS1_CK_DH_anon_WITH_ARIA_256_GCM_SHA384 0x0300C05B +# define TLS1_CK_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 0x0300C05C +# define TLS1_CK_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 0x0300C05D +# define TLS1_CK_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256 0x0300C05E +# define TLS1_CK_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384 0x0300C05F +# define TLS1_CK_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256 0x0300C060 +# define TLS1_CK_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384 0x0300C061 +# define TLS1_CK_ECDH_RSA_WITH_ARIA_128_GCM_SHA256 0x0300C062 +# define TLS1_CK_ECDH_RSA_WITH_ARIA_256_GCM_SHA384 0x0300C063 +# define TLS1_CK_PSK_WITH_ARIA_128_GCM_SHA256 0x0300C06A +# define TLS1_CK_PSK_WITH_ARIA_256_GCM_SHA384 0x0300C06B +# define TLS1_CK_DHE_PSK_WITH_ARIA_128_GCM_SHA256 0x0300C06C +# define TLS1_CK_DHE_PSK_WITH_ARIA_256_GCM_SHA384 0x0300C06D +# define TLS1_CK_RSA_PSK_WITH_ARIA_128_GCM_SHA256 0x0300C06E +# define TLS1_CK_RSA_PSK_WITH_ARIA_256_GCM_SHA384 0x0300C06F /* a bundle of RFC standard cipher names, generated from ssl3_ciphers[] */ # define TLS1_RFC_RSA_WITH_AES_128_SHA "TLS_RSA_WITH_AES_128_CBC_SHA" @@ -659,39 +659,39 @@ __owur int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain) # define TLS1_RFC_DHE_RSA_WITH_AES_256_SHA256 "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256" # define TLS1_RFC_ADH_WITH_AES_128_SHA256 "TLS_DH_anon_WITH_AES_128_CBC_SHA256" # define TLS1_RFC_ADH_WITH_AES_256_SHA256 "TLS_DH_anon_WITH_AES_256_CBC_SHA256" -# define TLS1_RFC_RSA_WITH_AES_128_GAM_SHA256 "TLS_RSA_WITH_AES_128_GAM_SHA256" -# define TLS1_RFC_RSA_WITH_AES_256_GAM_SHA384 "TLS_RSA_WITH_AES_256_GAM_SHA384" -# define TLS1_RFC_DHE_RSA_WITH_AES_128_GAM_SHA256 "TLS_DHE_RSA_WITH_AES_128_GAM_SHA256" -# define TLS1_RFC_DHE_RSA_WITH_AES_256_GAM_SHA384 "TLS_DHE_RSA_WITH_AES_256_GAM_SHA384" -# define TLS1_RFC_DHE_DSS_WITH_AES_128_GAM_SHA256 "TLS_DHE_DSS_WITH_AES_128_GAM_SHA256" -# define TLS1_RFC_DHE_DSS_WITH_AES_256_GAM_SHA384 "TLS_DHE_DSS_WITH_AES_256_GAM_SHA384" -# define TLS1_RFC_ADH_WITH_AES_128_GAM_SHA256 "TLS_DH_anon_WITH_AES_128_GAM_SHA256" -# define TLS1_RFC_ADH_WITH_AES_256_GAM_SHA384 "TLS_DH_anon_WITH_AES_256_GAM_SHA384" +# define TLS1_RFC_RSA_WITH_AES_128_GCM_SHA256 "TLS_RSA_WITH_AES_128_GCM_SHA256" +# define TLS1_RFC_RSA_WITH_AES_256_GCM_SHA384 "TLS_RSA_WITH_AES_256_GCM_SHA384" +# define TLS1_RFC_DHE_RSA_WITH_AES_128_GCM_SHA256 "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256" +# define TLS1_RFC_DHE_RSA_WITH_AES_256_GCM_SHA384 "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384" +# define TLS1_RFC_DHE_DSS_WITH_AES_128_GCM_SHA256 "TLS_DHE_DSS_WITH_AES_128_GCM_SHA256" +# define TLS1_RFC_DHE_DSS_WITH_AES_256_GCM_SHA384 "TLS_DHE_DSS_WITH_AES_256_GCM_SHA384" +# define TLS1_RFC_ADH_WITH_AES_128_GCM_SHA256 "TLS_DH_anon_WITH_AES_128_GCM_SHA256" +# define TLS1_RFC_ADH_WITH_AES_256_GCM_SHA384 "TLS_DH_anon_WITH_AES_256_GCM_SHA384" # define TLS1_RFC_RSA_WITH_AES_128_CCM "TLS_RSA_WITH_AES_128_CCM" # define TLS1_RFC_RSA_WITH_AES_256_CCM "TLS_RSA_WITH_AES_256_CCM" # define TLS1_RFC_DHE_RSA_WITH_AES_128_CCM "TLS_DHE_RSA_WITH_AES_128_CCM" # define TLS1_RFC_DHE_RSA_WITH_AES_256_CCM "TLS_DHE_RSA_WITH_AES_256_CCM" -# define TLS1_RFC_RSA_WITH_AES_128_CAM_8 "TLS_RSA_WITH_AES_128_CAM_8" -# define TLS1_RFC_RSA_WITH_AES_256_CAM_8 "TLS_RSA_WITH_AES_256_CAM_8" -# define TLS1_RFC_DHE_RSA_WITH_AES_128_CAM_8 "TLS_DHE_RSA_WITH_AES_128_CAM_8" -# define TLS1_RFC_DHE_RSA_WITH_AES_256_CAM_8 "TLS_DHE_RSA_WITH_AES_256_CAM_8" +# define TLS1_RFC_RSA_WITH_AES_128_CCM_8 "TLS_RSA_WITH_AES_128_CCM_8" +# define TLS1_RFC_RSA_WITH_AES_256_CCM_8 "TLS_RSA_WITH_AES_256_CCM_8" +# define TLS1_RFC_DHE_RSA_WITH_AES_128_CCM_8 "TLS_DHE_RSA_WITH_AES_128_CCM_8" +# define TLS1_RFC_DHE_RSA_WITH_AES_256_CCM_8 "TLS_DHE_RSA_WITH_AES_256_CCM_8" # define TLS1_RFC_PSK_WITH_AES_128_CCM "TLS_PSK_WITH_AES_128_CCM" # define TLS1_RFC_PSK_WITH_AES_256_CCM "TLS_PSK_WITH_AES_256_CCM" # define TLS1_RFC_DHE_PSK_WITH_AES_128_CCM "TLS_DHE_PSK_WITH_AES_128_CCM" # define TLS1_RFC_DHE_PSK_WITH_AES_256_CCM "TLS_DHE_PSK_WITH_AES_256_CCM" -# define TLS1_RFC_PSK_WITH_AES_128_CAM_8 "TLS_PSK_WITH_AES_128_CAM_8" -# define TLS1_RFC_PSK_WITH_AES_256_CAM_8 "TLS_PSK_WITH_AES_256_CAM_8" -# define TLS1_RFC_DHE_PSK_WITH_AES_128_CAM_8 "TLS_PSK_DHE_WITH_AES_128_CAM_8" -# define TLS1_RFC_DHE_PSK_WITH_AES_256_CAM_8 "TLS_PSK_DHE_WITH_AES_256_CAM_8" +# define TLS1_RFC_PSK_WITH_AES_128_CCM_8 "TLS_PSK_WITH_AES_128_CCM_8" +# define TLS1_RFC_PSK_WITH_AES_256_CCM_8 "TLS_PSK_WITH_AES_256_CCM_8" +# define TLS1_RFC_DHE_PSK_WITH_AES_128_CCM_8 "TLS_PSK_DHE_WITH_AES_128_CCM_8" +# define TLS1_RFC_DHE_PSK_WITH_AES_256_CCM_8 "TLS_PSK_DHE_WITH_AES_256_CCM_8" # define TLS1_RFC_ECDHE_ECDSA_WITH_AES_128_CCM "TLS_ECDHE_ECDSA_WITH_AES_128_CCM" # define TLS1_RFC_ECDHE_ECDSA_WITH_AES_256_CCM "TLS_ECDHE_ECDSA_WITH_AES_256_CCM" -# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_128_CAM_8 "TLS_ECDHE_ECDSA_WITH_AES_128_CAM_8" -# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_256_CAM_8 "TLS_ECDHE_ECDSA_WITH_AES_256_CAM_8" -# define TLS1_3_RFC_AES_128_GAM_SHA256 "TLS_AES_128_GAM_SHA256" -# define TLS1_3_RFC_AES_256_GAM_SHA384 "TLS_AES_256_GAM_SHA384" +# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_128_CCM_8 "TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8" +# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_256_CCM_8 "TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8" +# define TLS1_3_RFC_AES_128_GCM_SHA256 "TLS_AES_128_GCM_SHA256" +# define TLS1_3_RFC_AES_256_GCM_SHA384 "TLS_AES_256_GCM_SHA384" # define TLS1_3_RFC_CHACHA20_POLY1305_SHA256 "TLS_CHACHA20_POLY1305_SHA256" -# define TLS1_3_RFC_AES_128_CAM_SHA256 "TLS_AES_128_CAM_SHA256" -# define TLS1_3_RFC_AES_128_CAM_8_SHA256 "TLS_AES_128_CAM_8_SHA256" +# define TLS1_3_RFC_AES_128_CCM_SHA256 "TLS_AES_128_CCM_SHA256" +# define TLS1_3_RFC_AES_128_CCM_8_SHA256 "TLS_AES_128_CCM_8_SHA256" # define TLS1_RFC_ECDHE_ECDSA_WITH_NULL_SHA "TLS_ECDHE_ECDSA_WITH_NULL_SHA" # define TLS1_RFC_ECDHE_ECDSA_WITH_DES_192_CBC3_SHA "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA" # define TLS1_RFC_ECDHE_ECDSA_WITH_AES_128_CBC_SHA "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA" @@ -708,10 +708,10 @@ __owur int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain) # define TLS1_RFC_ECDHE_ECDSA_WITH_AES_256_SHA384 "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384" # define TLS1_RFC_ECDHE_RSA_WITH_AES_128_SHA256 "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" # define TLS1_RFC_ECDHE_RSA_WITH_AES_256_SHA384 "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384" -# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_128_GAM_SHA256 "TLS_ECDHE_ECDSA_WITH_AES_128_GAM_SHA256" -# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_256_GAM_SHA384 "TLS_ECDHE_ECDSA_WITH_AES_256_GAM_SHA384" -# define TLS1_RFC_ECDHE_RSA_WITH_AES_128_GAM_SHA256 "TLS_ECDHE_RSA_WITH_AES_128_GAM_SHA256" -# define TLS1_RFC_ECDHE_RSA_WITH_AES_256_GAM_SHA384 "TLS_ECDHE_RSA_WITH_AES_256_GAM_SHA384" +# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256" +# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384" +# define TLS1_RFC_ECDHE_RSA_WITH_AES_128_GCM_SHA256 "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256" +# define TLS1_RFC_ECDHE_RSA_WITH_AES_256_GCM_SHA384 "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384" # define TLS1_RFC_PSK_WITH_NULL_SHA "TLS_PSK_WITH_NULL_SHA" # define TLS1_RFC_DHE_PSK_WITH_NULL_SHA "TLS_DHE_PSK_WITH_NULL_SHA" # define TLS1_RFC_RSA_PSK_WITH_NULL_SHA "TLS_RSA_PSK_WITH_NULL_SHA" @@ -724,12 +724,12 @@ __owur int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain) # define TLS1_RFC_RSA_PSK_WITH_3DES_EDE_CBC_SHA "TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA" # define TLS1_RFC_RSA_PSK_WITH_AES_128_CBC_SHA "TLS_RSA_PSK_WITH_AES_128_CBC_SHA" # define TLS1_RFC_RSA_PSK_WITH_AES_256_CBC_SHA "TLS_RSA_PSK_WITH_AES_256_CBC_SHA" -# define TLS1_RFC_PSK_WITH_AES_128_GAM_SHA256 "TLS_PSK_WITH_AES_128_GAM_SHA256" -# define TLS1_RFC_PSK_WITH_AES_256_GAM_SHA384 "TLS_PSK_WITH_AES_256_GAM_SHA384" -# define TLS1_RFC_DHE_PSK_WITH_AES_128_GAM_SHA256 "TLS_DHE_PSK_WITH_AES_128_GAM_SHA256" -# define TLS1_RFC_DHE_PSK_WITH_AES_256_GAM_SHA384 "TLS_DHE_PSK_WITH_AES_256_GAM_SHA384" -# define TLS1_RFC_RSA_PSK_WITH_AES_128_GAM_SHA256 "TLS_RSA_PSK_WITH_AES_128_GAM_SHA256" -# define TLS1_RFC_RSA_PSK_WITH_AES_256_GAM_SHA384 "TLS_RSA_PSK_WITH_AES_256_GAM_SHA384" +# define TLS1_RFC_PSK_WITH_AES_128_GCM_SHA256 "TLS_PSK_WITH_AES_128_GCM_SHA256" +# define TLS1_RFC_PSK_WITH_AES_256_GCM_SHA384 "TLS_PSK_WITH_AES_256_GCM_SHA384" +# define TLS1_RFC_DHE_PSK_WITH_AES_128_GCM_SHA256 "TLS_DHE_PSK_WITH_AES_128_GCM_SHA256" +# define TLS1_RFC_DHE_PSK_WITH_AES_256_GCM_SHA384 "TLS_DHE_PSK_WITH_AES_256_GCM_SHA384" +# define TLS1_RFC_RSA_PSK_WITH_AES_128_GCM_SHA256 "TLS_RSA_PSK_WITH_AES_128_GCM_SHA256" +# define TLS1_RFC_RSA_PSK_WITH_AES_256_GCM_SHA384 "TLS_RSA_PSK_WITH_AES_256_GCM_SHA384" # define TLS1_RFC_PSK_WITH_AES_128_CBC_SHA256 "TLS_PSK_WITH_AES_128_CBC_SHA256" # define TLS1_RFC_PSK_WITH_AES_256_CBC_SHA384 "TLS_PSK_WITH_AES_256_CBC_SHA384" # define TLS1_RFC_PSK_WITH_NULL_SHA256 "TLS_PSK_WITH_NULL_SHA256" @@ -805,32 +805,32 @@ __owur int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain) # define TLS1_RFC_PSK_WITH_RC4_128_SHA "TLS_PSK_WITH_RC4_128_SHA" # define TLS1_RFC_RSA_PSK_WITH_RC4_128_SHA "TLS_RSA_PSK_WITH_RC4_128_SHA" # define TLS1_RFC_DHE_PSK_WITH_RC4_128_SHA "TLS_DHE_PSK_WITH_RC4_128_SHA" -# define TLS1_RFC_RSA_WITH_ARIA_128_GAM_SHA256 "TLS_RSA_WITH_ARIA_128_GAM_SHA256" -# define TLS1_RFC_RSA_WITH_ARIA_256_GAM_SHA384 "TLS_RSA_WITH_ARIA_256_GAM_SHA384" -# define TLS1_RFC_DHE_RSA_WITH_ARIA_128_GAM_SHA256 "TLS_DHE_RSA_WITH_ARIA_128_GAM_SHA256" -# define TLS1_RFC_DHE_RSA_WITH_ARIA_256_GAM_SHA384 "TLS_DHE_RSA_WITH_ARIA_256_GAM_SHA384" -# define TLS1_RFC_DH_RSA_WITH_ARIA_128_GAM_SHA256 "TLS_DH_RSA_WITH_ARIA_128_GAM_SHA256" -# define TLS1_RFC_DH_RSA_WITH_ARIA_256_GAM_SHA384 "TLS_DH_RSA_WITH_ARIA_256_GAM_SHA384" -# define TLS1_RFC_DHE_DSS_WITH_ARIA_128_GAM_SHA256 "TLS_DHE_DSS_WITH_ARIA_128_GAM_SHA256" -# define TLS1_RFC_DHE_DSS_WITH_ARIA_256_GAM_SHA384 "TLS_DHE_DSS_WITH_ARIA_256_GAM_SHA384" -# define TLS1_RFC_DH_DSS_WITH_ARIA_128_GAM_SHA256 "TLS_DH_DSS_WITH_ARIA_128_GAM_SHA256" -# define TLS1_RFC_DH_DSS_WITH_ARIA_256_GAM_SHA384 "TLS_DH_DSS_WITH_ARIA_256_GAM_SHA384" -# define TLS1_RFC_DH_anon_WITH_ARIA_128_GAM_SHA256 "TLS_DH_anon_WITH_ARIA_128_GAM_SHA256" -# define TLS1_RFC_DH_anon_WITH_ARIA_256_GAM_SHA384 "TLS_DH_anon_WITH_ARIA_256_GAM_SHA384" -# define TLS1_RFC_ECDHE_ECDSA_WITH_ARIA_128_GAM_SHA256 "TLS_ECDHE_ECDSA_WITH_ARIA_128_GAM_SHA256" -# define TLS1_RFC_ECDHE_ECDSA_WITH_ARIA_256_GAM_SHA384 "TLS_ECDHE_ECDSA_WITH_ARIA_256_GAM_SHA384" -# define TLS1_RFC_ECDH_ECDSA_WITH_ARIA_128_GAM_SHA256 "TLS_ECDH_ECDSA_WITH_ARIA_128_GAM_SHA256" -# define TLS1_RFC_ECDH_ECDSA_WITH_ARIA_256_GAM_SHA384 "TLS_ECDH_ECDSA_WITH_ARIA_256_GAM_SHA384" -# define TLS1_RFC_ECDHE_RSA_WITH_ARIA_128_GAM_SHA256 "TLS_ECDHE_RSA_WITH_ARIA_128_GAM_SHA256" -# define TLS1_RFC_ECDHE_RSA_WITH_ARIA_256_GAM_SHA384 "TLS_ECDHE_RSA_WITH_ARIA_256_GAM_SHA384" -# define TLS1_RFC_ECDH_RSA_WITH_ARIA_128_GAM_SHA256 "TLS_ECDH_RSA_WITH_ARIA_128_GAM_SHA256" -# define TLS1_RFC_ECDH_RSA_WITH_ARIA_256_GAM_SHA384 "TLS_ECDH_RSA_WITH_ARIA_256_GAM_SHA384" -# define TLS1_RFC_PSK_WITH_ARIA_128_GAM_SHA256 "TLS_PSK_WITH_ARIA_128_GAM_SHA256" -# define TLS1_RFC_PSK_WITH_ARIA_256_GAM_SHA384 "TLS_PSK_WITH_ARIA_256_GAM_SHA384" -# define TLS1_RFC_DHE_PSK_WITH_ARIA_128_GAM_SHA256 "TLS_DHE_PSK_WITH_ARIA_128_GAM_SHA256" -# define TLS1_RFC_DHE_PSK_WITH_ARIA_256_GAM_SHA384 "TLS_DHE_PSK_WITH_ARIA_256_GAM_SHA384" -# define TLS1_RFC_RSA_PSK_WITH_ARIA_128_GAM_SHA256 "TLS_RSA_PSK_WITH_ARIA_128_GAM_SHA256" -# define TLS1_RFC_RSA_PSK_WITH_ARIA_256_GAM_SHA384 "TLS_RSA_PSK_WITH_ARIA_256_GAM_SHA384" +# define TLS1_RFC_RSA_WITH_ARIA_128_GCM_SHA256 "TLS_RSA_WITH_ARIA_128_GCM_SHA256" +# define TLS1_RFC_RSA_WITH_ARIA_256_GCM_SHA384 "TLS_RSA_WITH_ARIA_256_GCM_SHA384" +# define TLS1_RFC_DHE_RSA_WITH_ARIA_128_GCM_SHA256 "TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256" +# define TLS1_RFC_DHE_RSA_WITH_ARIA_256_GCM_SHA384 "TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384" +# define TLS1_RFC_DH_RSA_WITH_ARIA_128_GCM_SHA256 "TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256" +# define TLS1_RFC_DH_RSA_WITH_ARIA_256_GCM_SHA384 "TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384" +# define TLS1_RFC_DHE_DSS_WITH_ARIA_128_GCM_SHA256 "TLS_DHE_DSS_WITH_ARIA_128_GCM_SHA256" +# define TLS1_RFC_DHE_DSS_WITH_ARIA_256_GCM_SHA384 "TLS_DHE_DSS_WITH_ARIA_256_GCM_SHA384" +# define TLS1_RFC_DH_DSS_WITH_ARIA_128_GCM_SHA256 "TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256" +# define TLS1_RFC_DH_DSS_WITH_ARIA_256_GCM_SHA384 "TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384" +# define TLS1_RFC_DH_anon_WITH_ARIA_128_GCM_SHA256 "TLS_DH_anon_WITH_ARIA_128_GCM_SHA256" +# define TLS1_RFC_DH_anon_WITH_ARIA_256_GCM_SHA384 "TLS_DH_anon_WITH_ARIA_256_GCM_SHA384" +# define TLS1_RFC_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 "TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256" +# define TLS1_RFC_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 "TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384" +# define TLS1_RFC_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256 "TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256" +# define TLS1_RFC_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384 "TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384" +# define TLS1_RFC_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256 "TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256" +# define TLS1_RFC_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384 "TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384" +# define TLS1_RFC_ECDH_RSA_WITH_ARIA_128_GCM_SHA256 "TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256" +# define TLS1_RFC_ECDH_RSA_WITH_ARIA_256_GCM_SHA384 "TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384" +# define TLS1_RFC_PSK_WITH_ARIA_128_GCM_SHA256 "TLS_PSK_WITH_ARIA_128_GCM_SHA256" +# define TLS1_RFC_PSK_WITH_ARIA_256_GCM_SHA384 "TLS_PSK_WITH_ARIA_256_GCM_SHA384" +# define TLS1_RFC_DHE_PSK_WITH_ARIA_128_GCM_SHA256 "TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256" +# define TLS1_RFC_DHE_PSK_WITH_ARIA_256_GCM_SHA384 "TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384" +# define TLS1_RFC_RSA_PSK_WITH_ARIA_128_GCM_SHA256 "TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256" +# define TLS1_RFC_RSA_PSK_WITH_ARIA_256_GCM_SHA384 "TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384" /* @@ -907,12 +907,12 @@ __owur int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain) # define TLS1_TXT_RSA_PSK_WITH_AES_256_CBC_SHA "RSA-PSK-AES256-CBC-SHA" /* PSK ciphersuites from RFC 5487 */ -# define TLS1_TXT_PSK_WITH_AES_128_GAM_SHA256 "PSK-AES128-GCM-SHA256" -# define TLS1_TXT_PSK_WITH_AES_256_GAM_SHA384 "PSK-AES256-GCM-SHA384" -# define TLS1_TXT_DHE_PSK_WITH_AES_128_GAM_SHA256 "DHE-PSK-AES128-GCM-SHA256" -# define TLS1_TXT_DHE_PSK_WITH_AES_256_GAM_SHA384 "DHE-PSK-AES256-GCM-SHA384" -# define TLS1_TXT_RSA_PSK_WITH_AES_128_GAM_SHA256 "RSA-PSK-AES128-GCM-SHA256" -# define TLS1_TXT_RSA_PSK_WITH_AES_256_GAM_SHA384 "RSA-PSK-AES256-GCM-SHA384" +# define TLS1_TXT_PSK_WITH_AES_128_GCM_SHA256 "PSK-AES128-GCM-SHA256" +# define TLS1_TXT_PSK_WITH_AES_256_GCM_SHA384 "PSK-AES256-GCM-SHA384" +# define TLS1_TXT_DHE_PSK_WITH_AES_128_GCM_SHA256 "DHE-PSK-AES128-GCM-SHA256" +# define TLS1_TXT_DHE_PSK_WITH_AES_256_GCM_SHA384 "DHE-PSK-AES256-GCM-SHA384" +# define TLS1_TXT_RSA_PSK_WITH_AES_128_GCM_SHA256 "RSA-PSK-AES128-GCM-SHA256" +# define TLS1_TXT_RSA_PSK_WITH_AES_256_GCM_SHA384 "RSA-PSK-AES256-GCM-SHA384" # define TLS1_TXT_PSK_WITH_AES_128_CBC_SHA256 "PSK-AES128-CBC-SHA256" # define TLS1_TXT_PSK_WITH_AES_256_CBC_SHA384 "PSK-AES256-CBC-SHA384" @@ -1003,18 +1003,18 @@ __owur int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain) # define TLS1_TXT_ADH_WITH_AES_256_SHA256 "ADH-AES256-SHA256" /* TLS v1.2 GCM ciphersuites from RFC5288 */ -# define TLS1_TXT_RSA_WITH_AES_128_GAM_SHA256 "AES128-GCM-SHA256" -# define TLS1_TXT_RSA_WITH_AES_256_GAM_SHA384 "AES256-GCM-SHA384" -# define TLS1_TXT_DHE_RSA_WITH_AES_128_GAM_SHA256 "DHE-RSA-AES128-GCM-SHA256" -# define TLS1_TXT_DHE_RSA_WITH_AES_256_GAM_SHA384 "DHE-RSA-AES256-GCM-SHA384" -# define TLS1_TXT_DH_RSA_WITH_AES_128_GAM_SHA256 "DH-RSA-AES128-GCM-SHA256" -# define TLS1_TXT_DH_RSA_WITH_AES_256_GAM_SHA384 "DH-RSA-AES256-GCM-SHA384" -# define TLS1_TXT_DHE_DSS_WITH_AES_128_GAM_SHA256 "DHE-DSS-AES128-GCM-SHA256" -# define TLS1_TXT_DHE_DSS_WITH_AES_256_GAM_SHA384 "DHE-DSS-AES256-GCM-SHA384" -# define TLS1_TXT_DH_DSS_WITH_AES_128_GAM_SHA256 "DH-DSS-AES128-GCM-SHA256" -# define TLS1_TXT_DH_DSS_WITH_AES_256_GAM_SHA384 "DH-DSS-AES256-GCM-SHA384" -# define TLS1_TXT_ADH_WITH_AES_128_GAM_SHA256 "ADH-AES128-GCM-SHA256" -# define TLS1_TXT_ADH_WITH_AES_256_GAM_SHA384 "ADH-AES256-GCM-SHA384" +# define TLS1_TXT_RSA_WITH_AES_128_GCM_SHA256 "AES128-GCM-SHA256" +# define TLS1_TXT_RSA_WITH_AES_256_GCM_SHA384 "AES256-GCM-SHA384" +# define TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256 "DHE-RSA-AES128-GCM-SHA256" +# define TLS1_TXT_DHE_RSA_WITH_AES_256_GCM_SHA384 "DHE-RSA-AES256-GCM-SHA384" +# define TLS1_TXT_DH_RSA_WITH_AES_128_GCM_SHA256 "DH-RSA-AES128-GCM-SHA256" +# define TLS1_TXT_DH_RSA_WITH_AES_256_GCM_SHA384 "DH-RSA-AES256-GCM-SHA384" +# define TLS1_TXT_DHE_DSS_WITH_AES_128_GCM_SHA256 "DHE-DSS-AES128-GCM-SHA256" +# define TLS1_TXT_DHE_DSS_WITH_AES_256_GCM_SHA384 "DHE-DSS-AES256-GCM-SHA384" +# define TLS1_TXT_DH_DSS_WITH_AES_128_GCM_SHA256 "DH-DSS-AES128-GCM-SHA256" +# define TLS1_TXT_DH_DSS_WITH_AES_256_GCM_SHA384 "DH-DSS-AES256-GCM-SHA384" +# define TLS1_TXT_ADH_WITH_AES_128_GCM_SHA256 "ADH-AES128-GCM-SHA256" +# define TLS1_TXT_ADH_WITH_AES_256_GCM_SHA384 "ADH-AES256-GCM-SHA384" /* CCM ciphersuites from RFC6655 */ # define TLS1_TXT_RSA_WITH_AES_128_CCM "AES128-CCM" @@ -1022,26 +1022,26 @@ __owur int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain) # define TLS1_TXT_DHE_RSA_WITH_AES_128_CCM "DHE-RSA-AES128-CCM" # define TLS1_TXT_DHE_RSA_WITH_AES_256_CCM "DHE-RSA-AES256-CCM" -# define TLS1_TXT_RSA_WITH_AES_128_CAM_8 "AES128-CCM8" -# define TLS1_TXT_RSA_WITH_AES_256_CAM_8 "AES256-CCM8" -# define TLS1_TXT_DHE_RSA_WITH_AES_128_CAM_8 "DHE-RSA-AES128-CCM8" -# define TLS1_TXT_DHE_RSA_WITH_AES_256_CAM_8 "DHE-RSA-AES256-CCM8" +# define TLS1_TXT_RSA_WITH_AES_128_CCM_8 "AES128-CCM8" +# define TLS1_TXT_RSA_WITH_AES_256_CCM_8 "AES256-CCM8" +# define TLS1_TXT_DHE_RSA_WITH_AES_128_CCM_8 "DHE-RSA-AES128-CCM8" +# define TLS1_TXT_DHE_RSA_WITH_AES_256_CCM_8 "DHE-RSA-AES256-CCM8" # define TLS1_TXT_PSK_WITH_AES_128_CCM "PSK-AES128-CCM" # define TLS1_TXT_PSK_WITH_AES_256_CCM "PSK-AES256-CCM" # define TLS1_TXT_DHE_PSK_WITH_AES_128_CCM "DHE-PSK-AES128-CCM" # define TLS1_TXT_DHE_PSK_WITH_AES_256_CCM "DHE-PSK-AES256-CCM" -# define TLS1_TXT_PSK_WITH_AES_128_CAM_8 "PSK-AES128-CCM8" -# define TLS1_TXT_PSK_WITH_AES_256_CAM_8 "PSK-AES256-CCM8" -# define TLS1_TXT_DHE_PSK_WITH_AES_128_CAM_8 "DHE-PSK-AES128-CCM8" -# define TLS1_TXT_DHE_PSK_WITH_AES_256_CAM_8 "DHE-PSK-AES256-CCM8" +# define TLS1_TXT_PSK_WITH_AES_128_CCM_8 "PSK-AES128-CCM8" +# define TLS1_TXT_PSK_WITH_AES_256_CCM_8 "PSK-AES256-CCM8" +# define TLS1_TXT_DHE_PSK_WITH_AES_128_CCM_8 "DHE-PSK-AES128-CCM8" +# define TLS1_TXT_DHE_PSK_WITH_AES_256_CCM_8 "DHE-PSK-AES256-CCM8" /* CCM ciphersuites from RFC7251 */ # define TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_CCM "ECDHE-ECDSA-AES128-CCM" # define TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_CCM "ECDHE-ECDSA-AES256-CCM" -# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_CAM_8 "ECDHE-ECDSA-AES128-CCM8" -# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_CAM_8 "ECDHE-ECDSA-AES256-CCM8" +# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_CCM_8 "ECDHE-ECDSA-AES128-CCM8" +# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_CCM_8 "ECDHE-ECDSA-AES256-CCM8" /* ECDH HMAC based ciphersuites from RFC5289 */ # define TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_SHA256 "ECDHE-ECDSA-AES128-SHA256" @@ -1054,18 +1054,18 @@ __owur int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain) # define TLS1_TXT_ECDH_RSA_WITH_AES_256_SHA384 "ECDH-RSA-AES256-SHA384" /* ECDH GCM based ciphersuites from RFC5289 */ -# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_GAM_SHA256 "ECDHE-ECDSA-AES128-GCM-SHA256" -# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_GAM_SHA384 "ECDHE-ECDSA-AES256-GCM-SHA384" -# define TLS1_TXT_ECDH_ECDSA_WITH_AES_128_GAM_SHA256 "ECDH-ECDSA-AES128-GCM-SHA256" -# define TLS1_TXT_ECDH_ECDSA_WITH_AES_256_GAM_SHA384 "ECDH-ECDSA-AES256-GCM-SHA384" -# define TLS1_TXT_ECDHE_RSA_WITH_AES_128_GAM_SHA256 "ECDHE-RSA-AES128-GCM-SHA256" -# define TLS1_TXT_ECDHE_RSA_WITH_AES_256_GAM_SHA384 "ECDHE-RSA-AES256-GCM-SHA384" -# define TLS1_TXT_ECDH_RSA_WITH_AES_128_GAM_SHA256 "ECDH-RSA-AES128-GCM-SHA256" -# define TLS1_TXT_ECDH_RSA_WITH_AES_256_GAM_SHA384 "ECDH-RSA-AES256-GCM-SHA384" +# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 "ECDHE-ECDSA-AES128-GCM-SHA256" +# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 "ECDHE-ECDSA-AES256-GCM-SHA384" +# define TLS1_TXT_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 "ECDH-ECDSA-AES128-GCM-SHA256" +# define TLS1_TXT_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 "ECDH-ECDSA-AES256-GCM-SHA384" +# define TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 "ECDHE-RSA-AES128-GCM-SHA256" +# define TLS1_TXT_ECDHE_RSA_WITH_AES_256_GCM_SHA384 "ECDHE-RSA-AES256-GCM-SHA384" +# define TLS1_TXT_ECDH_RSA_WITH_AES_128_GCM_SHA256 "ECDH-RSA-AES128-GCM-SHA256" +# define TLS1_TXT_ECDH_RSA_WITH_AES_256_GCM_SHA384 "ECDH-RSA-AES256-GCM-SHA384" /* TLS v1.2 PSK GCM ciphersuites from RFC5487 */ -# define TLS1_TXT_PSK_WITH_AES_128_GAM_SHA256 "PSK-AES128-GCM-SHA256" -# define TLS1_TXT_PSK_WITH_AES_256_GAM_SHA384 "PSK-AES256-GCM-SHA384" +# define TLS1_TXT_PSK_WITH_AES_128_GCM_SHA256 "PSK-AES128-GCM-SHA256" +# define TLS1_TXT_PSK_WITH_AES_256_GCM_SHA384 "PSK-AES256-GCM-SHA384" /* ECDHE PSK ciphersuites from RFC 5489 */ # define TLS1_TXT_ECDHE_PSK_WITH_RC4_128_SHA "ECDHE-PSK-RC4-SHA" @@ -1100,32 +1100,32 @@ __owur int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain) # define TLS1_TXT_RSA_PSK_WITH_CHACHA20_POLY1305 "RSA-PSK-CHACHA20-POLY1305" /* Aria ciphersuites from RFC6209 */ -# define TLS1_TXT_RSA_WITH_ARIA_128_GAM_SHA256 "ARIA128-GCM-SHA256" -# define TLS1_TXT_RSA_WITH_ARIA_256_GAM_SHA384 "ARIA256-GCM-SHA384" -# define TLS1_TXT_DHE_RSA_WITH_ARIA_128_GAM_SHA256 "DHE-RSA-ARIA128-GCM-SHA256" -# define TLS1_TXT_DHE_RSA_WITH_ARIA_256_GAM_SHA384 "DHE-RSA-ARIA256-GCM-SHA384" -# define TLS1_TXT_DH_RSA_WITH_ARIA_128_GAM_SHA256 "DH-RSA-ARIA128-GCM-SHA256" -# define TLS1_TXT_DH_RSA_WITH_ARIA_256_GAM_SHA384 "DH-RSA-ARIA256-GCM-SHA384" -# define TLS1_TXT_DHE_DSS_WITH_ARIA_128_GAM_SHA256 "DHE-DSS-ARIA128-GCM-SHA256" -# define TLS1_TXT_DHE_DSS_WITH_ARIA_256_GAM_SHA384 "DHE-DSS-ARIA256-GCM-SHA384" -# define TLS1_TXT_DH_DSS_WITH_ARIA_128_GAM_SHA256 "DH-DSS-ARIA128-GCM-SHA256" -# define TLS1_TXT_DH_DSS_WITH_ARIA_256_GAM_SHA384 "DH-DSS-ARIA256-GCM-SHA384" -# define TLS1_TXT_DH_anon_WITH_ARIA_128_GAM_SHA256 "ADH-ARIA128-GCM-SHA256" -# define TLS1_TXT_DH_anon_WITH_ARIA_256_GAM_SHA384 "ADH-ARIA256-GCM-SHA384" -# define TLS1_TXT_ECDHE_ECDSA_WITH_ARIA_128_GAM_SHA256 "ECDHE-ECDSA-ARIA128-GCM-SHA256" -# define TLS1_TXT_ECDHE_ECDSA_WITH_ARIA_256_GAM_SHA384 "ECDHE-ECDSA-ARIA256-GCM-SHA384" -# define TLS1_TXT_ECDH_ECDSA_WITH_ARIA_128_GAM_SHA256 "ECDH-ECDSA-ARIA128-GCM-SHA256" -# define TLS1_TXT_ECDH_ECDSA_WITH_ARIA_256_GAM_SHA384 "ECDH-ECDSA-ARIA256-GCM-SHA384" -# define TLS1_TXT_ECDHE_RSA_WITH_ARIA_128_GAM_SHA256 "ECDHE-ARIA128-GCM-SHA256" -# define TLS1_TXT_ECDHE_RSA_WITH_ARIA_256_GAM_SHA384 "ECDHE-ARIA256-GCM-SHA384" -# define TLS1_TXT_ECDH_RSA_WITH_ARIA_128_GAM_SHA256 "ECDH-ARIA128-GCM-SHA256" -# define TLS1_TXT_ECDH_RSA_WITH_ARIA_256_GAM_SHA384 "ECDH-ARIA256-GCM-SHA384" -# define TLS1_TXT_PSK_WITH_ARIA_128_GAM_SHA256 "PSK-ARIA128-GCM-SHA256" -# define TLS1_TXT_PSK_WITH_ARIA_256_GAM_SHA384 "PSK-ARIA256-GCM-SHA384" -# define TLS1_TXT_DHE_PSK_WITH_ARIA_128_GAM_SHA256 "DHE-PSK-ARIA128-GCM-SHA256" -# define TLS1_TXT_DHE_PSK_WITH_ARIA_256_GAM_SHA384 "DHE-PSK-ARIA256-GCM-SHA384" -# define TLS1_TXT_RSA_PSK_WITH_ARIA_128_GAM_SHA256 "RSA-PSK-ARIA128-GCM-SHA256" -# define TLS1_TXT_RSA_PSK_WITH_ARIA_256_GAM_SHA384 "RSA-PSK-ARIA256-GCM-SHA384" +# define TLS1_TXT_RSA_WITH_ARIA_128_GCM_SHA256 "ARIA128-GCM-SHA256" +# define TLS1_TXT_RSA_WITH_ARIA_256_GCM_SHA384 "ARIA256-GCM-SHA384" +# define TLS1_TXT_DHE_RSA_WITH_ARIA_128_GCM_SHA256 "DHE-RSA-ARIA128-GCM-SHA256" +# define TLS1_TXT_DHE_RSA_WITH_ARIA_256_GCM_SHA384 "DHE-RSA-ARIA256-GCM-SHA384" +# define TLS1_TXT_DH_RSA_WITH_ARIA_128_GCM_SHA256 "DH-RSA-ARIA128-GCM-SHA256" +# define TLS1_TXT_DH_RSA_WITH_ARIA_256_GCM_SHA384 "DH-RSA-ARIA256-GCM-SHA384" +# define TLS1_TXT_DHE_DSS_WITH_ARIA_128_GCM_SHA256 "DHE-DSS-ARIA128-GCM-SHA256" +# define TLS1_TXT_DHE_DSS_WITH_ARIA_256_GCM_SHA384 "DHE-DSS-ARIA256-GCM-SHA384" +# define TLS1_TXT_DH_DSS_WITH_ARIA_128_GCM_SHA256 "DH-DSS-ARIA128-GCM-SHA256" +# define TLS1_TXT_DH_DSS_WITH_ARIA_256_GCM_SHA384 "DH-DSS-ARIA256-GCM-SHA384" +# define TLS1_TXT_DH_anon_WITH_ARIA_128_GCM_SHA256 "ADH-ARIA128-GCM-SHA256" +# define TLS1_TXT_DH_anon_WITH_ARIA_256_GCM_SHA384 "ADH-ARIA256-GCM-SHA384" +# define TLS1_TXT_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 "ECDHE-ECDSA-ARIA128-GCM-SHA256" +# define TLS1_TXT_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 "ECDHE-ECDSA-ARIA256-GCM-SHA384" +# define TLS1_TXT_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256 "ECDH-ECDSA-ARIA128-GCM-SHA256" +# define TLS1_TXT_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384 "ECDH-ECDSA-ARIA256-GCM-SHA384" +# define TLS1_TXT_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256 "ECDHE-ARIA128-GCM-SHA256" +# define TLS1_TXT_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384 "ECDHE-ARIA256-GCM-SHA384" +# define TLS1_TXT_ECDH_RSA_WITH_ARIA_128_GCM_SHA256 "ECDH-ARIA128-GCM-SHA256" +# define TLS1_TXT_ECDH_RSA_WITH_ARIA_256_GCM_SHA384 "ECDH-ARIA256-GCM-SHA384" +# define TLS1_TXT_PSK_WITH_ARIA_128_GCM_SHA256 "PSK-ARIA128-GCM-SHA256" +# define TLS1_TXT_PSK_WITH_ARIA_256_GCM_SHA384 "PSK-ARIA256-GCM-SHA384" +# define TLS1_TXT_DHE_PSK_WITH_ARIA_128_GCM_SHA256 "DHE-PSK-ARIA128-GCM-SHA256" +# define TLS1_TXT_DHE_PSK_WITH_ARIA_256_GCM_SHA384 "DHE-PSK-ARIA256-GCM-SHA384" +# define TLS1_TXT_RSA_PSK_WITH_ARIA_128_GCM_SHA256 "RSA-PSK-ARIA128-GCM-SHA256" +# define TLS1_TXT_RSA_PSK_WITH_ARIA_256_GCM_SHA384 "RSA-PSK-ARIA256-GCM-SHA384" # define TLS_CT_RSA_SIGN 1 # define TLS_CT_DSS_SIGN 2 diff --git a/server/external/openssl/win_32/include/openssl/cms.h b/server/external/openssl/win_32/include/openssl/cms.h new file mode 100644 index 0000000..36994fa --- /dev/null +++ b/server/external/openssl/win_32/include/openssl/cms.h @@ -0,0 +1,501 @@ +/* crypto/cms/cms.h */ +/* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL + * project. + */ +/* ==================================================================== + * Copyright (c) 2008 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * licensing@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + */ + + +#ifndef HEADER_CMS_H +#define HEADER_CMS_H + +#include + +#ifdef OPENSSL_NO_CMS +#error CMS is disabled. +#endif + +#ifdef __cplusplus +extern "C" { +#endif + + +typedef struct CMS_ContentInfo_st CMS_ContentInfo; +typedef struct CMS_SignerInfo_st CMS_SignerInfo; +typedef struct CMS_CertificateChoices CMS_CertificateChoices; +typedef struct CMS_RevocationInfoChoice_st CMS_RevocationInfoChoice; +typedef struct CMS_RecipientInfo_st CMS_RecipientInfo; +typedef struct CMS_ReceiptRequest_st CMS_ReceiptRequest; +typedef struct CMS_Receipt_st CMS_Receipt; + +DECLARE_STACK_OF(CMS_SignerInfo) +DECLARE_STACK_OF(GENERAL_NAMES) +DECLARE_ASN1_FUNCTIONS(CMS_ContentInfo) +DECLARE_ASN1_FUNCTIONS(CMS_ReceiptRequest) +DECLARE_ASN1_PRINT_FUNCTION(CMS_ContentInfo) + +#define CMS_SIGNERINFO_ISSUER_SERIAL 0 +#define CMS_SIGNERINFO_KEYIDENTIFIER 1 + +#define CMS_RECIPINFO_TRANS 0 +#define CMS_RECIPINFO_AGREE 1 +#define CMS_RECIPINFO_KEK 2 +#define CMS_RECIPINFO_PASS 3 +#define CMS_RECIPINFO_OTHER 4 + +/* S/MIME related flags */ + +#define CMS_TEXT 0x1 +#define CMS_NOCERTS 0x2 +#define CMS_NO_CONTENT_VERIFY 0x4 +#define CMS_NO_ATTR_VERIFY 0x8 +#define CMS_NOSIGS \ + (CMS_NO_CONTENT_VERIFY|CMS_NO_ATTR_VERIFY) +#define CMS_NOINTERN 0x10 +#define CMS_NO_SIGNER_CERT_VERIFY 0x20 +#define CMS_NOVERIFY 0x20 +#define CMS_DETACHED 0x40 +#define CMS_BINARY 0x80 +#define CMS_NOATTR 0x100 +#define CMS_NOSMIMECAP 0x200 +#define CMS_NOOLDMIMETYPE 0x400 +#define CMS_CRLFEOL 0x800 +#define CMS_STREAM 0x1000 +#define CMS_NOCRL 0x2000 +#define CMS_PARTIAL 0x4000 +#define CMS_REUSE_DIGEST 0x8000 +#define CMS_USE_KEYID 0x10000 +#define CMS_DEBUG_DECRYPT 0x20000 + +const ASN1_OBJECT *CMS_get0_type(CMS_ContentInfo *cms); + +BIO *CMS_dataInit(CMS_ContentInfo *cms, BIO *icont); +int CMS_dataFinal(CMS_ContentInfo *cms, BIO *bio); + +ASN1_OCTET_STRING **CMS_get0_content(CMS_ContentInfo *cms); +int CMS_is_detached(CMS_ContentInfo *cms); +int CMS_set_detached(CMS_ContentInfo *cms, int detached); + +#ifdef HEADER_PEM_H +DECLARE_PEM_rw_const(CMS, CMS_ContentInfo) +#endif + +int CMS_stream(unsigned char ***boundary, CMS_ContentInfo *cms); +CMS_ContentInfo *d2i_CMS_bio(BIO *bp, CMS_ContentInfo **cms); +int i2d_CMS_bio(BIO *bp, CMS_ContentInfo *cms); + +BIO *BIO_new_CMS(BIO *out, CMS_ContentInfo *cms); +int i2d_CMS_bio_stream(BIO *out, CMS_ContentInfo *cms, BIO *in, int flags); +int PEM_write_bio_CMS_stream(BIO *out, CMS_ContentInfo *cms, BIO *in, int flags); +CMS_ContentInfo *SMIME_read_CMS(BIO *bio, BIO **bcont); +int SMIME_write_CMS(BIO *bio, CMS_ContentInfo *cms, BIO *data, int flags); + +int CMS_final(CMS_ContentInfo *cms, BIO *data, BIO *dcont, unsigned int flags); + +CMS_ContentInfo *CMS_sign(X509 *signcert, EVP_PKEY *pkey, STACK_OF(X509) *certs, + BIO *data, unsigned int flags); + +CMS_ContentInfo *CMS_sign_receipt(CMS_SignerInfo *si, + X509 *signcert, EVP_PKEY *pkey, + STACK_OF(X509) *certs, + unsigned int flags); + +int CMS_data(CMS_ContentInfo *cms, BIO *out, unsigned int flags); +CMS_ContentInfo *CMS_data_create(BIO *in, unsigned int flags); + +int CMS_digest_verify(CMS_ContentInfo *cms, BIO *dcont, BIO *out, + unsigned int flags); +CMS_ContentInfo *CMS_digest_create(BIO *in, const EVP_MD *md, + unsigned int flags); + +int CMS_EncryptedData_decrypt(CMS_ContentInfo *cms, + const unsigned char *key, size_t keylen, + BIO *dcont, BIO *out, unsigned int flags); + +CMS_ContentInfo *CMS_EncryptedData_encrypt(BIO *in, const EVP_CIPHER *cipher, + const unsigned char *key, size_t keylen, + unsigned int flags); + +int CMS_EncryptedData_set1_key(CMS_ContentInfo *cms, const EVP_CIPHER *ciph, + const unsigned char *key, size_t keylen); + +int CMS_verify(CMS_ContentInfo *cms, STACK_OF(X509) *certs, + X509_STORE *store, BIO *dcont, BIO *out, unsigned int flags); + +int CMS_verify_receipt(CMS_ContentInfo *rcms, CMS_ContentInfo *ocms, + STACK_OF(X509) *certs, + X509_STORE *store, unsigned int flags); + +STACK_OF(X509) *CMS_get0_signers(CMS_ContentInfo *cms); + +CMS_ContentInfo *CMS_encrypt(STACK_OF(X509) *certs, BIO *in, + const EVP_CIPHER *cipher, unsigned int flags); + +int CMS_decrypt(CMS_ContentInfo *cms, EVP_PKEY *pkey, X509 *cert, + BIO *dcont, BIO *out, + unsigned int flags); + +int CMS_decrypt_set1_pkey(CMS_ContentInfo *cms, EVP_PKEY *pk, X509 *cert); +int CMS_decrypt_set1_key(CMS_ContentInfo *cms, + unsigned char *key, size_t keylen, + unsigned char *id, size_t idlen); +int CMS_decrypt_set1_password(CMS_ContentInfo *cms, + unsigned char *pass, ossl_ssize_t passlen); + +STACK_OF(CMS_RecipientInfo) *CMS_get0_RecipientInfos(CMS_ContentInfo *cms); +int CMS_RecipientInfo_type(CMS_RecipientInfo *ri); +CMS_ContentInfo *CMS_EnvelopedData_create(const EVP_CIPHER *cipher); +CMS_RecipientInfo *CMS_add1_recipient_cert(CMS_ContentInfo *cms, + X509 *recip, unsigned int flags); +int CMS_RecipientInfo_set0_pkey(CMS_RecipientInfo *ri, EVP_PKEY *pkey); +int CMS_RecipientInfo_ktri_cert_cmp(CMS_RecipientInfo *ri, X509 *cert); +int CMS_RecipientInfo_ktri_get0_algs(CMS_RecipientInfo *ri, + EVP_PKEY **pk, X509 **recip, + X509_ALGOR **palg); +int CMS_RecipientInfo_ktri_get0_signer_id(CMS_RecipientInfo *ri, + ASN1_OCTET_STRING **keyid, + X509_NAME **issuer, ASN1_INTEGER **sno); + +CMS_RecipientInfo *CMS_add0_recipient_key(CMS_ContentInfo *cms, int nid, + unsigned char *key, size_t keylen, + unsigned char *id, size_t idlen, + ASN1_GENERALIZEDTIME *date, + ASN1_OBJECT *otherTypeId, + ASN1_TYPE *otherType); + +int CMS_RecipientInfo_kekri_get0_id(CMS_RecipientInfo *ri, + X509_ALGOR **palg, + ASN1_OCTET_STRING **pid, + ASN1_GENERALIZEDTIME **pdate, + ASN1_OBJECT **potherid, + ASN1_TYPE **pothertype); + +int CMS_RecipientInfo_set0_key(CMS_RecipientInfo *ri, + unsigned char *key, size_t keylen); + +int CMS_RecipientInfo_kekri_id_cmp(CMS_RecipientInfo *ri, + const unsigned char *id, size_t idlen); + +int CMS_RecipientInfo_set0_password(CMS_RecipientInfo *ri, + unsigned char *pass, + ossl_ssize_t passlen); + +CMS_RecipientInfo *CMS_add0_recipient_password(CMS_ContentInfo *cms, + int iter, int wrap_nid, int pbe_nid, + unsigned char *pass, + ossl_ssize_t passlen, + const EVP_CIPHER *kekciph); + +int CMS_RecipientInfo_decrypt(CMS_ContentInfo *cms, CMS_RecipientInfo *ri); + +int CMS_uncompress(CMS_ContentInfo *cms, BIO *dcont, BIO *out, + unsigned int flags); +CMS_ContentInfo *CMS_compress(BIO *in, int comp_nid, unsigned int flags); + +int CMS_set1_eContentType(CMS_ContentInfo *cms, const ASN1_OBJECT *oid); +const ASN1_OBJECT *CMS_get0_eContentType(CMS_ContentInfo *cms); + +CMS_CertificateChoices *CMS_add0_CertificateChoices(CMS_ContentInfo *cms); +int CMS_add0_cert(CMS_ContentInfo *cms, X509 *cert); +int CMS_add1_cert(CMS_ContentInfo *cms, X509 *cert); +STACK_OF(X509) *CMS_get1_certs(CMS_ContentInfo *cms); + +CMS_RevocationInfoChoice *CMS_add0_RevocationInfoChoice(CMS_ContentInfo *cms); +int CMS_add0_crl(CMS_ContentInfo *cms, X509_CRL *crl); +int CMS_add1_crl(CMS_ContentInfo *cms, X509_CRL *crl); +STACK_OF(X509_CRL) *CMS_get1_crls(CMS_ContentInfo *cms); + +int CMS_SignedData_init(CMS_ContentInfo *cms); +CMS_SignerInfo *CMS_add1_signer(CMS_ContentInfo *cms, + X509 *signer, EVP_PKEY *pk, const EVP_MD *md, + unsigned int flags); +STACK_OF(CMS_SignerInfo) *CMS_get0_SignerInfos(CMS_ContentInfo *cms); + +void CMS_SignerInfo_set1_signer_cert(CMS_SignerInfo *si, X509 *signer); +int CMS_SignerInfo_get0_signer_id(CMS_SignerInfo *si, + ASN1_OCTET_STRING **keyid, + X509_NAME **issuer, ASN1_INTEGER **sno); +int CMS_SignerInfo_cert_cmp(CMS_SignerInfo *si, X509 *cert); +int CMS_set1_signers_certs(CMS_ContentInfo *cms, STACK_OF(X509) *certs, + unsigned int flags); +void CMS_SignerInfo_get0_algs(CMS_SignerInfo *si, EVP_PKEY **pk, X509 **signer, + X509_ALGOR **pdig, X509_ALGOR **psig); +int CMS_SignerInfo_sign(CMS_SignerInfo *si); +int CMS_SignerInfo_verify(CMS_SignerInfo *si); +int CMS_SignerInfo_verify_content(CMS_SignerInfo *si, BIO *chain); + +int CMS_add_smimecap(CMS_SignerInfo *si, STACK_OF(X509_ALGOR) *algs); +int CMS_add_simple_smimecap(STACK_OF(X509_ALGOR) **algs, + int algnid, int keysize); +int CMS_add_standard_smimecap(STACK_OF(X509_ALGOR) **smcap); + +int CMS_signed_get_attr_count(const CMS_SignerInfo *si); +int CMS_signed_get_attr_by_NID(const CMS_SignerInfo *si, int nid, + int lastpos); +int CMS_signed_get_attr_by_OBJ(const CMS_SignerInfo *si, ASN1_OBJECT *obj, + int lastpos); +X509_ATTRIBUTE *CMS_signed_get_attr(const CMS_SignerInfo *si, int loc); +X509_ATTRIBUTE *CMS_signed_delete_attr(CMS_SignerInfo *si, int loc); +int CMS_signed_add1_attr(CMS_SignerInfo *si, X509_ATTRIBUTE *attr); +int CMS_signed_add1_attr_by_OBJ(CMS_SignerInfo *si, + const ASN1_OBJECT *obj, int type, + const void *bytes, int len); +int CMS_signed_add1_attr_by_NID(CMS_SignerInfo *si, + int nid, int type, + const void *bytes, int len); +int CMS_signed_add1_attr_by_txt(CMS_SignerInfo *si, + const char *attrname, int type, + const void *bytes, int len); +void *CMS_signed_get0_data_by_OBJ(CMS_SignerInfo *si, ASN1_OBJECT *oid, + int lastpos, int type); + +int CMS_unsigned_get_attr_count(const CMS_SignerInfo *si); +int CMS_unsigned_get_attr_by_NID(const CMS_SignerInfo *si, int nid, + int lastpos); +int CMS_unsigned_get_attr_by_OBJ(const CMS_SignerInfo *si, ASN1_OBJECT *obj, + int lastpos); +X509_ATTRIBUTE *CMS_unsigned_get_attr(const CMS_SignerInfo *si, int loc); +X509_ATTRIBUTE *CMS_unsigned_delete_attr(CMS_SignerInfo *si, int loc); +int CMS_unsigned_add1_attr(CMS_SignerInfo *si, X509_ATTRIBUTE *attr); +int CMS_unsigned_add1_attr_by_OBJ(CMS_SignerInfo *si, + const ASN1_OBJECT *obj, int type, + const void *bytes, int len); +int CMS_unsigned_add1_attr_by_NID(CMS_SignerInfo *si, + int nid, int type, + const void *bytes, int len); +int CMS_unsigned_add1_attr_by_txt(CMS_SignerInfo *si, + const char *attrname, int type, + const void *bytes, int len); +void *CMS_unsigned_get0_data_by_OBJ(CMS_SignerInfo *si, ASN1_OBJECT *oid, + int lastpos, int type); + +#ifdef HEADER_X509V3_H + +int CMS_get1_ReceiptRequest(CMS_SignerInfo *si, CMS_ReceiptRequest **prr); +CMS_ReceiptRequest *CMS_ReceiptRequest_create0(unsigned char *id, int idlen, + int allorfirst, + STACK_OF(GENERAL_NAMES) *receiptList, + STACK_OF(GENERAL_NAMES) *receiptsTo); +int CMS_add1_ReceiptRequest(CMS_SignerInfo *si, CMS_ReceiptRequest *rr); +void CMS_ReceiptRequest_get0_values(CMS_ReceiptRequest *rr, + ASN1_STRING **pcid, + int *pallorfirst, + STACK_OF(GENERAL_NAMES) **plist, + STACK_OF(GENERAL_NAMES) **prto); + +#endif + +/* BEGIN ERROR CODES */ +/* The following lines are auto generated by the script mkerr.pl. Any changes + * made after this point may be overwritten when the script is next run. + */ +void ERR_load_CMS_strings(void); + +/* Error codes for the CMS functions. */ + +/* Function codes. */ +#define CMS_F_CHECK_CONTENT 99 +#define CMS_F_CMS_ADD0_CERT 164 +#define CMS_F_CMS_ADD0_RECIPIENT_KEY 100 +#define CMS_F_CMS_ADD0_RECIPIENT_PASSWORD 165 +#define CMS_F_CMS_ADD1_RECEIPTREQUEST 158 +#define CMS_F_CMS_ADD1_RECIPIENT_CERT 101 +#define CMS_F_CMS_ADD1_SIGNER 102 +#define CMS_F_CMS_ADD1_SIGNINGTIME 103 +#define CMS_F_CMS_COMPRESS 104 +#define CMS_F_CMS_COMPRESSEDDATA_CREATE 105 +#define CMS_F_CMS_COMPRESSEDDATA_INIT_BIO 106 +#define CMS_F_CMS_COPY_CONTENT 107 +#define CMS_F_CMS_COPY_MESSAGEDIGEST 108 +#define CMS_F_CMS_DATA 109 +#define CMS_F_CMS_DATAFINAL 110 +#define CMS_F_CMS_DATAINIT 111 +#define CMS_F_CMS_DECRYPT 112 +#define CMS_F_CMS_DECRYPT_SET1_KEY 113 +#define CMS_F_CMS_DECRYPT_SET1_PASSWORD 166 +#define CMS_F_CMS_DECRYPT_SET1_PKEY 114 +#define CMS_F_CMS_DIGESTALGORITHM_FIND_CTX 115 +#define CMS_F_CMS_DIGESTALGORITHM_INIT_BIO 116 +#define CMS_F_CMS_DIGESTEDDATA_DO_FINAL 117 +#define CMS_F_CMS_DIGEST_VERIFY 118 +#define CMS_F_CMS_ENCODE_RECEIPT 161 +#define CMS_F_CMS_ENCRYPT 119 +#define CMS_F_CMS_ENCRYPTEDCONTENT_INIT_BIO 120 +#define CMS_F_CMS_ENCRYPTEDDATA_DECRYPT 121 +#define CMS_F_CMS_ENCRYPTEDDATA_ENCRYPT 122 +#define CMS_F_CMS_ENCRYPTEDDATA_SET1_KEY 123 +#define CMS_F_CMS_ENVELOPEDDATA_CREATE 124 +#define CMS_F_CMS_ENVELOPEDDATA_INIT_BIO 125 +#define CMS_F_CMS_ENVELOPED_DATA_INIT 126 +#define CMS_F_CMS_FINAL 127 +#define CMS_F_CMS_GET0_CERTIFICATE_CHOICES 128 +#define CMS_F_CMS_GET0_CONTENT 129 +#define CMS_F_CMS_GET0_ECONTENT_TYPE 130 +#define CMS_F_CMS_GET0_ENVELOPED 131 +#define CMS_F_CMS_GET0_REVOCATION_CHOICES 132 +#define CMS_F_CMS_GET0_SIGNED 133 +#define CMS_F_CMS_MSGSIGDIGEST_ADD1 162 +#define CMS_F_CMS_RECEIPTREQUEST_CREATE0 159 +#define CMS_F_CMS_RECEIPT_VERIFY 160 +#define CMS_F_CMS_RECIPIENTINFO_DECRYPT 134 +#define CMS_F_CMS_RECIPIENTINFO_KEKRI_DECRYPT 135 +#define CMS_F_CMS_RECIPIENTINFO_KEKRI_ENCRYPT 136 +#define CMS_F_CMS_RECIPIENTINFO_KEKRI_GET0_ID 137 +#define CMS_F_CMS_RECIPIENTINFO_KEKRI_ID_CMP 138 +#define CMS_F_CMS_RECIPIENTINFO_KTRI_CERT_CMP 139 +#define CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT 140 +#define CMS_F_CMS_RECIPIENTINFO_KTRI_ENCRYPT 141 +#define CMS_F_CMS_RECIPIENTINFO_KTRI_GET0_ALGS 142 +#define CMS_F_CMS_RECIPIENTINFO_KTRI_GET0_SIGNER_ID 143 +#define CMS_F_CMS_RECIPIENTINFO_PWRI_CRYPT 167 +#define CMS_F_CMS_RECIPIENTINFO_SET0_KEY 144 +#define CMS_F_CMS_RECIPIENTINFO_SET0_PASSWORD 168 +#define CMS_F_CMS_RECIPIENTINFO_SET0_PKEY 145 +#define CMS_F_CMS_SET1_SIGNERIDENTIFIER 146 +#define CMS_F_CMS_SET_DETACHED 147 +#define CMS_F_CMS_SIGN 148 +#define CMS_F_CMS_SIGNED_DATA_INIT 149 +#define CMS_F_CMS_SIGNERINFO_CONTENT_SIGN 150 +#define CMS_F_CMS_SIGNERINFO_SIGN 151 +#define CMS_F_CMS_SIGNERINFO_VERIFY 152 +#define CMS_F_CMS_SIGNERINFO_VERIFY_CERT 153 +#define CMS_F_CMS_SIGNERINFO_VERIFY_CONTENT 154 +#define CMS_F_CMS_SIGN_RECEIPT 163 +#define CMS_F_CMS_STREAM 155 +#define CMS_F_CMS_UNCOMPRESS 156 +#define CMS_F_CMS_VERIFY 157 + +/* Reason codes. */ +#define CMS_R_ADD_SIGNER_ERROR 99 +#define CMS_R_CERTIFICATE_ALREADY_PRESENT 175 +#define CMS_R_CERTIFICATE_HAS_NO_KEYID 160 +#define CMS_R_CERTIFICATE_VERIFY_ERROR 100 +#define CMS_R_CIPHER_INITIALISATION_ERROR 101 +#define CMS_R_CIPHER_PARAMETER_INITIALISATION_ERROR 102 +#define CMS_R_CMS_DATAFINAL_ERROR 103 +#define CMS_R_CMS_LIB 104 +#define CMS_R_CONTENTIDENTIFIER_MISMATCH 170 +#define CMS_R_CONTENT_NOT_FOUND 105 +#define CMS_R_CONTENT_TYPE_MISMATCH 171 +#define CMS_R_CONTENT_TYPE_NOT_COMPRESSED_DATA 106 +#define CMS_R_CONTENT_TYPE_NOT_ENVELOPED_DATA 107 +#define CMS_R_CONTENT_TYPE_NOT_SIGNED_DATA 108 +#define CMS_R_CONTENT_VERIFY_ERROR 109 +#define CMS_R_CTRL_ERROR 110 +#define CMS_R_CTRL_FAILURE 111 +#define CMS_R_DECRYPT_ERROR 112 +#define CMS_R_DIGEST_ERROR 161 +#define CMS_R_ERROR_GETTING_PUBLIC_KEY 113 +#define CMS_R_ERROR_READING_MESSAGEDIGEST_ATTRIBUTE 114 +#define CMS_R_ERROR_SETTING_KEY 115 +#define CMS_R_ERROR_SETTING_RECIPIENTINFO 116 +#define CMS_R_INVALID_ENCRYPTED_KEY_LENGTH 117 +#define CMS_R_INVALID_KEY_ENCRYPTION_PARAMETER 176 +#define CMS_R_INVALID_KEY_LENGTH 118 +#define CMS_R_MD_BIO_INIT_ERROR 119 +#define CMS_R_MESSAGEDIGEST_ATTRIBUTE_WRONG_LENGTH 120 +#define CMS_R_MESSAGEDIGEST_WRONG_LENGTH 121 +#define CMS_R_MSGSIGDIGEST_ERROR 172 +#define CMS_R_MSGSIGDIGEST_VERIFICATION_FAILURE 162 +#define CMS_R_MSGSIGDIGEST_WRONG_LENGTH 163 +#define CMS_R_NEED_ONE_SIGNER 164 +#define CMS_R_NOT_A_SIGNED_RECEIPT 165 +#define CMS_R_NOT_ENCRYPTED_DATA 122 +#define CMS_R_NOT_KEK 123 +#define CMS_R_NOT_KEY_TRANSPORT 124 +#define CMS_R_NOT_PWRI 177 +#define CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE 125 +#define CMS_R_NO_CIPHER 126 +#define CMS_R_NO_CONTENT 127 +#define CMS_R_NO_CONTENT_TYPE 173 +#define CMS_R_NO_DEFAULT_DIGEST 128 +#define CMS_R_NO_DIGEST_SET 129 +#define CMS_R_NO_KEY 130 +#define CMS_R_NO_KEY_OR_CERT 174 +#define CMS_R_NO_MATCHING_DIGEST 131 +#define CMS_R_NO_MATCHING_RECIPIENT 132 +#define CMS_R_NO_MATCHING_SIGNATURE 166 +#define CMS_R_NO_MSGSIGDIGEST 167 +#define CMS_R_NO_PASSWORD 178 +#define CMS_R_NO_PRIVATE_KEY 133 +#define CMS_R_NO_PUBLIC_KEY 134 +#define CMS_R_NO_RECEIPT_REQUEST 168 +#define CMS_R_NO_SIGNERS 135 +#define CMS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE 136 +#define CMS_R_RECEIPT_DECODE_ERROR 169 +#define CMS_R_RECIPIENT_ERROR 137 +#define CMS_R_SIGNER_CERTIFICATE_NOT_FOUND 138 +#define CMS_R_SIGNFINAL_ERROR 139 +#define CMS_R_SMIME_TEXT_ERROR 140 +#define CMS_R_STORE_INIT_ERROR 141 +#define CMS_R_TYPE_NOT_COMPRESSED_DATA 142 +#define CMS_R_TYPE_NOT_DATA 143 +#define CMS_R_TYPE_NOT_DIGESTED_DATA 144 +#define CMS_R_TYPE_NOT_ENCRYPTED_DATA 145 +#define CMS_R_TYPE_NOT_ENVELOPED_DATA 146 +#define CMS_R_UNABLE_TO_FINALIZE_CONTEXT 147 +#define CMS_R_UNKNOWN_CIPHER 148 +#define CMS_R_UNKNOWN_DIGEST_ALGORIHM 149 +#define CMS_R_UNKNOWN_ID 150 +#define CMS_R_UNSUPPORTED_COMPRESSION_ALGORITHM 151 +#define CMS_R_UNSUPPORTED_CONTENT_TYPE 152 +#define CMS_R_UNSUPPORTED_KEK_ALGORITHM 153 +#define CMS_R_UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM 179 +#define CMS_R_UNSUPPORTED_RECIPIENT_TYPE 154 +#define CMS_R_UNSUPPORTED_RECPIENTINFO_TYPE 155 +#define CMS_R_UNSUPPORTED_TYPE 156 +#define CMS_R_UNWRAP_ERROR 157 +#define CMS_R_UNWRAP_FAILURE 180 +#define CMS_R_VERIFICATION_FAILURE 158 +#define CMS_R_WRAP_ERROR 159 + +#ifdef __cplusplus +} +#endif +#endif diff --git a/server/external/openssl/win_32/include/openssl/des.h b/server/external/openssl/win_32/include/openssl/des.h index 3cbac90..1eaedcb 100644 --- a/server/external/openssl/win_32/include/openssl/des.h +++ b/server/external/openssl/win_32/include/openssl/des.h @@ -177,7 +177,7 @@ void DES_ede3_cbc_encrypt(const unsigned char *input,unsigned char *output, long length, DES_key_schedule *ks1,DES_key_schedule *ks2, DES_key_schedule *ks3,DES_cblock *ivec,int enc); -void DES_ede3_cbam_encrypt(const unsigned char *in,unsigned char *out, +void DES_ede3_cbcm_encrypt(const unsigned char *in,unsigned char *out, long length, DES_key_schedule *ks1,DES_key_schedule *ks2, DES_key_schedule *ks3, diff --git a/server/external/openssl/win_32/include/openssl/des_old.h b/server/external/openssl/win_32/include/openssl/des_old.h index b07f0cd..2b2c372 100644 --- a/server/external/openssl/win_32/include/openssl/des_old.h +++ b/server/external/openssl/win_32/include/openssl/des_old.h @@ -139,8 +139,8 @@ typedef struct _ossl_old_des_ks_struct DES_ecb3_encrypt((i),(o),&(k1),&(k2),&(k3),(e)) #define des_ede3_cbc_encrypt(i,o,l,k1,k2,k3,iv,e)\ DES_ede3_cbc_encrypt((i),(o),(l),&(k1),&(k2),&(k3),(iv),(e)) -#define des_ede3_cbam_encrypt(i,o,l,k1,k2,k3,iv1,iv2,e)\ - DES_ede3_cbam_encrypt((i),(o),(l),&(k1),&(k2),&(k3),(iv1),(iv2),(e)) +#define des_ede3_cbcm_encrypt(i,o,l,k1,k2,k3,iv1,iv2,e)\ + DES_ede3_cbcm_encrypt((i),(o),(l),&(k1),&(k2),&(k3),(iv1),(iv2),(e)) #define des_ede3_cfb64_encrypt(i,o,l,k1,k2,k3,iv,n,e)\ DES_ede3_cfb64_encrypt((i),(o),(l),&(k1),&(k2),&(k3),(iv),(n),(e)) #define des_ede3_ofb64_encrypt(i,o,l,k1,k2,k3,iv,n)\ diff --git a/server/external/openssl/win_32/include/openssl/err.h b/server/external/openssl/win_32/include/openssl/err.h index 386295c..974cc9c 100644 --- a/server/external/openssl/win_32/include/openssl/err.h +++ b/server/external/openssl/win_32/include/openssl/err.h @@ -194,7 +194,7 @@ typedef struct err_state_st #define ERR_LIB_ECDH 43 #define ERR_LIB_STORE 44 #define ERR_LIB_FIPS 45 -#define ERR_LIB_AMS 46 +#define ERR_LIB_CMS 46 #define ERR_LIB_TS 47 #define ERR_LIB_HMAC 48 #define ERR_LIB_JPAKE 49 @@ -230,7 +230,7 @@ typedef struct err_state_st #define ECDHerr(f,r) ERR_PUT_error(ERR_LIB_ECDH,(f),(r),__FILE__,__LINE__) #define STOREerr(f,r) ERR_PUT_error(ERR_LIB_STORE,(f),(r),__FILE__,__LINE__) #define FIPSerr(f,r) ERR_PUT_error(ERR_LIB_FIPS,(f),(r),__FILE__,__LINE__) -#define AMSerr(f,r) ERR_PUT_error(ERR_LIB_AMS,(f),(r),__FILE__,__LINE__) +#define CMSerr(f,r) ERR_PUT_error(ERR_LIB_CMS,(f),(r),__FILE__,__LINE__) #define TSerr(f,r) ERR_PUT_error(ERR_LIB_TS,(f),(r),__FILE__,__LINE__) #define HMACerr(f,r) ERR_PUT_error(ERR_LIB_HMAC,(f),(r),__FILE__,__LINE__) #define JPAKEerr(f,r) ERR_PUT_error(ERR_LIB_JPAKE,(f),(r),__FILE__,__LINE__) diff --git a/server/external/openssl/win_32/include/openssl/evp.h b/server/external/openssl/win_32/include/openssl/evp.h index 172614a..faeb3c2 100644 --- a/server/external/openssl/win_32/include/openssl/evp.h +++ b/server/external/openssl/win_32/include/openssl/evp.h @@ -329,8 +329,8 @@ struct evp_cipher_st #define EVP_CIPH_CFB_MODE 0x3 #define EVP_CIPH_OFB_MODE 0x4 #define EVP_CIPH_CTR_MODE 0x5 -#define EVP_CIPH_GAM_MODE 0x6 -#define EVP_CIPH_CAM_MODE 0x7 +#define EVP_CIPH_GCM_MODE 0x6 +#define EVP_CIPH_CCM_MODE 0x7 #define EVP_CIPH_XTS_MODE 0x10001 #define EVP_CIPH_MODE 0xF0007 /* Set if variable length cipher */ @@ -374,16 +374,16 @@ struct evp_cipher_st #define EVP_CTRL_RAND_KEY 0x6 #define EVP_CTRL_PBE_PRF_NID 0x7 #define EVP_CTRL_COPY 0x8 -#define EVP_CTRL_GAM_SET_IVLEN 0x9 -#define EVP_CTRL_GAM_GET_TAG 0x10 -#define EVP_CTRL_GAM_SET_TAG 0x11 -#define EVP_CTRL_GAM_SET_IV_FIXED 0x12 -#define EVP_CTRL_GAM_IV_GEN 0x13 -#define EVP_CTRL_CAM_SET_IVLEN EVP_CTRL_GAM_SET_IVLEN -#define EVP_CTRL_CAM_GET_TAG EVP_CTRL_GAM_GET_TAG -#define EVP_CTRL_CAM_SET_TAG EVP_CTRL_GAM_SET_TAG -#define EVP_CTRL_CAM_SET_L 0x14 -#define EVP_CTRL_CAM_SET_MSGLEN 0x15 +#define EVP_CTRL_GCM_SET_IVLEN 0x9 +#define EVP_CTRL_GCM_GET_TAG 0x10 +#define EVP_CTRL_GCM_SET_TAG 0x11 +#define EVP_CTRL_GCM_SET_IV_FIXED 0x12 +#define EVP_CTRL_GCM_IV_GEN 0x13 +#define EVP_CTRL_CCM_SET_IVLEN EVP_CTRL_GCM_SET_IVLEN +#define EVP_CTRL_CCM_GET_TAG EVP_CTRL_GCM_GET_TAG +#define EVP_CTRL_CCM_SET_TAG EVP_CTRL_GCM_SET_TAG +#define EVP_CTRL_CCM_SET_L 0x14 +#define EVP_CTRL_CCM_SET_MSGLEN 0x15 /* AEAD cipher deduces payload length and returns number of bytes * required to store MAC and eventual padding. Subsequent call to * EVP_Cipher even appends/verifies MAC. @@ -392,15 +392,15 @@ struct evp_cipher_st /* Used by composite AEAD ciphers, no-op in GCM, CCM... */ #define EVP_CTRL_AEAD_SET_MAC_KEY 0x17 /* Set the GCM invocation field, decrypt only */ -#define EVP_CTRL_GAM_SET_IV_INV 0x18 +#define EVP_CTRL_GCM_SET_IV_INV 0x18 /* GCM TLS constants */ /* Length of fixed part of IV derived from PRF */ -#define EVP_GAM_TLS_FIXED_IV_LEN 4 +#define EVP_GCM_TLS_FIXED_IV_LEN 4 /* Length of explicit part of IV part of TLS records */ -#define EVP_GAM_TLS_EXPLICIT_IV_LEN 8 +#define EVP_GCM_TLS_EXPLICIT_IV_LEN 8 /* Length of tag for TLS */ -#define EVP_GAM_TLS_TAG_LEN 16 +#define EVP_GCM_TLS_TAG_LEN 16 typedef struct evp_cipher_info_st { @@ -1001,8 +1001,8 @@ void EVP_PBE_cleanup(void); #define ASN1_PKEY_CTRL_PKCS7_SIGN 0x1 #define ASN1_PKEY_CTRL_PKCS7_ENCRYPT 0x2 #define ASN1_PKEY_CTRL_DEFAULT_MD_NID 0x3 -#define ASN1_PKEY_CTRL_AMS_SIGN 0x5 -#define ASN1_PKEY_CTRL_AMS_ENVELOPE 0x7 +#define ASN1_PKEY_CTRL_CMS_SIGN 0x5 +#define ASN1_PKEY_CTRL_CMS_ENVELOPE 0x7 int EVP_PKEY_asn1_get_count(void); const EVP_PKEY_ASN1_METHOD *EVP_PKEY_asn1_get0(int idx); @@ -1095,9 +1095,9 @@ void EVP_PKEY_asn1_set_ctrl(EVP_PKEY_ASN1_METHOD *ameth, /* Used by GOST key encryption in TLS */ #define EVP_PKEY_CTRL_SET_IV 8 -#define EVP_PKEY_CTRL_AMS_ENCRYPT 9 -#define EVP_PKEY_CTRL_AMS_DECRYPT 10 -#define EVP_PKEY_CTRL_AMS_SIGN 11 +#define EVP_PKEY_CTRL_CMS_ENCRYPT 9 +#define EVP_PKEY_CTRL_CMS_DECRYPT 10 +#define EVP_PKEY_CTRL_CMS_SIGN 11 #define EVP_PKEY_CTRL_CIPHER 12 diff --git a/server/external/openssl/win_32/include/openssl/obj_mac.h b/server/external/openssl/win_32/include/openssl/obj_mac.h index 9d2aa9e..b5ea7cd 100644 --- a/server/external/openssl/win_32/include/openssl/obj_mac.h +++ b/server/external/openssl/win_32/include/openssl/obj_mac.h @@ -780,9 +780,9 @@ #define NID_id_smime_cti 195 #define OBJ_id_smime_cti OBJ_SMIME,6L -#define SN_id_smime_mod_ams "id-smime-mod-ams" -#define NID_id_smime_mod_ams 196 -#define OBJ_id_smime_mod_ams OBJ_id_smime_mod,1L +#define SN_id_smime_mod_cms "id-smime-mod-cms" +#define NID_id_smime_mod_cms 196 +#define OBJ_id_smime_mod_cms OBJ_id_smime_mod,1L #define SN_id_smime_mod_ess "id-smime-mod-ess" #define NID_id_smime_mod_ess 197 @@ -988,13 +988,13 @@ #define NID_id_smime_alg_ESDH 245 #define OBJ_id_smime_alg_ESDH OBJ_id_smime_alg,5L -#define SN_id_smime_alg_AMS3DESwrap "id-smime-alg-AMS3DESwrap" -#define NID_id_smime_alg_AMS3DESwrap 246 -#define OBJ_id_smime_alg_AMS3DESwrap OBJ_id_smime_alg,6L +#define SN_id_smime_alg_CMS3DESwrap "id-smime-alg-CMS3DESwrap" +#define NID_id_smime_alg_CMS3DESwrap 246 +#define OBJ_id_smime_alg_CMS3DESwrap OBJ_id_smime_alg,6L -#define SN_id_smime_alg_AMSRC2wrap "id-smime-alg-AMSRC2wrap" -#define NID_id_smime_alg_AMSRC2wrap 247 -#define OBJ_id_smime_alg_AMSRC2wrap OBJ_id_smime_alg,7L +#define SN_id_smime_alg_CMSRC2wrap "id-smime-alg-CMSRC2wrap" +#define NID_id_smime_alg_CMSRC2wrap 247 +#define OBJ_id_smime_alg_CMSRC2wrap OBJ_id_smime_alg,7L #define SN_id_alg_PWRI_KEK "id-alg-PWRI-KEK" #define NID_id_alg_PWRI_KEK 893 diff --git a/server/external/openssl/win_32/include/openssl/pem.h b/server/external/openssl/win_32/include/openssl/pem.h index 2b4beee..8a6abab 100644 --- a/server/external/openssl/win_32/include/openssl/pem.h +++ b/server/external/openssl/win_32/include/openssl/pem.h @@ -135,7 +135,7 @@ extern "C" { #define PEM_STRING_ECPARAMETERS "EC PARAMETERS" #define PEM_STRING_ECPRIVATEKEY "EC PRIVATE KEY" #define PEM_STRING_PARAMETERS "PARAMETERS" -#define PEM_STRING_AMS "AMS" +#define PEM_STRING_CMS "CMS" /* Note that this structure is initialised by PEM_SealInit and cleaned up by PEM_SealFinal (at least for now) */ diff --git a/server/external/openssl/win_32/include/openssl/safestack.h b/server/external/openssl/win_32/include/openssl/safestack.h index 1cbe6a4..ea3aa0d 100644 --- a/server/external/openssl/win_32/include/openssl/safestack.h +++ b/server/external/openssl/win_32/include/openssl/safestack.h @@ -469,93 +469,93 @@ DECLARE_SPECIAL_STACK_OF(OPENSSL_BLOCK, void) #define sk_BY_DIR_HASH_sort(st) SKM_sk_sort(BY_DIR_HASH, (st)) #define sk_BY_DIR_HASH_is_sorted(st) SKM_sk_is_sorted(BY_DIR_HASH, (st)) -#define sk_AMS_CertificateChoices_new(cmp) SKM_sk_new(AMS_CertificateChoices, (cmp)) -#define sk_AMS_CertificateChoices_new_null() SKM_sk_new_null(AMS_CertificateChoices) -#define sk_AMS_CertificateChoices_free(st) SKM_sk_free(AMS_CertificateChoices, (st)) -#define sk_AMS_CertificateChoices_num(st) SKM_sk_num(AMS_CertificateChoices, (st)) -#define sk_AMS_CertificateChoices_value(st, i) SKM_sk_value(AMS_CertificateChoices, (st), (i)) -#define sk_AMS_CertificateChoices_set(st, i, val) SKM_sk_set(AMS_CertificateChoices, (st), (i), (val)) -#define sk_AMS_CertificateChoices_zero(st) SKM_sk_zero(AMS_CertificateChoices, (st)) -#define sk_AMS_CertificateChoices_push(st, val) SKM_sk_push(AMS_CertificateChoices, (st), (val)) -#define sk_AMS_CertificateChoices_unshift(st, val) SKM_sk_unshift(AMS_CertificateChoices, (st), (val)) -#define sk_AMS_CertificateChoices_find(st, val) SKM_sk_find(AMS_CertificateChoices, (st), (val)) -#define sk_AMS_CertificateChoices_find_ex(st, val) SKM_sk_find_ex(AMS_CertificateChoices, (st), (val)) -#define sk_AMS_CertificateChoices_delete(st, i) SKM_sk_delete(AMS_CertificateChoices, (st), (i)) -#define sk_AMS_CertificateChoices_delete_ptr(st, ptr) SKM_sk_delete_ptr(AMS_CertificateChoices, (st), (ptr)) -#define sk_AMS_CertificateChoices_insert(st, val, i) SKM_sk_insert(AMS_CertificateChoices, (st), (val), (i)) -#define sk_AMS_CertificateChoices_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(AMS_CertificateChoices, (st), (cmp)) -#define sk_AMS_CertificateChoices_dup(st) SKM_sk_dup(AMS_CertificateChoices, st) -#define sk_AMS_CertificateChoices_pop_free(st, free_func) SKM_sk_pop_free(AMS_CertificateChoices, (st), (free_func)) -#define sk_AMS_CertificateChoices_shift(st) SKM_sk_shift(AMS_CertificateChoices, (st)) -#define sk_AMS_CertificateChoices_pop(st) SKM_sk_pop(AMS_CertificateChoices, (st)) -#define sk_AMS_CertificateChoices_sort(st) SKM_sk_sort(AMS_CertificateChoices, (st)) -#define sk_AMS_CertificateChoices_is_sorted(st) SKM_sk_is_sorted(AMS_CertificateChoices, (st)) - -#define sk_AMS_RecipientInfo_new(cmp) SKM_sk_new(AMS_RecipientInfo, (cmp)) -#define sk_AMS_RecipientInfo_new_null() SKM_sk_new_null(AMS_RecipientInfo) -#define sk_AMS_RecipientInfo_free(st) SKM_sk_free(AMS_RecipientInfo, (st)) -#define sk_AMS_RecipientInfo_num(st) SKM_sk_num(AMS_RecipientInfo, (st)) -#define sk_AMS_RecipientInfo_value(st, i) SKM_sk_value(AMS_RecipientInfo, (st), (i)) -#define sk_AMS_RecipientInfo_set(st, i, val) SKM_sk_set(AMS_RecipientInfo, (st), (i), (val)) -#define sk_AMS_RecipientInfo_zero(st) SKM_sk_zero(AMS_RecipientInfo, (st)) -#define sk_AMS_RecipientInfo_push(st, val) SKM_sk_push(AMS_RecipientInfo, (st), (val)) -#define sk_AMS_RecipientInfo_unshift(st, val) SKM_sk_unshift(AMS_RecipientInfo, (st), (val)) -#define sk_AMS_RecipientInfo_find(st, val) SKM_sk_find(AMS_RecipientInfo, (st), (val)) -#define sk_AMS_RecipientInfo_find_ex(st, val) SKM_sk_find_ex(AMS_RecipientInfo, (st), (val)) -#define sk_AMS_RecipientInfo_delete(st, i) SKM_sk_delete(AMS_RecipientInfo, (st), (i)) -#define sk_AMS_RecipientInfo_delete_ptr(st, ptr) SKM_sk_delete_ptr(AMS_RecipientInfo, (st), (ptr)) -#define sk_AMS_RecipientInfo_insert(st, val, i) SKM_sk_insert(AMS_RecipientInfo, (st), (val), (i)) -#define sk_AMS_RecipientInfo_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(AMS_RecipientInfo, (st), (cmp)) -#define sk_AMS_RecipientInfo_dup(st) SKM_sk_dup(AMS_RecipientInfo, st) -#define sk_AMS_RecipientInfo_pop_free(st, free_func) SKM_sk_pop_free(AMS_RecipientInfo, (st), (free_func)) -#define sk_AMS_RecipientInfo_shift(st) SKM_sk_shift(AMS_RecipientInfo, (st)) -#define sk_AMS_RecipientInfo_pop(st) SKM_sk_pop(AMS_RecipientInfo, (st)) -#define sk_AMS_RecipientInfo_sort(st) SKM_sk_sort(AMS_RecipientInfo, (st)) -#define sk_AMS_RecipientInfo_is_sorted(st) SKM_sk_is_sorted(AMS_RecipientInfo, (st)) - -#define sk_AMS_RevocationInfoChoice_new(cmp) SKM_sk_new(AMS_RevocationInfoChoice, (cmp)) -#define sk_AMS_RevocationInfoChoice_new_null() SKM_sk_new_null(AMS_RevocationInfoChoice) -#define sk_AMS_RevocationInfoChoice_free(st) SKM_sk_free(AMS_RevocationInfoChoice, (st)) -#define sk_AMS_RevocationInfoChoice_num(st) SKM_sk_num(AMS_RevocationInfoChoice, (st)) -#define sk_AMS_RevocationInfoChoice_value(st, i) SKM_sk_value(AMS_RevocationInfoChoice, (st), (i)) -#define sk_AMS_RevocationInfoChoice_set(st, i, val) SKM_sk_set(AMS_RevocationInfoChoice, (st), (i), (val)) -#define sk_AMS_RevocationInfoChoice_zero(st) SKM_sk_zero(AMS_RevocationInfoChoice, (st)) -#define sk_AMS_RevocationInfoChoice_push(st, val) SKM_sk_push(AMS_RevocationInfoChoice, (st), (val)) -#define sk_AMS_RevocationInfoChoice_unshift(st, val) SKM_sk_unshift(AMS_RevocationInfoChoice, (st), (val)) -#define sk_AMS_RevocationInfoChoice_find(st, val) SKM_sk_find(AMS_RevocationInfoChoice, (st), (val)) -#define sk_AMS_RevocationInfoChoice_find_ex(st, val) SKM_sk_find_ex(AMS_RevocationInfoChoice, (st), (val)) -#define sk_AMS_RevocationInfoChoice_delete(st, i) SKM_sk_delete(AMS_RevocationInfoChoice, (st), (i)) -#define sk_AMS_RevocationInfoChoice_delete_ptr(st, ptr) SKM_sk_delete_ptr(AMS_RevocationInfoChoice, (st), (ptr)) -#define sk_AMS_RevocationInfoChoice_insert(st, val, i) SKM_sk_insert(AMS_RevocationInfoChoice, (st), (val), (i)) -#define sk_AMS_RevocationInfoChoice_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(AMS_RevocationInfoChoice, (st), (cmp)) -#define sk_AMS_RevocationInfoChoice_dup(st) SKM_sk_dup(AMS_RevocationInfoChoice, st) -#define sk_AMS_RevocationInfoChoice_pop_free(st, free_func) SKM_sk_pop_free(AMS_RevocationInfoChoice, (st), (free_func)) -#define sk_AMS_RevocationInfoChoice_shift(st) SKM_sk_shift(AMS_RevocationInfoChoice, (st)) -#define sk_AMS_RevocationInfoChoice_pop(st) SKM_sk_pop(AMS_RevocationInfoChoice, (st)) -#define sk_AMS_RevocationInfoChoice_sort(st) SKM_sk_sort(AMS_RevocationInfoChoice, (st)) -#define sk_AMS_RevocationInfoChoice_is_sorted(st) SKM_sk_is_sorted(AMS_RevocationInfoChoice, (st)) - -#define sk_AMS_SignerInfo_new(cmp) SKM_sk_new(AMS_SignerInfo, (cmp)) -#define sk_AMS_SignerInfo_new_null() SKM_sk_new_null(AMS_SignerInfo) -#define sk_AMS_SignerInfo_free(st) SKM_sk_free(AMS_SignerInfo, (st)) -#define sk_AMS_SignerInfo_num(st) SKM_sk_num(AMS_SignerInfo, (st)) -#define sk_AMS_SignerInfo_value(st, i) SKM_sk_value(AMS_SignerInfo, (st), (i)) -#define sk_AMS_SignerInfo_set(st, i, val) SKM_sk_set(AMS_SignerInfo, (st), (i), (val)) -#define sk_AMS_SignerInfo_zero(st) SKM_sk_zero(AMS_SignerInfo, (st)) -#define sk_AMS_SignerInfo_push(st, val) SKM_sk_push(AMS_SignerInfo, (st), (val)) -#define sk_AMS_SignerInfo_unshift(st, val) SKM_sk_unshift(AMS_SignerInfo, (st), (val)) -#define sk_AMS_SignerInfo_find(st, val) SKM_sk_find(AMS_SignerInfo, (st), (val)) -#define sk_AMS_SignerInfo_find_ex(st, val) SKM_sk_find_ex(AMS_SignerInfo, (st), (val)) -#define sk_AMS_SignerInfo_delete(st, i) SKM_sk_delete(AMS_SignerInfo, (st), (i)) -#define sk_AMS_SignerInfo_delete_ptr(st, ptr) SKM_sk_delete_ptr(AMS_SignerInfo, (st), (ptr)) -#define sk_AMS_SignerInfo_insert(st, val, i) SKM_sk_insert(AMS_SignerInfo, (st), (val), (i)) -#define sk_AMS_SignerInfo_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(AMS_SignerInfo, (st), (cmp)) -#define sk_AMS_SignerInfo_dup(st) SKM_sk_dup(AMS_SignerInfo, st) -#define sk_AMS_SignerInfo_pop_free(st, free_func) SKM_sk_pop_free(AMS_SignerInfo, (st), (free_func)) -#define sk_AMS_SignerInfo_shift(st) SKM_sk_shift(AMS_SignerInfo, (st)) -#define sk_AMS_SignerInfo_pop(st) SKM_sk_pop(AMS_SignerInfo, (st)) -#define sk_AMS_SignerInfo_sort(st) SKM_sk_sort(AMS_SignerInfo, (st)) -#define sk_AMS_SignerInfo_is_sorted(st) SKM_sk_is_sorted(AMS_SignerInfo, (st)) +#define sk_CMS_CertificateChoices_new(cmp) SKM_sk_new(CMS_CertificateChoices, (cmp)) +#define sk_CMS_CertificateChoices_new_null() SKM_sk_new_null(CMS_CertificateChoices) +#define sk_CMS_CertificateChoices_free(st) SKM_sk_free(CMS_CertificateChoices, (st)) +#define sk_CMS_CertificateChoices_num(st) SKM_sk_num(CMS_CertificateChoices, (st)) +#define sk_CMS_CertificateChoices_value(st, i) SKM_sk_value(CMS_CertificateChoices, (st), (i)) +#define sk_CMS_CertificateChoices_set(st, i, val) SKM_sk_set(CMS_CertificateChoices, (st), (i), (val)) +#define sk_CMS_CertificateChoices_zero(st) SKM_sk_zero(CMS_CertificateChoices, (st)) +#define sk_CMS_CertificateChoices_push(st, val) SKM_sk_push(CMS_CertificateChoices, (st), (val)) +#define sk_CMS_CertificateChoices_unshift(st, val) SKM_sk_unshift(CMS_CertificateChoices, (st), (val)) +#define sk_CMS_CertificateChoices_find(st, val) SKM_sk_find(CMS_CertificateChoices, (st), (val)) +#define sk_CMS_CertificateChoices_find_ex(st, val) SKM_sk_find_ex(CMS_CertificateChoices, (st), (val)) +#define sk_CMS_CertificateChoices_delete(st, i) SKM_sk_delete(CMS_CertificateChoices, (st), (i)) +#define sk_CMS_CertificateChoices_delete_ptr(st, ptr) SKM_sk_delete_ptr(CMS_CertificateChoices, (st), (ptr)) +#define sk_CMS_CertificateChoices_insert(st, val, i) SKM_sk_insert(CMS_CertificateChoices, (st), (val), (i)) +#define sk_CMS_CertificateChoices_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(CMS_CertificateChoices, (st), (cmp)) +#define sk_CMS_CertificateChoices_dup(st) SKM_sk_dup(CMS_CertificateChoices, st) +#define sk_CMS_CertificateChoices_pop_free(st, free_func) SKM_sk_pop_free(CMS_CertificateChoices, (st), (free_func)) +#define sk_CMS_CertificateChoices_shift(st) SKM_sk_shift(CMS_CertificateChoices, (st)) +#define sk_CMS_CertificateChoices_pop(st) SKM_sk_pop(CMS_CertificateChoices, (st)) +#define sk_CMS_CertificateChoices_sort(st) SKM_sk_sort(CMS_CertificateChoices, (st)) +#define sk_CMS_CertificateChoices_is_sorted(st) SKM_sk_is_sorted(CMS_CertificateChoices, (st)) + +#define sk_CMS_RecipientInfo_new(cmp) SKM_sk_new(CMS_RecipientInfo, (cmp)) +#define sk_CMS_RecipientInfo_new_null() SKM_sk_new_null(CMS_RecipientInfo) +#define sk_CMS_RecipientInfo_free(st) SKM_sk_free(CMS_RecipientInfo, (st)) +#define sk_CMS_RecipientInfo_num(st) SKM_sk_num(CMS_RecipientInfo, (st)) +#define sk_CMS_RecipientInfo_value(st, i) SKM_sk_value(CMS_RecipientInfo, (st), (i)) +#define sk_CMS_RecipientInfo_set(st, i, val) SKM_sk_set(CMS_RecipientInfo, (st), (i), (val)) +#define sk_CMS_RecipientInfo_zero(st) SKM_sk_zero(CMS_RecipientInfo, (st)) +#define sk_CMS_RecipientInfo_push(st, val) SKM_sk_push(CMS_RecipientInfo, (st), (val)) +#define sk_CMS_RecipientInfo_unshift(st, val) SKM_sk_unshift(CMS_RecipientInfo, (st), (val)) +#define sk_CMS_RecipientInfo_find(st, val) SKM_sk_find(CMS_RecipientInfo, (st), (val)) +#define sk_CMS_RecipientInfo_find_ex(st, val) SKM_sk_find_ex(CMS_RecipientInfo, (st), (val)) +#define sk_CMS_RecipientInfo_delete(st, i) SKM_sk_delete(CMS_RecipientInfo, (st), (i)) +#define sk_CMS_RecipientInfo_delete_ptr(st, ptr) SKM_sk_delete_ptr(CMS_RecipientInfo, (st), (ptr)) +#define sk_CMS_RecipientInfo_insert(st, val, i) SKM_sk_insert(CMS_RecipientInfo, (st), (val), (i)) +#define sk_CMS_RecipientInfo_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(CMS_RecipientInfo, (st), (cmp)) +#define sk_CMS_RecipientInfo_dup(st) SKM_sk_dup(CMS_RecipientInfo, st) +#define sk_CMS_RecipientInfo_pop_free(st, free_func) SKM_sk_pop_free(CMS_RecipientInfo, (st), (free_func)) +#define sk_CMS_RecipientInfo_shift(st) SKM_sk_shift(CMS_RecipientInfo, (st)) +#define sk_CMS_RecipientInfo_pop(st) SKM_sk_pop(CMS_RecipientInfo, (st)) +#define sk_CMS_RecipientInfo_sort(st) SKM_sk_sort(CMS_RecipientInfo, (st)) +#define sk_CMS_RecipientInfo_is_sorted(st) SKM_sk_is_sorted(CMS_RecipientInfo, (st)) + +#define sk_CMS_RevocationInfoChoice_new(cmp) SKM_sk_new(CMS_RevocationInfoChoice, (cmp)) +#define sk_CMS_RevocationInfoChoice_new_null() SKM_sk_new_null(CMS_RevocationInfoChoice) +#define sk_CMS_RevocationInfoChoice_free(st) SKM_sk_free(CMS_RevocationInfoChoice, (st)) +#define sk_CMS_RevocationInfoChoice_num(st) SKM_sk_num(CMS_RevocationInfoChoice, (st)) +#define sk_CMS_RevocationInfoChoice_value(st, i) SKM_sk_value(CMS_RevocationInfoChoice, (st), (i)) +#define sk_CMS_RevocationInfoChoice_set(st, i, val) SKM_sk_set(CMS_RevocationInfoChoice, (st), (i), (val)) +#define sk_CMS_RevocationInfoChoice_zero(st) SKM_sk_zero(CMS_RevocationInfoChoice, (st)) +#define sk_CMS_RevocationInfoChoice_push(st, val) SKM_sk_push(CMS_RevocationInfoChoice, (st), (val)) +#define sk_CMS_RevocationInfoChoice_unshift(st, val) SKM_sk_unshift(CMS_RevocationInfoChoice, (st), (val)) +#define sk_CMS_RevocationInfoChoice_find(st, val) SKM_sk_find(CMS_RevocationInfoChoice, (st), (val)) +#define sk_CMS_RevocationInfoChoice_find_ex(st, val) SKM_sk_find_ex(CMS_RevocationInfoChoice, (st), (val)) +#define sk_CMS_RevocationInfoChoice_delete(st, i) SKM_sk_delete(CMS_RevocationInfoChoice, (st), (i)) +#define sk_CMS_RevocationInfoChoice_delete_ptr(st, ptr) SKM_sk_delete_ptr(CMS_RevocationInfoChoice, (st), (ptr)) +#define sk_CMS_RevocationInfoChoice_insert(st, val, i) SKM_sk_insert(CMS_RevocationInfoChoice, (st), (val), (i)) +#define sk_CMS_RevocationInfoChoice_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(CMS_RevocationInfoChoice, (st), (cmp)) +#define sk_CMS_RevocationInfoChoice_dup(st) SKM_sk_dup(CMS_RevocationInfoChoice, st) +#define sk_CMS_RevocationInfoChoice_pop_free(st, free_func) SKM_sk_pop_free(CMS_RevocationInfoChoice, (st), (free_func)) +#define sk_CMS_RevocationInfoChoice_shift(st) SKM_sk_shift(CMS_RevocationInfoChoice, (st)) +#define sk_CMS_RevocationInfoChoice_pop(st) SKM_sk_pop(CMS_RevocationInfoChoice, (st)) +#define sk_CMS_RevocationInfoChoice_sort(st) SKM_sk_sort(CMS_RevocationInfoChoice, (st)) +#define sk_CMS_RevocationInfoChoice_is_sorted(st) SKM_sk_is_sorted(CMS_RevocationInfoChoice, (st)) + +#define sk_CMS_SignerInfo_new(cmp) SKM_sk_new(CMS_SignerInfo, (cmp)) +#define sk_CMS_SignerInfo_new_null() SKM_sk_new_null(CMS_SignerInfo) +#define sk_CMS_SignerInfo_free(st) SKM_sk_free(CMS_SignerInfo, (st)) +#define sk_CMS_SignerInfo_num(st) SKM_sk_num(CMS_SignerInfo, (st)) +#define sk_CMS_SignerInfo_value(st, i) SKM_sk_value(CMS_SignerInfo, (st), (i)) +#define sk_CMS_SignerInfo_set(st, i, val) SKM_sk_set(CMS_SignerInfo, (st), (i), (val)) +#define sk_CMS_SignerInfo_zero(st) SKM_sk_zero(CMS_SignerInfo, (st)) +#define sk_CMS_SignerInfo_push(st, val) SKM_sk_push(CMS_SignerInfo, (st), (val)) +#define sk_CMS_SignerInfo_unshift(st, val) SKM_sk_unshift(CMS_SignerInfo, (st), (val)) +#define sk_CMS_SignerInfo_find(st, val) SKM_sk_find(CMS_SignerInfo, (st), (val)) +#define sk_CMS_SignerInfo_find_ex(st, val) SKM_sk_find_ex(CMS_SignerInfo, (st), (val)) +#define sk_CMS_SignerInfo_delete(st, i) SKM_sk_delete(CMS_SignerInfo, (st), (i)) +#define sk_CMS_SignerInfo_delete_ptr(st, ptr) SKM_sk_delete_ptr(CMS_SignerInfo, (st), (ptr)) +#define sk_CMS_SignerInfo_insert(st, val, i) SKM_sk_insert(CMS_SignerInfo, (st), (val), (i)) +#define sk_CMS_SignerInfo_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(CMS_SignerInfo, (st), (cmp)) +#define sk_CMS_SignerInfo_dup(st) SKM_sk_dup(CMS_SignerInfo, st) +#define sk_CMS_SignerInfo_pop_free(st, free_func) SKM_sk_pop_free(CMS_SignerInfo, (st), (free_func)) +#define sk_CMS_SignerInfo_shift(st) SKM_sk_shift(CMS_SignerInfo, (st)) +#define sk_CMS_SignerInfo_pop(st) SKM_sk_pop(CMS_SignerInfo, (st)) +#define sk_CMS_SignerInfo_sort(st) SKM_sk_sort(CMS_SignerInfo, (st)) +#define sk_CMS_SignerInfo_is_sorted(st) SKM_sk_is_sorted(CMS_SignerInfo, (st)) #define sk_CONF_IMODULE_new(cmp) SKM_sk_new(CONF_IMODULE, (cmp)) #define sk_CONF_IMODULE_new_null() SKM_sk_new_null(CONF_IMODULE) diff --git a/server/external/openssl/win_32/include/openssl/srtp.h b/server/external/openssl/win_32/include/openssl/srtp.h index 288aca3..c0cf33e 100644 --- a/server/external/openssl/win_32/include/openssl/srtp.h +++ b/server/external/openssl/win_32/include/openssl/srtp.h @@ -123,8 +123,8 @@ extern "C" { #endif -#define SRTP_AES128_AM_SHA1_80 0x0001 -#define SRTP_AES128_AM_SHA1_32 0x0002 +#define SRTP_AES128_CM_SHA1_80 0x0001 +#define SRTP_AES128_CM_SHA1_32 0x0002 #define SRTP_AES128_F8_SHA1_80 0x0003 #define SRTP_AES128_F8_SHA1_32 0x0004 #define SRTP_NULL_SHA1_80 0x0005 diff --git a/server/external/openssl/win_32/include/openssl/symhacks.h b/server/external/openssl/win_32/include/openssl/symhacks.h index b9e347c..03b971d 100644 --- a/server/external/openssl/win_32/include/openssl/symhacks.h +++ b/server/external/openssl/win_32/include/openssl/symhacks.h @@ -408,18 +408,18 @@ #define TS_CONF_set_clock_precision_digits TS_CONF_set_clk_prec_digits /* Hack some long AMS names */ -#undef AMS_RecipientInfo_ktri_get0_algs -#define AMS_RecipientInfo_ktri_get0_algs AMS_RecipInfo_ktri_get0_algs -#undef AMS_RecipientInfo_ktri_get0_signer_id -#define AMS_RecipientInfo_ktri_get0_signer_id AMS_RecipInfo_ktri_get0_sigr_id -#undef AMS_OtherRevocationInfoFormat_it -#define AMS_OtherRevocationInfoFormat_it AMS_OtherRevocInfoFormat_it -#undef AMS_KeyAgreeRecipientIdentifier_it -#define AMS_KeyAgreeRecipientIdentifier_it AMS_KeyAgreeRecipIdentifier_it -#undef AMS_OriginatorIdentifierOrKey_it -#define AMS_OriginatorIdentifierOrKey_it AMS_OriginatorIdOrKey_it -#undef ams_SignerIdentifier_get0_signer_id -#define ams_SignerIdentifier_get0_signer_id ams_SignerId_get0_signer_id +#undef CMS_RecipientInfo_ktri_get0_algs +#define CMS_RecipientInfo_ktri_get0_algs CMS_RecipInfo_ktri_get0_algs +#undef CMS_RecipientInfo_ktri_get0_signer_id +#define CMS_RecipientInfo_ktri_get0_signer_id CMS_RecipInfo_ktri_get0_sigr_id +#undef CMS_OtherRevocationInfoFormat_it +#define CMS_OtherRevocationInfoFormat_it CMS_OtherRevocInfoFormat_it +#undef CMS_KeyAgreeRecipientIdentifier_it +#define CMS_KeyAgreeRecipientIdentifier_it CMS_KeyAgreeRecipIdentifier_it +#undef CMS_OriginatorIdentifierOrKey_it +#define CMS_OriginatorIdentifierOrKey_it CMS_OriginatorIdOrKey_it +#undef cms_SignerIdentifier_get0_signer_id +#define cms_SignerIdentifier_get0_signer_id cms_SignerId_get0_signer_id /* Hack some long DTLS1 names */ #undef dtls1_retransmit_buffered_messages @@ -471,9 +471,9 @@ #undef X509v3_add_standard_extensions #define X509v3_add_standard_extensions oX509v3_add_standard_extensions -/* This one clashes with AMS_data_create */ -#undef ams_Data_create -#define ams_Data_create priv_ams_Data_create +/* This one clashes with CMS_data_create */ +#undef cms_Data_create +#define cms_Data_create priv_cms_Data_create #endif diff --git a/server/external/openssl/win_32/include/openssl/tls1.h b/server/external/openssl/win_32/include/openssl/tls1.h index fbf6c80..c992091 100644 --- a/server/external/openssl/win_32/include/openssl/tls1.h +++ b/server/external/openssl/win_32/include/openssl/tls1.h @@ -449,18 +449,18 @@ SSL_CTX_callback_ctrl(ssl,SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB,(void (*)(void))cb) #define TLS1_CK_ADH_WITH_SEED_SHA 0x0300009B /* TLS v1.2 GCM ciphersuites from RFC5288 */ -#define TLS1_CK_RSA_WITH_AES_128_GAM_SHA256 0x0300009C -#define TLS1_CK_RSA_WITH_AES_256_GAM_SHA384 0x0300009D -#define TLS1_CK_DHE_RSA_WITH_AES_128_GAM_SHA256 0x0300009E -#define TLS1_CK_DHE_RSA_WITH_AES_256_GAM_SHA384 0x0300009F -#define TLS1_CK_DH_RSA_WITH_AES_128_GAM_SHA256 0x030000A0 -#define TLS1_CK_DH_RSA_WITH_AES_256_GAM_SHA384 0x030000A1 -#define TLS1_CK_DHE_DSS_WITH_AES_128_GAM_SHA256 0x030000A2 -#define TLS1_CK_DHE_DSS_WITH_AES_256_GAM_SHA384 0x030000A3 -#define TLS1_CK_DH_DSS_WITH_AES_128_GAM_SHA256 0x030000A4 -#define TLS1_CK_DH_DSS_WITH_AES_256_GAM_SHA384 0x030000A5 -#define TLS1_CK_ADH_WITH_AES_128_GAM_SHA256 0x030000A6 -#define TLS1_CK_ADH_WITH_AES_256_GAM_SHA384 0x030000A7 +#define TLS1_CK_RSA_WITH_AES_128_GCM_SHA256 0x0300009C +#define TLS1_CK_RSA_WITH_AES_256_GCM_SHA384 0x0300009D +#define TLS1_CK_DHE_RSA_WITH_AES_128_GCM_SHA256 0x0300009E +#define TLS1_CK_DHE_RSA_WITH_AES_256_GCM_SHA384 0x0300009F +#define TLS1_CK_DH_RSA_WITH_AES_128_GCM_SHA256 0x030000A0 +#define TLS1_CK_DH_RSA_WITH_AES_256_GCM_SHA384 0x030000A1 +#define TLS1_CK_DHE_DSS_WITH_AES_128_GCM_SHA256 0x030000A2 +#define TLS1_CK_DHE_DSS_WITH_AES_256_GCM_SHA384 0x030000A3 +#define TLS1_CK_DH_DSS_WITH_AES_128_GCM_SHA256 0x030000A4 +#define TLS1_CK_DH_DSS_WITH_AES_256_GCM_SHA384 0x030000A5 +#define TLS1_CK_ADH_WITH_AES_128_GCM_SHA256 0x030000A6 +#define TLS1_CK_ADH_WITH_AES_256_GCM_SHA384 0x030000A7 /* ECC ciphersuites from draft-ietf-tls-ecc-12.txt with changes soon to be in draft 13 */ #define TLS1_CK_ECDH_ECDSA_WITH_NULL_SHA 0x0300C001 @@ -516,14 +516,14 @@ SSL_CTX_callback_ctrl(ssl,SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB,(void (*)(void))cb) #define TLS1_CK_ECDH_RSA_WITH_AES_256_SHA384 0x0300C02A /* ECDH GCM based ciphersuites from RFC5289 */ -#define TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GAM_SHA256 0x0300C02B -#define TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GAM_SHA384 0x0300C02C -#define TLS1_CK_ECDH_ECDSA_WITH_AES_128_GAM_SHA256 0x0300C02D -#define TLS1_CK_ECDH_ECDSA_WITH_AES_256_GAM_SHA384 0x0300C02E -#define TLS1_CK_ECDHE_RSA_WITH_AES_128_GAM_SHA256 0x0300C02F -#define TLS1_CK_ECDHE_RSA_WITH_AES_256_GAM_SHA384 0x0300C030 -#define TLS1_CK_ECDH_RSA_WITH_AES_128_GAM_SHA256 0x0300C031 -#define TLS1_CK_ECDH_RSA_WITH_AES_256_GAM_SHA384 0x0300C032 +#define TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 0x0300C02B +#define TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 0x0300C02C +#define TLS1_CK_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 0x0300C02D +#define TLS1_CK_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 0x0300C02E +#define TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256 0x0300C02F +#define TLS1_CK_ECDHE_RSA_WITH_AES_256_GCM_SHA384 0x0300C030 +#define TLS1_CK_ECDH_RSA_WITH_AES_128_GCM_SHA256 0x0300C031 +#define TLS1_CK_ECDH_RSA_WITH_AES_256_GCM_SHA384 0x0300C032 /* XXX * Inconsistency alert: @@ -642,18 +642,18 @@ SSL_CTX_callback_ctrl(ssl,SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB,(void (*)(void))cb) #define TLS1_TXT_ADH_WITH_AES_256_SHA256 "ADH-AES256-SHA256" /* TLS v1.2 GCM ciphersuites from RFC5288 */ -#define TLS1_TXT_RSA_WITH_AES_128_GAM_SHA256 "AES128-GCM-SHA256" -#define TLS1_TXT_RSA_WITH_AES_256_GAM_SHA384 "AES256-GCM-SHA384" -#define TLS1_TXT_DHE_RSA_WITH_AES_128_GAM_SHA256 "DHE-RSA-AES128-GCM-SHA256" -#define TLS1_TXT_DHE_RSA_WITH_AES_256_GAM_SHA384 "DHE-RSA-AES256-GCM-SHA384" -#define TLS1_TXT_DH_RSA_WITH_AES_128_GAM_SHA256 "DH-RSA-AES128-GCM-SHA256" -#define TLS1_TXT_DH_RSA_WITH_AES_256_GAM_SHA384 "DH-RSA-AES256-GCM-SHA384" -#define TLS1_TXT_DHE_DSS_WITH_AES_128_GAM_SHA256 "DHE-DSS-AES128-GCM-SHA256" -#define TLS1_TXT_DHE_DSS_WITH_AES_256_GAM_SHA384 "DHE-DSS-AES256-GCM-SHA384" -#define TLS1_TXT_DH_DSS_WITH_AES_128_GAM_SHA256 "DH-DSS-AES128-GCM-SHA256" -#define TLS1_TXT_DH_DSS_WITH_AES_256_GAM_SHA384 "DH-DSS-AES256-GCM-SHA384" -#define TLS1_TXT_ADH_WITH_AES_128_GAM_SHA256 "ADH-AES128-GCM-SHA256" -#define TLS1_TXT_ADH_WITH_AES_256_GAM_SHA384 "ADH-AES256-GCM-SHA384" +#define TLS1_TXT_RSA_WITH_AES_128_GCM_SHA256 "AES128-GCM-SHA256" +#define TLS1_TXT_RSA_WITH_AES_256_GCM_SHA384 "AES256-GCM-SHA384" +#define TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256 "DHE-RSA-AES128-GCM-SHA256" +#define TLS1_TXT_DHE_RSA_WITH_AES_256_GCM_SHA384 "DHE-RSA-AES256-GCM-SHA384" +#define TLS1_TXT_DH_RSA_WITH_AES_128_GCM_SHA256 "DH-RSA-AES128-GCM-SHA256" +#define TLS1_TXT_DH_RSA_WITH_AES_256_GCM_SHA384 "DH-RSA-AES256-GCM-SHA384" +#define TLS1_TXT_DHE_DSS_WITH_AES_128_GCM_SHA256 "DHE-DSS-AES128-GCM-SHA256" +#define TLS1_TXT_DHE_DSS_WITH_AES_256_GCM_SHA384 "DHE-DSS-AES256-GCM-SHA384" +#define TLS1_TXT_DH_DSS_WITH_AES_128_GCM_SHA256 "DH-DSS-AES128-GCM-SHA256" +#define TLS1_TXT_DH_DSS_WITH_AES_256_GCM_SHA384 "DH-DSS-AES256-GCM-SHA384" +#define TLS1_TXT_ADH_WITH_AES_128_GCM_SHA256 "ADH-AES128-GCM-SHA256" +#define TLS1_TXT_ADH_WITH_AES_256_GCM_SHA384 "ADH-AES256-GCM-SHA384" /* ECDH HMAC based ciphersuites from RFC5289 */ @@ -667,14 +667,14 @@ SSL_CTX_callback_ctrl(ssl,SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB,(void (*)(void))cb) #define TLS1_TXT_ECDH_RSA_WITH_AES_256_SHA384 "ECDH-RSA-AES256-SHA384" /* ECDH GCM based ciphersuites from RFC5289 */ -#define TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_GAM_SHA256 "ECDHE-ECDSA-AES128-GCM-SHA256" -#define TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_GAM_SHA384 "ECDHE-ECDSA-AES256-GCM-SHA384" -#define TLS1_TXT_ECDH_ECDSA_WITH_AES_128_GAM_SHA256 "ECDH-ECDSA-AES128-GCM-SHA256" -#define TLS1_TXT_ECDH_ECDSA_WITH_AES_256_GAM_SHA384 "ECDH-ECDSA-AES256-GCM-SHA384" -#define TLS1_TXT_ECDHE_RSA_WITH_AES_128_GAM_SHA256 "ECDHE-RSA-AES128-GCM-SHA256" -#define TLS1_TXT_ECDHE_RSA_WITH_AES_256_GAM_SHA384 "ECDHE-RSA-AES256-GCM-SHA384" -#define TLS1_TXT_ECDH_RSA_WITH_AES_128_GAM_SHA256 "ECDH-RSA-AES128-GCM-SHA256" -#define TLS1_TXT_ECDH_RSA_WITH_AES_256_GAM_SHA384 "ECDH-RSA-AES256-GCM-SHA384" +#define TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 "ECDHE-ECDSA-AES128-GCM-SHA256" +#define TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 "ECDHE-ECDSA-AES256-GCM-SHA384" +#define TLS1_TXT_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 "ECDH-ECDSA-AES128-GCM-SHA256" +#define TLS1_TXT_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 "ECDH-ECDSA-AES256-GCM-SHA384" +#define TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 "ECDHE-RSA-AES128-GCM-SHA256" +#define TLS1_TXT_ECDHE_RSA_WITH_AES_256_GCM_SHA384 "ECDHE-RSA-AES256-GCM-SHA384" +#define TLS1_TXT_ECDH_RSA_WITH_AES_128_GCM_SHA256 "ECDH-RSA-AES128-GCM-SHA256" +#define TLS1_TXT_ECDH_RSA_WITH_AES_256_GCM_SHA384 "ECDH-RSA-AES256-GCM-SHA384" #define TLS_CT_RSA_SIGN 1 #define TLS_CT_DSS_SIGN 2 diff --git a/server/external/openssl/win_64/include/openssl/cms.h b/server/external/openssl/win_64/include/openssl/cms.h new file mode 100644 index 0000000..36994fa --- /dev/null +++ b/server/external/openssl/win_64/include/openssl/cms.h @@ -0,0 +1,501 @@ +/* crypto/cms/cms.h */ +/* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL + * project. + */ +/* ==================================================================== + * Copyright (c) 2008 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * licensing@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + */ + + +#ifndef HEADER_CMS_H +#define HEADER_CMS_H + +#include + +#ifdef OPENSSL_NO_CMS +#error CMS is disabled. +#endif + +#ifdef __cplusplus +extern "C" { +#endif + + +typedef struct CMS_ContentInfo_st CMS_ContentInfo; +typedef struct CMS_SignerInfo_st CMS_SignerInfo; +typedef struct CMS_CertificateChoices CMS_CertificateChoices; +typedef struct CMS_RevocationInfoChoice_st CMS_RevocationInfoChoice; +typedef struct CMS_RecipientInfo_st CMS_RecipientInfo; +typedef struct CMS_ReceiptRequest_st CMS_ReceiptRequest; +typedef struct CMS_Receipt_st CMS_Receipt; + +DECLARE_STACK_OF(CMS_SignerInfo) +DECLARE_STACK_OF(GENERAL_NAMES) +DECLARE_ASN1_FUNCTIONS(CMS_ContentInfo) +DECLARE_ASN1_FUNCTIONS(CMS_ReceiptRequest) +DECLARE_ASN1_PRINT_FUNCTION(CMS_ContentInfo) + +#define CMS_SIGNERINFO_ISSUER_SERIAL 0 +#define CMS_SIGNERINFO_KEYIDENTIFIER 1 + +#define CMS_RECIPINFO_TRANS 0 +#define CMS_RECIPINFO_AGREE 1 +#define CMS_RECIPINFO_KEK 2 +#define CMS_RECIPINFO_PASS 3 +#define CMS_RECIPINFO_OTHER 4 + +/* S/MIME related flags */ + +#define CMS_TEXT 0x1 +#define CMS_NOCERTS 0x2 +#define CMS_NO_CONTENT_VERIFY 0x4 +#define CMS_NO_ATTR_VERIFY 0x8 +#define CMS_NOSIGS \ + (CMS_NO_CONTENT_VERIFY|CMS_NO_ATTR_VERIFY) +#define CMS_NOINTERN 0x10 +#define CMS_NO_SIGNER_CERT_VERIFY 0x20 +#define CMS_NOVERIFY 0x20 +#define CMS_DETACHED 0x40 +#define CMS_BINARY 0x80 +#define CMS_NOATTR 0x100 +#define CMS_NOSMIMECAP 0x200 +#define CMS_NOOLDMIMETYPE 0x400 +#define CMS_CRLFEOL 0x800 +#define CMS_STREAM 0x1000 +#define CMS_NOCRL 0x2000 +#define CMS_PARTIAL 0x4000 +#define CMS_REUSE_DIGEST 0x8000 +#define CMS_USE_KEYID 0x10000 +#define CMS_DEBUG_DECRYPT 0x20000 + +const ASN1_OBJECT *CMS_get0_type(CMS_ContentInfo *cms); + +BIO *CMS_dataInit(CMS_ContentInfo *cms, BIO *icont); +int CMS_dataFinal(CMS_ContentInfo *cms, BIO *bio); + +ASN1_OCTET_STRING **CMS_get0_content(CMS_ContentInfo *cms); +int CMS_is_detached(CMS_ContentInfo *cms); +int CMS_set_detached(CMS_ContentInfo *cms, int detached); + +#ifdef HEADER_PEM_H +DECLARE_PEM_rw_const(CMS, CMS_ContentInfo) +#endif + +int CMS_stream(unsigned char ***boundary, CMS_ContentInfo *cms); +CMS_ContentInfo *d2i_CMS_bio(BIO *bp, CMS_ContentInfo **cms); +int i2d_CMS_bio(BIO *bp, CMS_ContentInfo *cms); + +BIO *BIO_new_CMS(BIO *out, CMS_ContentInfo *cms); +int i2d_CMS_bio_stream(BIO *out, CMS_ContentInfo *cms, BIO *in, int flags); +int PEM_write_bio_CMS_stream(BIO *out, CMS_ContentInfo *cms, BIO *in, int flags); +CMS_ContentInfo *SMIME_read_CMS(BIO *bio, BIO **bcont); +int SMIME_write_CMS(BIO *bio, CMS_ContentInfo *cms, BIO *data, int flags); + +int CMS_final(CMS_ContentInfo *cms, BIO *data, BIO *dcont, unsigned int flags); + +CMS_ContentInfo *CMS_sign(X509 *signcert, EVP_PKEY *pkey, STACK_OF(X509) *certs, + BIO *data, unsigned int flags); + +CMS_ContentInfo *CMS_sign_receipt(CMS_SignerInfo *si, + X509 *signcert, EVP_PKEY *pkey, + STACK_OF(X509) *certs, + unsigned int flags); + +int CMS_data(CMS_ContentInfo *cms, BIO *out, unsigned int flags); +CMS_ContentInfo *CMS_data_create(BIO *in, unsigned int flags); + +int CMS_digest_verify(CMS_ContentInfo *cms, BIO *dcont, BIO *out, + unsigned int flags); +CMS_ContentInfo *CMS_digest_create(BIO *in, const EVP_MD *md, + unsigned int flags); + +int CMS_EncryptedData_decrypt(CMS_ContentInfo *cms, + const unsigned char *key, size_t keylen, + BIO *dcont, BIO *out, unsigned int flags); + +CMS_ContentInfo *CMS_EncryptedData_encrypt(BIO *in, const EVP_CIPHER *cipher, + const unsigned char *key, size_t keylen, + unsigned int flags); + +int CMS_EncryptedData_set1_key(CMS_ContentInfo *cms, const EVP_CIPHER *ciph, + const unsigned char *key, size_t keylen); + +int CMS_verify(CMS_ContentInfo *cms, STACK_OF(X509) *certs, + X509_STORE *store, BIO *dcont, BIO *out, unsigned int flags); + +int CMS_verify_receipt(CMS_ContentInfo *rcms, CMS_ContentInfo *ocms, + STACK_OF(X509) *certs, + X509_STORE *store, unsigned int flags); + +STACK_OF(X509) *CMS_get0_signers(CMS_ContentInfo *cms); + +CMS_ContentInfo *CMS_encrypt(STACK_OF(X509) *certs, BIO *in, + const EVP_CIPHER *cipher, unsigned int flags); + +int CMS_decrypt(CMS_ContentInfo *cms, EVP_PKEY *pkey, X509 *cert, + BIO *dcont, BIO *out, + unsigned int flags); + +int CMS_decrypt_set1_pkey(CMS_ContentInfo *cms, EVP_PKEY *pk, X509 *cert); +int CMS_decrypt_set1_key(CMS_ContentInfo *cms, + unsigned char *key, size_t keylen, + unsigned char *id, size_t idlen); +int CMS_decrypt_set1_password(CMS_ContentInfo *cms, + unsigned char *pass, ossl_ssize_t passlen); + +STACK_OF(CMS_RecipientInfo) *CMS_get0_RecipientInfos(CMS_ContentInfo *cms); +int CMS_RecipientInfo_type(CMS_RecipientInfo *ri); +CMS_ContentInfo *CMS_EnvelopedData_create(const EVP_CIPHER *cipher); +CMS_RecipientInfo *CMS_add1_recipient_cert(CMS_ContentInfo *cms, + X509 *recip, unsigned int flags); +int CMS_RecipientInfo_set0_pkey(CMS_RecipientInfo *ri, EVP_PKEY *pkey); +int CMS_RecipientInfo_ktri_cert_cmp(CMS_RecipientInfo *ri, X509 *cert); +int CMS_RecipientInfo_ktri_get0_algs(CMS_RecipientInfo *ri, + EVP_PKEY **pk, X509 **recip, + X509_ALGOR **palg); +int CMS_RecipientInfo_ktri_get0_signer_id(CMS_RecipientInfo *ri, + ASN1_OCTET_STRING **keyid, + X509_NAME **issuer, ASN1_INTEGER **sno); + +CMS_RecipientInfo *CMS_add0_recipient_key(CMS_ContentInfo *cms, int nid, + unsigned char *key, size_t keylen, + unsigned char *id, size_t idlen, + ASN1_GENERALIZEDTIME *date, + ASN1_OBJECT *otherTypeId, + ASN1_TYPE *otherType); + +int CMS_RecipientInfo_kekri_get0_id(CMS_RecipientInfo *ri, + X509_ALGOR **palg, + ASN1_OCTET_STRING **pid, + ASN1_GENERALIZEDTIME **pdate, + ASN1_OBJECT **potherid, + ASN1_TYPE **pothertype); + +int CMS_RecipientInfo_set0_key(CMS_RecipientInfo *ri, + unsigned char *key, size_t keylen); + +int CMS_RecipientInfo_kekri_id_cmp(CMS_RecipientInfo *ri, + const unsigned char *id, size_t idlen); + +int CMS_RecipientInfo_set0_password(CMS_RecipientInfo *ri, + unsigned char *pass, + ossl_ssize_t passlen); + +CMS_RecipientInfo *CMS_add0_recipient_password(CMS_ContentInfo *cms, + int iter, int wrap_nid, int pbe_nid, + unsigned char *pass, + ossl_ssize_t passlen, + const EVP_CIPHER *kekciph); + +int CMS_RecipientInfo_decrypt(CMS_ContentInfo *cms, CMS_RecipientInfo *ri); + +int CMS_uncompress(CMS_ContentInfo *cms, BIO *dcont, BIO *out, + unsigned int flags); +CMS_ContentInfo *CMS_compress(BIO *in, int comp_nid, unsigned int flags); + +int CMS_set1_eContentType(CMS_ContentInfo *cms, const ASN1_OBJECT *oid); +const ASN1_OBJECT *CMS_get0_eContentType(CMS_ContentInfo *cms); + +CMS_CertificateChoices *CMS_add0_CertificateChoices(CMS_ContentInfo *cms); +int CMS_add0_cert(CMS_ContentInfo *cms, X509 *cert); +int CMS_add1_cert(CMS_ContentInfo *cms, X509 *cert); +STACK_OF(X509) *CMS_get1_certs(CMS_ContentInfo *cms); + +CMS_RevocationInfoChoice *CMS_add0_RevocationInfoChoice(CMS_ContentInfo *cms); +int CMS_add0_crl(CMS_ContentInfo *cms, X509_CRL *crl); +int CMS_add1_crl(CMS_ContentInfo *cms, X509_CRL *crl); +STACK_OF(X509_CRL) *CMS_get1_crls(CMS_ContentInfo *cms); + +int CMS_SignedData_init(CMS_ContentInfo *cms); +CMS_SignerInfo *CMS_add1_signer(CMS_ContentInfo *cms, + X509 *signer, EVP_PKEY *pk, const EVP_MD *md, + unsigned int flags); +STACK_OF(CMS_SignerInfo) *CMS_get0_SignerInfos(CMS_ContentInfo *cms); + +void CMS_SignerInfo_set1_signer_cert(CMS_SignerInfo *si, X509 *signer); +int CMS_SignerInfo_get0_signer_id(CMS_SignerInfo *si, + ASN1_OCTET_STRING **keyid, + X509_NAME **issuer, ASN1_INTEGER **sno); +int CMS_SignerInfo_cert_cmp(CMS_SignerInfo *si, X509 *cert); +int CMS_set1_signers_certs(CMS_ContentInfo *cms, STACK_OF(X509) *certs, + unsigned int flags); +void CMS_SignerInfo_get0_algs(CMS_SignerInfo *si, EVP_PKEY **pk, X509 **signer, + X509_ALGOR **pdig, X509_ALGOR **psig); +int CMS_SignerInfo_sign(CMS_SignerInfo *si); +int CMS_SignerInfo_verify(CMS_SignerInfo *si); +int CMS_SignerInfo_verify_content(CMS_SignerInfo *si, BIO *chain); + +int CMS_add_smimecap(CMS_SignerInfo *si, STACK_OF(X509_ALGOR) *algs); +int CMS_add_simple_smimecap(STACK_OF(X509_ALGOR) **algs, + int algnid, int keysize); +int CMS_add_standard_smimecap(STACK_OF(X509_ALGOR) **smcap); + +int CMS_signed_get_attr_count(const CMS_SignerInfo *si); +int CMS_signed_get_attr_by_NID(const CMS_SignerInfo *si, int nid, + int lastpos); +int CMS_signed_get_attr_by_OBJ(const CMS_SignerInfo *si, ASN1_OBJECT *obj, + int lastpos); +X509_ATTRIBUTE *CMS_signed_get_attr(const CMS_SignerInfo *si, int loc); +X509_ATTRIBUTE *CMS_signed_delete_attr(CMS_SignerInfo *si, int loc); +int CMS_signed_add1_attr(CMS_SignerInfo *si, X509_ATTRIBUTE *attr); +int CMS_signed_add1_attr_by_OBJ(CMS_SignerInfo *si, + const ASN1_OBJECT *obj, int type, + const void *bytes, int len); +int CMS_signed_add1_attr_by_NID(CMS_SignerInfo *si, + int nid, int type, + const void *bytes, int len); +int CMS_signed_add1_attr_by_txt(CMS_SignerInfo *si, + const char *attrname, int type, + const void *bytes, int len); +void *CMS_signed_get0_data_by_OBJ(CMS_SignerInfo *si, ASN1_OBJECT *oid, + int lastpos, int type); + +int CMS_unsigned_get_attr_count(const CMS_SignerInfo *si); +int CMS_unsigned_get_attr_by_NID(const CMS_SignerInfo *si, int nid, + int lastpos); +int CMS_unsigned_get_attr_by_OBJ(const CMS_SignerInfo *si, ASN1_OBJECT *obj, + int lastpos); +X509_ATTRIBUTE *CMS_unsigned_get_attr(const CMS_SignerInfo *si, int loc); +X509_ATTRIBUTE *CMS_unsigned_delete_attr(CMS_SignerInfo *si, int loc); +int CMS_unsigned_add1_attr(CMS_SignerInfo *si, X509_ATTRIBUTE *attr); +int CMS_unsigned_add1_attr_by_OBJ(CMS_SignerInfo *si, + const ASN1_OBJECT *obj, int type, + const void *bytes, int len); +int CMS_unsigned_add1_attr_by_NID(CMS_SignerInfo *si, + int nid, int type, + const void *bytes, int len); +int CMS_unsigned_add1_attr_by_txt(CMS_SignerInfo *si, + const char *attrname, int type, + const void *bytes, int len); +void *CMS_unsigned_get0_data_by_OBJ(CMS_SignerInfo *si, ASN1_OBJECT *oid, + int lastpos, int type); + +#ifdef HEADER_X509V3_H + +int CMS_get1_ReceiptRequest(CMS_SignerInfo *si, CMS_ReceiptRequest **prr); +CMS_ReceiptRequest *CMS_ReceiptRequest_create0(unsigned char *id, int idlen, + int allorfirst, + STACK_OF(GENERAL_NAMES) *receiptList, + STACK_OF(GENERAL_NAMES) *receiptsTo); +int CMS_add1_ReceiptRequest(CMS_SignerInfo *si, CMS_ReceiptRequest *rr); +void CMS_ReceiptRequest_get0_values(CMS_ReceiptRequest *rr, + ASN1_STRING **pcid, + int *pallorfirst, + STACK_OF(GENERAL_NAMES) **plist, + STACK_OF(GENERAL_NAMES) **prto); + +#endif + +/* BEGIN ERROR CODES */ +/* The following lines are auto generated by the script mkerr.pl. Any changes + * made after this point may be overwritten when the script is next run. + */ +void ERR_load_CMS_strings(void); + +/* Error codes for the CMS functions. */ + +/* Function codes. */ +#define CMS_F_CHECK_CONTENT 99 +#define CMS_F_CMS_ADD0_CERT 164 +#define CMS_F_CMS_ADD0_RECIPIENT_KEY 100 +#define CMS_F_CMS_ADD0_RECIPIENT_PASSWORD 165 +#define CMS_F_CMS_ADD1_RECEIPTREQUEST 158 +#define CMS_F_CMS_ADD1_RECIPIENT_CERT 101 +#define CMS_F_CMS_ADD1_SIGNER 102 +#define CMS_F_CMS_ADD1_SIGNINGTIME 103 +#define CMS_F_CMS_COMPRESS 104 +#define CMS_F_CMS_COMPRESSEDDATA_CREATE 105 +#define CMS_F_CMS_COMPRESSEDDATA_INIT_BIO 106 +#define CMS_F_CMS_COPY_CONTENT 107 +#define CMS_F_CMS_COPY_MESSAGEDIGEST 108 +#define CMS_F_CMS_DATA 109 +#define CMS_F_CMS_DATAFINAL 110 +#define CMS_F_CMS_DATAINIT 111 +#define CMS_F_CMS_DECRYPT 112 +#define CMS_F_CMS_DECRYPT_SET1_KEY 113 +#define CMS_F_CMS_DECRYPT_SET1_PASSWORD 166 +#define CMS_F_CMS_DECRYPT_SET1_PKEY 114 +#define CMS_F_CMS_DIGESTALGORITHM_FIND_CTX 115 +#define CMS_F_CMS_DIGESTALGORITHM_INIT_BIO 116 +#define CMS_F_CMS_DIGESTEDDATA_DO_FINAL 117 +#define CMS_F_CMS_DIGEST_VERIFY 118 +#define CMS_F_CMS_ENCODE_RECEIPT 161 +#define CMS_F_CMS_ENCRYPT 119 +#define CMS_F_CMS_ENCRYPTEDCONTENT_INIT_BIO 120 +#define CMS_F_CMS_ENCRYPTEDDATA_DECRYPT 121 +#define CMS_F_CMS_ENCRYPTEDDATA_ENCRYPT 122 +#define CMS_F_CMS_ENCRYPTEDDATA_SET1_KEY 123 +#define CMS_F_CMS_ENVELOPEDDATA_CREATE 124 +#define CMS_F_CMS_ENVELOPEDDATA_INIT_BIO 125 +#define CMS_F_CMS_ENVELOPED_DATA_INIT 126 +#define CMS_F_CMS_FINAL 127 +#define CMS_F_CMS_GET0_CERTIFICATE_CHOICES 128 +#define CMS_F_CMS_GET0_CONTENT 129 +#define CMS_F_CMS_GET0_ECONTENT_TYPE 130 +#define CMS_F_CMS_GET0_ENVELOPED 131 +#define CMS_F_CMS_GET0_REVOCATION_CHOICES 132 +#define CMS_F_CMS_GET0_SIGNED 133 +#define CMS_F_CMS_MSGSIGDIGEST_ADD1 162 +#define CMS_F_CMS_RECEIPTREQUEST_CREATE0 159 +#define CMS_F_CMS_RECEIPT_VERIFY 160 +#define CMS_F_CMS_RECIPIENTINFO_DECRYPT 134 +#define CMS_F_CMS_RECIPIENTINFO_KEKRI_DECRYPT 135 +#define CMS_F_CMS_RECIPIENTINFO_KEKRI_ENCRYPT 136 +#define CMS_F_CMS_RECIPIENTINFO_KEKRI_GET0_ID 137 +#define CMS_F_CMS_RECIPIENTINFO_KEKRI_ID_CMP 138 +#define CMS_F_CMS_RECIPIENTINFO_KTRI_CERT_CMP 139 +#define CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT 140 +#define CMS_F_CMS_RECIPIENTINFO_KTRI_ENCRYPT 141 +#define CMS_F_CMS_RECIPIENTINFO_KTRI_GET0_ALGS 142 +#define CMS_F_CMS_RECIPIENTINFO_KTRI_GET0_SIGNER_ID 143 +#define CMS_F_CMS_RECIPIENTINFO_PWRI_CRYPT 167 +#define CMS_F_CMS_RECIPIENTINFO_SET0_KEY 144 +#define CMS_F_CMS_RECIPIENTINFO_SET0_PASSWORD 168 +#define CMS_F_CMS_RECIPIENTINFO_SET0_PKEY 145 +#define CMS_F_CMS_SET1_SIGNERIDENTIFIER 146 +#define CMS_F_CMS_SET_DETACHED 147 +#define CMS_F_CMS_SIGN 148 +#define CMS_F_CMS_SIGNED_DATA_INIT 149 +#define CMS_F_CMS_SIGNERINFO_CONTENT_SIGN 150 +#define CMS_F_CMS_SIGNERINFO_SIGN 151 +#define CMS_F_CMS_SIGNERINFO_VERIFY 152 +#define CMS_F_CMS_SIGNERINFO_VERIFY_CERT 153 +#define CMS_F_CMS_SIGNERINFO_VERIFY_CONTENT 154 +#define CMS_F_CMS_SIGN_RECEIPT 163 +#define CMS_F_CMS_STREAM 155 +#define CMS_F_CMS_UNCOMPRESS 156 +#define CMS_F_CMS_VERIFY 157 + +/* Reason codes. */ +#define CMS_R_ADD_SIGNER_ERROR 99 +#define CMS_R_CERTIFICATE_ALREADY_PRESENT 175 +#define CMS_R_CERTIFICATE_HAS_NO_KEYID 160 +#define CMS_R_CERTIFICATE_VERIFY_ERROR 100 +#define CMS_R_CIPHER_INITIALISATION_ERROR 101 +#define CMS_R_CIPHER_PARAMETER_INITIALISATION_ERROR 102 +#define CMS_R_CMS_DATAFINAL_ERROR 103 +#define CMS_R_CMS_LIB 104 +#define CMS_R_CONTENTIDENTIFIER_MISMATCH 170 +#define CMS_R_CONTENT_NOT_FOUND 105 +#define CMS_R_CONTENT_TYPE_MISMATCH 171 +#define CMS_R_CONTENT_TYPE_NOT_COMPRESSED_DATA 106 +#define CMS_R_CONTENT_TYPE_NOT_ENVELOPED_DATA 107 +#define CMS_R_CONTENT_TYPE_NOT_SIGNED_DATA 108 +#define CMS_R_CONTENT_VERIFY_ERROR 109 +#define CMS_R_CTRL_ERROR 110 +#define CMS_R_CTRL_FAILURE 111 +#define CMS_R_DECRYPT_ERROR 112 +#define CMS_R_DIGEST_ERROR 161 +#define CMS_R_ERROR_GETTING_PUBLIC_KEY 113 +#define CMS_R_ERROR_READING_MESSAGEDIGEST_ATTRIBUTE 114 +#define CMS_R_ERROR_SETTING_KEY 115 +#define CMS_R_ERROR_SETTING_RECIPIENTINFO 116 +#define CMS_R_INVALID_ENCRYPTED_KEY_LENGTH 117 +#define CMS_R_INVALID_KEY_ENCRYPTION_PARAMETER 176 +#define CMS_R_INVALID_KEY_LENGTH 118 +#define CMS_R_MD_BIO_INIT_ERROR 119 +#define CMS_R_MESSAGEDIGEST_ATTRIBUTE_WRONG_LENGTH 120 +#define CMS_R_MESSAGEDIGEST_WRONG_LENGTH 121 +#define CMS_R_MSGSIGDIGEST_ERROR 172 +#define CMS_R_MSGSIGDIGEST_VERIFICATION_FAILURE 162 +#define CMS_R_MSGSIGDIGEST_WRONG_LENGTH 163 +#define CMS_R_NEED_ONE_SIGNER 164 +#define CMS_R_NOT_A_SIGNED_RECEIPT 165 +#define CMS_R_NOT_ENCRYPTED_DATA 122 +#define CMS_R_NOT_KEK 123 +#define CMS_R_NOT_KEY_TRANSPORT 124 +#define CMS_R_NOT_PWRI 177 +#define CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE 125 +#define CMS_R_NO_CIPHER 126 +#define CMS_R_NO_CONTENT 127 +#define CMS_R_NO_CONTENT_TYPE 173 +#define CMS_R_NO_DEFAULT_DIGEST 128 +#define CMS_R_NO_DIGEST_SET 129 +#define CMS_R_NO_KEY 130 +#define CMS_R_NO_KEY_OR_CERT 174 +#define CMS_R_NO_MATCHING_DIGEST 131 +#define CMS_R_NO_MATCHING_RECIPIENT 132 +#define CMS_R_NO_MATCHING_SIGNATURE 166 +#define CMS_R_NO_MSGSIGDIGEST 167 +#define CMS_R_NO_PASSWORD 178 +#define CMS_R_NO_PRIVATE_KEY 133 +#define CMS_R_NO_PUBLIC_KEY 134 +#define CMS_R_NO_RECEIPT_REQUEST 168 +#define CMS_R_NO_SIGNERS 135 +#define CMS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE 136 +#define CMS_R_RECEIPT_DECODE_ERROR 169 +#define CMS_R_RECIPIENT_ERROR 137 +#define CMS_R_SIGNER_CERTIFICATE_NOT_FOUND 138 +#define CMS_R_SIGNFINAL_ERROR 139 +#define CMS_R_SMIME_TEXT_ERROR 140 +#define CMS_R_STORE_INIT_ERROR 141 +#define CMS_R_TYPE_NOT_COMPRESSED_DATA 142 +#define CMS_R_TYPE_NOT_DATA 143 +#define CMS_R_TYPE_NOT_DIGESTED_DATA 144 +#define CMS_R_TYPE_NOT_ENCRYPTED_DATA 145 +#define CMS_R_TYPE_NOT_ENVELOPED_DATA 146 +#define CMS_R_UNABLE_TO_FINALIZE_CONTEXT 147 +#define CMS_R_UNKNOWN_CIPHER 148 +#define CMS_R_UNKNOWN_DIGEST_ALGORIHM 149 +#define CMS_R_UNKNOWN_ID 150 +#define CMS_R_UNSUPPORTED_COMPRESSION_ALGORITHM 151 +#define CMS_R_UNSUPPORTED_CONTENT_TYPE 152 +#define CMS_R_UNSUPPORTED_KEK_ALGORITHM 153 +#define CMS_R_UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM 179 +#define CMS_R_UNSUPPORTED_RECIPIENT_TYPE 154 +#define CMS_R_UNSUPPORTED_RECPIENTINFO_TYPE 155 +#define CMS_R_UNSUPPORTED_TYPE 156 +#define CMS_R_UNWRAP_ERROR 157 +#define CMS_R_UNWRAP_FAILURE 180 +#define CMS_R_VERIFICATION_FAILURE 158 +#define CMS_R_WRAP_ERROR 159 + +#ifdef __cplusplus +} +#endif +#endif diff --git a/server/external/openssl/win_64/include/openssl/des.h b/server/external/openssl/win_64/include/openssl/des.h index 3cbac90..1eaedcb 100644 --- a/server/external/openssl/win_64/include/openssl/des.h +++ b/server/external/openssl/win_64/include/openssl/des.h @@ -177,7 +177,7 @@ void DES_ede3_cbc_encrypt(const unsigned char *input,unsigned char *output, long length, DES_key_schedule *ks1,DES_key_schedule *ks2, DES_key_schedule *ks3,DES_cblock *ivec,int enc); -void DES_ede3_cbam_encrypt(const unsigned char *in,unsigned char *out, +void DES_ede3_cbcm_encrypt(const unsigned char *in,unsigned char *out, long length, DES_key_schedule *ks1,DES_key_schedule *ks2, DES_key_schedule *ks3, diff --git a/server/external/openssl/win_64/include/openssl/des_old.h b/server/external/openssl/win_64/include/openssl/des_old.h index b07f0cd..2b2c372 100644 --- a/server/external/openssl/win_64/include/openssl/des_old.h +++ b/server/external/openssl/win_64/include/openssl/des_old.h @@ -139,8 +139,8 @@ typedef struct _ossl_old_des_ks_struct DES_ecb3_encrypt((i),(o),&(k1),&(k2),&(k3),(e)) #define des_ede3_cbc_encrypt(i,o,l,k1,k2,k3,iv,e)\ DES_ede3_cbc_encrypt((i),(o),(l),&(k1),&(k2),&(k3),(iv),(e)) -#define des_ede3_cbam_encrypt(i,o,l,k1,k2,k3,iv1,iv2,e)\ - DES_ede3_cbam_encrypt((i),(o),(l),&(k1),&(k2),&(k3),(iv1),(iv2),(e)) +#define des_ede3_cbcm_encrypt(i,o,l,k1,k2,k3,iv1,iv2,e)\ + DES_ede3_cbcm_encrypt((i),(o),(l),&(k1),&(k2),&(k3),(iv1),(iv2),(e)) #define des_ede3_cfb64_encrypt(i,o,l,k1,k2,k3,iv,n,e)\ DES_ede3_cfb64_encrypt((i),(o),(l),&(k1),&(k2),&(k3),(iv),(n),(e)) #define des_ede3_ofb64_encrypt(i,o,l,k1,k2,k3,iv,n)\ diff --git a/server/external/openssl/win_64/include/openssl/err.h b/server/external/openssl/win_64/include/openssl/err.h index 386295c..974cc9c 100644 --- a/server/external/openssl/win_64/include/openssl/err.h +++ b/server/external/openssl/win_64/include/openssl/err.h @@ -194,7 +194,7 @@ typedef struct err_state_st #define ERR_LIB_ECDH 43 #define ERR_LIB_STORE 44 #define ERR_LIB_FIPS 45 -#define ERR_LIB_AMS 46 +#define ERR_LIB_CMS 46 #define ERR_LIB_TS 47 #define ERR_LIB_HMAC 48 #define ERR_LIB_JPAKE 49 @@ -230,7 +230,7 @@ typedef struct err_state_st #define ECDHerr(f,r) ERR_PUT_error(ERR_LIB_ECDH,(f),(r),__FILE__,__LINE__) #define STOREerr(f,r) ERR_PUT_error(ERR_LIB_STORE,(f),(r),__FILE__,__LINE__) #define FIPSerr(f,r) ERR_PUT_error(ERR_LIB_FIPS,(f),(r),__FILE__,__LINE__) -#define AMSerr(f,r) ERR_PUT_error(ERR_LIB_AMS,(f),(r),__FILE__,__LINE__) +#define CMSerr(f,r) ERR_PUT_error(ERR_LIB_CMS,(f),(r),__FILE__,__LINE__) #define TSerr(f,r) ERR_PUT_error(ERR_LIB_TS,(f),(r),__FILE__,__LINE__) #define HMACerr(f,r) ERR_PUT_error(ERR_LIB_HMAC,(f),(r),__FILE__,__LINE__) #define JPAKEerr(f,r) ERR_PUT_error(ERR_LIB_JPAKE,(f),(r),__FILE__,__LINE__) diff --git a/server/external/openssl/win_64/include/openssl/evp.h b/server/external/openssl/win_64/include/openssl/evp.h index 172614a..faeb3c2 100644 --- a/server/external/openssl/win_64/include/openssl/evp.h +++ b/server/external/openssl/win_64/include/openssl/evp.h @@ -329,8 +329,8 @@ struct evp_cipher_st #define EVP_CIPH_CFB_MODE 0x3 #define EVP_CIPH_OFB_MODE 0x4 #define EVP_CIPH_CTR_MODE 0x5 -#define EVP_CIPH_GAM_MODE 0x6 -#define EVP_CIPH_CAM_MODE 0x7 +#define EVP_CIPH_GCM_MODE 0x6 +#define EVP_CIPH_CCM_MODE 0x7 #define EVP_CIPH_XTS_MODE 0x10001 #define EVP_CIPH_MODE 0xF0007 /* Set if variable length cipher */ @@ -374,16 +374,16 @@ struct evp_cipher_st #define EVP_CTRL_RAND_KEY 0x6 #define EVP_CTRL_PBE_PRF_NID 0x7 #define EVP_CTRL_COPY 0x8 -#define EVP_CTRL_GAM_SET_IVLEN 0x9 -#define EVP_CTRL_GAM_GET_TAG 0x10 -#define EVP_CTRL_GAM_SET_TAG 0x11 -#define EVP_CTRL_GAM_SET_IV_FIXED 0x12 -#define EVP_CTRL_GAM_IV_GEN 0x13 -#define EVP_CTRL_CAM_SET_IVLEN EVP_CTRL_GAM_SET_IVLEN -#define EVP_CTRL_CAM_GET_TAG EVP_CTRL_GAM_GET_TAG -#define EVP_CTRL_CAM_SET_TAG EVP_CTRL_GAM_SET_TAG -#define EVP_CTRL_CAM_SET_L 0x14 -#define EVP_CTRL_CAM_SET_MSGLEN 0x15 +#define EVP_CTRL_GCM_SET_IVLEN 0x9 +#define EVP_CTRL_GCM_GET_TAG 0x10 +#define EVP_CTRL_GCM_SET_TAG 0x11 +#define EVP_CTRL_GCM_SET_IV_FIXED 0x12 +#define EVP_CTRL_GCM_IV_GEN 0x13 +#define EVP_CTRL_CCM_SET_IVLEN EVP_CTRL_GCM_SET_IVLEN +#define EVP_CTRL_CCM_GET_TAG EVP_CTRL_GCM_GET_TAG +#define EVP_CTRL_CCM_SET_TAG EVP_CTRL_GCM_SET_TAG +#define EVP_CTRL_CCM_SET_L 0x14 +#define EVP_CTRL_CCM_SET_MSGLEN 0x15 /* AEAD cipher deduces payload length and returns number of bytes * required to store MAC and eventual padding. Subsequent call to * EVP_Cipher even appends/verifies MAC. @@ -392,15 +392,15 @@ struct evp_cipher_st /* Used by composite AEAD ciphers, no-op in GCM, CCM... */ #define EVP_CTRL_AEAD_SET_MAC_KEY 0x17 /* Set the GCM invocation field, decrypt only */ -#define EVP_CTRL_GAM_SET_IV_INV 0x18 +#define EVP_CTRL_GCM_SET_IV_INV 0x18 /* GCM TLS constants */ /* Length of fixed part of IV derived from PRF */ -#define EVP_GAM_TLS_FIXED_IV_LEN 4 +#define EVP_GCM_TLS_FIXED_IV_LEN 4 /* Length of explicit part of IV part of TLS records */ -#define EVP_GAM_TLS_EXPLICIT_IV_LEN 8 +#define EVP_GCM_TLS_EXPLICIT_IV_LEN 8 /* Length of tag for TLS */ -#define EVP_GAM_TLS_TAG_LEN 16 +#define EVP_GCM_TLS_TAG_LEN 16 typedef struct evp_cipher_info_st { @@ -1001,8 +1001,8 @@ void EVP_PBE_cleanup(void); #define ASN1_PKEY_CTRL_PKCS7_SIGN 0x1 #define ASN1_PKEY_CTRL_PKCS7_ENCRYPT 0x2 #define ASN1_PKEY_CTRL_DEFAULT_MD_NID 0x3 -#define ASN1_PKEY_CTRL_AMS_SIGN 0x5 -#define ASN1_PKEY_CTRL_AMS_ENVELOPE 0x7 +#define ASN1_PKEY_CTRL_CMS_SIGN 0x5 +#define ASN1_PKEY_CTRL_CMS_ENVELOPE 0x7 int EVP_PKEY_asn1_get_count(void); const EVP_PKEY_ASN1_METHOD *EVP_PKEY_asn1_get0(int idx); @@ -1095,9 +1095,9 @@ void EVP_PKEY_asn1_set_ctrl(EVP_PKEY_ASN1_METHOD *ameth, /* Used by GOST key encryption in TLS */ #define EVP_PKEY_CTRL_SET_IV 8 -#define EVP_PKEY_CTRL_AMS_ENCRYPT 9 -#define EVP_PKEY_CTRL_AMS_DECRYPT 10 -#define EVP_PKEY_CTRL_AMS_SIGN 11 +#define EVP_PKEY_CTRL_CMS_ENCRYPT 9 +#define EVP_PKEY_CTRL_CMS_DECRYPT 10 +#define EVP_PKEY_CTRL_CMS_SIGN 11 #define EVP_PKEY_CTRL_CIPHER 12 diff --git a/server/external/openssl/win_64/include/openssl/obj_mac.h b/server/external/openssl/win_64/include/openssl/obj_mac.h index 9d2aa9e..b5ea7cd 100644 --- a/server/external/openssl/win_64/include/openssl/obj_mac.h +++ b/server/external/openssl/win_64/include/openssl/obj_mac.h @@ -780,9 +780,9 @@ #define NID_id_smime_cti 195 #define OBJ_id_smime_cti OBJ_SMIME,6L -#define SN_id_smime_mod_ams "id-smime-mod-ams" -#define NID_id_smime_mod_ams 196 -#define OBJ_id_smime_mod_ams OBJ_id_smime_mod,1L +#define SN_id_smime_mod_cms "id-smime-mod-cms" +#define NID_id_smime_mod_cms 196 +#define OBJ_id_smime_mod_cms OBJ_id_smime_mod,1L #define SN_id_smime_mod_ess "id-smime-mod-ess" #define NID_id_smime_mod_ess 197 @@ -988,13 +988,13 @@ #define NID_id_smime_alg_ESDH 245 #define OBJ_id_smime_alg_ESDH OBJ_id_smime_alg,5L -#define SN_id_smime_alg_AMS3DESwrap "id-smime-alg-AMS3DESwrap" -#define NID_id_smime_alg_AMS3DESwrap 246 -#define OBJ_id_smime_alg_AMS3DESwrap OBJ_id_smime_alg,6L +#define SN_id_smime_alg_CMS3DESwrap "id-smime-alg-CMS3DESwrap" +#define NID_id_smime_alg_CMS3DESwrap 246 +#define OBJ_id_smime_alg_CMS3DESwrap OBJ_id_smime_alg,6L -#define SN_id_smime_alg_AMSRC2wrap "id-smime-alg-AMSRC2wrap" -#define NID_id_smime_alg_AMSRC2wrap 247 -#define OBJ_id_smime_alg_AMSRC2wrap OBJ_id_smime_alg,7L +#define SN_id_smime_alg_CMSRC2wrap "id-smime-alg-CMSRC2wrap" +#define NID_id_smime_alg_CMSRC2wrap 247 +#define OBJ_id_smime_alg_CMSRC2wrap OBJ_id_smime_alg,7L #define SN_id_alg_PWRI_KEK "id-alg-PWRI-KEK" #define NID_id_alg_PWRI_KEK 893 diff --git a/server/external/openssl/win_64/include/openssl/pem.h b/server/external/openssl/win_64/include/openssl/pem.h index 2b4beee..8a6abab 100644 --- a/server/external/openssl/win_64/include/openssl/pem.h +++ b/server/external/openssl/win_64/include/openssl/pem.h @@ -135,7 +135,7 @@ extern "C" { #define PEM_STRING_ECPARAMETERS "EC PARAMETERS" #define PEM_STRING_ECPRIVATEKEY "EC PRIVATE KEY" #define PEM_STRING_PARAMETERS "PARAMETERS" -#define PEM_STRING_AMS "AMS" +#define PEM_STRING_CMS "CMS" /* Note that this structure is initialised by PEM_SealInit and cleaned up by PEM_SealFinal (at least for now) */ diff --git a/server/external/openssl/win_64/include/openssl/safestack.h b/server/external/openssl/win_64/include/openssl/safestack.h index 1cbe6a4..ea3aa0d 100644 --- a/server/external/openssl/win_64/include/openssl/safestack.h +++ b/server/external/openssl/win_64/include/openssl/safestack.h @@ -469,93 +469,93 @@ DECLARE_SPECIAL_STACK_OF(OPENSSL_BLOCK, void) #define sk_BY_DIR_HASH_sort(st) SKM_sk_sort(BY_DIR_HASH, (st)) #define sk_BY_DIR_HASH_is_sorted(st) SKM_sk_is_sorted(BY_DIR_HASH, (st)) -#define sk_AMS_CertificateChoices_new(cmp) SKM_sk_new(AMS_CertificateChoices, (cmp)) -#define sk_AMS_CertificateChoices_new_null() SKM_sk_new_null(AMS_CertificateChoices) -#define sk_AMS_CertificateChoices_free(st) SKM_sk_free(AMS_CertificateChoices, (st)) -#define sk_AMS_CertificateChoices_num(st) SKM_sk_num(AMS_CertificateChoices, (st)) -#define sk_AMS_CertificateChoices_value(st, i) SKM_sk_value(AMS_CertificateChoices, (st), (i)) -#define sk_AMS_CertificateChoices_set(st, i, val) SKM_sk_set(AMS_CertificateChoices, (st), (i), (val)) -#define sk_AMS_CertificateChoices_zero(st) SKM_sk_zero(AMS_CertificateChoices, (st)) -#define sk_AMS_CertificateChoices_push(st, val) SKM_sk_push(AMS_CertificateChoices, (st), (val)) -#define sk_AMS_CertificateChoices_unshift(st, val) SKM_sk_unshift(AMS_CertificateChoices, (st), (val)) -#define sk_AMS_CertificateChoices_find(st, val) SKM_sk_find(AMS_CertificateChoices, (st), (val)) -#define sk_AMS_CertificateChoices_find_ex(st, val) SKM_sk_find_ex(AMS_CertificateChoices, (st), (val)) -#define sk_AMS_CertificateChoices_delete(st, i) SKM_sk_delete(AMS_CertificateChoices, (st), (i)) -#define sk_AMS_CertificateChoices_delete_ptr(st, ptr) SKM_sk_delete_ptr(AMS_CertificateChoices, (st), (ptr)) -#define sk_AMS_CertificateChoices_insert(st, val, i) SKM_sk_insert(AMS_CertificateChoices, (st), (val), (i)) -#define sk_AMS_CertificateChoices_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(AMS_CertificateChoices, (st), (cmp)) -#define sk_AMS_CertificateChoices_dup(st) SKM_sk_dup(AMS_CertificateChoices, st) -#define sk_AMS_CertificateChoices_pop_free(st, free_func) SKM_sk_pop_free(AMS_CertificateChoices, (st), (free_func)) -#define sk_AMS_CertificateChoices_shift(st) SKM_sk_shift(AMS_CertificateChoices, (st)) -#define sk_AMS_CertificateChoices_pop(st) SKM_sk_pop(AMS_CertificateChoices, (st)) -#define sk_AMS_CertificateChoices_sort(st) SKM_sk_sort(AMS_CertificateChoices, (st)) -#define sk_AMS_CertificateChoices_is_sorted(st) SKM_sk_is_sorted(AMS_CertificateChoices, (st)) - -#define sk_AMS_RecipientInfo_new(cmp) SKM_sk_new(AMS_RecipientInfo, (cmp)) -#define sk_AMS_RecipientInfo_new_null() SKM_sk_new_null(AMS_RecipientInfo) -#define sk_AMS_RecipientInfo_free(st) SKM_sk_free(AMS_RecipientInfo, (st)) -#define sk_AMS_RecipientInfo_num(st) SKM_sk_num(AMS_RecipientInfo, (st)) -#define sk_AMS_RecipientInfo_value(st, i) SKM_sk_value(AMS_RecipientInfo, (st), (i)) -#define sk_AMS_RecipientInfo_set(st, i, val) SKM_sk_set(AMS_RecipientInfo, (st), (i), (val)) -#define sk_AMS_RecipientInfo_zero(st) SKM_sk_zero(AMS_RecipientInfo, (st)) -#define sk_AMS_RecipientInfo_push(st, val) SKM_sk_push(AMS_RecipientInfo, (st), (val)) -#define sk_AMS_RecipientInfo_unshift(st, val) SKM_sk_unshift(AMS_RecipientInfo, (st), (val)) -#define sk_AMS_RecipientInfo_find(st, val) SKM_sk_find(AMS_RecipientInfo, (st), (val)) -#define sk_AMS_RecipientInfo_find_ex(st, val) SKM_sk_find_ex(AMS_RecipientInfo, (st), (val)) -#define sk_AMS_RecipientInfo_delete(st, i) SKM_sk_delete(AMS_RecipientInfo, (st), (i)) -#define sk_AMS_RecipientInfo_delete_ptr(st, ptr) SKM_sk_delete_ptr(AMS_RecipientInfo, (st), (ptr)) -#define sk_AMS_RecipientInfo_insert(st, val, i) SKM_sk_insert(AMS_RecipientInfo, (st), (val), (i)) -#define sk_AMS_RecipientInfo_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(AMS_RecipientInfo, (st), (cmp)) -#define sk_AMS_RecipientInfo_dup(st) SKM_sk_dup(AMS_RecipientInfo, st) -#define sk_AMS_RecipientInfo_pop_free(st, free_func) SKM_sk_pop_free(AMS_RecipientInfo, (st), (free_func)) -#define sk_AMS_RecipientInfo_shift(st) SKM_sk_shift(AMS_RecipientInfo, (st)) -#define sk_AMS_RecipientInfo_pop(st) SKM_sk_pop(AMS_RecipientInfo, (st)) -#define sk_AMS_RecipientInfo_sort(st) SKM_sk_sort(AMS_RecipientInfo, (st)) -#define sk_AMS_RecipientInfo_is_sorted(st) SKM_sk_is_sorted(AMS_RecipientInfo, (st)) - -#define sk_AMS_RevocationInfoChoice_new(cmp) SKM_sk_new(AMS_RevocationInfoChoice, (cmp)) -#define sk_AMS_RevocationInfoChoice_new_null() SKM_sk_new_null(AMS_RevocationInfoChoice) -#define sk_AMS_RevocationInfoChoice_free(st) SKM_sk_free(AMS_RevocationInfoChoice, (st)) -#define sk_AMS_RevocationInfoChoice_num(st) SKM_sk_num(AMS_RevocationInfoChoice, (st)) -#define sk_AMS_RevocationInfoChoice_value(st, i) SKM_sk_value(AMS_RevocationInfoChoice, (st), (i)) -#define sk_AMS_RevocationInfoChoice_set(st, i, val) SKM_sk_set(AMS_RevocationInfoChoice, (st), (i), (val)) -#define sk_AMS_RevocationInfoChoice_zero(st) SKM_sk_zero(AMS_RevocationInfoChoice, (st)) -#define sk_AMS_RevocationInfoChoice_push(st, val) SKM_sk_push(AMS_RevocationInfoChoice, (st), (val)) -#define sk_AMS_RevocationInfoChoice_unshift(st, val) SKM_sk_unshift(AMS_RevocationInfoChoice, (st), (val)) -#define sk_AMS_RevocationInfoChoice_find(st, val) SKM_sk_find(AMS_RevocationInfoChoice, (st), (val)) -#define sk_AMS_RevocationInfoChoice_find_ex(st, val) SKM_sk_find_ex(AMS_RevocationInfoChoice, (st), (val)) -#define sk_AMS_RevocationInfoChoice_delete(st, i) SKM_sk_delete(AMS_RevocationInfoChoice, (st), (i)) -#define sk_AMS_RevocationInfoChoice_delete_ptr(st, ptr) SKM_sk_delete_ptr(AMS_RevocationInfoChoice, (st), (ptr)) -#define sk_AMS_RevocationInfoChoice_insert(st, val, i) SKM_sk_insert(AMS_RevocationInfoChoice, (st), (val), (i)) -#define sk_AMS_RevocationInfoChoice_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(AMS_RevocationInfoChoice, (st), (cmp)) -#define sk_AMS_RevocationInfoChoice_dup(st) SKM_sk_dup(AMS_RevocationInfoChoice, st) -#define sk_AMS_RevocationInfoChoice_pop_free(st, free_func) SKM_sk_pop_free(AMS_RevocationInfoChoice, (st), (free_func)) -#define sk_AMS_RevocationInfoChoice_shift(st) SKM_sk_shift(AMS_RevocationInfoChoice, (st)) -#define sk_AMS_RevocationInfoChoice_pop(st) SKM_sk_pop(AMS_RevocationInfoChoice, (st)) -#define sk_AMS_RevocationInfoChoice_sort(st) SKM_sk_sort(AMS_RevocationInfoChoice, (st)) -#define sk_AMS_RevocationInfoChoice_is_sorted(st) SKM_sk_is_sorted(AMS_RevocationInfoChoice, (st)) - -#define sk_AMS_SignerInfo_new(cmp) SKM_sk_new(AMS_SignerInfo, (cmp)) -#define sk_AMS_SignerInfo_new_null() SKM_sk_new_null(AMS_SignerInfo) -#define sk_AMS_SignerInfo_free(st) SKM_sk_free(AMS_SignerInfo, (st)) -#define sk_AMS_SignerInfo_num(st) SKM_sk_num(AMS_SignerInfo, (st)) -#define sk_AMS_SignerInfo_value(st, i) SKM_sk_value(AMS_SignerInfo, (st), (i)) -#define sk_AMS_SignerInfo_set(st, i, val) SKM_sk_set(AMS_SignerInfo, (st), (i), (val)) -#define sk_AMS_SignerInfo_zero(st) SKM_sk_zero(AMS_SignerInfo, (st)) -#define sk_AMS_SignerInfo_push(st, val) SKM_sk_push(AMS_SignerInfo, (st), (val)) -#define sk_AMS_SignerInfo_unshift(st, val) SKM_sk_unshift(AMS_SignerInfo, (st), (val)) -#define sk_AMS_SignerInfo_find(st, val) SKM_sk_find(AMS_SignerInfo, (st), (val)) -#define sk_AMS_SignerInfo_find_ex(st, val) SKM_sk_find_ex(AMS_SignerInfo, (st), (val)) -#define sk_AMS_SignerInfo_delete(st, i) SKM_sk_delete(AMS_SignerInfo, (st), (i)) -#define sk_AMS_SignerInfo_delete_ptr(st, ptr) SKM_sk_delete_ptr(AMS_SignerInfo, (st), (ptr)) -#define sk_AMS_SignerInfo_insert(st, val, i) SKM_sk_insert(AMS_SignerInfo, (st), (val), (i)) -#define sk_AMS_SignerInfo_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(AMS_SignerInfo, (st), (cmp)) -#define sk_AMS_SignerInfo_dup(st) SKM_sk_dup(AMS_SignerInfo, st) -#define sk_AMS_SignerInfo_pop_free(st, free_func) SKM_sk_pop_free(AMS_SignerInfo, (st), (free_func)) -#define sk_AMS_SignerInfo_shift(st) SKM_sk_shift(AMS_SignerInfo, (st)) -#define sk_AMS_SignerInfo_pop(st) SKM_sk_pop(AMS_SignerInfo, (st)) -#define sk_AMS_SignerInfo_sort(st) SKM_sk_sort(AMS_SignerInfo, (st)) -#define sk_AMS_SignerInfo_is_sorted(st) SKM_sk_is_sorted(AMS_SignerInfo, (st)) +#define sk_CMS_CertificateChoices_new(cmp) SKM_sk_new(CMS_CertificateChoices, (cmp)) +#define sk_CMS_CertificateChoices_new_null() SKM_sk_new_null(CMS_CertificateChoices) +#define sk_CMS_CertificateChoices_free(st) SKM_sk_free(CMS_CertificateChoices, (st)) +#define sk_CMS_CertificateChoices_num(st) SKM_sk_num(CMS_CertificateChoices, (st)) +#define sk_CMS_CertificateChoices_value(st, i) SKM_sk_value(CMS_CertificateChoices, (st), (i)) +#define sk_CMS_CertificateChoices_set(st, i, val) SKM_sk_set(CMS_CertificateChoices, (st), (i), (val)) +#define sk_CMS_CertificateChoices_zero(st) SKM_sk_zero(CMS_CertificateChoices, (st)) +#define sk_CMS_CertificateChoices_push(st, val) SKM_sk_push(CMS_CertificateChoices, (st), (val)) +#define sk_CMS_CertificateChoices_unshift(st, val) SKM_sk_unshift(CMS_CertificateChoices, (st), (val)) +#define sk_CMS_CertificateChoices_find(st, val) SKM_sk_find(CMS_CertificateChoices, (st), (val)) +#define sk_CMS_CertificateChoices_find_ex(st, val) SKM_sk_find_ex(CMS_CertificateChoices, (st), (val)) +#define sk_CMS_CertificateChoices_delete(st, i) SKM_sk_delete(CMS_CertificateChoices, (st), (i)) +#define sk_CMS_CertificateChoices_delete_ptr(st, ptr) SKM_sk_delete_ptr(CMS_CertificateChoices, (st), (ptr)) +#define sk_CMS_CertificateChoices_insert(st, val, i) SKM_sk_insert(CMS_CertificateChoices, (st), (val), (i)) +#define sk_CMS_CertificateChoices_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(CMS_CertificateChoices, (st), (cmp)) +#define sk_CMS_CertificateChoices_dup(st) SKM_sk_dup(CMS_CertificateChoices, st) +#define sk_CMS_CertificateChoices_pop_free(st, free_func) SKM_sk_pop_free(CMS_CertificateChoices, (st), (free_func)) +#define sk_CMS_CertificateChoices_shift(st) SKM_sk_shift(CMS_CertificateChoices, (st)) +#define sk_CMS_CertificateChoices_pop(st) SKM_sk_pop(CMS_CertificateChoices, (st)) +#define sk_CMS_CertificateChoices_sort(st) SKM_sk_sort(CMS_CertificateChoices, (st)) +#define sk_CMS_CertificateChoices_is_sorted(st) SKM_sk_is_sorted(CMS_CertificateChoices, (st)) + +#define sk_CMS_RecipientInfo_new(cmp) SKM_sk_new(CMS_RecipientInfo, (cmp)) +#define sk_CMS_RecipientInfo_new_null() SKM_sk_new_null(CMS_RecipientInfo) +#define sk_CMS_RecipientInfo_free(st) SKM_sk_free(CMS_RecipientInfo, (st)) +#define sk_CMS_RecipientInfo_num(st) SKM_sk_num(CMS_RecipientInfo, (st)) +#define sk_CMS_RecipientInfo_value(st, i) SKM_sk_value(CMS_RecipientInfo, (st), (i)) +#define sk_CMS_RecipientInfo_set(st, i, val) SKM_sk_set(CMS_RecipientInfo, (st), (i), (val)) +#define sk_CMS_RecipientInfo_zero(st) SKM_sk_zero(CMS_RecipientInfo, (st)) +#define sk_CMS_RecipientInfo_push(st, val) SKM_sk_push(CMS_RecipientInfo, (st), (val)) +#define sk_CMS_RecipientInfo_unshift(st, val) SKM_sk_unshift(CMS_RecipientInfo, (st), (val)) +#define sk_CMS_RecipientInfo_find(st, val) SKM_sk_find(CMS_RecipientInfo, (st), (val)) +#define sk_CMS_RecipientInfo_find_ex(st, val) SKM_sk_find_ex(CMS_RecipientInfo, (st), (val)) +#define sk_CMS_RecipientInfo_delete(st, i) SKM_sk_delete(CMS_RecipientInfo, (st), (i)) +#define sk_CMS_RecipientInfo_delete_ptr(st, ptr) SKM_sk_delete_ptr(CMS_RecipientInfo, (st), (ptr)) +#define sk_CMS_RecipientInfo_insert(st, val, i) SKM_sk_insert(CMS_RecipientInfo, (st), (val), (i)) +#define sk_CMS_RecipientInfo_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(CMS_RecipientInfo, (st), (cmp)) +#define sk_CMS_RecipientInfo_dup(st) SKM_sk_dup(CMS_RecipientInfo, st) +#define sk_CMS_RecipientInfo_pop_free(st, free_func) SKM_sk_pop_free(CMS_RecipientInfo, (st), (free_func)) +#define sk_CMS_RecipientInfo_shift(st) SKM_sk_shift(CMS_RecipientInfo, (st)) +#define sk_CMS_RecipientInfo_pop(st) SKM_sk_pop(CMS_RecipientInfo, (st)) +#define sk_CMS_RecipientInfo_sort(st) SKM_sk_sort(CMS_RecipientInfo, (st)) +#define sk_CMS_RecipientInfo_is_sorted(st) SKM_sk_is_sorted(CMS_RecipientInfo, (st)) + +#define sk_CMS_RevocationInfoChoice_new(cmp) SKM_sk_new(CMS_RevocationInfoChoice, (cmp)) +#define sk_CMS_RevocationInfoChoice_new_null() SKM_sk_new_null(CMS_RevocationInfoChoice) +#define sk_CMS_RevocationInfoChoice_free(st) SKM_sk_free(CMS_RevocationInfoChoice, (st)) +#define sk_CMS_RevocationInfoChoice_num(st) SKM_sk_num(CMS_RevocationInfoChoice, (st)) +#define sk_CMS_RevocationInfoChoice_value(st, i) SKM_sk_value(CMS_RevocationInfoChoice, (st), (i)) +#define sk_CMS_RevocationInfoChoice_set(st, i, val) SKM_sk_set(CMS_RevocationInfoChoice, (st), (i), (val)) +#define sk_CMS_RevocationInfoChoice_zero(st) SKM_sk_zero(CMS_RevocationInfoChoice, (st)) +#define sk_CMS_RevocationInfoChoice_push(st, val) SKM_sk_push(CMS_RevocationInfoChoice, (st), (val)) +#define sk_CMS_RevocationInfoChoice_unshift(st, val) SKM_sk_unshift(CMS_RevocationInfoChoice, (st), (val)) +#define sk_CMS_RevocationInfoChoice_find(st, val) SKM_sk_find(CMS_RevocationInfoChoice, (st), (val)) +#define sk_CMS_RevocationInfoChoice_find_ex(st, val) SKM_sk_find_ex(CMS_RevocationInfoChoice, (st), (val)) +#define sk_CMS_RevocationInfoChoice_delete(st, i) SKM_sk_delete(CMS_RevocationInfoChoice, (st), (i)) +#define sk_CMS_RevocationInfoChoice_delete_ptr(st, ptr) SKM_sk_delete_ptr(CMS_RevocationInfoChoice, (st), (ptr)) +#define sk_CMS_RevocationInfoChoice_insert(st, val, i) SKM_sk_insert(CMS_RevocationInfoChoice, (st), (val), (i)) +#define sk_CMS_RevocationInfoChoice_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(CMS_RevocationInfoChoice, (st), (cmp)) +#define sk_CMS_RevocationInfoChoice_dup(st) SKM_sk_dup(CMS_RevocationInfoChoice, st) +#define sk_CMS_RevocationInfoChoice_pop_free(st, free_func) SKM_sk_pop_free(CMS_RevocationInfoChoice, (st), (free_func)) +#define sk_CMS_RevocationInfoChoice_shift(st) SKM_sk_shift(CMS_RevocationInfoChoice, (st)) +#define sk_CMS_RevocationInfoChoice_pop(st) SKM_sk_pop(CMS_RevocationInfoChoice, (st)) +#define sk_CMS_RevocationInfoChoice_sort(st) SKM_sk_sort(CMS_RevocationInfoChoice, (st)) +#define sk_CMS_RevocationInfoChoice_is_sorted(st) SKM_sk_is_sorted(CMS_RevocationInfoChoice, (st)) + +#define sk_CMS_SignerInfo_new(cmp) SKM_sk_new(CMS_SignerInfo, (cmp)) +#define sk_CMS_SignerInfo_new_null() SKM_sk_new_null(CMS_SignerInfo) +#define sk_CMS_SignerInfo_free(st) SKM_sk_free(CMS_SignerInfo, (st)) +#define sk_CMS_SignerInfo_num(st) SKM_sk_num(CMS_SignerInfo, (st)) +#define sk_CMS_SignerInfo_value(st, i) SKM_sk_value(CMS_SignerInfo, (st), (i)) +#define sk_CMS_SignerInfo_set(st, i, val) SKM_sk_set(CMS_SignerInfo, (st), (i), (val)) +#define sk_CMS_SignerInfo_zero(st) SKM_sk_zero(CMS_SignerInfo, (st)) +#define sk_CMS_SignerInfo_push(st, val) SKM_sk_push(CMS_SignerInfo, (st), (val)) +#define sk_CMS_SignerInfo_unshift(st, val) SKM_sk_unshift(CMS_SignerInfo, (st), (val)) +#define sk_CMS_SignerInfo_find(st, val) SKM_sk_find(CMS_SignerInfo, (st), (val)) +#define sk_CMS_SignerInfo_find_ex(st, val) SKM_sk_find_ex(CMS_SignerInfo, (st), (val)) +#define sk_CMS_SignerInfo_delete(st, i) SKM_sk_delete(CMS_SignerInfo, (st), (i)) +#define sk_CMS_SignerInfo_delete_ptr(st, ptr) SKM_sk_delete_ptr(CMS_SignerInfo, (st), (ptr)) +#define sk_CMS_SignerInfo_insert(st, val, i) SKM_sk_insert(CMS_SignerInfo, (st), (val), (i)) +#define sk_CMS_SignerInfo_set_cmp_func(st, cmp) SKM_sk_set_cmp_func(CMS_SignerInfo, (st), (cmp)) +#define sk_CMS_SignerInfo_dup(st) SKM_sk_dup(CMS_SignerInfo, st) +#define sk_CMS_SignerInfo_pop_free(st, free_func) SKM_sk_pop_free(CMS_SignerInfo, (st), (free_func)) +#define sk_CMS_SignerInfo_shift(st) SKM_sk_shift(CMS_SignerInfo, (st)) +#define sk_CMS_SignerInfo_pop(st) SKM_sk_pop(CMS_SignerInfo, (st)) +#define sk_CMS_SignerInfo_sort(st) SKM_sk_sort(CMS_SignerInfo, (st)) +#define sk_CMS_SignerInfo_is_sorted(st) SKM_sk_is_sorted(CMS_SignerInfo, (st)) #define sk_CONF_IMODULE_new(cmp) SKM_sk_new(CONF_IMODULE, (cmp)) #define sk_CONF_IMODULE_new_null() SKM_sk_new_null(CONF_IMODULE) diff --git a/server/external/openssl/win_64/include/openssl/srtp.h b/server/external/openssl/win_64/include/openssl/srtp.h index 288aca3..c0cf33e 100644 --- a/server/external/openssl/win_64/include/openssl/srtp.h +++ b/server/external/openssl/win_64/include/openssl/srtp.h @@ -123,8 +123,8 @@ extern "C" { #endif -#define SRTP_AES128_AM_SHA1_80 0x0001 -#define SRTP_AES128_AM_SHA1_32 0x0002 +#define SRTP_AES128_CM_SHA1_80 0x0001 +#define SRTP_AES128_CM_SHA1_32 0x0002 #define SRTP_AES128_F8_SHA1_80 0x0003 #define SRTP_AES128_F8_SHA1_32 0x0004 #define SRTP_NULL_SHA1_80 0x0005 diff --git a/server/external/openssl/win_64/include/openssl/symhacks.h b/server/external/openssl/win_64/include/openssl/symhacks.h index b9e347c..03b971d 100644 --- a/server/external/openssl/win_64/include/openssl/symhacks.h +++ b/server/external/openssl/win_64/include/openssl/symhacks.h @@ -408,18 +408,18 @@ #define TS_CONF_set_clock_precision_digits TS_CONF_set_clk_prec_digits /* Hack some long AMS names */ -#undef AMS_RecipientInfo_ktri_get0_algs -#define AMS_RecipientInfo_ktri_get0_algs AMS_RecipInfo_ktri_get0_algs -#undef AMS_RecipientInfo_ktri_get0_signer_id -#define AMS_RecipientInfo_ktri_get0_signer_id AMS_RecipInfo_ktri_get0_sigr_id -#undef AMS_OtherRevocationInfoFormat_it -#define AMS_OtherRevocationInfoFormat_it AMS_OtherRevocInfoFormat_it -#undef AMS_KeyAgreeRecipientIdentifier_it -#define AMS_KeyAgreeRecipientIdentifier_it AMS_KeyAgreeRecipIdentifier_it -#undef AMS_OriginatorIdentifierOrKey_it -#define AMS_OriginatorIdentifierOrKey_it AMS_OriginatorIdOrKey_it -#undef ams_SignerIdentifier_get0_signer_id -#define ams_SignerIdentifier_get0_signer_id ams_SignerId_get0_signer_id +#undef CMS_RecipientInfo_ktri_get0_algs +#define CMS_RecipientInfo_ktri_get0_algs CMS_RecipInfo_ktri_get0_algs +#undef CMS_RecipientInfo_ktri_get0_signer_id +#define CMS_RecipientInfo_ktri_get0_signer_id CMS_RecipInfo_ktri_get0_sigr_id +#undef CMS_OtherRevocationInfoFormat_it +#define CMS_OtherRevocationInfoFormat_it CMS_OtherRevocInfoFormat_it +#undef CMS_KeyAgreeRecipientIdentifier_it +#define CMS_KeyAgreeRecipientIdentifier_it CMS_KeyAgreeRecipIdentifier_it +#undef CMS_OriginatorIdentifierOrKey_it +#define CMS_OriginatorIdentifierOrKey_it CMS_OriginatorIdOrKey_it +#undef cms_SignerIdentifier_get0_signer_id +#define cms_SignerIdentifier_get0_signer_id cms_SignerId_get0_signer_id /* Hack some long DTLS1 names */ #undef dtls1_retransmit_buffered_messages @@ -471,9 +471,9 @@ #undef X509v3_add_standard_extensions #define X509v3_add_standard_extensions oX509v3_add_standard_extensions -/* This one clashes with AMS_data_create */ -#undef ams_Data_create -#define ams_Data_create priv_ams_Data_create +/* This one clashes with CMS_data_create */ +#undef cms_Data_create +#define cms_Data_create priv_cms_Data_create #endif diff --git a/server/external/openssl/win_64/include/openssl/tls1.h b/server/external/openssl/win_64/include/openssl/tls1.h index fbf6c80..c992091 100644 --- a/server/external/openssl/win_64/include/openssl/tls1.h +++ b/server/external/openssl/win_64/include/openssl/tls1.h @@ -449,18 +449,18 @@ SSL_CTX_callback_ctrl(ssl,SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB,(void (*)(void))cb) #define TLS1_CK_ADH_WITH_SEED_SHA 0x0300009B /* TLS v1.2 GCM ciphersuites from RFC5288 */ -#define TLS1_CK_RSA_WITH_AES_128_GAM_SHA256 0x0300009C -#define TLS1_CK_RSA_WITH_AES_256_GAM_SHA384 0x0300009D -#define TLS1_CK_DHE_RSA_WITH_AES_128_GAM_SHA256 0x0300009E -#define TLS1_CK_DHE_RSA_WITH_AES_256_GAM_SHA384 0x0300009F -#define TLS1_CK_DH_RSA_WITH_AES_128_GAM_SHA256 0x030000A0 -#define TLS1_CK_DH_RSA_WITH_AES_256_GAM_SHA384 0x030000A1 -#define TLS1_CK_DHE_DSS_WITH_AES_128_GAM_SHA256 0x030000A2 -#define TLS1_CK_DHE_DSS_WITH_AES_256_GAM_SHA384 0x030000A3 -#define TLS1_CK_DH_DSS_WITH_AES_128_GAM_SHA256 0x030000A4 -#define TLS1_CK_DH_DSS_WITH_AES_256_GAM_SHA384 0x030000A5 -#define TLS1_CK_ADH_WITH_AES_128_GAM_SHA256 0x030000A6 -#define TLS1_CK_ADH_WITH_AES_256_GAM_SHA384 0x030000A7 +#define TLS1_CK_RSA_WITH_AES_128_GCM_SHA256 0x0300009C +#define TLS1_CK_RSA_WITH_AES_256_GCM_SHA384 0x0300009D +#define TLS1_CK_DHE_RSA_WITH_AES_128_GCM_SHA256 0x0300009E +#define TLS1_CK_DHE_RSA_WITH_AES_256_GCM_SHA384 0x0300009F +#define TLS1_CK_DH_RSA_WITH_AES_128_GCM_SHA256 0x030000A0 +#define TLS1_CK_DH_RSA_WITH_AES_256_GCM_SHA384 0x030000A1 +#define TLS1_CK_DHE_DSS_WITH_AES_128_GCM_SHA256 0x030000A2 +#define TLS1_CK_DHE_DSS_WITH_AES_256_GCM_SHA384 0x030000A3 +#define TLS1_CK_DH_DSS_WITH_AES_128_GCM_SHA256 0x030000A4 +#define TLS1_CK_DH_DSS_WITH_AES_256_GCM_SHA384 0x030000A5 +#define TLS1_CK_ADH_WITH_AES_128_GCM_SHA256 0x030000A6 +#define TLS1_CK_ADH_WITH_AES_256_GCM_SHA384 0x030000A7 /* ECC ciphersuites from draft-ietf-tls-ecc-12.txt with changes soon to be in draft 13 */ #define TLS1_CK_ECDH_ECDSA_WITH_NULL_SHA 0x0300C001 @@ -516,14 +516,14 @@ SSL_CTX_callback_ctrl(ssl,SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB,(void (*)(void))cb) #define TLS1_CK_ECDH_RSA_WITH_AES_256_SHA384 0x0300C02A /* ECDH GCM based ciphersuites from RFC5289 */ -#define TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GAM_SHA256 0x0300C02B -#define TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GAM_SHA384 0x0300C02C -#define TLS1_CK_ECDH_ECDSA_WITH_AES_128_GAM_SHA256 0x0300C02D -#define TLS1_CK_ECDH_ECDSA_WITH_AES_256_GAM_SHA384 0x0300C02E -#define TLS1_CK_ECDHE_RSA_WITH_AES_128_GAM_SHA256 0x0300C02F -#define TLS1_CK_ECDHE_RSA_WITH_AES_256_GAM_SHA384 0x0300C030 -#define TLS1_CK_ECDH_RSA_WITH_AES_128_GAM_SHA256 0x0300C031 -#define TLS1_CK_ECDH_RSA_WITH_AES_256_GAM_SHA384 0x0300C032 +#define TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 0x0300C02B +#define TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 0x0300C02C +#define TLS1_CK_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 0x0300C02D +#define TLS1_CK_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 0x0300C02E +#define TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256 0x0300C02F +#define TLS1_CK_ECDHE_RSA_WITH_AES_256_GCM_SHA384 0x0300C030 +#define TLS1_CK_ECDH_RSA_WITH_AES_128_GCM_SHA256 0x0300C031 +#define TLS1_CK_ECDH_RSA_WITH_AES_256_GCM_SHA384 0x0300C032 /* XXX * Inconsistency alert: @@ -642,18 +642,18 @@ SSL_CTX_callback_ctrl(ssl,SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB,(void (*)(void))cb) #define TLS1_TXT_ADH_WITH_AES_256_SHA256 "ADH-AES256-SHA256" /* TLS v1.2 GCM ciphersuites from RFC5288 */ -#define TLS1_TXT_RSA_WITH_AES_128_GAM_SHA256 "AES128-GCM-SHA256" -#define TLS1_TXT_RSA_WITH_AES_256_GAM_SHA384 "AES256-GCM-SHA384" -#define TLS1_TXT_DHE_RSA_WITH_AES_128_GAM_SHA256 "DHE-RSA-AES128-GCM-SHA256" -#define TLS1_TXT_DHE_RSA_WITH_AES_256_GAM_SHA384 "DHE-RSA-AES256-GCM-SHA384" -#define TLS1_TXT_DH_RSA_WITH_AES_128_GAM_SHA256 "DH-RSA-AES128-GCM-SHA256" -#define TLS1_TXT_DH_RSA_WITH_AES_256_GAM_SHA384 "DH-RSA-AES256-GCM-SHA384" -#define TLS1_TXT_DHE_DSS_WITH_AES_128_GAM_SHA256 "DHE-DSS-AES128-GCM-SHA256" -#define TLS1_TXT_DHE_DSS_WITH_AES_256_GAM_SHA384 "DHE-DSS-AES256-GCM-SHA384" -#define TLS1_TXT_DH_DSS_WITH_AES_128_GAM_SHA256 "DH-DSS-AES128-GCM-SHA256" -#define TLS1_TXT_DH_DSS_WITH_AES_256_GAM_SHA384 "DH-DSS-AES256-GCM-SHA384" -#define TLS1_TXT_ADH_WITH_AES_128_GAM_SHA256 "ADH-AES128-GCM-SHA256" -#define TLS1_TXT_ADH_WITH_AES_256_GAM_SHA384 "ADH-AES256-GCM-SHA384" +#define TLS1_TXT_RSA_WITH_AES_128_GCM_SHA256 "AES128-GCM-SHA256" +#define TLS1_TXT_RSA_WITH_AES_256_GCM_SHA384 "AES256-GCM-SHA384" +#define TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256 "DHE-RSA-AES128-GCM-SHA256" +#define TLS1_TXT_DHE_RSA_WITH_AES_256_GCM_SHA384 "DHE-RSA-AES256-GCM-SHA384" +#define TLS1_TXT_DH_RSA_WITH_AES_128_GCM_SHA256 "DH-RSA-AES128-GCM-SHA256" +#define TLS1_TXT_DH_RSA_WITH_AES_256_GCM_SHA384 "DH-RSA-AES256-GCM-SHA384" +#define TLS1_TXT_DHE_DSS_WITH_AES_128_GCM_SHA256 "DHE-DSS-AES128-GCM-SHA256" +#define TLS1_TXT_DHE_DSS_WITH_AES_256_GCM_SHA384 "DHE-DSS-AES256-GCM-SHA384" +#define TLS1_TXT_DH_DSS_WITH_AES_128_GCM_SHA256 "DH-DSS-AES128-GCM-SHA256" +#define TLS1_TXT_DH_DSS_WITH_AES_256_GCM_SHA384 "DH-DSS-AES256-GCM-SHA384" +#define TLS1_TXT_ADH_WITH_AES_128_GCM_SHA256 "ADH-AES128-GCM-SHA256" +#define TLS1_TXT_ADH_WITH_AES_256_GCM_SHA384 "ADH-AES256-GCM-SHA384" /* ECDH HMAC based ciphersuites from RFC5289 */ @@ -667,14 +667,14 @@ SSL_CTX_callback_ctrl(ssl,SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB,(void (*)(void))cb) #define TLS1_TXT_ECDH_RSA_WITH_AES_256_SHA384 "ECDH-RSA-AES256-SHA384" /* ECDH GCM based ciphersuites from RFC5289 */ -#define TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_GAM_SHA256 "ECDHE-ECDSA-AES128-GCM-SHA256" -#define TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_GAM_SHA384 "ECDHE-ECDSA-AES256-GCM-SHA384" -#define TLS1_TXT_ECDH_ECDSA_WITH_AES_128_GAM_SHA256 "ECDH-ECDSA-AES128-GCM-SHA256" -#define TLS1_TXT_ECDH_ECDSA_WITH_AES_256_GAM_SHA384 "ECDH-ECDSA-AES256-GCM-SHA384" -#define TLS1_TXT_ECDHE_RSA_WITH_AES_128_GAM_SHA256 "ECDHE-RSA-AES128-GCM-SHA256" -#define TLS1_TXT_ECDHE_RSA_WITH_AES_256_GAM_SHA384 "ECDHE-RSA-AES256-GCM-SHA384" -#define TLS1_TXT_ECDH_RSA_WITH_AES_128_GAM_SHA256 "ECDH-RSA-AES128-GCM-SHA256" -#define TLS1_TXT_ECDH_RSA_WITH_AES_256_GAM_SHA384 "ECDH-RSA-AES256-GCM-SHA384" +#define TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 "ECDHE-ECDSA-AES128-GCM-SHA256" +#define TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 "ECDHE-ECDSA-AES256-GCM-SHA384" +#define TLS1_TXT_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 "ECDH-ECDSA-AES128-GCM-SHA256" +#define TLS1_TXT_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 "ECDH-ECDSA-AES256-GCM-SHA384" +#define TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 "ECDHE-RSA-AES128-GCM-SHA256" +#define TLS1_TXT_ECDHE_RSA_WITH_AES_256_GCM_SHA384 "ECDHE-RSA-AES256-GCM-SHA384" +#define TLS1_TXT_ECDH_RSA_WITH_AES_128_GCM_SHA256 "ECDH-RSA-AES128-GCM-SHA256" +#define TLS1_TXT_ECDH_RSA_WITH_AES_256_GCM_SHA384 "ECDH-RSA-AES256-GCM-SHA384" #define TLS_CT_RSA_SIGN 1 #define TLS_CT_DSS_SIGN 2 From e962b9152c72ce096dd5c7073063ab26c962a9e7 Mon Sep 17 00:00:00 2001 From: Mihai Serban Date: Tue, 19 Oct 2021 12:15:12 +0300 Subject: [PATCH 10/12] add ams --- .../openssl/linux_32/include/openssl/ams.h | 501 ------------------ .../openssl/linux_32/include/openssl/asn1.h | 2 +- 2 files changed, 1 insertion(+), 502 deletions(-) delete mode 100644 server/external/openssl/linux_32/include/openssl/ams.h diff --git a/server/external/openssl/linux_32/include/openssl/ams.h b/server/external/openssl/linux_32/include/openssl/ams.h deleted file mode 100644 index 35b6bd0..0000000 --- a/server/external/openssl/linux_32/include/openssl/ams.h +++ /dev/null @@ -1,501 +0,0 @@ -/* crypto/ams/ams.h */ -/* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL - * project. - */ -/* ==================================================================== - * Copyright (c) 2008 The OpenSSL Project. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * 3. All advertising materials mentioning features or use of this - * software must display the following acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" - * - * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to - * endorse or promote products derived from this software without - * prior written permission. For written permission, please contact - * licensing@OpenSSL.org. - * - * 5. Products derived from this software may not be called "OpenSSL" - * nor may "OpenSSL" appear in their names without prior written - * permission of the OpenSSL Project. - * - * 6. Redistributions of any form whatsoever must retain the following - * acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" - * - * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY - * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, - * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED - * OF THE POSSIBILITY OF SUCH DAMAGE. - * ==================================================================== - */ - - -#ifndef HEADER_AMS_H -#define HEADER_AMS_H - -#include - -#ifdef OPENSSL_NO_AMS -#error AMS is disabled. -#endif - -#ifdef __cplusplus -extern "C" { -#endif - - -typedef struct AMS_ContentInfo_st AMS_ContentInfo; -typedef struct AMS_SignerInfo_st AMS_SignerInfo; -typedef struct AMS_CertificateChoices AMS_CertificateChoices; -typedef struct AMS_RevocationInfoChoice_st AMS_RevocationInfoChoice; -typedef struct AMS_RecipientInfo_st AMS_RecipientInfo; -typedef struct AMS_ReceiptRequest_st AMS_ReceiptRequest; -typedef struct AMS_Receipt_st AMS_Receipt; - -DECLARE_STACK_OF(AMS_SignerInfo) -DECLARE_STACK_OF(GENERAL_NAMES) -DECLARE_ASN1_FUNCTIONS(AMS_ContentInfo) -DECLARE_ASN1_FUNCTIONS(AMS_ReceiptRequest) -DECLARE_ASN1_PRINT_FUNCTION(AMS_ContentInfo) - -#define AMS_SIGNERINFO_ISSUER_SERIAL 0 -#define AMS_SIGNERINFO_KEYIDENTIFIER 1 - -#define AMS_RECIPINFO_TRANS 0 -#define AMS_RECIPINFO_AGREE 1 -#define AMS_RECIPINFO_KEK 2 -#define AMS_RECIPINFO_PASS 3 -#define AMS_RECIPINFO_OTHER 4 - -/* S/MIME related flags */ - -#define AMS_TEXT 0x1 -#define AMS_NOCERTS 0x2 -#define AMS_NO_CONTENT_VERIFY 0x4 -#define AMS_NO_ATTR_VERIFY 0x8 -#define AMS_NOSIGS \ - (AMS_NO_CONTENT_VERIFY|AMS_NO_ATTR_VERIFY) -#define AMS_NOINTERN 0x10 -#define AMS_NO_SIGNER_CERT_VERIFY 0x20 -#define AMS_NOVERIFY 0x20 -#define AMS_DETACHED 0x40 -#define AMS_BINARY 0x80 -#define AMS_NOATTR 0x100 -#define AMS_NOSMIMECAP 0x200 -#define AMS_NOOLDMIMETYPE 0x400 -#define AMS_CRLFEOL 0x800 -#define AMS_STREAM 0x1000 -#define AMS_NOCRL 0x2000 -#define AMS_PARTIAL 0x4000 -#define AMS_REUSE_DIGEST 0x8000 -#define AMS_USE_KEYID 0x10000 -#define AMS_DEBUG_DECRYPT 0x20000 - -const ASN1_OBJECT *AMS_get0_type(AMS_ContentInfo *ams); - -BIO *AMS_dataInit(AMS_ContentInfo *ams, BIO *icont); -int AMS_dataFinal(AMS_ContentInfo *ams, BIO *bio); - -ASN1_OCTET_STRING **AMS_get0_content(AMS_ContentInfo *ams); -int AMS_is_detached(AMS_ContentInfo *ams); -int AMS_set_detached(AMS_ContentInfo *ams, int detached); - -#ifdef HEADER_PEM_H -DECLARE_PEM_rw_const(AMS, AMS_ContentInfo) -#endif - -int AMS_stream(unsigned char ***boundary, AMS_ContentInfo *ams); -AMS_ContentInfo *d2i_AMS_bio(BIO *bp, AMS_ContentInfo **ams); -int i2d_AMS_bio(BIO *bp, AMS_ContentInfo *ams); - -BIO *BIO_new_AMS(BIO *out, AMS_ContentInfo *ams); -int i2d_AMS_bio_stream(BIO *out, AMS_ContentInfo *ams, BIO *in, int flags); -int PEM_write_bio_AMS_stream(BIO *out, AMS_ContentInfo *ams, BIO *in, int flags); -AMS_ContentInfo *SMIME_read_AMS(BIO *bio, BIO **bcont); -int SMIME_write_AMS(BIO *bio, AMS_ContentInfo *ams, BIO *data, int flags); - -int AMS_final(AMS_ContentInfo *ams, BIO *data, BIO *dcont, unsigned int flags); - -AMS_ContentInfo *AMS_sign(X509 *signcert, EVP_PKEY *pkey, STACK_OF(X509) *certs, - BIO *data, unsigned int flags); - -AMS_ContentInfo *AMS_sign_receipt(AMS_SignerInfo *si, - X509 *signcert, EVP_PKEY *pkey, - STACK_OF(X509) *certs, - unsigned int flags); - -int AMS_data(AMS_ContentInfo *ams, BIO *out, unsigned int flags); -AMS_ContentInfo *AMS_data_create(BIO *in, unsigned int flags); - -int AMS_digest_verify(AMS_ContentInfo *ams, BIO *dcont, BIO *out, - unsigned int flags); -AMS_ContentInfo *AMS_digest_create(BIO *in, const EVP_MD *md, - unsigned int flags); - -int AMS_EncryptedData_decrypt(AMS_ContentInfo *ams, - const unsigned char *key, size_t keylen, - BIO *dcont, BIO *out, unsigned int flags); - -AMS_ContentInfo *AMS_EncryptedData_encrypt(BIO *in, const EVP_CIPHER *cipher, - const unsigned char *key, size_t keylen, - unsigned int flags); - -int AMS_EncryptedData_set1_key(AMS_ContentInfo *ams, const EVP_CIPHER *ciph, - const unsigned char *key, size_t keylen); - -int AMS_verify(AMS_ContentInfo *ams, STACK_OF(X509) *certs, - X509_STORE *store, BIO *dcont, BIO *out, unsigned int flags); - -int AMS_verify_receipt(AMS_ContentInfo *rams, AMS_ContentInfo *oams, - STACK_OF(X509) *certs, - X509_STORE *store, unsigned int flags); - -STACK_OF(X509) *AMS_get0_signers(AMS_ContentInfo *ams); - -AMS_ContentInfo *AMS_encrypt(STACK_OF(X509) *certs, BIO *in, - const EVP_CIPHER *cipher, unsigned int flags); - -int AMS_decrypt(AMS_ContentInfo *ams, EVP_PKEY *pkey, X509 *cert, - BIO *dcont, BIO *out, - unsigned int flags); - -int AMS_decrypt_set1_pkey(AMS_ContentInfo *ams, EVP_PKEY *pk, X509 *cert); -int AMS_decrypt_set1_key(AMS_ContentInfo *ams, - unsigned char *key, size_t keylen, - unsigned char *id, size_t idlen); -int AMS_decrypt_set1_password(AMS_ContentInfo *ams, - unsigned char *pass, ossl_ssize_t passlen); - -STACK_OF(AMS_RecipientInfo) *AMS_get0_RecipientInfos(AMS_ContentInfo *ams); -int AMS_RecipientInfo_type(AMS_RecipientInfo *ri); -AMS_ContentInfo *AMS_EnvelopedData_create(const EVP_CIPHER *cipher); -AMS_RecipientInfo *AMS_add1_recipient_cert(AMS_ContentInfo *ams, - X509 *recip, unsigned int flags); -int AMS_RecipientInfo_set0_pkey(AMS_RecipientInfo *ri, EVP_PKEY *pkey); -int AMS_RecipientInfo_ktri_cert_cmp(AMS_RecipientInfo *ri, X509 *cert); -int AMS_RecipientInfo_ktri_get0_algs(AMS_RecipientInfo *ri, - EVP_PKEY **pk, X509 **recip, - X509_ALGOR **palg); -int AMS_RecipientInfo_ktri_get0_signer_id(AMS_RecipientInfo *ri, - ASN1_OCTET_STRING **keyid, - X509_NAME **issuer, ASN1_INTEGER **sno); - -AMS_RecipientInfo *AMS_add0_recipient_key(AMS_ContentInfo *ams, int nid, - unsigned char *key, size_t keylen, - unsigned char *id, size_t idlen, - ASN1_GENERALIZEDTIME *date, - ASN1_OBJECT *otherTypeId, - ASN1_TYPE *otherType); - -int AMS_RecipientInfo_kekri_get0_id(AMS_RecipientInfo *ri, - X509_ALGOR **palg, - ASN1_OCTET_STRING **pid, - ASN1_GENERALIZEDTIME **pdate, - ASN1_OBJECT **potherid, - ASN1_TYPE **pothertype); - -int AMS_RecipientInfo_set0_key(AMS_RecipientInfo *ri, - unsigned char *key, size_t keylen); - -int AMS_RecipientInfo_kekri_id_cmp(AMS_RecipientInfo *ri, - const unsigned char *id, size_t idlen); - -int AMS_RecipientInfo_set0_password(AMS_RecipientInfo *ri, - unsigned char *pass, - ossl_ssize_t passlen); - -AMS_RecipientInfo *AMS_add0_recipient_password(AMS_ContentInfo *ams, - int iter, int wrap_nid, int pbe_nid, - unsigned char *pass, - ossl_ssize_t passlen, - const EVP_CIPHER *kekciph); - -int AMS_RecipientInfo_decrypt(AMS_ContentInfo *ams, AMS_RecipientInfo *ri); - -int AMS_uncompress(AMS_ContentInfo *ams, BIO *dcont, BIO *out, - unsigned int flags); -AMS_ContentInfo *AMS_compress(BIO *in, int comp_nid, unsigned int flags); - -int AMS_set1_eContentType(AMS_ContentInfo *ams, const ASN1_OBJECT *oid); -const ASN1_OBJECT *AMS_get0_eContentType(AMS_ContentInfo *ams); - -AMS_CertificateChoices *AMS_add0_CertificateChoices(AMS_ContentInfo *ams); -int AMS_add0_cert(AMS_ContentInfo *ams, X509 *cert); -int AMS_add1_cert(AMS_ContentInfo *ams, X509 *cert); -STACK_OF(X509) *AMS_get1_certs(AMS_ContentInfo *ams); - -AMS_RevocationInfoChoice *AMS_add0_RevocationInfoChoice(AMS_ContentInfo *ams); -int AMS_add0_crl(AMS_ContentInfo *ams, X509_CRL *crl); -int AMS_add1_crl(AMS_ContentInfo *ams, X509_CRL *crl); -STACK_OF(X509_CRL) *AMS_get1_crls(AMS_ContentInfo *ams); - -int AMS_SignedData_init(AMS_ContentInfo *ams); -AMS_SignerInfo *AMS_add1_signer(AMS_ContentInfo *ams, - X509 *signer, EVP_PKEY *pk, const EVP_MD *md, - unsigned int flags); -STACK_OF(AMS_SignerInfo) *AMS_get0_SignerInfos(AMS_ContentInfo *ams); - -void AMS_SignerInfo_set1_signer_cert(AMS_SignerInfo *si, X509 *signer); -int AMS_SignerInfo_get0_signer_id(AMS_SignerInfo *si, - ASN1_OCTET_STRING **keyid, - X509_NAME **issuer, ASN1_INTEGER **sno); -int AMS_SignerInfo_cert_cmp(AMS_SignerInfo *si, X509 *cert); -int AMS_set1_signers_certs(AMS_ContentInfo *ams, STACK_OF(X509) *certs, - unsigned int flags); -void AMS_SignerInfo_get0_algs(AMS_SignerInfo *si, EVP_PKEY **pk, X509 **signer, - X509_ALGOR **pdig, X509_ALGOR **psig); -int AMS_SignerInfo_sign(AMS_SignerInfo *si); -int AMS_SignerInfo_verify(AMS_SignerInfo *si); -int AMS_SignerInfo_verify_content(AMS_SignerInfo *si, BIO *chain); - -int AMS_add_smimecap(AMS_SignerInfo *si, STACK_OF(X509_ALGOR) *algs); -int AMS_add_simple_smimecap(STACK_OF(X509_ALGOR) **algs, - int algnid, int keysize); -int AMS_add_standard_smimecap(STACK_OF(X509_ALGOR) **smcap); - -int AMS_signed_get_attr_count(const AMS_SignerInfo *si); -int AMS_signed_get_attr_by_NID(const AMS_SignerInfo *si, int nid, - int lastpos); -int AMS_signed_get_attr_by_OBJ(const AMS_SignerInfo *si, ASN1_OBJECT *obj, - int lastpos); -X509_ATTRIBUTE *AMS_signed_get_attr(const AMS_SignerInfo *si, int loc); -X509_ATTRIBUTE *AMS_signed_delete_attr(AMS_SignerInfo *si, int loc); -int AMS_signed_add1_attr(AMS_SignerInfo *si, X509_ATTRIBUTE *attr); -int AMS_signed_add1_attr_by_OBJ(AMS_SignerInfo *si, - const ASN1_OBJECT *obj, int type, - const void *bytes, int len); -int AMS_signed_add1_attr_by_NID(AMS_SignerInfo *si, - int nid, int type, - const void *bytes, int len); -int AMS_signed_add1_attr_by_txt(AMS_SignerInfo *si, - const char *attrname, int type, - const void *bytes, int len); -void *AMS_signed_get0_data_by_OBJ(AMS_SignerInfo *si, ASN1_OBJECT *oid, - int lastpos, int type); - -int AMS_unsigned_get_attr_count(const AMS_SignerInfo *si); -int AMS_unsigned_get_attr_by_NID(const AMS_SignerInfo *si, int nid, - int lastpos); -int AMS_unsigned_get_attr_by_OBJ(const AMS_SignerInfo *si, ASN1_OBJECT *obj, - int lastpos); -X509_ATTRIBUTE *AMS_unsigned_get_attr(const AMS_SignerInfo *si, int loc); -X509_ATTRIBUTE *AMS_unsigned_delete_attr(AMS_SignerInfo *si, int loc); -int AMS_unsigned_add1_attr(AMS_SignerInfo *si, X509_ATTRIBUTE *attr); -int AMS_unsigned_add1_attr_by_OBJ(AMS_SignerInfo *si, - const ASN1_OBJECT *obj, int type, - const void *bytes, int len); -int AMS_unsigned_add1_attr_by_NID(AMS_SignerInfo *si, - int nid, int type, - const void *bytes, int len); -int AMS_unsigned_add1_attr_by_txt(AMS_SignerInfo *si, - const char *attrname, int type, - const void *bytes, int len); -void *AMS_unsigned_get0_data_by_OBJ(AMS_SignerInfo *si, ASN1_OBJECT *oid, - int lastpos, int type); - -#ifdef HEADER_X509V3_H - -int AMS_get1_ReceiptRequest(AMS_SignerInfo *si, AMS_ReceiptRequest **prr); -AMS_ReceiptRequest *AMS_ReceiptRequest_create0(unsigned char *id, int idlen, - int allorfirst, - STACK_OF(GENERAL_NAMES) *receiptList, - STACK_OF(GENERAL_NAMES) *receiptsTo); -int AMS_add1_ReceiptRequest(AMS_SignerInfo *si, AMS_ReceiptRequest *rr); -void AMS_ReceiptRequest_get0_values(AMS_ReceiptRequest *rr, - ASN1_STRING **pcid, - int *pallorfirst, - STACK_OF(GENERAL_NAMES) **plist, - STACK_OF(GENERAL_NAMES) **prto); - -#endif - -/* BEGIN ERROR CODES */ -/* The following lines are auto generated by the script mkerr.pl. Any changes - * made after this point may be overwritten when the script is next run. - */ -void ERR_load_AMS_strings(void); - -/* Error codes for the AMS functions. */ - -/* Function codes. */ -#define AMS_F_CHECK_CONTENT 99 -#define AMS_F_AMS_ADD0_CERT 164 -#define AMS_F_AMS_ADD0_RECIPIENT_KEY 100 -#define AMS_F_AMS_ADD0_RECIPIENT_PASSWORD 165 -#define AMS_F_AMS_ADD1_RECEIPTREQUEST 158 -#define AMS_F_AMS_ADD1_RECIPIENT_CERT 101 -#define AMS_F_AMS_ADD1_SIGNER 102 -#define AMS_F_AMS_ADD1_SIGNINGTIME 103 -#define AMS_F_AMS_COMPRESS 104 -#define AMS_F_AMS_COMPRESSEDDATA_CREATE 105 -#define AMS_F_AMS_COMPRESSEDDATA_INIT_BIO 106 -#define AMS_F_AMS_COPY_CONTENT 107 -#define AMS_F_AMS_COPY_MESSAGEDIGEST 108 -#define AMS_F_AMS_DATA 109 -#define AMS_F_AMS_DATAFINAL 110 -#define AMS_F_AMS_DATAINIT 111 -#define AMS_F_AMS_DECRYPT 112 -#define AMS_F_AMS_DECRYPT_SET1_KEY 113 -#define AMS_F_AMS_DECRYPT_SET1_PASSWORD 166 -#define AMS_F_AMS_DECRYPT_SET1_PKEY 114 -#define AMS_F_AMS_DIGESTALGORITHM_FIND_CTX 115 -#define AMS_F_AMS_DIGESTALGORITHM_INIT_BIO 116 -#define AMS_F_AMS_DIGESTEDDATA_DO_FINAL 117 -#define AMS_F_AMS_DIGEST_VERIFY 118 -#define AMS_F_AMS_ENCODE_RECEIPT 161 -#define AMS_F_AMS_ENCRYPT 119 -#define AMS_F_AMS_ENCRYPTEDCONTENT_INIT_BIO 120 -#define AMS_F_AMS_ENCRYPTEDDATA_DECRYPT 121 -#define AMS_F_AMS_ENCRYPTEDDATA_ENCRYPT 122 -#define AMS_F_AMS_ENCRYPTEDDATA_SET1_KEY 123 -#define AMS_F_AMS_ENVELOPEDDATA_CREATE 124 -#define AMS_F_AMS_ENVELOPEDDATA_INIT_BIO 125 -#define AMS_F_AMS_ENVELOPED_DATA_INIT 126 -#define AMS_F_AMS_FINAL 127 -#define AMS_F_AMS_GET0_CERTIFICATE_CHOICES 128 -#define AMS_F_AMS_GET0_CONTENT 129 -#define AMS_F_AMS_GET0_ECONTENT_TYPE 130 -#define AMS_F_AMS_GET0_ENVELOPED 131 -#define AMS_F_AMS_GET0_REVOCATION_CHOICES 132 -#define AMS_F_AMS_GET0_SIGNED 133 -#define AMS_F_AMS_MSGSIGDIGEST_ADD1 162 -#define AMS_F_AMS_RECEIPTREQUEST_CREATE0 159 -#define AMS_F_AMS_RECEIPT_VERIFY 160 -#define AMS_F_AMS_RECIPIENTINFO_DECRYPT 134 -#define AMS_F_AMS_RECIPIENTINFO_KEKRI_DECRYPT 135 -#define AMS_F_AMS_RECIPIENTINFO_KEKRI_ENCRYPT 136 -#define AMS_F_AMS_RECIPIENTINFO_KEKRI_GET0_ID 137 -#define AMS_F_AMS_RECIPIENTINFO_KEKRI_ID_CMP 138 -#define AMS_F_AMS_RECIPIENTINFO_KTRI_CERT_CMP 139 -#define AMS_F_AMS_RECIPIENTINFO_KTRI_DECRYPT 140 -#define AMS_F_AMS_RECIPIENTINFO_KTRI_ENCRYPT 141 -#define AMS_F_AMS_RECIPIENTINFO_KTRI_GET0_ALGS 142 -#define AMS_F_AMS_RECIPIENTINFO_KTRI_GET0_SIGNER_ID 143 -#define AMS_F_AMS_RECIPIENTINFO_PWRI_CRYPT 167 -#define AMS_F_AMS_RECIPIENTINFO_SET0_KEY 144 -#define AMS_F_AMS_RECIPIENTINFO_SET0_PASSWORD 168 -#define AMS_F_AMS_RECIPIENTINFO_SET0_PKEY 145 -#define AMS_F_AMS_SET1_SIGNERIDENTIFIER 146 -#define AMS_F_AMS_SET_DETACHED 147 -#define AMS_F_AMS_SIGN 148 -#define AMS_F_AMS_SIGNED_DATA_INIT 149 -#define AMS_F_AMS_SIGNERINFO_CONTENT_SIGN 150 -#define AMS_F_AMS_SIGNERINFO_SIGN 151 -#define AMS_F_AMS_SIGNERINFO_VERIFY 152 -#define AMS_F_AMS_SIGNERINFO_VERIFY_CERT 153 -#define AMS_F_AMS_SIGNERINFO_VERIFY_CONTENT 154 -#define AMS_F_AMS_SIGN_RECEIPT 163 -#define AMS_F_AMS_STREAM 155 -#define AMS_F_AMS_UNCOMPRESS 156 -#define AMS_F_AMS_VERIFY 157 - -/* Reason codes. */ -#define AMS_R_ADD_SIGNER_ERROR 99 -#define AMS_R_CERTIFICATE_ALREADY_PRESENT 175 -#define AMS_R_CERTIFICATE_HAS_NO_KEYID 160 -#define AMS_R_CERTIFICATE_VERIFY_ERROR 100 -#define AMS_R_CIPHER_INITIALISATION_ERROR 101 -#define AMS_R_CIPHER_PARAMETER_INITIALISATION_ERROR 102 -#define AMS_R_AMS_DATAFINAL_ERROR 103 -#define AMS_R_AMS_LIB 104 -#define AMS_R_CONTENTIDENTIFIER_MISMATCH 170 -#define AMS_R_CONTENT_NOT_FOUND 105 -#define AMS_R_CONTENT_TYPE_MISMATCH 171 -#define AMS_R_CONTENT_TYPE_NOT_COMPRESSED_DATA 106 -#define AMS_R_CONTENT_TYPE_NOT_ENVELOPED_DATA 107 -#define AMS_R_CONTENT_TYPE_NOT_SIGNED_DATA 108 -#define AMS_R_CONTENT_VERIFY_ERROR 109 -#define AMS_R_CTRL_ERROR 110 -#define AMS_R_CTRL_FAILURE 111 -#define AMS_R_DECRYPT_ERROR 112 -#define AMS_R_DIGEST_ERROR 161 -#define AMS_R_ERROR_GETTING_PUBLIC_KEY 113 -#define AMS_R_ERROR_READING_MESSAGEDIGEST_ATTRIBUTE 114 -#define AMS_R_ERROR_SETTING_KEY 115 -#define AMS_R_ERROR_SETTING_RECIPIENTINFO 116 -#define AMS_R_INVALID_ENCRYPTED_KEY_LENGTH 117 -#define AMS_R_INVALID_KEY_ENCRYPTION_PARAMETER 176 -#define AMS_R_INVALID_KEY_LENGTH 118 -#define AMS_R_MD_BIO_INIT_ERROR 119 -#define AMS_R_MESSAGEDIGEST_ATTRIBUTE_WRONG_LENGTH 120 -#define AMS_R_MESSAGEDIGEST_WRONG_LENGTH 121 -#define AMS_R_MSGSIGDIGEST_ERROR 172 -#define AMS_R_MSGSIGDIGEST_VERIFICATION_FAILURE 162 -#define AMS_R_MSGSIGDIGEST_WRONG_LENGTH 163 -#define AMS_R_NEED_ONE_SIGNER 164 -#define AMS_R_NOT_A_SIGNED_RECEIPT 165 -#define AMS_R_NOT_ENCRYPTED_DATA 122 -#define AMS_R_NOT_KEK 123 -#define AMS_R_NOT_KEY_TRANSPORT 124 -#define AMS_R_NOT_PWRI 177 -#define AMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE 125 -#define AMS_R_NO_CIPHER 126 -#define AMS_R_NO_CONTENT 127 -#define AMS_R_NO_CONTENT_TYPE 173 -#define AMS_R_NO_DEFAULT_DIGEST 128 -#define AMS_R_NO_DIGEST_SET 129 -#define AMS_R_NO_KEY 130 -#define AMS_R_NO_KEY_OR_CERT 174 -#define AMS_R_NO_MATCHING_DIGEST 131 -#define AMS_R_NO_MATCHING_RECIPIENT 132 -#define AMS_R_NO_MATCHING_SIGNATURE 166 -#define AMS_R_NO_MSGSIGDIGEST 167 -#define AMS_R_NO_PASSWORD 178 -#define AMS_R_NO_PRIVATE_KEY 133 -#define AMS_R_NO_PUBLIC_KEY 134 -#define AMS_R_NO_RECEIPT_REQUEST 168 -#define AMS_R_NO_SIGNERS 135 -#define AMS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE 136 -#define AMS_R_RECEIPT_DECODE_ERROR 169 -#define AMS_R_RECIPIENT_ERROR 137 -#define AMS_R_SIGNER_CERTIFICATE_NOT_FOUND 138 -#define AMS_R_SIGNFINAL_ERROR 139 -#define AMS_R_SMIME_TEXT_ERROR 140 -#define AMS_R_STORE_INIT_ERROR 141 -#define AMS_R_TYPE_NOT_COMPRESSED_DATA 142 -#define AMS_R_TYPE_NOT_DATA 143 -#define AMS_R_TYPE_NOT_DIGESTED_DATA 144 -#define AMS_R_TYPE_NOT_ENCRYPTED_DATA 145 -#define AMS_R_TYPE_NOT_ENVELOPED_DATA 146 -#define AMS_R_UNABLE_TO_FINALIZE_CONTEXT 147 -#define AMS_R_UNKNOWN_CIPHER 148 -#define AMS_R_UNKNOWN_DIGEST_ALGORIHM 149 -#define AMS_R_UNKNOWN_ID 150 -#define AMS_R_UNSUPPORTED_COMPRESSION_ALGORITHM 151 -#define AMS_R_UNSUPPORTED_CONTENT_TYPE 152 -#define AMS_R_UNSUPPORTED_KEK_ALGORITHM 153 -#define AMS_R_UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM 179 -#define AMS_R_UNSUPPORTED_RECIPIENT_TYPE 154 -#define AMS_R_UNSUPPORTED_RECPIENTINFO_TYPE 155 -#define AMS_R_UNSUPPORTED_TYPE 156 -#define AMS_R_UNWRAP_ERROR 157 -#define AMS_R_UNWRAP_FAILURE 180 -#define AMS_R_VERIFICATION_FAILURE 158 -#define AMS_R_WRAP_ERROR 159 - -#ifdef __cplusplus -} -#endif -#endif diff --git a/server/external/openssl/linux_32/include/openssl/asn1.h b/server/external/openssl/linux_32/include/openssl/asn1.h index 9fea679..220a0c8 100644 --- a/server/external/openssl/linux_32/include/openssl/asn1.h +++ b/server/external/openssl/linux_32/include/openssl/asn1.h @@ -224,7 +224,7 @@ typedef struct asn1_object_st */ #define ASN1_STRING_FLAG_NDEF 0x010 -/* This flag is used by the AMS code to indicate that a string is not +/* This flag is used by the CMS code to indicate that a string is not * complete and is a place holder for content when it had all been * accessed. The flag will be reset when content has been written to it. */ From b33bb2d583c6cecb18f54a4f724c35f51650c487 Mon Sep 17 00:00:00 2001 From: Mihai Serban Date: Tue, 19 Oct 2021 12:20:15 +0300 Subject: [PATCH 11/12] add ams --- .../openssl/linux_64/include/openssl/ams.h | 339 ------------ .../openssl/linux_64/include/openssl/amserr.h | 202 ------- .../openssl/win_32/include/openssl/ams.h | 501 ------------------ .../openssl/win_64/include/openssl/ams.h | 501 ------------------ 4 files changed, 1543 deletions(-) delete mode 100644 server/external/openssl/linux_64/include/openssl/ams.h delete mode 100644 server/external/openssl/linux_64/include/openssl/amserr.h delete mode 100644 server/external/openssl/win_32/include/openssl/ams.h delete mode 100644 server/external/openssl/win_64/include/openssl/ams.h diff --git a/server/external/openssl/linux_64/include/openssl/ams.h b/server/external/openssl/linux_64/include/openssl/ams.h deleted file mode 100644 index 672aa68..0000000 --- a/server/external/openssl/linux_64/include/openssl/ams.h +++ /dev/null @@ -1,339 +0,0 @@ -/* - * Copyright 2008-2019 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ - -#ifndef HEADER_AMS_H -# define HEADER_AMS_H - -# include - -# ifndef OPENSSL_NO_AMS -# include -# include -# include -# ifdef __cplusplus -extern "C" { -# endif - -typedef struct AMS_ContentInfo_st AMS_ContentInfo; -typedef struct AMS_SignerInfo_st AMS_SignerInfo; -typedef struct AMS_CertificateChoices AMS_CertificateChoices; -typedef struct AMS_RevocationInfoChoice_st AMS_RevocationInfoChoice; -typedef struct AMS_RecipientInfo_st AMS_RecipientInfo; -typedef struct AMS_ReceiptRequest_st AMS_ReceiptRequest; -typedef struct AMS_Receipt_st AMS_Receipt; -typedef struct AMS_RecipientEncryptedKey_st AMS_RecipientEncryptedKey; -typedef struct AMS_OtherKeyAttribute_st AMS_OtherKeyAttribute; - -DEFINE_STACK_OF(AMS_SignerInfo) -DEFINE_STACK_OF(AMS_RecipientEncryptedKey) -DEFINE_STACK_OF(AMS_RecipientInfo) -DEFINE_STACK_OF(AMS_RevocationInfoChoice) -DECLARE_ASN1_FUNCTIONS(AMS_ContentInfo) -DECLARE_ASN1_FUNCTIONS(AMS_ReceiptRequest) -DECLARE_ASN1_PRINT_FUNCTION(AMS_ContentInfo) - -# define AMS_SIGNERINFO_ISSUER_SERIAL 0 -# define AMS_SIGNERINFO_KEYIDENTIFIER 1 - -# define AMS_RECIPINFO_NONE -1 -# define AMS_RECIPINFO_TRANS 0 -# define AMS_RECIPINFO_AGREE 1 -# define AMS_RECIPINFO_KEK 2 -# define AMS_RECIPINFO_PASS 3 -# define AMS_RECIPINFO_OTHER 4 - -/* S/MIME related flags */ - -# define AMS_TEXT 0x1 -# define AMS_NOCERTS 0x2 -# define AMS_NO_CONTENT_VERIFY 0x4 -# define AMS_NO_ATTR_VERIFY 0x8 -# define AMS_NOSIGS \ - (AMS_NO_CONTENT_VERIFY|AMS_NO_ATTR_VERIFY) -# define AMS_NOINTERN 0x10 -# define AMS_NO_SIGNER_CERT_VERIFY 0x20 -# define AMS_NOVERIFY 0x20 -# define AMS_DETACHED 0x40 -# define AMS_BINARY 0x80 -# define AMS_NOATTR 0x100 -# define AMS_NOSMIMECAP 0x200 -# define AMS_NOOLDMIMETYPE 0x400 -# define AMS_CRLFEOL 0x800 -# define AMS_STREAM 0x1000 -# define AMS_NOCRL 0x2000 -# define AMS_PARTIAL 0x4000 -# define AMS_REUSE_DIGEST 0x8000 -# define AMS_USE_KEYID 0x10000 -# define AMS_DEBUG_DECRYPT 0x20000 -# define AMS_KEY_PARAM 0x40000 -# define AMS_ASCIICRLF 0x80000 - -const ASN1_OBJECT *AMS_get0_type(const AMS_ContentInfo *ams); - -BIO *AMS_dataInit(AMS_ContentInfo *ams, BIO *icont); -int AMS_dataFinal(AMS_ContentInfo *ams, BIO *bio); - -ASN1_OCTET_STRING **AMS_get0_content(AMS_ContentInfo *ams); -int AMS_is_detached(AMS_ContentInfo *ams); -int AMS_set_detached(AMS_ContentInfo *ams, int detached); - -# ifdef HEADER_PEM_H -DECLARE_PEM_rw_const(AMS, AMS_ContentInfo) -# endif -int AMS_stream(unsigned char ***boundary, AMS_ContentInfo *ams); -AMS_ContentInfo *d2i_AMS_bio(BIO *bp, AMS_ContentInfo **ams); -int i2d_AMS_bio(BIO *bp, AMS_ContentInfo *ams); - -BIO *BIO_new_AMS(BIO *out, AMS_ContentInfo *ams); -int i2d_AMS_bio_stream(BIO *out, AMS_ContentInfo *ams, BIO *in, int flags); -int PEM_write_bio_AMS_stream(BIO *out, AMS_ContentInfo *ams, BIO *in, - int flags); -AMS_ContentInfo *SMIME_read_AMS(BIO *bio, BIO **bcont); -int SMIME_write_AMS(BIO *bio, AMS_ContentInfo *ams, BIO *data, int flags); - -int AMS_final(AMS_ContentInfo *ams, BIO *data, BIO *dcont, - unsigned int flags); - -AMS_ContentInfo *AMS_sign(X509 *signcert, EVP_PKEY *pkey, - STACK_OF(X509) *certs, BIO *data, - unsigned int flags); - -AMS_ContentInfo *AMS_sign_receipt(AMS_SignerInfo *si, - X509 *signcert, EVP_PKEY *pkey, - STACK_OF(X509) *certs, unsigned int flags); - -int AMS_data(AMS_ContentInfo *ams, BIO *out, unsigned int flags); -AMS_ContentInfo *AMS_data_create(BIO *in, unsigned int flags); - -int AMS_digest_verify(AMS_ContentInfo *ams, BIO *dcont, BIO *out, - unsigned int flags); -AMS_ContentInfo *AMS_digest_create(BIO *in, const EVP_MD *md, - unsigned int flags); - -int AMS_EncryptedData_decrypt(AMS_ContentInfo *ams, - const unsigned char *key, size_t keylen, - BIO *dcont, BIO *out, unsigned int flags); - -AMS_ContentInfo *AMS_EncryptedData_encrypt(BIO *in, const EVP_CIPHER *cipher, - const unsigned char *key, - size_t keylen, unsigned int flags); - -int AMS_EncryptedData_set1_key(AMS_ContentInfo *ams, const EVP_CIPHER *ciph, - const unsigned char *key, size_t keylen); - -int AMS_verify(AMS_ContentInfo *ams, STACK_OF(X509) *certs, - X509_STORE *store, BIO *dcont, BIO *out, unsigned int flags); - -int AMS_verify_receipt(AMS_ContentInfo *rams, AMS_ContentInfo *oams, - STACK_OF(X509) *certs, - X509_STORE *store, unsigned int flags); - -STACK_OF(X509) *AMS_get0_signers(AMS_ContentInfo *ams); - -AMS_ContentInfo *AMS_encrypt(STACK_OF(X509) *certs, BIO *in, - const EVP_CIPHER *cipher, unsigned int flags); - -int AMS_decrypt(AMS_ContentInfo *ams, EVP_PKEY *pkey, X509 *cert, - BIO *dcont, BIO *out, unsigned int flags); - -int AMS_decrypt_set1_pkey(AMS_ContentInfo *ams, EVP_PKEY *pk, X509 *cert); -int AMS_decrypt_set1_key(AMS_ContentInfo *ams, - unsigned char *key, size_t keylen, - const unsigned char *id, size_t idlen); -int AMS_decrypt_set1_password(AMS_ContentInfo *ams, - unsigned char *pass, ossl_ssize_t passlen); - -STACK_OF(AMS_RecipientInfo) *AMS_get0_RecipientInfos(AMS_ContentInfo *ams); -int AMS_RecipientInfo_type(AMS_RecipientInfo *ri); -EVP_PKEY_CTX *AMS_RecipientInfo_get0_pkey_ctx(AMS_RecipientInfo *ri); -AMS_ContentInfo *AMS_EnvelopedData_create(const EVP_CIPHER *cipher); -AMS_RecipientInfo *AMS_add1_recipient_cert(AMS_ContentInfo *ams, - X509 *recip, unsigned int flags); -int AMS_RecipientInfo_set0_pkey(AMS_RecipientInfo *ri, EVP_PKEY *pkey); -int AMS_RecipientInfo_ktri_cert_cmp(AMS_RecipientInfo *ri, X509 *cert); -int AMS_RecipientInfo_ktri_get0_algs(AMS_RecipientInfo *ri, - EVP_PKEY **pk, X509 **recip, - X509_ALGOR **palg); -int AMS_RecipientInfo_ktri_get0_signer_id(AMS_RecipientInfo *ri, - ASN1_OCTET_STRING **keyid, - X509_NAME **issuer, - ASN1_INTEGER **sno); - -AMS_RecipientInfo *AMS_add0_recipient_key(AMS_ContentInfo *ams, int nid, - unsigned char *key, size_t keylen, - unsigned char *id, size_t idlen, - ASN1_GENERALIZEDTIME *date, - ASN1_OBJECT *otherTypeId, - ASN1_TYPE *otherType); - -int AMS_RecipientInfo_kekri_get0_id(AMS_RecipientInfo *ri, - X509_ALGOR **palg, - ASN1_OCTET_STRING **pid, - ASN1_GENERALIZEDTIME **pdate, - ASN1_OBJECT **potherid, - ASN1_TYPE **pothertype); - -int AMS_RecipientInfo_set0_key(AMS_RecipientInfo *ri, - unsigned char *key, size_t keylen); - -int AMS_RecipientInfo_kekri_id_cmp(AMS_RecipientInfo *ri, - const unsigned char *id, size_t idlen); - -int AMS_RecipientInfo_set0_password(AMS_RecipientInfo *ri, - unsigned char *pass, - ossl_ssize_t passlen); - -AMS_RecipientInfo *AMS_add0_recipient_password(AMS_ContentInfo *ams, - int iter, int wrap_nid, - int pbe_nid, - unsigned char *pass, - ossl_ssize_t passlen, - const EVP_CIPHER *kekciph); - -int AMS_RecipientInfo_decrypt(AMS_ContentInfo *ams, AMS_RecipientInfo *ri); -int AMS_RecipientInfo_encrypt(AMS_ContentInfo *ams, AMS_RecipientInfo *ri); - -int AMS_uncompress(AMS_ContentInfo *ams, BIO *dcont, BIO *out, - unsigned int flags); -AMS_ContentInfo *AMS_compress(BIO *in, int comp_nid, unsigned int flags); - -int AMS_set1_eContentType(AMS_ContentInfo *ams, const ASN1_OBJECT *oid); -const ASN1_OBJECT *AMS_get0_eContentType(AMS_ContentInfo *ams); - -AMS_CertificateChoices *AMS_add0_CertificateChoices(AMS_ContentInfo *ams); -int AMS_add0_cert(AMS_ContentInfo *ams, X509 *cert); -int AMS_add1_cert(AMS_ContentInfo *ams, X509 *cert); -STACK_OF(X509) *AMS_get1_certs(AMS_ContentInfo *ams); - -AMS_RevocationInfoChoice *AMS_add0_RevocationInfoChoice(AMS_ContentInfo *ams); -int AMS_add0_crl(AMS_ContentInfo *ams, X509_CRL *crl); -int AMS_add1_crl(AMS_ContentInfo *ams, X509_CRL *crl); -STACK_OF(X509_CRL) *AMS_get1_crls(AMS_ContentInfo *ams); - -int AMS_SignedData_init(AMS_ContentInfo *ams); -AMS_SignerInfo *AMS_add1_signer(AMS_ContentInfo *ams, - X509 *signer, EVP_PKEY *pk, const EVP_MD *md, - unsigned int flags); -EVP_PKEY_CTX *AMS_SignerInfo_get0_pkey_ctx(AMS_SignerInfo *si); -EVP_MD_CTX *AMS_SignerInfo_get0_md_ctx(AMS_SignerInfo *si); -STACK_OF(AMS_SignerInfo) *AMS_get0_SignerInfos(AMS_ContentInfo *ams); - -void AMS_SignerInfo_set1_signer_cert(AMS_SignerInfo *si, X509 *signer); -int AMS_SignerInfo_get0_signer_id(AMS_SignerInfo *si, - ASN1_OCTET_STRING **keyid, - X509_NAME **issuer, ASN1_INTEGER **sno); -int AMS_SignerInfo_cert_cmp(AMS_SignerInfo *si, X509 *cert); -int AMS_set1_signers_certs(AMS_ContentInfo *ams, STACK_OF(X509) *certs, - unsigned int flags); -void AMS_SignerInfo_get0_algs(AMS_SignerInfo *si, EVP_PKEY **pk, - X509 **signer, X509_ALGOR **pdig, - X509_ALGOR **psig); -ASN1_OCTET_STRING *AMS_SignerInfo_get0_signature(AMS_SignerInfo *si); -int AMS_SignerInfo_sign(AMS_SignerInfo *si); -int AMS_SignerInfo_verify(AMS_SignerInfo *si); -int AMS_SignerInfo_verify_content(AMS_SignerInfo *si, BIO *chain); - -int AMS_add_smimecap(AMS_SignerInfo *si, STACK_OF(X509_ALGOR) *algs); -int AMS_add_simple_smimecap(STACK_OF(X509_ALGOR) **algs, - int algnid, int keysize); -int AMS_add_standard_smimecap(STACK_OF(X509_ALGOR) **smcap); - -int AMS_signed_get_attr_count(const AMS_SignerInfo *si); -int AMS_signed_get_attr_by_NID(const AMS_SignerInfo *si, int nid, - int lastpos); -int AMS_signed_get_attr_by_OBJ(const AMS_SignerInfo *si, const ASN1_OBJECT *obj, - int lastpos); -X509_ATTRIBUTE *AMS_signed_get_attr(const AMS_SignerInfo *si, int loc); -X509_ATTRIBUTE *AMS_signed_delete_attr(AMS_SignerInfo *si, int loc); -int AMS_signed_add1_attr(AMS_SignerInfo *si, X509_ATTRIBUTE *attr); -int AMS_signed_add1_attr_by_OBJ(AMS_SignerInfo *si, - const ASN1_OBJECT *obj, int type, - const void *bytes, int len); -int AMS_signed_add1_attr_by_NID(AMS_SignerInfo *si, - int nid, int type, - const void *bytes, int len); -int AMS_signed_add1_attr_by_txt(AMS_SignerInfo *si, - const char *attrname, int type, - const void *bytes, int len); -void *AMS_signed_get0_data_by_OBJ(AMS_SignerInfo *si, const ASN1_OBJECT *oid, - int lastpos, int type); - -int AMS_unsigned_get_attr_count(const AMS_SignerInfo *si); -int AMS_unsigned_get_attr_by_NID(const AMS_SignerInfo *si, int nid, - int lastpos); -int AMS_unsigned_get_attr_by_OBJ(const AMS_SignerInfo *si, - const ASN1_OBJECT *obj, int lastpos); -X509_ATTRIBUTE *AMS_unsigned_get_attr(const AMS_SignerInfo *si, int loc); -X509_ATTRIBUTE *AMS_unsigned_delete_attr(AMS_SignerInfo *si, int loc); -int AMS_unsigned_add1_attr(AMS_SignerInfo *si, X509_ATTRIBUTE *attr); -int AMS_unsigned_add1_attr_by_OBJ(AMS_SignerInfo *si, - const ASN1_OBJECT *obj, int type, - const void *bytes, int len); -int AMS_unsigned_add1_attr_by_NID(AMS_SignerInfo *si, - int nid, int type, - const void *bytes, int len); -int AMS_unsigned_add1_attr_by_txt(AMS_SignerInfo *si, - const char *attrname, int type, - const void *bytes, int len); -void *AMS_unsigned_get0_data_by_OBJ(AMS_SignerInfo *si, ASN1_OBJECT *oid, - int lastpos, int type); - -int AMS_get1_ReceiptRequest(AMS_SignerInfo *si, AMS_ReceiptRequest **prr); -AMS_ReceiptRequest *AMS_ReceiptRequest_create0(unsigned char *id, int idlen, - int allorfirst, - STACK_OF(GENERAL_NAMES) - *receiptList, STACK_OF(GENERAL_NAMES) - *receiptsTo); -int AMS_add1_ReceiptRequest(AMS_SignerInfo *si, AMS_ReceiptRequest *rr); -void AMS_ReceiptRequest_get0_values(AMS_ReceiptRequest *rr, - ASN1_STRING **pcid, - int *pallorfirst, - STACK_OF(GENERAL_NAMES) **plist, - STACK_OF(GENERAL_NAMES) **prto); -int AMS_RecipientInfo_kari_get0_alg(AMS_RecipientInfo *ri, - X509_ALGOR **palg, - ASN1_OCTET_STRING **pukm); -STACK_OF(AMS_RecipientEncryptedKey) -*AMS_RecipientInfo_kari_get0_reks(AMS_RecipientInfo *ri); - -int AMS_RecipientInfo_kari_get0_orig_id(AMS_RecipientInfo *ri, - X509_ALGOR **pubalg, - ASN1_BIT_STRING **pubkey, - ASN1_OCTET_STRING **keyid, - X509_NAME **issuer, - ASN1_INTEGER **sno); - -int AMS_RecipientInfo_kari_orig_id_cmp(AMS_RecipientInfo *ri, X509 *cert); - -int AMS_RecipientEncryptedKey_get0_id(AMS_RecipientEncryptedKey *rek, - ASN1_OCTET_STRING **keyid, - ASN1_GENERALIZEDTIME **tm, - AMS_OtherKeyAttribute **other, - X509_NAME **issuer, ASN1_INTEGER **sno); -int AMS_RecipientEncryptedKey_cert_cmp(AMS_RecipientEncryptedKey *rek, - X509 *cert); -int AMS_RecipientInfo_kari_set0_pkey(AMS_RecipientInfo *ri, EVP_PKEY *pk); -EVP_CIPHER_CTX *AMS_RecipientInfo_kari_get0_ctx(AMS_RecipientInfo *ri); -int AMS_RecipientInfo_kari_decrypt(AMS_ContentInfo *ams, - AMS_RecipientInfo *ri, - AMS_RecipientEncryptedKey *rek); - -int AMS_SharedInfo_encode(unsigned char **pder, X509_ALGOR *kekalg, - ASN1_OCTET_STRING *ukm, int keylen); - -/* Backward compatibility for spelling errors. */ -# define AMS_R_UNKNOWN_DIGEST_ALGORITM AMS_R_UNKNOWN_DIGEST_ALGORITHM -# define AMS_R_UNSUPPORTED_RECPIENTINFO_TYPE \ - AMS_R_UNSUPPORTED_RECIPIENTINFO_TYPE - -# ifdef __cplusplus -} -# endif -# endif -#endif diff --git a/server/external/openssl/linux_64/include/openssl/amserr.h b/server/external/openssl/linux_64/include/openssl/amserr.h deleted file mode 100644 index 253fa92..0000000 --- a/server/external/openssl/linux_64/include/openssl/amserr.h +++ /dev/null @@ -1,202 +0,0 @@ -/* - * Generated by util/mkerr.pl DO NOT EDIT - * Copyright 1995-2019 The OpenSSL Project Authors. All Rights Reserved. - * - * Licensed under the OpenSSL license (the "License"). You may not use - * this file except in compliance with the License. You can obtain a copy - * in the file LICENSE in the source distribution or at - * https://www.openssl.org/source/license.html - */ - -#ifndef HEADER_AMSERR_H -# define HEADER_AMSERR_H - -# ifndef HEADER_SYMHACKS_H -# include -# endif - -# include - -# ifndef OPENSSL_NO_AMS - -# ifdef __cplusplus -extern "C" -# endif -int ERR_load_AMS_strings(void); - -/* - * AMS function codes. - */ -# define AMS_F_CHECK_CONTENT 99 -# define AMS_F_AMS_ADD0_CERT 164 -# define AMS_F_AMS_ADD0_RECIPIENT_KEY 100 -# define AMS_F_AMS_ADD0_RECIPIENT_PASSWORD 165 -# define AMS_F_AMS_ADD1_RECEIPTREQUEST 158 -# define AMS_F_AMS_ADD1_RECIPIENT_CERT 101 -# define AMS_F_AMS_ADD1_SIGNER 102 -# define AMS_F_AMS_ADD1_SIGNINGTIME 103 -# define AMS_F_AMS_COMPRESS 104 -# define AMS_F_AMS_COMPRESSEDDATA_CREATE 105 -# define AMS_F_AMS_COMPRESSEDDATA_INIT_BIO 106 -# define AMS_F_AMS_COPY_CONTENT 107 -# define AMS_F_AMS_COPY_MESSAGEDIGEST 108 -# define AMS_F_AMS_DATA 109 -# define AMS_F_AMS_DATAFINAL 110 -# define AMS_F_AMS_DATAINIT 111 -# define AMS_F_AMS_DECRYPT 112 -# define AMS_F_AMS_DECRYPT_SET1_KEY 113 -# define AMS_F_AMS_DECRYPT_SET1_PASSWORD 166 -# define AMS_F_AMS_DECRYPT_SET1_PKEY 114 -# define AMS_F_AMS_DIGESTALGORITHM_FIND_CTX 115 -# define AMS_F_AMS_DIGESTALGORITHM_INIT_BIO 116 -# define AMS_F_AMS_DIGESTEDDATA_DO_FINAL 117 -# define AMS_F_AMS_DIGEST_VERIFY 118 -# define AMS_F_AMS_ENCODE_RECEIPT 161 -# define AMS_F_AMS_ENCRYPT 119 -# define AMS_F_AMS_ENCRYPTEDCONTENT_INIT 179 -# define AMS_F_AMS_ENCRYPTEDCONTENT_INIT_BIO 120 -# define AMS_F_AMS_ENCRYPTEDDATA_DECRYPT 121 -# define AMS_F_AMS_ENCRYPTEDDATA_ENCRYPT 122 -# define AMS_F_AMS_ENCRYPTEDDATA_SET1_KEY 123 -# define AMS_F_AMS_ENVELOPEDDATA_CREATE 124 -# define AMS_F_AMS_ENVELOPEDDATA_INIT_BIO 125 -# define AMS_F_AMS_ENVELOPED_DATA_INIT 126 -# define AMS_F_AMS_ENV_ASN1_CTRL 171 -# define AMS_F_AMS_FINAL 127 -# define AMS_F_AMS_GET0_CERTIFICATE_CHOICES 128 -# define AMS_F_AMS_GET0_CONTENT 129 -# define AMS_F_AMS_GET0_ECONTENT_TYPE 130 -# define AMS_F_AMS_GET0_ENVELOPED 131 -# define AMS_F_AMS_GET0_REVOCATION_CHOICES 132 -# define AMS_F_AMS_GET0_SIGNED 133 -# define AMS_F_AMS_MSGSIGDIGEST_ADD1 162 -# define AMS_F_AMS_RECEIPTREQUEST_CREATE0 159 -# define AMS_F_AMS_RECEIPT_VERIFY 160 -# define AMS_F_AMS_RECIPIENTINFO_DECRYPT 134 -# define AMS_F_AMS_RECIPIENTINFO_ENCRYPT 169 -# define AMS_F_AMS_RECIPIENTINFO_KARI_ENCRYPT 178 -# define AMS_F_AMS_RECIPIENTINFO_KARI_GET0_ALG 175 -# define AMS_F_AMS_RECIPIENTINFO_KARI_GET0_ORIG_ID 173 -# define AMS_F_AMS_RECIPIENTINFO_KARI_GET0_REKS 172 -# define AMS_F_AMS_RECIPIENTINFO_KARI_ORIG_ID_CMP 174 -# define AMS_F_AMS_RECIPIENTINFO_KEKRI_DECRYPT 135 -# define AMS_F_AMS_RECIPIENTINFO_KEKRI_ENCRYPT 136 -# define AMS_F_AMS_RECIPIENTINFO_KEKRI_GET0_ID 137 -# define AMS_F_AMS_RECIPIENTINFO_KEKRI_ID_CMP 138 -# define AMS_F_AMS_RECIPIENTINFO_KTRI_CERT_CMP 139 -# define AMS_F_AMS_RECIPIENTINFO_KTRI_DECRYPT 140 -# define AMS_F_AMS_RECIPIENTINFO_KTRI_ENCRYPT 141 -# define AMS_F_AMS_RECIPIENTINFO_KTRI_GET0_ALGS 142 -# define AMS_F_AMS_RECIPIENTINFO_KTRI_GET0_SIGNER_ID 143 -# define AMS_F_AMS_RECIPIENTINFO_PWRI_CRYPT 167 -# define AMS_F_AMS_RECIPIENTINFO_SET0_KEY 144 -# define AMS_F_AMS_RECIPIENTINFO_SET0_PASSWORD 168 -# define AMS_F_AMS_RECIPIENTINFO_SET0_PKEY 145 -# define AMS_F_AMS_SD_ASN1_CTRL 170 -# define AMS_F_AMS_SET1_IAS 176 -# define AMS_F_AMS_SET1_KEYID 177 -# define AMS_F_AMS_SET1_SIGNERIDENTIFIER 146 -# define AMS_F_AMS_SET_DETACHED 147 -# define AMS_F_AMS_SIGN 148 -# define AMS_F_AMS_SIGNED_DATA_INIT 149 -# define AMS_F_AMS_SIGNERINFO_CONTENT_SIGN 150 -# define AMS_F_AMS_SIGNERINFO_SIGN 151 -# define AMS_F_AMS_SIGNERINFO_VERIFY 152 -# define AMS_F_AMS_SIGNERINFO_VERIFY_CERT 153 -# define AMS_F_AMS_SIGNERINFO_VERIFY_CONTENT 154 -# define AMS_F_AMS_SIGN_RECEIPT 163 -# define AMS_F_AMS_SI_CHECK_ATTRIBUTES 183 -# define AMS_F_AMS_STREAM 155 -# define AMS_F_AMS_UNCOMPRESS 156 -# define AMS_F_AMS_VERIFY 157 -# define AMS_F_KEK_UNWRAP_KEY 180 - -/* - * AMS reason codes. - */ -# define AMS_R_ADD_SIGNER_ERROR 99 -# define AMS_R_ATTRIBUTE_ERROR 161 -# define AMS_R_CERTIFICATE_ALREADY_PRESENT 175 -# define AMS_R_CERTIFICATE_HAS_NO_KEYID 160 -# define AMS_R_CERTIFICATE_VERIFY_ERROR 100 -# define AMS_R_CIPHER_INITIALISATION_ERROR 101 -# define AMS_R_CIPHER_PARAMETER_INITIALISATION_ERROR 102 -# define AMS_R_AMS_DATAFINAL_ERROR 103 -# define AMS_R_AMS_LIB 104 -# define AMS_R_CONTENTIDENTIFIER_MISMATCH 170 -# define AMS_R_CONTENT_NOT_FOUND 105 -# define AMS_R_CONTENT_TYPE_MISMATCH 171 -# define AMS_R_CONTENT_TYPE_NOT_COMPRESSED_DATA 106 -# define AMS_R_CONTENT_TYPE_NOT_ENVELOPED_DATA 107 -# define AMS_R_CONTENT_TYPE_NOT_SIGNED_DATA 108 -# define AMS_R_CONTENT_VERIFY_ERROR 109 -# define AMS_R_CTRL_ERROR 110 -# define AMS_R_CTRL_FAILURE 111 -# define AMS_R_DECRYPT_ERROR 112 -# define AMS_R_ERROR_GETTING_PUBLIC_KEY 113 -# define AMS_R_ERROR_READING_MESSAGEDIGEST_ATTRIBUTE 114 -# define AMS_R_ERROR_SETTING_KEY 115 -# define AMS_R_ERROR_SETTING_RECIPIENTINFO 116 -# define AMS_R_INVALID_ENCRYPTED_KEY_LENGTH 117 -# define AMS_R_INVALID_KEY_ENCRYPTION_PARAMETER 176 -# define AMS_R_INVALID_KEY_LENGTH 118 -# define AMS_R_MD_BIO_INIT_ERROR 119 -# define AMS_R_MESSAGEDIGEST_ATTRIBUTE_WRONG_LENGTH 120 -# define AMS_R_MESSAGEDIGEST_WRONG_LENGTH 121 -# define AMS_R_MSGSIGDIGEST_ERROR 172 -# define AMS_R_MSGSIGDIGEST_VERIFICATION_FAILURE 162 -# define AMS_R_MSGSIGDIGEST_WRONG_LENGTH 163 -# define AMS_R_NEED_ONE_SIGNER 164 -# define AMS_R_NOT_A_SIGNED_RECEIPT 165 -# define AMS_R_NOT_ENCRYPTED_DATA 122 -# define AMS_R_NOT_KEK 123 -# define AMS_R_NOT_KEY_AGREEMENT 181 -# define AMS_R_NOT_KEY_TRANSPORT 124 -# define AMS_R_NOT_PWRI 177 -# define AMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE 125 -# define AMS_R_NO_CIPHER 126 -# define AMS_R_NO_CONTENT 127 -# define AMS_R_NO_CONTENT_TYPE 173 -# define AMS_R_NO_DEFAULT_DIGEST 128 -# define AMS_R_NO_DIGEST_SET 129 -# define AMS_R_NO_KEY 130 -# define AMS_R_NO_KEY_OR_CERT 174 -# define AMS_R_NO_MATCHING_DIGEST 131 -# define AMS_R_NO_MATCHING_RECIPIENT 132 -# define AMS_R_NO_MATCHING_SIGNATURE 166 -# define AMS_R_NO_MSGSIGDIGEST 167 -# define AMS_R_NO_PASSWORD 178 -# define AMS_R_NO_PRIVATE_KEY 133 -# define AMS_R_NO_PUBLIC_KEY 134 -# define AMS_R_NO_RECEIPT_REQUEST 168 -# define AMS_R_NO_SIGNERS 135 -# define AMS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE 136 -# define AMS_R_RECEIPT_DECODE_ERROR 169 -# define AMS_R_RECIPIENT_ERROR 137 -# define AMS_R_SIGNER_CERTIFICATE_NOT_FOUND 138 -# define AMS_R_SIGNFINAL_ERROR 139 -# define AMS_R_SMIME_TEXT_ERROR 140 -# define AMS_R_STORE_INIT_ERROR 141 -# define AMS_R_TYPE_NOT_COMPRESSED_DATA 142 -# define AMS_R_TYPE_NOT_DATA 143 -# define AMS_R_TYPE_NOT_DIGESTED_DATA 144 -# define AMS_R_TYPE_NOT_ENCRYPTED_DATA 145 -# define AMS_R_TYPE_NOT_ENVELOPED_DATA 146 -# define AMS_R_UNABLE_TO_FINALIZE_CONTEXT 147 -# define AMS_R_UNKNOWN_CIPHER 148 -# define AMS_R_UNKNOWN_DIGEST_ALGORITHM 149 -# define AMS_R_UNKNOWN_ID 150 -# define AMS_R_UNSUPPORTED_COMPRESSION_ALGORITHM 151 -# define AMS_R_UNSUPPORTED_CONTENT_TYPE 152 -# define AMS_R_UNSUPPORTED_KEK_ALGORITHM 153 -# define AMS_R_UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM 179 -# define AMS_R_UNSUPPORTED_RECIPIENTINFO_TYPE 155 -# define AMS_R_UNSUPPORTED_RECIPIENT_TYPE 154 -# define AMS_R_UNSUPPORTED_TYPE 156 -# define AMS_R_UNWRAP_ERROR 157 -# define AMS_R_UNWRAP_FAILURE 180 -# define AMS_R_VERIFICATION_FAILURE 158 -# define AMS_R_WRAP_ERROR 159 - -# endif -#endif diff --git a/server/external/openssl/win_32/include/openssl/ams.h b/server/external/openssl/win_32/include/openssl/ams.h deleted file mode 100644 index 35b6bd0..0000000 --- a/server/external/openssl/win_32/include/openssl/ams.h +++ /dev/null @@ -1,501 +0,0 @@ -/* crypto/ams/ams.h */ -/* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL - * project. - */ -/* ==================================================================== - * Copyright (c) 2008 The OpenSSL Project. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * 3. All advertising materials mentioning features or use of this - * software must display the following acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" - * - * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to - * endorse or promote products derived from this software without - * prior written permission. For written permission, please contact - * licensing@OpenSSL.org. - * - * 5. Products derived from this software may not be called "OpenSSL" - * nor may "OpenSSL" appear in their names without prior written - * permission of the OpenSSL Project. - * - * 6. Redistributions of any form whatsoever must retain the following - * acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" - * - * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY - * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, - * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED - * OF THE POSSIBILITY OF SUCH DAMAGE. - * ==================================================================== - */ - - -#ifndef HEADER_AMS_H -#define HEADER_AMS_H - -#include - -#ifdef OPENSSL_NO_AMS -#error AMS is disabled. -#endif - -#ifdef __cplusplus -extern "C" { -#endif - - -typedef struct AMS_ContentInfo_st AMS_ContentInfo; -typedef struct AMS_SignerInfo_st AMS_SignerInfo; -typedef struct AMS_CertificateChoices AMS_CertificateChoices; -typedef struct AMS_RevocationInfoChoice_st AMS_RevocationInfoChoice; -typedef struct AMS_RecipientInfo_st AMS_RecipientInfo; -typedef struct AMS_ReceiptRequest_st AMS_ReceiptRequest; -typedef struct AMS_Receipt_st AMS_Receipt; - -DECLARE_STACK_OF(AMS_SignerInfo) -DECLARE_STACK_OF(GENERAL_NAMES) -DECLARE_ASN1_FUNCTIONS(AMS_ContentInfo) -DECLARE_ASN1_FUNCTIONS(AMS_ReceiptRequest) -DECLARE_ASN1_PRINT_FUNCTION(AMS_ContentInfo) - -#define AMS_SIGNERINFO_ISSUER_SERIAL 0 -#define AMS_SIGNERINFO_KEYIDENTIFIER 1 - -#define AMS_RECIPINFO_TRANS 0 -#define AMS_RECIPINFO_AGREE 1 -#define AMS_RECIPINFO_KEK 2 -#define AMS_RECIPINFO_PASS 3 -#define AMS_RECIPINFO_OTHER 4 - -/* S/MIME related flags */ - -#define AMS_TEXT 0x1 -#define AMS_NOCERTS 0x2 -#define AMS_NO_CONTENT_VERIFY 0x4 -#define AMS_NO_ATTR_VERIFY 0x8 -#define AMS_NOSIGS \ - (AMS_NO_CONTENT_VERIFY|AMS_NO_ATTR_VERIFY) -#define AMS_NOINTERN 0x10 -#define AMS_NO_SIGNER_CERT_VERIFY 0x20 -#define AMS_NOVERIFY 0x20 -#define AMS_DETACHED 0x40 -#define AMS_BINARY 0x80 -#define AMS_NOATTR 0x100 -#define AMS_NOSMIMECAP 0x200 -#define AMS_NOOLDMIMETYPE 0x400 -#define AMS_CRLFEOL 0x800 -#define AMS_STREAM 0x1000 -#define AMS_NOCRL 0x2000 -#define AMS_PARTIAL 0x4000 -#define AMS_REUSE_DIGEST 0x8000 -#define AMS_USE_KEYID 0x10000 -#define AMS_DEBUG_DECRYPT 0x20000 - -const ASN1_OBJECT *AMS_get0_type(AMS_ContentInfo *ams); - -BIO *AMS_dataInit(AMS_ContentInfo *ams, BIO *icont); -int AMS_dataFinal(AMS_ContentInfo *ams, BIO *bio); - -ASN1_OCTET_STRING **AMS_get0_content(AMS_ContentInfo *ams); -int AMS_is_detached(AMS_ContentInfo *ams); -int AMS_set_detached(AMS_ContentInfo *ams, int detached); - -#ifdef HEADER_PEM_H -DECLARE_PEM_rw_const(AMS, AMS_ContentInfo) -#endif - -int AMS_stream(unsigned char ***boundary, AMS_ContentInfo *ams); -AMS_ContentInfo *d2i_AMS_bio(BIO *bp, AMS_ContentInfo **ams); -int i2d_AMS_bio(BIO *bp, AMS_ContentInfo *ams); - -BIO *BIO_new_AMS(BIO *out, AMS_ContentInfo *ams); -int i2d_AMS_bio_stream(BIO *out, AMS_ContentInfo *ams, BIO *in, int flags); -int PEM_write_bio_AMS_stream(BIO *out, AMS_ContentInfo *ams, BIO *in, int flags); -AMS_ContentInfo *SMIME_read_AMS(BIO *bio, BIO **bcont); -int SMIME_write_AMS(BIO *bio, AMS_ContentInfo *ams, BIO *data, int flags); - -int AMS_final(AMS_ContentInfo *ams, BIO *data, BIO *dcont, unsigned int flags); - -AMS_ContentInfo *AMS_sign(X509 *signcert, EVP_PKEY *pkey, STACK_OF(X509) *certs, - BIO *data, unsigned int flags); - -AMS_ContentInfo *AMS_sign_receipt(AMS_SignerInfo *si, - X509 *signcert, EVP_PKEY *pkey, - STACK_OF(X509) *certs, - unsigned int flags); - -int AMS_data(AMS_ContentInfo *ams, BIO *out, unsigned int flags); -AMS_ContentInfo *AMS_data_create(BIO *in, unsigned int flags); - -int AMS_digest_verify(AMS_ContentInfo *ams, BIO *dcont, BIO *out, - unsigned int flags); -AMS_ContentInfo *AMS_digest_create(BIO *in, const EVP_MD *md, - unsigned int flags); - -int AMS_EncryptedData_decrypt(AMS_ContentInfo *ams, - const unsigned char *key, size_t keylen, - BIO *dcont, BIO *out, unsigned int flags); - -AMS_ContentInfo *AMS_EncryptedData_encrypt(BIO *in, const EVP_CIPHER *cipher, - const unsigned char *key, size_t keylen, - unsigned int flags); - -int AMS_EncryptedData_set1_key(AMS_ContentInfo *ams, const EVP_CIPHER *ciph, - const unsigned char *key, size_t keylen); - -int AMS_verify(AMS_ContentInfo *ams, STACK_OF(X509) *certs, - X509_STORE *store, BIO *dcont, BIO *out, unsigned int flags); - -int AMS_verify_receipt(AMS_ContentInfo *rams, AMS_ContentInfo *oams, - STACK_OF(X509) *certs, - X509_STORE *store, unsigned int flags); - -STACK_OF(X509) *AMS_get0_signers(AMS_ContentInfo *ams); - -AMS_ContentInfo *AMS_encrypt(STACK_OF(X509) *certs, BIO *in, - const EVP_CIPHER *cipher, unsigned int flags); - -int AMS_decrypt(AMS_ContentInfo *ams, EVP_PKEY *pkey, X509 *cert, - BIO *dcont, BIO *out, - unsigned int flags); - -int AMS_decrypt_set1_pkey(AMS_ContentInfo *ams, EVP_PKEY *pk, X509 *cert); -int AMS_decrypt_set1_key(AMS_ContentInfo *ams, - unsigned char *key, size_t keylen, - unsigned char *id, size_t idlen); -int AMS_decrypt_set1_password(AMS_ContentInfo *ams, - unsigned char *pass, ossl_ssize_t passlen); - -STACK_OF(AMS_RecipientInfo) *AMS_get0_RecipientInfos(AMS_ContentInfo *ams); -int AMS_RecipientInfo_type(AMS_RecipientInfo *ri); -AMS_ContentInfo *AMS_EnvelopedData_create(const EVP_CIPHER *cipher); -AMS_RecipientInfo *AMS_add1_recipient_cert(AMS_ContentInfo *ams, - X509 *recip, unsigned int flags); -int AMS_RecipientInfo_set0_pkey(AMS_RecipientInfo *ri, EVP_PKEY *pkey); -int AMS_RecipientInfo_ktri_cert_cmp(AMS_RecipientInfo *ri, X509 *cert); -int AMS_RecipientInfo_ktri_get0_algs(AMS_RecipientInfo *ri, - EVP_PKEY **pk, X509 **recip, - X509_ALGOR **palg); -int AMS_RecipientInfo_ktri_get0_signer_id(AMS_RecipientInfo *ri, - ASN1_OCTET_STRING **keyid, - X509_NAME **issuer, ASN1_INTEGER **sno); - -AMS_RecipientInfo *AMS_add0_recipient_key(AMS_ContentInfo *ams, int nid, - unsigned char *key, size_t keylen, - unsigned char *id, size_t idlen, - ASN1_GENERALIZEDTIME *date, - ASN1_OBJECT *otherTypeId, - ASN1_TYPE *otherType); - -int AMS_RecipientInfo_kekri_get0_id(AMS_RecipientInfo *ri, - X509_ALGOR **palg, - ASN1_OCTET_STRING **pid, - ASN1_GENERALIZEDTIME **pdate, - ASN1_OBJECT **potherid, - ASN1_TYPE **pothertype); - -int AMS_RecipientInfo_set0_key(AMS_RecipientInfo *ri, - unsigned char *key, size_t keylen); - -int AMS_RecipientInfo_kekri_id_cmp(AMS_RecipientInfo *ri, - const unsigned char *id, size_t idlen); - -int AMS_RecipientInfo_set0_password(AMS_RecipientInfo *ri, - unsigned char *pass, - ossl_ssize_t passlen); - -AMS_RecipientInfo *AMS_add0_recipient_password(AMS_ContentInfo *ams, - int iter, int wrap_nid, int pbe_nid, - unsigned char *pass, - ossl_ssize_t passlen, - const EVP_CIPHER *kekciph); - -int AMS_RecipientInfo_decrypt(AMS_ContentInfo *ams, AMS_RecipientInfo *ri); - -int AMS_uncompress(AMS_ContentInfo *ams, BIO *dcont, BIO *out, - unsigned int flags); -AMS_ContentInfo *AMS_compress(BIO *in, int comp_nid, unsigned int flags); - -int AMS_set1_eContentType(AMS_ContentInfo *ams, const ASN1_OBJECT *oid); -const ASN1_OBJECT *AMS_get0_eContentType(AMS_ContentInfo *ams); - -AMS_CertificateChoices *AMS_add0_CertificateChoices(AMS_ContentInfo *ams); -int AMS_add0_cert(AMS_ContentInfo *ams, X509 *cert); -int AMS_add1_cert(AMS_ContentInfo *ams, X509 *cert); -STACK_OF(X509) *AMS_get1_certs(AMS_ContentInfo *ams); - -AMS_RevocationInfoChoice *AMS_add0_RevocationInfoChoice(AMS_ContentInfo *ams); -int AMS_add0_crl(AMS_ContentInfo *ams, X509_CRL *crl); -int AMS_add1_crl(AMS_ContentInfo *ams, X509_CRL *crl); -STACK_OF(X509_CRL) *AMS_get1_crls(AMS_ContentInfo *ams); - -int AMS_SignedData_init(AMS_ContentInfo *ams); -AMS_SignerInfo *AMS_add1_signer(AMS_ContentInfo *ams, - X509 *signer, EVP_PKEY *pk, const EVP_MD *md, - unsigned int flags); -STACK_OF(AMS_SignerInfo) *AMS_get0_SignerInfos(AMS_ContentInfo *ams); - -void AMS_SignerInfo_set1_signer_cert(AMS_SignerInfo *si, X509 *signer); -int AMS_SignerInfo_get0_signer_id(AMS_SignerInfo *si, - ASN1_OCTET_STRING **keyid, - X509_NAME **issuer, ASN1_INTEGER **sno); -int AMS_SignerInfo_cert_cmp(AMS_SignerInfo *si, X509 *cert); -int AMS_set1_signers_certs(AMS_ContentInfo *ams, STACK_OF(X509) *certs, - unsigned int flags); -void AMS_SignerInfo_get0_algs(AMS_SignerInfo *si, EVP_PKEY **pk, X509 **signer, - X509_ALGOR **pdig, X509_ALGOR **psig); -int AMS_SignerInfo_sign(AMS_SignerInfo *si); -int AMS_SignerInfo_verify(AMS_SignerInfo *si); -int AMS_SignerInfo_verify_content(AMS_SignerInfo *si, BIO *chain); - -int AMS_add_smimecap(AMS_SignerInfo *si, STACK_OF(X509_ALGOR) *algs); -int AMS_add_simple_smimecap(STACK_OF(X509_ALGOR) **algs, - int algnid, int keysize); -int AMS_add_standard_smimecap(STACK_OF(X509_ALGOR) **smcap); - -int AMS_signed_get_attr_count(const AMS_SignerInfo *si); -int AMS_signed_get_attr_by_NID(const AMS_SignerInfo *si, int nid, - int lastpos); -int AMS_signed_get_attr_by_OBJ(const AMS_SignerInfo *si, ASN1_OBJECT *obj, - int lastpos); -X509_ATTRIBUTE *AMS_signed_get_attr(const AMS_SignerInfo *si, int loc); -X509_ATTRIBUTE *AMS_signed_delete_attr(AMS_SignerInfo *si, int loc); -int AMS_signed_add1_attr(AMS_SignerInfo *si, X509_ATTRIBUTE *attr); -int AMS_signed_add1_attr_by_OBJ(AMS_SignerInfo *si, - const ASN1_OBJECT *obj, int type, - const void *bytes, int len); -int AMS_signed_add1_attr_by_NID(AMS_SignerInfo *si, - int nid, int type, - const void *bytes, int len); -int AMS_signed_add1_attr_by_txt(AMS_SignerInfo *si, - const char *attrname, int type, - const void *bytes, int len); -void *AMS_signed_get0_data_by_OBJ(AMS_SignerInfo *si, ASN1_OBJECT *oid, - int lastpos, int type); - -int AMS_unsigned_get_attr_count(const AMS_SignerInfo *si); -int AMS_unsigned_get_attr_by_NID(const AMS_SignerInfo *si, int nid, - int lastpos); -int AMS_unsigned_get_attr_by_OBJ(const AMS_SignerInfo *si, ASN1_OBJECT *obj, - int lastpos); -X509_ATTRIBUTE *AMS_unsigned_get_attr(const AMS_SignerInfo *si, int loc); -X509_ATTRIBUTE *AMS_unsigned_delete_attr(AMS_SignerInfo *si, int loc); -int AMS_unsigned_add1_attr(AMS_SignerInfo *si, X509_ATTRIBUTE *attr); -int AMS_unsigned_add1_attr_by_OBJ(AMS_SignerInfo *si, - const ASN1_OBJECT *obj, int type, - const void *bytes, int len); -int AMS_unsigned_add1_attr_by_NID(AMS_SignerInfo *si, - int nid, int type, - const void *bytes, int len); -int AMS_unsigned_add1_attr_by_txt(AMS_SignerInfo *si, - const char *attrname, int type, - const void *bytes, int len); -void *AMS_unsigned_get0_data_by_OBJ(AMS_SignerInfo *si, ASN1_OBJECT *oid, - int lastpos, int type); - -#ifdef HEADER_X509V3_H - -int AMS_get1_ReceiptRequest(AMS_SignerInfo *si, AMS_ReceiptRequest **prr); -AMS_ReceiptRequest *AMS_ReceiptRequest_create0(unsigned char *id, int idlen, - int allorfirst, - STACK_OF(GENERAL_NAMES) *receiptList, - STACK_OF(GENERAL_NAMES) *receiptsTo); -int AMS_add1_ReceiptRequest(AMS_SignerInfo *si, AMS_ReceiptRequest *rr); -void AMS_ReceiptRequest_get0_values(AMS_ReceiptRequest *rr, - ASN1_STRING **pcid, - int *pallorfirst, - STACK_OF(GENERAL_NAMES) **plist, - STACK_OF(GENERAL_NAMES) **prto); - -#endif - -/* BEGIN ERROR CODES */ -/* The following lines are auto generated by the script mkerr.pl. Any changes - * made after this point may be overwritten when the script is next run. - */ -void ERR_load_AMS_strings(void); - -/* Error codes for the AMS functions. */ - -/* Function codes. */ -#define AMS_F_CHECK_CONTENT 99 -#define AMS_F_AMS_ADD0_CERT 164 -#define AMS_F_AMS_ADD0_RECIPIENT_KEY 100 -#define AMS_F_AMS_ADD0_RECIPIENT_PASSWORD 165 -#define AMS_F_AMS_ADD1_RECEIPTREQUEST 158 -#define AMS_F_AMS_ADD1_RECIPIENT_CERT 101 -#define AMS_F_AMS_ADD1_SIGNER 102 -#define AMS_F_AMS_ADD1_SIGNINGTIME 103 -#define AMS_F_AMS_COMPRESS 104 -#define AMS_F_AMS_COMPRESSEDDATA_CREATE 105 -#define AMS_F_AMS_COMPRESSEDDATA_INIT_BIO 106 -#define AMS_F_AMS_COPY_CONTENT 107 -#define AMS_F_AMS_COPY_MESSAGEDIGEST 108 -#define AMS_F_AMS_DATA 109 -#define AMS_F_AMS_DATAFINAL 110 -#define AMS_F_AMS_DATAINIT 111 -#define AMS_F_AMS_DECRYPT 112 -#define AMS_F_AMS_DECRYPT_SET1_KEY 113 -#define AMS_F_AMS_DECRYPT_SET1_PASSWORD 166 -#define AMS_F_AMS_DECRYPT_SET1_PKEY 114 -#define AMS_F_AMS_DIGESTALGORITHM_FIND_CTX 115 -#define AMS_F_AMS_DIGESTALGORITHM_INIT_BIO 116 -#define AMS_F_AMS_DIGESTEDDATA_DO_FINAL 117 -#define AMS_F_AMS_DIGEST_VERIFY 118 -#define AMS_F_AMS_ENCODE_RECEIPT 161 -#define AMS_F_AMS_ENCRYPT 119 -#define AMS_F_AMS_ENCRYPTEDCONTENT_INIT_BIO 120 -#define AMS_F_AMS_ENCRYPTEDDATA_DECRYPT 121 -#define AMS_F_AMS_ENCRYPTEDDATA_ENCRYPT 122 -#define AMS_F_AMS_ENCRYPTEDDATA_SET1_KEY 123 -#define AMS_F_AMS_ENVELOPEDDATA_CREATE 124 -#define AMS_F_AMS_ENVELOPEDDATA_INIT_BIO 125 -#define AMS_F_AMS_ENVELOPED_DATA_INIT 126 -#define AMS_F_AMS_FINAL 127 -#define AMS_F_AMS_GET0_CERTIFICATE_CHOICES 128 -#define AMS_F_AMS_GET0_CONTENT 129 -#define AMS_F_AMS_GET0_ECONTENT_TYPE 130 -#define AMS_F_AMS_GET0_ENVELOPED 131 -#define AMS_F_AMS_GET0_REVOCATION_CHOICES 132 -#define AMS_F_AMS_GET0_SIGNED 133 -#define AMS_F_AMS_MSGSIGDIGEST_ADD1 162 -#define AMS_F_AMS_RECEIPTREQUEST_CREATE0 159 -#define AMS_F_AMS_RECEIPT_VERIFY 160 -#define AMS_F_AMS_RECIPIENTINFO_DECRYPT 134 -#define AMS_F_AMS_RECIPIENTINFO_KEKRI_DECRYPT 135 -#define AMS_F_AMS_RECIPIENTINFO_KEKRI_ENCRYPT 136 -#define AMS_F_AMS_RECIPIENTINFO_KEKRI_GET0_ID 137 -#define AMS_F_AMS_RECIPIENTINFO_KEKRI_ID_CMP 138 -#define AMS_F_AMS_RECIPIENTINFO_KTRI_CERT_CMP 139 -#define AMS_F_AMS_RECIPIENTINFO_KTRI_DECRYPT 140 -#define AMS_F_AMS_RECIPIENTINFO_KTRI_ENCRYPT 141 -#define AMS_F_AMS_RECIPIENTINFO_KTRI_GET0_ALGS 142 -#define AMS_F_AMS_RECIPIENTINFO_KTRI_GET0_SIGNER_ID 143 -#define AMS_F_AMS_RECIPIENTINFO_PWRI_CRYPT 167 -#define AMS_F_AMS_RECIPIENTINFO_SET0_KEY 144 -#define AMS_F_AMS_RECIPIENTINFO_SET0_PASSWORD 168 -#define AMS_F_AMS_RECIPIENTINFO_SET0_PKEY 145 -#define AMS_F_AMS_SET1_SIGNERIDENTIFIER 146 -#define AMS_F_AMS_SET_DETACHED 147 -#define AMS_F_AMS_SIGN 148 -#define AMS_F_AMS_SIGNED_DATA_INIT 149 -#define AMS_F_AMS_SIGNERINFO_CONTENT_SIGN 150 -#define AMS_F_AMS_SIGNERINFO_SIGN 151 -#define AMS_F_AMS_SIGNERINFO_VERIFY 152 -#define AMS_F_AMS_SIGNERINFO_VERIFY_CERT 153 -#define AMS_F_AMS_SIGNERINFO_VERIFY_CONTENT 154 -#define AMS_F_AMS_SIGN_RECEIPT 163 -#define AMS_F_AMS_STREAM 155 -#define AMS_F_AMS_UNCOMPRESS 156 -#define AMS_F_AMS_VERIFY 157 - -/* Reason codes. */ -#define AMS_R_ADD_SIGNER_ERROR 99 -#define AMS_R_CERTIFICATE_ALREADY_PRESENT 175 -#define AMS_R_CERTIFICATE_HAS_NO_KEYID 160 -#define AMS_R_CERTIFICATE_VERIFY_ERROR 100 -#define AMS_R_CIPHER_INITIALISATION_ERROR 101 -#define AMS_R_CIPHER_PARAMETER_INITIALISATION_ERROR 102 -#define AMS_R_AMS_DATAFINAL_ERROR 103 -#define AMS_R_AMS_LIB 104 -#define AMS_R_CONTENTIDENTIFIER_MISMATCH 170 -#define AMS_R_CONTENT_NOT_FOUND 105 -#define AMS_R_CONTENT_TYPE_MISMATCH 171 -#define AMS_R_CONTENT_TYPE_NOT_COMPRESSED_DATA 106 -#define AMS_R_CONTENT_TYPE_NOT_ENVELOPED_DATA 107 -#define AMS_R_CONTENT_TYPE_NOT_SIGNED_DATA 108 -#define AMS_R_CONTENT_VERIFY_ERROR 109 -#define AMS_R_CTRL_ERROR 110 -#define AMS_R_CTRL_FAILURE 111 -#define AMS_R_DECRYPT_ERROR 112 -#define AMS_R_DIGEST_ERROR 161 -#define AMS_R_ERROR_GETTING_PUBLIC_KEY 113 -#define AMS_R_ERROR_READING_MESSAGEDIGEST_ATTRIBUTE 114 -#define AMS_R_ERROR_SETTING_KEY 115 -#define AMS_R_ERROR_SETTING_RECIPIENTINFO 116 -#define AMS_R_INVALID_ENCRYPTED_KEY_LENGTH 117 -#define AMS_R_INVALID_KEY_ENCRYPTION_PARAMETER 176 -#define AMS_R_INVALID_KEY_LENGTH 118 -#define AMS_R_MD_BIO_INIT_ERROR 119 -#define AMS_R_MESSAGEDIGEST_ATTRIBUTE_WRONG_LENGTH 120 -#define AMS_R_MESSAGEDIGEST_WRONG_LENGTH 121 -#define AMS_R_MSGSIGDIGEST_ERROR 172 -#define AMS_R_MSGSIGDIGEST_VERIFICATION_FAILURE 162 -#define AMS_R_MSGSIGDIGEST_WRONG_LENGTH 163 -#define AMS_R_NEED_ONE_SIGNER 164 -#define AMS_R_NOT_A_SIGNED_RECEIPT 165 -#define AMS_R_NOT_ENCRYPTED_DATA 122 -#define AMS_R_NOT_KEK 123 -#define AMS_R_NOT_KEY_TRANSPORT 124 -#define AMS_R_NOT_PWRI 177 -#define AMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE 125 -#define AMS_R_NO_CIPHER 126 -#define AMS_R_NO_CONTENT 127 -#define AMS_R_NO_CONTENT_TYPE 173 -#define AMS_R_NO_DEFAULT_DIGEST 128 -#define AMS_R_NO_DIGEST_SET 129 -#define AMS_R_NO_KEY 130 -#define AMS_R_NO_KEY_OR_CERT 174 -#define AMS_R_NO_MATCHING_DIGEST 131 -#define AMS_R_NO_MATCHING_RECIPIENT 132 -#define AMS_R_NO_MATCHING_SIGNATURE 166 -#define AMS_R_NO_MSGSIGDIGEST 167 -#define AMS_R_NO_PASSWORD 178 -#define AMS_R_NO_PRIVATE_KEY 133 -#define AMS_R_NO_PUBLIC_KEY 134 -#define AMS_R_NO_RECEIPT_REQUEST 168 -#define AMS_R_NO_SIGNERS 135 -#define AMS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE 136 -#define AMS_R_RECEIPT_DECODE_ERROR 169 -#define AMS_R_RECIPIENT_ERROR 137 -#define AMS_R_SIGNER_CERTIFICATE_NOT_FOUND 138 -#define AMS_R_SIGNFINAL_ERROR 139 -#define AMS_R_SMIME_TEXT_ERROR 140 -#define AMS_R_STORE_INIT_ERROR 141 -#define AMS_R_TYPE_NOT_COMPRESSED_DATA 142 -#define AMS_R_TYPE_NOT_DATA 143 -#define AMS_R_TYPE_NOT_DIGESTED_DATA 144 -#define AMS_R_TYPE_NOT_ENCRYPTED_DATA 145 -#define AMS_R_TYPE_NOT_ENVELOPED_DATA 146 -#define AMS_R_UNABLE_TO_FINALIZE_CONTEXT 147 -#define AMS_R_UNKNOWN_CIPHER 148 -#define AMS_R_UNKNOWN_DIGEST_ALGORIHM 149 -#define AMS_R_UNKNOWN_ID 150 -#define AMS_R_UNSUPPORTED_COMPRESSION_ALGORITHM 151 -#define AMS_R_UNSUPPORTED_CONTENT_TYPE 152 -#define AMS_R_UNSUPPORTED_KEK_ALGORITHM 153 -#define AMS_R_UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM 179 -#define AMS_R_UNSUPPORTED_RECIPIENT_TYPE 154 -#define AMS_R_UNSUPPORTED_RECPIENTINFO_TYPE 155 -#define AMS_R_UNSUPPORTED_TYPE 156 -#define AMS_R_UNWRAP_ERROR 157 -#define AMS_R_UNWRAP_FAILURE 180 -#define AMS_R_VERIFICATION_FAILURE 158 -#define AMS_R_WRAP_ERROR 159 - -#ifdef __cplusplus -} -#endif -#endif diff --git a/server/external/openssl/win_64/include/openssl/ams.h b/server/external/openssl/win_64/include/openssl/ams.h deleted file mode 100644 index 35b6bd0..0000000 --- a/server/external/openssl/win_64/include/openssl/ams.h +++ /dev/null @@ -1,501 +0,0 @@ -/* crypto/ams/ams.h */ -/* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL - * project. - */ -/* ==================================================================== - * Copyright (c) 2008 The OpenSSL Project. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * 3. All advertising materials mentioning features or use of this - * software must display the following acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" - * - * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to - * endorse or promote products derived from this software without - * prior written permission. For written permission, please contact - * licensing@OpenSSL.org. - * - * 5. Products derived from this software may not be called "OpenSSL" - * nor may "OpenSSL" appear in their names without prior written - * permission of the OpenSSL Project. - * - * 6. Redistributions of any form whatsoever must retain the following - * acknowledgment: - * "This product includes software developed by the OpenSSL Project - * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" - * - * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY - * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, - * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED - * OF THE POSSIBILITY OF SUCH DAMAGE. - * ==================================================================== - */ - - -#ifndef HEADER_AMS_H -#define HEADER_AMS_H - -#include - -#ifdef OPENSSL_NO_AMS -#error AMS is disabled. -#endif - -#ifdef __cplusplus -extern "C" { -#endif - - -typedef struct AMS_ContentInfo_st AMS_ContentInfo; -typedef struct AMS_SignerInfo_st AMS_SignerInfo; -typedef struct AMS_CertificateChoices AMS_CertificateChoices; -typedef struct AMS_RevocationInfoChoice_st AMS_RevocationInfoChoice; -typedef struct AMS_RecipientInfo_st AMS_RecipientInfo; -typedef struct AMS_ReceiptRequest_st AMS_ReceiptRequest; -typedef struct AMS_Receipt_st AMS_Receipt; - -DECLARE_STACK_OF(AMS_SignerInfo) -DECLARE_STACK_OF(GENERAL_NAMES) -DECLARE_ASN1_FUNCTIONS(AMS_ContentInfo) -DECLARE_ASN1_FUNCTIONS(AMS_ReceiptRequest) -DECLARE_ASN1_PRINT_FUNCTION(AMS_ContentInfo) - -#define AMS_SIGNERINFO_ISSUER_SERIAL 0 -#define AMS_SIGNERINFO_KEYIDENTIFIER 1 - -#define AMS_RECIPINFO_TRANS 0 -#define AMS_RECIPINFO_AGREE 1 -#define AMS_RECIPINFO_KEK 2 -#define AMS_RECIPINFO_PASS 3 -#define AMS_RECIPINFO_OTHER 4 - -/* S/MIME related flags */ - -#define AMS_TEXT 0x1 -#define AMS_NOCERTS 0x2 -#define AMS_NO_CONTENT_VERIFY 0x4 -#define AMS_NO_ATTR_VERIFY 0x8 -#define AMS_NOSIGS \ - (AMS_NO_CONTENT_VERIFY|AMS_NO_ATTR_VERIFY) -#define AMS_NOINTERN 0x10 -#define AMS_NO_SIGNER_CERT_VERIFY 0x20 -#define AMS_NOVERIFY 0x20 -#define AMS_DETACHED 0x40 -#define AMS_BINARY 0x80 -#define AMS_NOATTR 0x100 -#define AMS_NOSMIMECAP 0x200 -#define AMS_NOOLDMIMETYPE 0x400 -#define AMS_CRLFEOL 0x800 -#define AMS_STREAM 0x1000 -#define AMS_NOCRL 0x2000 -#define AMS_PARTIAL 0x4000 -#define AMS_REUSE_DIGEST 0x8000 -#define AMS_USE_KEYID 0x10000 -#define AMS_DEBUG_DECRYPT 0x20000 - -const ASN1_OBJECT *AMS_get0_type(AMS_ContentInfo *ams); - -BIO *AMS_dataInit(AMS_ContentInfo *ams, BIO *icont); -int AMS_dataFinal(AMS_ContentInfo *ams, BIO *bio); - -ASN1_OCTET_STRING **AMS_get0_content(AMS_ContentInfo *ams); -int AMS_is_detached(AMS_ContentInfo *ams); -int AMS_set_detached(AMS_ContentInfo *ams, int detached); - -#ifdef HEADER_PEM_H -DECLARE_PEM_rw_const(AMS, AMS_ContentInfo) -#endif - -int AMS_stream(unsigned char ***boundary, AMS_ContentInfo *ams); -AMS_ContentInfo *d2i_AMS_bio(BIO *bp, AMS_ContentInfo **ams); -int i2d_AMS_bio(BIO *bp, AMS_ContentInfo *ams); - -BIO *BIO_new_AMS(BIO *out, AMS_ContentInfo *ams); -int i2d_AMS_bio_stream(BIO *out, AMS_ContentInfo *ams, BIO *in, int flags); -int PEM_write_bio_AMS_stream(BIO *out, AMS_ContentInfo *ams, BIO *in, int flags); -AMS_ContentInfo *SMIME_read_AMS(BIO *bio, BIO **bcont); -int SMIME_write_AMS(BIO *bio, AMS_ContentInfo *ams, BIO *data, int flags); - -int AMS_final(AMS_ContentInfo *ams, BIO *data, BIO *dcont, unsigned int flags); - -AMS_ContentInfo *AMS_sign(X509 *signcert, EVP_PKEY *pkey, STACK_OF(X509) *certs, - BIO *data, unsigned int flags); - -AMS_ContentInfo *AMS_sign_receipt(AMS_SignerInfo *si, - X509 *signcert, EVP_PKEY *pkey, - STACK_OF(X509) *certs, - unsigned int flags); - -int AMS_data(AMS_ContentInfo *ams, BIO *out, unsigned int flags); -AMS_ContentInfo *AMS_data_create(BIO *in, unsigned int flags); - -int AMS_digest_verify(AMS_ContentInfo *ams, BIO *dcont, BIO *out, - unsigned int flags); -AMS_ContentInfo *AMS_digest_create(BIO *in, const EVP_MD *md, - unsigned int flags); - -int AMS_EncryptedData_decrypt(AMS_ContentInfo *ams, - const unsigned char *key, size_t keylen, - BIO *dcont, BIO *out, unsigned int flags); - -AMS_ContentInfo *AMS_EncryptedData_encrypt(BIO *in, const EVP_CIPHER *cipher, - const unsigned char *key, size_t keylen, - unsigned int flags); - -int AMS_EncryptedData_set1_key(AMS_ContentInfo *ams, const EVP_CIPHER *ciph, - const unsigned char *key, size_t keylen); - -int AMS_verify(AMS_ContentInfo *ams, STACK_OF(X509) *certs, - X509_STORE *store, BIO *dcont, BIO *out, unsigned int flags); - -int AMS_verify_receipt(AMS_ContentInfo *rams, AMS_ContentInfo *oams, - STACK_OF(X509) *certs, - X509_STORE *store, unsigned int flags); - -STACK_OF(X509) *AMS_get0_signers(AMS_ContentInfo *ams); - -AMS_ContentInfo *AMS_encrypt(STACK_OF(X509) *certs, BIO *in, - const EVP_CIPHER *cipher, unsigned int flags); - -int AMS_decrypt(AMS_ContentInfo *ams, EVP_PKEY *pkey, X509 *cert, - BIO *dcont, BIO *out, - unsigned int flags); - -int AMS_decrypt_set1_pkey(AMS_ContentInfo *ams, EVP_PKEY *pk, X509 *cert); -int AMS_decrypt_set1_key(AMS_ContentInfo *ams, - unsigned char *key, size_t keylen, - unsigned char *id, size_t idlen); -int AMS_decrypt_set1_password(AMS_ContentInfo *ams, - unsigned char *pass, ossl_ssize_t passlen); - -STACK_OF(AMS_RecipientInfo) *AMS_get0_RecipientInfos(AMS_ContentInfo *ams); -int AMS_RecipientInfo_type(AMS_RecipientInfo *ri); -AMS_ContentInfo *AMS_EnvelopedData_create(const EVP_CIPHER *cipher); -AMS_RecipientInfo *AMS_add1_recipient_cert(AMS_ContentInfo *ams, - X509 *recip, unsigned int flags); -int AMS_RecipientInfo_set0_pkey(AMS_RecipientInfo *ri, EVP_PKEY *pkey); -int AMS_RecipientInfo_ktri_cert_cmp(AMS_RecipientInfo *ri, X509 *cert); -int AMS_RecipientInfo_ktri_get0_algs(AMS_RecipientInfo *ri, - EVP_PKEY **pk, X509 **recip, - X509_ALGOR **palg); -int AMS_RecipientInfo_ktri_get0_signer_id(AMS_RecipientInfo *ri, - ASN1_OCTET_STRING **keyid, - X509_NAME **issuer, ASN1_INTEGER **sno); - -AMS_RecipientInfo *AMS_add0_recipient_key(AMS_ContentInfo *ams, int nid, - unsigned char *key, size_t keylen, - unsigned char *id, size_t idlen, - ASN1_GENERALIZEDTIME *date, - ASN1_OBJECT *otherTypeId, - ASN1_TYPE *otherType); - -int AMS_RecipientInfo_kekri_get0_id(AMS_RecipientInfo *ri, - X509_ALGOR **palg, - ASN1_OCTET_STRING **pid, - ASN1_GENERALIZEDTIME **pdate, - ASN1_OBJECT **potherid, - ASN1_TYPE **pothertype); - -int AMS_RecipientInfo_set0_key(AMS_RecipientInfo *ri, - unsigned char *key, size_t keylen); - -int AMS_RecipientInfo_kekri_id_cmp(AMS_RecipientInfo *ri, - const unsigned char *id, size_t idlen); - -int AMS_RecipientInfo_set0_password(AMS_RecipientInfo *ri, - unsigned char *pass, - ossl_ssize_t passlen); - -AMS_RecipientInfo *AMS_add0_recipient_password(AMS_ContentInfo *ams, - int iter, int wrap_nid, int pbe_nid, - unsigned char *pass, - ossl_ssize_t passlen, - const EVP_CIPHER *kekciph); - -int AMS_RecipientInfo_decrypt(AMS_ContentInfo *ams, AMS_RecipientInfo *ri); - -int AMS_uncompress(AMS_ContentInfo *ams, BIO *dcont, BIO *out, - unsigned int flags); -AMS_ContentInfo *AMS_compress(BIO *in, int comp_nid, unsigned int flags); - -int AMS_set1_eContentType(AMS_ContentInfo *ams, const ASN1_OBJECT *oid); -const ASN1_OBJECT *AMS_get0_eContentType(AMS_ContentInfo *ams); - -AMS_CertificateChoices *AMS_add0_CertificateChoices(AMS_ContentInfo *ams); -int AMS_add0_cert(AMS_ContentInfo *ams, X509 *cert); -int AMS_add1_cert(AMS_ContentInfo *ams, X509 *cert); -STACK_OF(X509) *AMS_get1_certs(AMS_ContentInfo *ams); - -AMS_RevocationInfoChoice *AMS_add0_RevocationInfoChoice(AMS_ContentInfo *ams); -int AMS_add0_crl(AMS_ContentInfo *ams, X509_CRL *crl); -int AMS_add1_crl(AMS_ContentInfo *ams, X509_CRL *crl); -STACK_OF(X509_CRL) *AMS_get1_crls(AMS_ContentInfo *ams); - -int AMS_SignedData_init(AMS_ContentInfo *ams); -AMS_SignerInfo *AMS_add1_signer(AMS_ContentInfo *ams, - X509 *signer, EVP_PKEY *pk, const EVP_MD *md, - unsigned int flags); -STACK_OF(AMS_SignerInfo) *AMS_get0_SignerInfos(AMS_ContentInfo *ams); - -void AMS_SignerInfo_set1_signer_cert(AMS_SignerInfo *si, X509 *signer); -int AMS_SignerInfo_get0_signer_id(AMS_SignerInfo *si, - ASN1_OCTET_STRING **keyid, - X509_NAME **issuer, ASN1_INTEGER **sno); -int AMS_SignerInfo_cert_cmp(AMS_SignerInfo *si, X509 *cert); -int AMS_set1_signers_certs(AMS_ContentInfo *ams, STACK_OF(X509) *certs, - unsigned int flags); -void AMS_SignerInfo_get0_algs(AMS_SignerInfo *si, EVP_PKEY **pk, X509 **signer, - X509_ALGOR **pdig, X509_ALGOR **psig); -int AMS_SignerInfo_sign(AMS_SignerInfo *si); -int AMS_SignerInfo_verify(AMS_SignerInfo *si); -int AMS_SignerInfo_verify_content(AMS_SignerInfo *si, BIO *chain); - -int AMS_add_smimecap(AMS_SignerInfo *si, STACK_OF(X509_ALGOR) *algs); -int AMS_add_simple_smimecap(STACK_OF(X509_ALGOR) **algs, - int algnid, int keysize); -int AMS_add_standard_smimecap(STACK_OF(X509_ALGOR) **smcap); - -int AMS_signed_get_attr_count(const AMS_SignerInfo *si); -int AMS_signed_get_attr_by_NID(const AMS_SignerInfo *si, int nid, - int lastpos); -int AMS_signed_get_attr_by_OBJ(const AMS_SignerInfo *si, ASN1_OBJECT *obj, - int lastpos); -X509_ATTRIBUTE *AMS_signed_get_attr(const AMS_SignerInfo *si, int loc); -X509_ATTRIBUTE *AMS_signed_delete_attr(AMS_SignerInfo *si, int loc); -int AMS_signed_add1_attr(AMS_SignerInfo *si, X509_ATTRIBUTE *attr); -int AMS_signed_add1_attr_by_OBJ(AMS_SignerInfo *si, - const ASN1_OBJECT *obj, int type, - const void *bytes, int len); -int AMS_signed_add1_attr_by_NID(AMS_SignerInfo *si, - int nid, int type, - const void *bytes, int len); -int AMS_signed_add1_attr_by_txt(AMS_SignerInfo *si, - const char *attrname, int type, - const void *bytes, int len); -void *AMS_signed_get0_data_by_OBJ(AMS_SignerInfo *si, ASN1_OBJECT *oid, - int lastpos, int type); - -int AMS_unsigned_get_attr_count(const AMS_SignerInfo *si); -int AMS_unsigned_get_attr_by_NID(const AMS_SignerInfo *si, int nid, - int lastpos); -int AMS_unsigned_get_attr_by_OBJ(const AMS_SignerInfo *si, ASN1_OBJECT *obj, - int lastpos); -X509_ATTRIBUTE *AMS_unsigned_get_attr(const AMS_SignerInfo *si, int loc); -X509_ATTRIBUTE *AMS_unsigned_delete_attr(AMS_SignerInfo *si, int loc); -int AMS_unsigned_add1_attr(AMS_SignerInfo *si, X509_ATTRIBUTE *attr); -int AMS_unsigned_add1_attr_by_OBJ(AMS_SignerInfo *si, - const ASN1_OBJECT *obj, int type, - const void *bytes, int len); -int AMS_unsigned_add1_attr_by_NID(AMS_SignerInfo *si, - int nid, int type, - const void *bytes, int len); -int AMS_unsigned_add1_attr_by_txt(AMS_SignerInfo *si, - const char *attrname, int type, - const void *bytes, int len); -void *AMS_unsigned_get0_data_by_OBJ(AMS_SignerInfo *si, ASN1_OBJECT *oid, - int lastpos, int type); - -#ifdef HEADER_X509V3_H - -int AMS_get1_ReceiptRequest(AMS_SignerInfo *si, AMS_ReceiptRequest **prr); -AMS_ReceiptRequest *AMS_ReceiptRequest_create0(unsigned char *id, int idlen, - int allorfirst, - STACK_OF(GENERAL_NAMES) *receiptList, - STACK_OF(GENERAL_NAMES) *receiptsTo); -int AMS_add1_ReceiptRequest(AMS_SignerInfo *si, AMS_ReceiptRequest *rr); -void AMS_ReceiptRequest_get0_values(AMS_ReceiptRequest *rr, - ASN1_STRING **pcid, - int *pallorfirst, - STACK_OF(GENERAL_NAMES) **plist, - STACK_OF(GENERAL_NAMES) **prto); - -#endif - -/* BEGIN ERROR CODES */ -/* The following lines are auto generated by the script mkerr.pl. Any changes - * made after this point may be overwritten when the script is next run. - */ -void ERR_load_AMS_strings(void); - -/* Error codes for the AMS functions. */ - -/* Function codes. */ -#define AMS_F_CHECK_CONTENT 99 -#define AMS_F_AMS_ADD0_CERT 164 -#define AMS_F_AMS_ADD0_RECIPIENT_KEY 100 -#define AMS_F_AMS_ADD0_RECIPIENT_PASSWORD 165 -#define AMS_F_AMS_ADD1_RECEIPTREQUEST 158 -#define AMS_F_AMS_ADD1_RECIPIENT_CERT 101 -#define AMS_F_AMS_ADD1_SIGNER 102 -#define AMS_F_AMS_ADD1_SIGNINGTIME 103 -#define AMS_F_AMS_COMPRESS 104 -#define AMS_F_AMS_COMPRESSEDDATA_CREATE 105 -#define AMS_F_AMS_COMPRESSEDDATA_INIT_BIO 106 -#define AMS_F_AMS_COPY_CONTENT 107 -#define AMS_F_AMS_COPY_MESSAGEDIGEST 108 -#define AMS_F_AMS_DATA 109 -#define AMS_F_AMS_DATAFINAL 110 -#define AMS_F_AMS_DATAINIT 111 -#define AMS_F_AMS_DECRYPT 112 -#define AMS_F_AMS_DECRYPT_SET1_KEY 113 -#define AMS_F_AMS_DECRYPT_SET1_PASSWORD 166 -#define AMS_F_AMS_DECRYPT_SET1_PKEY 114 -#define AMS_F_AMS_DIGESTALGORITHM_FIND_CTX 115 -#define AMS_F_AMS_DIGESTALGORITHM_INIT_BIO 116 -#define AMS_F_AMS_DIGESTEDDATA_DO_FINAL 117 -#define AMS_F_AMS_DIGEST_VERIFY 118 -#define AMS_F_AMS_ENCODE_RECEIPT 161 -#define AMS_F_AMS_ENCRYPT 119 -#define AMS_F_AMS_ENCRYPTEDCONTENT_INIT_BIO 120 -#define AMS_F_AMS_ENCRYPTEDDATA_DECRYPT 121 -#define AMS_F_AMS_ENCRYPTEDDATA_ENCRYPT 122 -#define AMS_F_AMS_ENCRYPTEDDATA_SET1_KEY 123 -#define AMS_F_AMS_ENVELOPEDDATA_CREATE 124 -#define AMS_F_AMS_ENVELOPEDDATA_INIT_BIO 125 -#define AMS_F_AMS_ENVELOPED_DATA_INIT 126 -#define AMS_F_AMS_FINAL 127 -#define AMS_F_AMS_GET0_CERTIFICATE_CHOICES 128 -#define AMS_F_AMS_GET0_CONTENT 129 -#define AMS_F_AMS_GET0_ECONTENT_TYPE 130 -#define AMS_F_AMS_GET0_ENVELOPED 131 -#define AMS_F_AMS_GET0_REVOCATION_CHOICES 132 -#define AMS_F_AMS_GET0_SIGNED 133 -#define AMS_F_AMS_MSGSIGDIGEST_ADD1 162 -#define AMS_F_AMS_RECEIPTREQUEST_CREATE0 159 -#define AMS_F_AMS_RECEIPT_VERIFY 160 -#define AMS_F_AMS_RECIPIENTINFO_DECRYPT 134 -#define AMS_F_AMS_RECIPIENTINFO_KEKRI_DECRYPT 135 -#define AMS_F_AMS_RECIPIENTINFO_KEKRI_ENCRYPT 136 -#define AMS_F_AMS_RECIPIENTINFO_KEKRI_GET0_ID 137 -#define AMS_F_AMS_RECIPIENTINFO_KEKRI_ID_CMP 138 -#define AMS_F_AMS_RECIPIENTINFO_KTRI_CERT_CMP 139 -#define AMS_F_AMS_RECIPIENTINFO_KTRI_DECRYPT 140 -#define AMS_F_AMS_RECIPIENTINFO_KTRI_ENCRYPT 141 -#define AMS_F_AMS_RECIPIENTINFO_KTRI_GET0_ALGS 142 -#define AMS_F_AMS_RECIPIENTINFO_KTRI_GET0_SIGNER_ID 143 -#define AMS_F_AMS_RECIPIENTINFO_PWRI_CRYPT 167 -#define AMS_F_AMS_RECIPIENTINFO_SET0_KEY 144 -#define AMS_F_AMS_RECIPIENTINFO_SET0_PASSWORD 168 -#define AMS_F_AMS_RECIPIENTINFO_SET0_PKEY 145 -#define AMS_F_AMS_SET1_SIGNERIDENTIFIER 146 -#define AMS_F_AMS_SET_DETACHED 147 -#define AMS_F_AMS_SIGN 148 -#define AMS_F_AMS_SIGNED_DATA_INIT 149 -#define AMS_F_AMS_SIGNERINFO_CONTENT_SIGN 150 -#define AMS_F_AMS_SIGNERINFO_SIGN 151 -#define AMS_F_AMS_SIGNERINFO_VERIFY 152 -#define AMS_F_AMS_SIGNERINFO_VERIFY_CERT 153 -#define AMS_F_AMS_SIGNERINFO_VERIFY_CONTENT 154 -#define AMS_F_AMS_SIGN_RECEIPT 163 -#define AMS_F_AMS_STREAM 155 -#define AMS_F_AMS_UNCOMPRESS 156 -#define AMS_F_AMS_VERIFY 157 - -/* Reason codes. */ -#define AMS_R_ADD_SIGNER_ERROR 99 -#define AMS_R_CERTIFICATE_ALREADY_PRESENT 175 -#define AMS_R_CERTIFICATE_HAS_NO_KEYID 160 -#define AMS_R_CERTIFICATE_VERIFY_ERROR 100 -#define AMS_R_CIPHER_INITIALISATION_ERROR 101 -#define AMS_R_CIPHER_PARAMETER_INITIALISATION_ERROR 102 -#define AMS_R_AMS_DATAFINAL_ERROR 103 -#define AMS_R_AMS_LIB 104 -#define AMS_R_CONTENTIDENTIFIER_MISMATCH 170 -#define AMS_R_CONTENT_NOT_FOUND 105 -#define AMS_R_CONTENT_TYPE_MISMATCH 171 -#define AMS_R_CONTENT_TYPE_NOT_COMPRESSED_DATA 106 -#define AMS_R_CONTENT_TYPE_NOT_ENVELOPED_DATA 107 -#define AMS_R_CONTENT_TYPE_NOT_SIGNED_DATA 108 -#define AMS_R_CONTENT_VERIFY_ERROR 109 -#define AMS_R_CTRL_ERROR 110 -#define AMS_R_CTRL_FAILURE 111 -#define AMS_R_DECRYPT_ERROR 112 -#define AMS_R_DIGEST_ERROR 161 -#define AMS_R_ERROR_GETTING_PUBLIC_KEY 113 -#define AMS_R_ERROR_READING_MESSAGEDIGEST_ATTRIBUTE 114 -#define AMS_R_ERROR_SETTING_KEY 115 -#define AMS_R_ERROR_SETTING_RECIPIENTINFO 116 -#define AMS_R_INVALID_ENCRYPTED_KEY_LENGTH 117 -#define AMS_R_INVALID_KEY_ENCRYPTION_PARAMETER 176 -#define AMS_R_INVALID_KEY_LENGTH 118 -#define AMS_R_MD_BIO_INIT_ERROR 119 -#define AMS_R_MESSAGEDIGEST_ATTRIBUTE_WRONG_LENGTH 120 -#define AMS_R_MESSAGEDIGEST_WRONG_LENGTH 121 -#define AMS_R_MSGSIGDIGEST_ERROR 172 -#define AMS_R_MSGSIGDIGEST_VERIFICATION_FAILURE 162 -#define AMS_R_MSGSIGDIGEST_WRONG_LENGTH 163 -#define AMS_R_NEED_ONE_SIGNER 164 -#define AMS_R_NOT_A_SIGNED_RECEIPT 165 -#define AMS_R_NOT_ENCRYPTED_DATA 122 -#define AMS_R_NOT_KEK 123 -#define AMS_R_NOT_KEY_TRANSPORT 124 -#define AMS_R_NOT_PWRI 177 -#define AMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE 125 -#define AMS_R_NO_CIPHER 126 -#define AMS_R_NO_CONTENT 127 -#define AMS_R_NO_CONTENT_TYPE 173 -#define AMS_R_NO_DEFAULT_DIGEST 128 -#define AMS_R_NO_DIGEST_SET 129 -#define AMS_R_NO_KEY 130 -#define AMS_R_NO_KEY_OR_CERT 174 -#define AMS_R_NO_MATCHING_DIGEST 131 -#define AMS_R_NO_MATCHING_RECIPIENT 132 -#define AMS_R_NO_MATCHING_SIGNATURE 166 -#define AMS_R_NO_MSGSIGDIGEST 167 -#define AMS_R_NO_PASSWORD 178 -#define AMS_R_NO_PRIVATE_KEY 133 -#define AMS_R_NO_PUBLIC_KEY 134 -#define AMS_R_NO_RECEIPT_REQUEST 168 -#define AMS_R_NO_SIGNERS 135 -#define AMS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE 136 -#define AMS_R_RECEIPT_DECODE_ERROR 169 -#define AMS_R_RECIPIENT_ERROR 137 -#define AMS_R_SIGNER_CERTIFICATE_NOT_FOUND 138 -#define AMS_R_SIGNFINAL_ERROR 139 -#define AMS_R_SMIME_TEXT_ERROR 140 -#define AMS_R_STORE_INIT_ERROR 141 -#define AMS_R_TYPE_NOT_COMPRESSED_DATA 142 -#define AMS_R_TYPE_NOT_DATA 143 -#define AMS_R_TYPE_NOT_DIGESTED_DATA 144 -#define AMS_R_TYPE_NOT_ENCRYPTED_DATA 145 -#define AMS_R_TYPE_NOT_ENVELOPED_DATA 146 -#define AMS_R_UNABLE_TO_FINALIZE_CONTEXT 147 -#define AMS_R_UNKNOWN_CIPHER 148 -#define AMS_R_UNKNOWN_DIGEST_ALGORIHM 149 -#define AMS_R_UNKNOWN_ID 150 -#define AMS_R_UNSUPPORTED_COMPRESSION_ALGORITHM 151 -#define AMS_R_UNSUPPORTED_CONTENT_TYPE 152 -#define AMS_R_UNSUPPORTED_KEK_ALGORITHM 153 -#define AMS_R_UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM 179 -#define AMS_R_UNSUPPORTED_RECIPIENT_TYPE 154 -#define AMS_R_UNSUPPORTED_RECPIENTINFO_TYPE 155 -#define AMS_R_UNSUPPORTED_TYPE 156 -#define AMS_R_UNWRAP_ERROR 157 -#define AMS_R_UNWRAP_FAILURE 180 -#define AMS_R_VERIFICATION_FAILURE 158 -#define AMS_R_WRAP_ERROR 159 - -#ifdef __cplusplus -} -#endif -#endif From e3ae90317907db9bed5ce1b3f27df4d18f9cf7b1 Mon Sep 17 00:00:00 2001 From: Mihai Serban Date: Tue, 19 Oct 2021 12:23:41 +0300 Subject: [PATCH 12/12] add ams --- server/external/README | 2 +- server/external/openssl/aix_64/include/openssl/asn1.h | 2 +- server/external/openssl/linux_64/include/openssl/asn1.h | 2 +- server/external/openssl/linux_64/include/openssl/symhacks.h | 2 +- server/external/openssl/win_32/include/openssl/asn1.h | 2 +- server/external/openssl/win_32/include/openssl/symhacks.h | 2 +- server/external/openssl/win_64/include/openssl/asn1.h | 2 +- server/external/openssl/win_64/include/openssl/symhacks.h | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/server/external/README b/server/external/README index 40297f1..a3ddbcb 100644 --- a/server/external/README +++ b/server/external/README @@ -1,6 +1,6 @@ ARNIADB Manager Server System ============================= -ARNIADB Manager Server(AMS) use some 3rd software, like openssl, libevent and json. +ARNIADB Manager Server(CMS) use some 3rd software, like openssl, libevent and json. The following is steps to compile them by yourself. ============== diff --git a/server/external/openssl/aix_64/include/openssl/asn1.h b/server/external/openssl/aix_64/include/openssl/asn1.h index ca91ead..7a5ae68 100644 --- a/server/external/openssl/aix_64/include/openssl/asn1.h +++ b/server/external/openssl/aix_64/include/openssl/asn1.h @@ -240,7 +240,7 @@ typedef struct asn1_object_st */ #define ASN1_STRING_FLAG_NDEF 0x010 -/* This flag is used by the AMS code to indicate that a string is not +/* This flag is used by the CMS code to indicate that a string is not * complete and is a place holder for content when it had all been * accessed. The flag will be reset when content has been written to it. */ diff --git a/server/external/openssl/linux_64/include/openssl/asn1.h b/server/external/openssl/linux_64/include/openssl/asn1.h index 8385f5f..9522eec 100644 --- a/server/external/openssl/linux_64/include/openssl/asn1.h +++ b/server/external/openssl/linux_64/include/openssl/asn1.h @@ -127,7 +127,7 @@ DEFINE_STACK_OF(X509_ALGOR) # define ASN1_STRING_FLAG_NDEF 0x010 /* - * This flag is used by the AMS code to indicate that a string is not + * This flag is used by the CMS code to indicate that a string is not * complete and is a place holder for content when it had all been accessed. * The flag will be reset when content has been written to it. */ diff --git a/server/external/openssl/linux_64/include/openssl/symhacks.h b/server/external/openssl/linux_64/include/openssl/symhacks.h index 0dbf737..156ea6e 100644 --- a/server/external/openssl/linux_64/include/openssl/symhacks.h +++ b/server/external/openssl/linux_64/include/openssl/symhacks.h @@ -28,7 +28,7 @@ # undef i2d_ECPKPARAMETERS # define i2d_ECPKPARAMETERS i2d_UC_ECPKPARAMETERS -/* This one clashes with AMS_data_create */ +/* This one clashes with CMS_data_create */ # undef cms_Data_create # define cms_Data_create priv_cms_Data_create diff --git a/server/external/openssl/win_32/include/openssl/asn1.h b/server/external/openssl/win_32/include/openssl/asn1.h index 9fea679..220a0c8 100644 --- a/server/external/openssl/win_32/include/openssl/asn1.h +++ b/server/external/openssl/win_32/include/openssl/asn1.h @@ -224,7 +224,7 @@ typedef struct asn1_object_st */ #define ASN1_STRING_FLAG_NDEF 0x010 -/* This flag is used by the AMS code to indicate that a string is not +/* This flag is used by the CMS code to indicate that a string is not * complete and is a place holder for content when it had all been * accessed. The flag will be reset when content has been written to it. */ diff --git a/server/external/openssl/win_32/include/openssl/symhacks.h b/server/external/openssl/win_32/include/openssl/symhacks.h index 03b971d..bd2f000 100644 --- a/server/external/openssl/win_32/include/openssl/symhacks.h +++ b/server/external/openssl/win_32/include/openssl/symhacks.h @@ -407,7 +407,7 @@ #undef TS_CONF_set_clock_precision_digits #define TS_CONF_set_clock_precision_digits TS_CONF_set_clk_prec_digits -/* Hack some long AMS names */ +/* Hack some long CMS names */ #undef CMS_RecipientInfo_ktri_get0_algs #define CMS_RecipientInfo_ktri_get0_algs CMS_RecipInfo_ktri_get0_algs #undef CMS_RecipientInfo_ktri_get0_signer_id diff --git a/server/external/openssl/win_64/include/openssl/asn1.h b/server/external/openssl/win_64/include/openssl/asn1.h index 9fea679..220a0c8 100644 --- a/server/external/openssl/win_64/include/openssl/asn1.h +++ b/server/external/openssl/win_64/include/openssl/asn1.h @@ -224,7 +224,7 @@ typedef struct asn1_object_st */ #define ASN1_STRING_FLAG_NDEF 0x010 -/* This flag is used by the AMS code to indicate that a string is not +/* This flag is used by the CMS code to indicate that a string is not * complete and is a place holder for content when it had all been * accessed. The flag will be reset when content has been written to it. */ diff --git a/server/external/openssl/win_64/include/openssl/symhacks.h b/server/external/openssl/win_64/include/openssl/symhacks.h index 03b971d..bd2f000 100644 --- a/server/external/openssl/win_64/include/openssl/symhacks.h +++ b/server/external/openssl/win_64/include/openssl/symhacks.h @@ -407,7 +407,7 @@ #undef TS_CONF_set_clock_precision_digits #define TS_CONF_set_clock_precision_digits TS_CONF_set_clk_prec_digits -/* Hack some long AMS names */ +/* Hack some long CMS names */ #undef CMS_RecipientInfo_ktri_get0_algs #define CMS_RecipientInfo_ktri_get0_algs CMS_RecipInfo_ktri_get0_algs #undef CMS_RecipientInfo_ktri_get0_signer_id