484 Commits

Author SHA1 Message Date
8d046f6280 added UIkit markup for ckeditor winix function 2021-01-21 19:17:33 +01:00
9a6696699f added UIkit markup for emacs winix function 2021-01-21 19:17:06 +01:00
56f2eec597 CodeMirror editor updated to version 5.59.2 - it is used in emacs winix function 2021-01-21 19:08:48 +01:00
d29b33532d added UIkit markup for login winix function 2021-01-21 17:13:27 +01:00
a16e82bf54 updated .gitignore 2021-01-21 17:12:56 +01:00
46c17cc441 added UIkit https://getuikit.com front-end framework to index_head_functions_add.html and index.html 2021-01-21 17:10:04 +01:00
2099092e16 updated .gitignore 2021-01-21 17:08:05 +01:00
88b7517337 dodany plik .gitignore 2021-01-21 11:35:40 +01:00
619236329c Makefile.dep
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1223 e52654a7-88a9-db11-a3e9-0013d4bc506e
2019-09-26 18:25:21 +00:00
76160a5ba6 Makefile deps
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1219 e52654a7-88a9-db11-a3e9-0013d4bc506e
2019-09-25 16:25:44 +00:00
e95f32231a fixed: FileLog::get_local_date we need to synchronize when using time_zones pointer
(FileLog::get_local_date is used by Log::PrintDate() and Log of course can be used from different threads)



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1218 e52654a7-88a9-db11-a3e9-0013d4bc506e
2019-09-25 16:25:20 +00:00
be81307faa Makefiles deps
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1199 e52654a7-88a9-db11-a3e9-0013d4bc506e
2019-08-20 12:24:22 +00:00
177e58da4e changed: if there is no body we do not parse application/json to space
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1183 e52654a7-88a9-db11-a3e9-0013d4bc506e
2019-03-25 00:51:51 +00:00
4c2efc08fd fixed: permissions to symlinks and directories with redirect flag were incorrectly checked
(there was no session set and the request was treated the same as from a not logged user)
fixed: in BaseThread there was used 'log' in the main thread (this logger is only for the other thread)
added: in BaseThread we have a main_log now - logger which puts to the main log buffer from the main thread




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1182 e52654a7-88a9-db11-a3e9-0013d4bc506e
2019-03-19 18:08:09 +00:00
ae03922491 seo plugin: added calling WINIX_FILE_CHANGED
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1180 e52654a7-88a9-db11-a3e9-0013d4bc506e
2019-03-14 13:46:40 +00:00
ab005118ba added: a new plugin: seo
new winix function: "seo", it allowes to edit subject, description and keywords for a page
description and keywords are stored in meta



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1179 e52654a7-88a9-db11-a3e9-0013d4bc506e
2019-03-14 13:33:40 +00:00
eec8635af4 changed: templates/item.cpp to use last_item instead of item
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1178 e52654a7-88a9-db11-a3e9-0013d4bc506e
2019-03-14 13:31:35 +00:00
5060997d2a Makefile.dep
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1176 e52654a7-88a9-db11-a3e9-0013d4bc506e
2019-03-07 18:02:52 +00:00
0ac5a21a14 Makefile.dep
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1172 e52654a7-88a9-db11-a3e9-0013d4bc506e
2019-03-06 18:19:29 +00:00
def0f8d144 merge from branch 0.7.x:
- initial support for morm
- added: WinixBase, WinixModel, WinixSystem, WinixRequest
- logger moved to pikotools




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1171 e52654a7-88a9-db11-a3e9-0013d4bc506e
2019-03-06 11:53:28 +00:00
8895f0dcac - json_generic_serializer was not set when there was a redirect
- if there is a redirect and the json return answer is requested
  then we send 'redirect_to' field in 'info' space




git-svn-id: svn://ttmath.org/publicrep/winix/branches/0.7.x@1169 e52654a7-88a9-db11-a3e9-0013d4bc506e
2019-02-19 10:36:20 +00:00
4f8db81c85 added to Locale:
const std::wstring & GetReplace(const wchar_t * key, Types ... types)
key is a string pattern which has %0, %1 parameters which will be replaced with 'types'




git-svn-id: svn://ttmath.org/publicrep/winix/branches/0.7.x@1164 e52654a7-88a9-db11-a3e9-0013d4bc506e
2019-01-07 03:32:17 +00:00
aa388e248d fixed: crash in thread plugin
ThreadInfo was not correctly initialized (plugin pointer was null)
added to PluginInfo: set_dependency_for(WinixModel * winix_model)




git-svn-id: svn://ttmath.org/publicrep/winix/branches/0.7.x@1162 e52654a7-88a9-db11-a3e9-0013d4bc506e
2019-01-02 11:33:19 +00:00
e5d7403c54 Makefile.dep
git-svn-id: svn://ttmath.org/publicrep/winix/branches/0.7.x@1161 e52654a7-88a9-db11-a3e9-0013d4bc506e
2019-01-02 09:12:42 +00:00
4f57d6134c fixed: in Templates: TemplatesFunctions::plugin was not set
git-svn-id: svn://ttmath.org/publicrep/winix/branches/0.7.x@1160 e52654a7-88a9-db11-a3e9-0013d4bc506e
2019-01-02 04:36:24 +00:00
03f6b54a5b Makefile dep
git-svn-id: svn://ttmath.org/publicrep/winix/branches/0.7.x@1158 e52654a7-88a9-db11-a3e9-0013d4bc506e
2018-11-24 17:09:48 +00:00
63ef007ca1 changed: class Cur -> struct Cur in plugin.h
git-svn-id: svn://ttmath.org/publicrep/winix/branches/0.7.x@1154 e52654a7-88a9-db11-a3e9-0013d4bc506e
2018-11-23 18:34:01 +00:00
603e0679e7 Makefiles: added path to morm/src to -I flags
git-svn-id: svn://ttmath.org/publicrep/winix/branches/0.7.x@1152 e52654a7-88a9-db11-a3e9-0013d4bc506e
2018-11-23 18:28:15 +00:00
b90445de4a updated to the new pikotools api - we have a logger for morm and ezc
pikotools has now Log and FileLog classes
which are base classes for winix Log and FileLog classes




git-svn-id: svn://ttmath.org/publicrep/winix/branches/0.7.x@1151 e52654a7-88a9-db11-a3e9-0013d4bc506e
2018-11-23 17:53:43 +00:00
491dd27ebf some work in the new api:
- log_level and save_each_line moved from Log to FileLog
- other fixes in loggers
- DirContainer from Dirs and LoadAvg had no dependencies set




git-svn-id: svn://ttmath.org/publicrep/winix/branches/0.7.x@1148 e52654a7-88a9-db11-a3e9-0013d4bc506e
2018-11-21 22:53:24 +00:00
89d303f375 some work on dependency injection
git-svn-id: svn://ttmath.org/publicrep/winix/branches/0.7.x@1147 e52654a7-88a9-db11-a3e9-0013d4bc506e
2018-11-21 17:51:15 +00:00
a2ffc1e81c start working on 0.7.x branch
- added FileLog which stores content to the file log
- now Log is only a wrapper - it puts messages to the local buffer and when logsave is used then the buffer is put to FileLog
- new base classes:
  WinixBase (Log, Config*, Synchro*)
  WinixModel : public WinixBase (morm::ModelConnector*, Plugin*)
  WinixSystem : public WinixModel (System*)
  WinixRequest : public WinixSystem (SLog, Cur*)
- singletons: log, slog, plugin are depracated - now references to them are in base classses (WinixBase, WinixModel)
- DbBase,  DbConn and Db are depracated - now we are using Morm project (in WinixModel there is a model_connector pointer)
  each thread will have its own ModelConnector





git-svn-id: svn://ttmath.org/publicrep/winix/branches/0.7.x@1146 e52654a7-88a9-db11-a3e9-0013d4bc506e
2018-11-21 11:03:53 +00:00
a7c47140ae creating branch 0.7.x
git-svn-id: svn://ttmath.org/publicrep/winix/branches/0.7.x@1145 e52654a7-88a9-db11-a3e9-0013d4bc506e
2018-11-21 10:50:34 +00:00
ebd7f85fdb updated: html files for jquery-file-upload
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1143 e52654a7-88a9-db11-a3e9-0013d4bc506e
2018-11-15 17:01:40 +00:00
833c04776f changed Makefile.dep
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1141 e52654a7-88a9-db11-a3e9-0013d4bc506e
2018-11-14 17:15:03 +00:00
919c2f62f5 using PT::IsSubString* methods from pikotools
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1138 e52654a7-88a9-db11-a3e9-0013d4bc506e
2018-11-01 00:46:44 +00:00
8f6004d444 removed some IsSubstring* functions
(they are in Pikotools in text/convert.h now)



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1135 e52654a7-88a9-db11-a3e9-0013d4bc506e
2018-10-29 23:51:11 +00:00
1b8f5dc673 added to HTMLFilter:
- possibility to remove html entities
  method: SkipEntity(bool)




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1132 e52654a7-88a9-db11-a3e9-0013d4bc506e
2018-10-24 16:31:42 +00:00
027a8ec428 added to HTMLFilter:
- now we can parse " and ' in html attributes
- we can skip html tags and commentaries, added method:
  void SkipAllTags(bool skip_all_tags, bool skip_commentaries);
- there is virtual method: virtual void ItemFound();
  which is called when a html tag is parsed




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1129 e52654a7-88a9-db11-a3e9-0013d4bc506e
2018-10-23 23:28:45 +00:00
d1e7765e98 backend winix
dodanie opisu strefy czasowej dla Warszawy na 2018 rok




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1128 e52654a7-88a9-db11-a3e9-0013d4bc506e
2018-10-23 21:00:36 +00:00
2d1b2e6b6e Makefile.dep
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1123 e52654a7-88a9-db11-a3e9-0013d4bc506e
2018-07-05 11:15:42 +00:00
350fc551e5 fixed: a default winix function was selected before the mount point was calculated
also a mount point should be cleared (set to an empty mount point) at the
       end of a request




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1117 e52654a7-88a9-db11-a3e9-0013d4bc506e
2018-07-02 12:02:19 +00:00
1c05c31721 added: antispam mechanism
each html form has a hidden form_id and counter_id
counter_id on the client side is generated through javascript code
on the server the form_id and counter_id is stored in the session
after sending the html form the server checks the form_id and counter_id




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1116 e52654a7-88a9-db11-a3e9-0013d4bc506e
2018-07-02 11:16:36 +00:00
08123fe6ac changed the algorithm how sessions work:
- if the IP is banned or there is no a winix function then we set a temporary session
- else
  if there is a session's cookie sent by the client then:
   - if the cookie is a correct session's cookie then we set the session from the cookie
   - or if the cookie is not a correct session's cookie (e.g. session expired) and the winix function
     requires a cookie then we set a new session
   - or if there is no cookie sent then if a winix function requires a session we create a new session

  if there was an error creating a new session or event counters reach a ban limit then a temporary session will be used





git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1115 e52654a7-88a9-db11-a3e9-0013d4bc506e
2018-06-20 15:00:02 +00:00
35b93b1655 changed: now we are parsing directories and functions before checking a session
added:   need_session to FunctionBase (true if the functions requires a session)
         default: true
         



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1114 e52654a7-88a9-db11-a3e9-0013d4bc506e
2018-06-19 13:52:08 +00:00
436a198c36 changed: using PT::ToLower instead of ToSmall
using PT::ToUpper instead of ToCapital
         using PT::EqualNoCase instead of EqualNoCase
         



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1112 e52654a7-88a9-db11-a3e9-0013d4bc506e
2018-05-25 17:22:12 +00:00
aa58faf145 some work on integrating ckeditor4
added ezc blocks: ckeditor_old_browsers_support, ckeditor, ckeditor_small
defined in ckeditor.html



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1109 e52654a7-88a9-db11-a3e9-0013d4bc506e
2018-05-10 17:21:39 +00:00
dcc6d35cba added: start integrating CKEditor4
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1108 e52654a7-88a9-db11-a3e9-0013d4bc506e
2018-05-09 22:48:14 +00:00
3f29cdc01e changed: config parameters: log_check_proxy_ip_header -> check_proxy_ip_header and log_proxy_ip_header -> proxy_ip_header
added: Request::ip_str (std::wstring) (string of the client's IP address)



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1105 e52654a7-88a9-db11-a3e9-0013d4bc506e
2018-05-01 11:22:55 +00:00
ba7d55b7c1 added: config parameters:
bool log_check_proxy_ip_header;
       // check whether there is a 'log_proxy_ip_header' header
       // and if so then log the IP address from it
       // default: false

       std::wstring log_proxy_ip_header;
       // proxy header representing the real IP address of a client
       // default: X-Real-IP





git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1104 e52654a7-88a9-db11-a3e9-0013d4bc506e
2018-05-01 10:43:20 +00:00
6252a0e732 added: Request::post_in (PT::Space) for input when application/json content type is used
from the client




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1102 e52654a7-88a9-db11-a3e9-0013d4bc506e
2018-04-26 18:56:31 +00:00
ca14b1a427 added: Request::header_in (Space) http input headers (without cookies)
added: config parameter: log_env_http_variables (bool) (for logging http headers)
added: support for DELETE http method, added method FunctionBase::MakeDelete()
changed: winix version incremented to 0.6.6




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1100 e52654a7-88a9-db11-a3e9-0013d4bc506e
2018-04-25 19:48:47 +00:00
b01db89942 added config parameter: db_postgresql_smaller_than_10
default false
if true then we are not using ROW() statements in sql queries




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1099 e52654a7-88a9-db11-a3e9-0013d4bc506e
2018-04-25 09:37:56 +00:00
fd421c54e3 changed: Makefile (added Logger from pikotools)
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1096 e52654a7-88a9-db11-a3e9-0013d4bc506e
2018-04-23 14:29:58 +00:00
55992b5066 added: std::wstring * Request::ParamValuep(const wchar_t * param_name)
for taking a pointer (can be null) to a parameter value
added: bool System::IsSSLRequired(bool try_to_use_ssl)
       returns true if we should use ssl
       try_to_use_ssl is to be meant: config->use_ssl, config->use_ssl_static, config->use_ssl_common
       



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1094 e52654a7-88a9-db11-a3e9-0013d4bc506e
2018-04-22 21:26:56 +00:00
a5dfc9974f added: a virtual dctor() for BaseThread class
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1080 e52654a7-88a9-db11-a3e9-0013d4bc506e
2018-04-16 22:44:59 +00:00
7b4a17c934 changed: makefile dep
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1076 e52654a7-88a9-db11-a3e9-0013d4bc506e
2018-03-23 19:27:32 +00:00
c2a1097dd5 added: dependency on the morm project
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1074 e52654a7-88a9-db11-a3e9-0013d4bc506e
2018-03-13 22:34:59 +00:00
ccf78dcb02 updated to the new Pikotools API
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1071 e52654a7-88a9-db11-a3e9-0013d4bc506e
2018-01-06 18:12:53 +00:00
3eff400d88 added: "assume_connection_is_through_ssl" config parameter
winix is testing an environment variable "HTTPS" for the value "on"
       to think that the connection is made via SSL
       you can set assume_connection_is_through_ssl to true for the winix
       to not testing any environment variables but just think the connection
       was made by https (useful when using proxy)
       default: false




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1069 e52654a7-88a9-db11-a3e9-0013d4bc506e
2018-01-01 00:14:02 +00:00
5ab816b5be fixed: in progresql 10 we have to use ROW() expression to construct
a row where only one item is given



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1068 e52654a7-88a9-db11-a3e9-0013d4bc506e
2018-01-01 00:12:33 +00:00
e57840faed fixed: static files loaded to /var such as /var/ckeditor_winix.js were not properly returned
(html filter was used but they are mostly javascript files)
added: new Item::ContentType: ct_other
       if an item has ct_other then the html filter is not used for the content





git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1040 e52654a7-88a9-db11-a3e9-0013d4bc506e
2016-07-13 13:13:56 +00:00
240bf4dc5d changed: the way how raw template is set
option for setting raw template from 'emacs' function has been removed
         now we have index_raw.html template and it can be set from 'template' function
removed: template index_fullscreen.html
changed: some work in miscspace (changed: space_list_tab, space_list_tab_value and space_list_tab_has_next)
fixed:   main index template could not be set through 'template' function





git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1039 e52654a7-88a9-db11-a3e9-0013d4bc506e
2016-04-04 16:02:36 +00:00
abd1500f07 changed: some refactoring in miscspace
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1036 e52654a7-88a9-db11-a3e9-0013d4bc506e
2016-03-23 15:20:42 +00:00
42144bb31c some refactoring in miscspace(.h|.cpp)
space() renamed to space_value() and takes a third parameter: escape (bool)
space_noescape() removed

space_tab() renamed to space_list_tab()
space_tab_value() renamed to space_list_tab_value()
space_tab_has_next() renamed to space_list_tab_has_next()





git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1035 e52654a7-88a9-db11-a3e9-0013d4bc506e
2016-03-22 14:53:43 +00:00
7ed41a03ae fixed: some paths in Makefile.dep were not relative
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1031 e52654a7-88a9-db11-a3e9-0013d4bc506e
2016-03-18 08:56:19 +00:00
1286ceeddf changed: winix project has been moved to 'winixd' subdirectory
in Makefiles we are caltulating relative paths now (by using relative_path program)
	 



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1030 e52654a7-88a9-db11-a3e9-0013d4bc506e
2016-03-17 13:46:20 +00:00
145efe937c moved winix directories to winixdsubdirectory
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1028 e52654a7-88a9-db11-a3e9-0013d4bc506e
2016-03-17 08:26:02 +00:00
ed5adb3f23 moved winix directories to winixd subdirectory
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1027 e52654a7-88a9-db11-a3e9-0013d4bc506e
2016-03-17 08:24:59 +00:00
7d0508961e added: log info about what html template is used
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1026 e52654a7-88a9-db11-a3e9-0013d4bc506e
2016-03-16 14:11:47 +00:00
e53e2e6af9 added: some work in RegisterMail plugin
(added looking for files in a config directory)



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1024 e52654a7-88a9-db11-a3e9-0013d4bc506e
2016-02-03 18:10:40 +00:00
4fafd2a478 changed: Makefile
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1023 e52654a7-88a9-db11-a3e9-0013d4bc506e
2016-02-01 11:12:54 +00:00
f15da4d049 fixed: in FunctionParser we do not treat '+' as a space
added: some work in MailRegister plugin
       (adding mails to db, showing mails)



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1021 e52654a7-88a9-db11-a3e9-0013d4bc506e
2016-02-01 10:15:23 +00:00
057607f9e5 start working on a new plugin: mailregister
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1020 e52654a7-88a9-db11-a3e9-0013d4bc506e
2016-01-31 19:52:17 +00:00
c433b3fd41 updated to the new Ezc API
[ezc stream] has gone, now we have [ezc out] and [out]
the output streams have names now: it's a std::map, before we have a std::vector
and the streams are serialized to "out" space in json
Request::out_streams[] are split into Request::out_main_stream and Request::out_streams class



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1017 e52654a7-88a9-db11-a3e9-0013d4bc506e
2015-11-15 22:23:36 +00:00
632b49ab90 fixed: meta and admin meta information were not saved in memory (in system.dirs)
when 'meta' winix function was used
added: to DbItemsQuery
       sort_index_asc and sort_index_date
       different sort type can be made by 'index' and by 'date'
		     



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1013 e52654a7-88a9-db11-a3e9-0013d4bc506e
2015-06-16 02:37:07 +00:00
f54df8d600 updated: to the new EZC api (ezc functions can be methods of some special objects)
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1012 e52654a7-88a9-db11-a3e9-0013d4bc506e
2015-06-14 18:24:08 +00:00
d8451ceaa0 fixed: checking for ssl redirect
we should take into account cur.request->function->need_ssl too



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1010 e52654a7-88a9-db11-a3e9-0013d4bc506e
2015-05-29 09:46:29 +00:00
62f178c2ee fixed: in App::CheckIfNeedSSLredirect()
winix made an incorrect redirect from/to SSL



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1009 e52654a7-88a9-db11-a3e9-0013d4bc506e
2015-05-29 09:24:43 +00:00
eb4e7343e7 changed: now 'emacs' winix function uses CodeMirror editor
currently only htmlmixed mode is implemented


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1008 e52654a7-88a9-db11-a3e9-0013d4bc506e
2015-04-18 18:50:39 +00:00
5274e8e8ff added: "server_mode" config option (std::wstring)
you can assign any string to it such as "production" "dev"
       this value is not used by winix itself
       you can refer to it from [server_mode] and [server_mode_is] ezc functions





git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1007 e52654a7-88a9-db11-a3e9-0013d4bc506e
2015-04-16 14:43:52 +00:00
ae2a885d6c fixed: rm winix function returned incorrectly formated json when using jquery upload (delete file button)
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1006 e52654a7-88a9-db11-a3e9-0013d4bc506e
2015-03-20 11:00:22 +00:00
901663b145 updated: to the new ezc api
added:   following ezc functions: ezc_and_not, ezc_any_not, ezc_or_not, ezc_one_not, is, is_not, is_empty, is_not_empty





git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1005 e52654a7-88a9-db11-a3e9-0013d4bc506e
2015-03-08 23:22:05 +00:00
dc301d4c50 changed: editors (emacs, ckeditor...) doesn't set an item's title now (if it was empty)
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1003 e52654a7-88a9-db11-a3e9-0013d4bc506e
2015-03-02 21:23:29 +00:00
34f0535a26 added: some ezc functions for displaying current date
current_sec, current_min, current_hour, current_year, ...



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1002 e52654a7-88a9-db11-a3e9-0013d4bc506e
2015-02-22 10:23:52 +00:00
af0e2a778d changed: some refactoring in System: in IsMemberOfGroup method
changed: some log messages at startup (about non existing empty group for uploads directory)




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1001 e52654a7-88a9-db11-a3e9-0013d4bc506e
2015-01-02 08:18:06 +00:00
904f1e70f2 fixed: compiling on Debian (it has no MSG_EOF flag)
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@1000 e52654a7-88a9-db11-a3e9-0013d4bc506e
2015-01-02 07:15:22 +00:00
ddf7ef30ad fixed: compiling od Debian
sockaddr_un has no sun_len member



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@999 e52654a7-88a9-db11-a3e9-0013d4bc506e
2015-01-02 07:14:15 +00:00
0a43870e76 fixed: the way how winix is closing
beforehand we made a http connection from the special thread
       now we just send a fastcgi packet to the unix socket

       the old way was broken because it requires the http server to work
       and if the operating system is going to shutdown/reboot then the http server
       can be first closed and consequently the winix cannot wake up from
       the main thread (and will be terminated SIGKILL by the os)
       



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@998 e52654a7-88a9-db11-a3e9-0013d4bc506e
2015-01-02 07:01:08 +00:00
f875bd2944 changed: when a client doesn't send a session cookie we can instead of ban just use a temporary session
added: config option:
	// the way we behave when no_session_cookie_treshold limit is exceeded
 	// 0 - if a client doesn't send a session cookie again then use a temporary session
 	//     (other sessions from this IP address are not affected)
 	// 1 - add this IP address to ban list and create a temporary session
 	//     (this will block other sessions from this IP address too)
 	// default: 0
 	int no_session_cookie_ban_mode;




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@996 e52654a7-88a9-db11-a3e9-0013d4bc506e
2014-11-25 12:02:22 +00:00
c9bf20201b added: possibility to ban if a session cookie is incorrect (when we are using encoded cookies)
added:   possibility to ban if a client tries to hijack the session cookie
added:   possibility to ban if a client did not send a session cookie
renamed: ezc functions:
         login_cannot_login -> ipban_is_login_allowed_from_this_ip  (and the return value was changed)
         login_when_available_login -> ipban_current_ip_expires_time
added: config options:
       // after how many broken encoded cookie we should ban the current IP
       // default: 2 (value in the range <0 - 65535>)
       size_t broken_encoded_cookie_treshold;

       // after how many incorrect session identifiers (or session indices) we should ban the current IP
       // do not set this value too low, as people connecting from the same IP address (from behind a NAT)
       // would be banned if they have an old session cookie remembered in the browser
       // default: 128 (value in the range <0 - 65535>)
       size_t session_hijacking_treshold;

       // after how many times a client will be banned if it did not send a session cookie
       // default: 1000 (value in the range <0 - 65535>)
       size_t no_session_cookie_treshold;








git-svn-id: svn://ttmath.org/publicrep/winix/trunk@995 e52654a7-88a9-db11-a3e9-0013d4bc506e
2014-11-24 20:22:30 +00:00
76314aab10 added: possibility to encode the session cookie (added files core/sessionidmanager.h and core/sessionidmanager.cpp)
added: config options:
       // whether or not we should encode the session cookie
       // (we have a special algorithm)
       // default: false
       bool session_cookie_encode;

       // if session_cookie_encode is true then you should provide
       // a file where AES keys will be stored
       std::wstring session_keys_file;

       // each session has an index -- an unsigned int value
       // this value is sent in the cookie string (is encoded)
       // and is incremented when session_index_time_increment time is passed since the last incrementing
       // if a client sent the cookie back the difference between
       // current index and the index in the cookie should be less than or equal to session_allow_index_difference
       // default: 8
       size_t session_allow_index_difference;

       // the time which should pass after the session index is incremented
       // default: 30
       // (session_allow_index_difference + 1) * session_index_time_increment should be less than a time
       // load of a page and all elements on it such as images (of course it depends on client's download too)
       time_t session_index_time_increment;

       // time in seconds after a new AES key pair should be generated
       // we have 256 pairs of keys so this time multiplied by 256 should not be less than
       // the max time of a session (session_remember_max_idle),
       // by default: 256 * 2 days = 512 days = 1.4 year > 3 months (session_remember_max_idle)
       // default: 172800 = 2 days (max: 2678400 = 1 month, min: 10)
       size_t session_key_renew_time;

changed: when printing the time of a request we print only two non-zero digits






git-svn-id: svn://ttmath.org/publicrep/winix/trunk@994 e52654a7-88a9-db11-a3e9-0013d4bc506e
2014-11-22 15:30:56 +00:00
3547d326b8 define AR macro in the main Makefile
this is for pikotools and tito libraries



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@993 e52654a7-88a9-db11-a3e9-0013d4bc506e
2014-11-12 04:14:16 +00:00
0ecb2ac70e added: to HtmlTextStream: Escape(bool) method
now the output html streams can be turn into no-escaping mode
       default true (set when a request is clearing)




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@990 e52654a7-88a9-db11-a3e9-0013d4bc506e
2014-11-06 21:17:41 +00:00
8f8defe0de updated: to the new Ezc API
removed statements: [if-index ...] [is ...] [is-no ...]
added:   generic ezc functions:
         and, any (the same as and), or, one (the same as or), not, cmp, trim
         to_lower, to_upper, index
changed: in misc:
         added treat_new_line_as_white flag to IsWhite() SkipWhite() and TrimWhite()
         TrimWhite(), TrimFirst(), TrimLast(), Trim() are using only wide characters now
         (they were templates before)
         added: IsInt(), IsSize(), IsFloat()
changed: version to 0.6.4






git-svn-id: svn://ttmath.org/publicrep/winix/trunk@989 e52654a7-88a9-db11-a3e9-0013d4bc506e
2014-11-02 17:47:34 +00:00
db5572e864 removed: svn:executable attribute from files
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@984 e52654a7-88a9-db11-a3e9-0013d4bc506e
2014-11-01 17:05:20 +00:00
1100cf75d7 updated: to the new Ezc API
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@983 e52654a7-88a9-db11-a3e9-0013d4bc506e
2014-10-28 19:14:46 +00:00
4fda06b547 fixed: PatternCacher incorrectly rebuilt the cache
some new Ezc::Pattern objects were inserted
       the storage container is std::map<long,...>
       but we traverse it as a std::vector e.g.:
       for(size_t i=0 ; i<pattern_tab.size() ; ++i)
           RebuildCache(pattern_tab[i].pattern);
       so eventually new patterns were added to the map
       (operator [])




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@980 e52654a7-88a9-db11-a3e9-0013d4bc506e
2014-10-21 07:27:21 +00:00
fb18b2238e added: two options to the config:
ezc_error_prefix (string)
        ezc_error_postfix (string)
        // prefix and postfix used when there is an error in Ezc patterns
        // default:
        // prefix:  "<!-- "
        // postfix: " -->"
added:  Ezc::Blocks to templates
added:  although patterns have pointers to functions and blocks cached
        the Ezc::Generator should use SetFunctions() and SetBlocks() method
        in order to correctly recognize variables (aliases)




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@978 e52654a7-88a9-db11-a3e9-0013d4bc506e
2014-10-19 21:20:09 +00:00
5266a7e4e5 updated: to the new Ezc API
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@974 e52654a7-88a9-db11-a3e9-0013d4bc506e
2014-10-18 18:12:04 +00:00
8196fb77d1 changed: now we do not use std::string and char* in the Winix API
everywhere we are using std::wstring and wchar_t*
         (std::string and char* is used only locally in some places
         especially when creating a path to OS file system etc.)
added:   to the special thread when winix closes:
         a write function for curl: FetchPageOnExitCurlCallback()
         without this function the curl library will print
         the page's content to the standart output
changed: TextStream<> class from core can make
         UTF8<->wide strings conversions
removed: from config: utf8 option
         now winix expects UTF8 from the user's input (html forms, url-es)
         and outputs strings in the UTF8 format




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@965 e52654a7-88a9-db11-a3e9-0013d4bc506e
2014-10-09 20:44:56 +00:00
4abf6642f7 setting a Winix Licence: 2 Clause BSD Licence
changed: version to 0.6.2



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@963 e52654a7-88a9-db11-a3e9-0013d4bc506e
2014-10-04 18:04:03 +00:00
e3284dcfbc fixed: winix incorrectly used config options: upload_dirs_chmod and upload_files_chmod
added: to config: upload_group
       a group name for newly uploaded files (and created necessary directories in the file system)




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@961 e52654a7-88a9-db11-a3e9-0013d4bc506e
2014-09-28 17:30:05 +00:00
f064ff6b3d added: htmltextstream escapes more characters now:
added characters:
          "  -> &#quot;
          '  -> &#39; (&apos; but IE8 has a problem with &apos;)
          10 -> &#10;
          13 -> &#13;
added: two ezc filters:
       fil_html_quote
          "  -> &#quot;
          '  -> &#39; (&apos; but IE8 has a problem with &apos;)
       fil_html_newline
          10 -> &#10;
          13 -> &#13;
changed: fun_subject.html uses <div class="winix_input_a"> now





git-svn-id: svn://ttmath.org/publicrep/winix/trunk@959 e52654a7-88a9-db11-a3e9-0013d4bc506e
2014-09-22 23:54:24 +00:00
bfa5d8cc05 changed: plugin jQuery File Upload has been updated to version 9.7.0
(changed 'upload' and 'rm' winix functions)



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@958 e52654a7-88a9-db11-a3e9-0013d4bc506e
2014-08-06 20:14:10 +00:00
6614919c13 added: possibility to save a pid file
new config option: pid_file (a full path to a pid file)



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@957 e52654a7-88a9-db11-a3e9-0013d4bc506e
2014-08-04 21:11:14 +00:00
8379acdb7f fixed: item content should not be escaped in 'raw' mode
(it was not escaped only when execute bits were set)



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@956 e52654a7-88a9-db11-a3e9-0013d4bc506e
2014-08-03 18:33:07 +00:00
160ddc258d added: to htmlfilter: the filter is able to recognize a special tag, default called: <nofilter>
content between <nofilter>...</nofilter> will not be filtered



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@955 e52654a7-88a9-db11-a3e9-0013d4bc506e
2014-06-18 23:18:28 +00:00
01892d2766 added: flag has_pass to User structure
if false that means the user has not set a password yet 
       (this can be used by a plugins to create a new account without a password set)
       in order to login the user first has to set a new password
       (this can be done from a some kind of activation link send via email etc)
       



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@954 e52654a7-88a9-db11-a3e9-0013d4bc506e
2014-06-07 11:20:44 +00:00
222955a2e7 fixed: in Synchro: we should have a table (map) of reference counters
each one for each thread
fixed: on Linux: pthread mutexes by default behaves differently than on FreeBSD
       we have to set PTHREAD_MUTEX_ERRORCHECK attribute 
       when creating a mutex
       



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@953 e52654a7-88a9-db11-a3e9-0013d4bc506e
2014-02-14 11:20:22 +00:00
37b22c3559 added: some debug logs to export plugin
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@952 e52654a7-88a9-db11-a3e9-0013d4bc506e
2014-02-12 22:32:06 +00:00
afbd522362 fixed: in Makefile: 'cp' in Linux behaves differently
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@951 e52654a7-88a9-db11-a3e9-0013d4bc506e
2014-02-12 20:49:50 +00:00
a4bed3ab14 fixed: compiling on Debian with GCC 4.8
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@950 e52654a7-88a9-db11-a3e9-0013d4bc506e
2014-02-12 17:21:42 +00:00
7468e7a36c added: namespace Winix over all *.h/*.cpp files
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@948 e52654a7-88a9-db11-a3e9-0013d4bc506e
2014-02-12 16:30:49 +00:00
145445c713 changed: now we use curl to fetch a page from the special thread when winix quits
(before we were using BSD's fetch)
fixed:   we didn't use FCGX_Finish_r() on the request made from the special thread
         so the thread hangs (now we can use pthread_join correctly from the main thread)



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@947 e52654a7-88a9-db11-a3e9-0013d4bc506e
2014-02-11 21:00:32 +00:00
7fa9314c6b changed: in ClearOutputStreams() referencing 'config' only if not null
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@946 e52654a7-88a9-db11-a3e9-0013d4bc506e
2013-12-23 03:29:33 +00:00
5d37b6c6ae fixed: winix incorrectly sent the binary stream
headers and cookies were not sent
       (instead of headers the content was sent, so the client's browser was unable to open it correctly)
added: standard http headers are added by winix only if there are not such headers already
       e.g. if a plugin adds "Content-Type" header then winix will not overwrite it 
       (headers names are case sensitive)


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@945 e52654a7-88a9-db11-a3e9-0013d4bc506e
2013-12-19 17:19:47 +00:00
fe1f84e29d added: -O0 -g for CXXFLAGS for temporarily debugging
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@944 e52654a7-88a9-db11-a3e9-0013d4bc506e
2013-12-18 12:13:28 +00:00
83e27a6653 fixed: problem with building
added #include <utility> to App (for std::move)



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@943 e52654a7-88a9-db11-a3e9-0013d4bc506e
2013-12-09 16:03:45 +00:00
ee9c68b04e added: generating Content-Length header when text answer is sent to the client
added:   now we are able to use the html filter for the whole out_streams (when ajax is used the output is filtered too)
         splitted FilterCompressSend() function -- first we are making the filtering
         (after filtering we know the size of the content to send)
added:   to Compress:
         Compressing(const char * source, size_t source_len, BinaryPage & out_stream, int encoding);
changed: some refactoring in App




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@942 e52654a7-88a9-db11-a3e9-0013d4bc506e
2013-12-04 01:21:57 +00:00
c04874397b fixed: security vulnerability in 'ln' winix function
a user could create a hardlink to any file and the new link 
       had user_id, group_id and permissions the same as for new generated files,
       this allowes to overwrite any existing file in the filesystem,
       now user_id, group_id, permissions are the same as from the oryginal file



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@941 e52654a7-88a9-db11-a3e9-0013d4bc506e
2013-12-03 12:33:41 +00:00
375604edd6 removed: Request::debug all stream used for debugging info
some environment variables were put there
removed: config variable: debug_info
removed: Request::role (responder, authorizer)
         now we have only one role: responder
added:   new config variables:
         log_env_variables (default false) - when true then fastcgi environment
         variables are logged to the log file
         log_http_answer_headers (default false) - when true all http headers
         created by winix ale logged (note that the www server can add/adjust other headers)
changed: some refactoring in Request struct
changed: CookieTab to std::map<std::wstring, std::wstring>
         beforehand std::string was used
         (changed CookieParser as well)
changed: Request::SetCookie() to AddCookie()
added:   Request::out_headers (a PT::Space struct)
         http headers (without cookies) send back to the client
added:   Request::out_cookies (a PT::Space struct)
         cookies send to the client
changed: App class to use Request::out_headers and Request::out_cookies
         some SendHeaders...() methods were renamed to PrepareHeaders...()
         and they create output in Request::out_headers first (and out_cookies)
         and later it is sent
added:   two plugin messages:
         // http headers (without cookies) were created and are ready to send
         // here you can make some changes to them
         // in p1 you have a pointer to the PT::Space (Request::out_headers)
         #define WINIX_PREPARE_TO_SEND_HTTP_HEADERS		31070

         // http cookies were created and are ready to send
         // here you can make some changes to them
         // in p1 you have a pointer to the PT::Space (Request::out_cookies)
         #define WINIX_PREPARE_TO_SEND_HTTP_COOKIES		31080
added:   config variable:
         // how many output streams do we have in Request class
         // default: 16 (64 maximum)
         size_t ezc_out_streams_size;




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@940 e52654a7-88a9-db11-a3e9-0013d4bc506e
2013-11-29 21:39:23 +00:00
3e32f3784f removed: -O0 -g from production Makefile
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@939 e52654a7-88a9-db11-a3e9-0013d4bc506e
2013-11-25 23:44:01 +00:00
5c4a54d998 added: -O0 -g to the production Makefile
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@938 e52654a7-88a9-db11-a3e9-0013d4bc506e
2013-11-25 23:37:52 +00:00
3af3ac3f6f removed: ezn patterns for rawcontent and ajaxcontent:
index_rawcontent.html, index_ajaxcontent.html
         now we have out_streams in Request and some special
         keyword in ezc templates for sending content to the 
         specified streams
changed: the way how winix answers to the client's browsers:
         info from Request class:
	                                   winix answer send to the client's browser
	                                                       |
	                                                       |
	                                          depending on send_bin_stream
	                               -------------------------------------------------
	                               |                                               |
	                          text answer                                     binary answer
	                               |                                               |
	                   depending on return_json                          sending out_bin_stream
	             ------------------------------------
	             |                                  |
	       normal request                     ajax request
	             |                                  |
	   sending out_streams[0]           depending on return_info_only
	                              ------------------------------------------------------
	                              |                                                    |
	                 generating JSON object from:                   generating JSON object only from info
	                 out_streams and info, e.g.:                    e.g.:
	                 {                                              { info object serialized here }
	                  "stream_1": "some html content",
	                  "stream_2": "some other html content",
	                  "info": { info object serialized here }
	                 }
	                 note that out_streams[0] is not sent
	                 in JSON answers
	
	




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@937 e52654a7-88a9-db11-a3e9-0013d4bc506e
2013-11-14 20:59:23 +00:00
d801f53154 changed: now we are using the C++ 11 language (-std=c++11) and we are using
the clang compiler by default
changed: Makefile files have been a little cleaned
         the main Makefile now will not compile winix and winix.so if there
         were not any changes to source files (it's faster)
         (added Makefile.dep in the global directory with list of all source/header files)
changed: winix version to 0.5.5




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@933 e52654a7-88a9-db11-a3e9-0013d4bc506e
2013-10-15 21:57:51 +00:00
a6b06f82e9 fixed: compiling in the clang (new version of c++ std lib)
(added some header files)
added: three messsages in ticket plugin:
       // send by showtickets winix function when tickets are loaded (and sorted)
       // in p1 you have a pointer to the ticket tab: std::vector<Ticket::Ticket> (include "ticket.h")
       // in p2 you have a pointer to the sort tab:   std::vector<Item*>
       // those tables don't have to be equal in size (in the case when there is no some tickets in the database)
       #define WINIX_PL_TICKET_TICKETS_LOADED                 4106
       
       // a new ticket has been added
       // in p1 you have a pointer to the Ticket::Ticket structure (include "ticket.h")
       // in p2 you have a pointer to the Item structure
       #define WINIX_PL_TICKET_ADDED_NEW                              4107
       
       // a ticket has been changed
       // in p1 you have a pointer to the Ticket::Ticket structure (include "ticket.h")
       // in p2 you have a pointer to the Item structure
       #define WINIX_PL_TICKET_CHANGED                                        4108

added: two ezc functions for tickets:
       ticket_does_param_id_have_value()
       tickets_tab_does_param_id_have_value()
       (they take two integer arguments -- testing whether a specified param_id has the given value)
changed: some more minor additions in tickets templates




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@932 e52654a7-88a9-db11-a3e9-0013d4bc506e
2013-10-10 11:59:21 +00:00
b7f3f84080 changed: in 'showtickets' winix function
now tickets are sorted by the sort_index and then by date
changed: html in 'sort' winix function (added items' subjects to the item lists)



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@931 e52654a7-88a9-db11-a3e9-0013d4bc506e
2013-07-08 14:42:14 +00:00
26715bdd4c changed: html for 'upload' winix function
all static files (css/js) are downloaded from our server now



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@930 e52654a7-88a9-db11-a3e9-0013d4bc506e
2013-07-02 07:14:19 +00:00
083fa7857f fixed: in notify/notify.cpp: a correct locale id should be taken
(we were not able to send: a mail with an activation link and 
        a mail with the reset password link when we didn't have a locale with id 0 loaded)



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@929 e52654a7-88a9-db11-a3e9-0013d4bc506e
2013-05-16 21:02:17 +00:00
9ffda3e070 changed: in passwd: a redirect make only if a password has been changed
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@928 e52654a7-88a9-db11-a3e9-0013d4bc506e
2013-05-16 20:11:27 +00:00
81160dbbe9 fixed: a passwd winix function should allow a non loged person to reset his password (permission fix)
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@927 e52654a7-88a9-db11-a3e9-0013d4bc506e
2013-05-16 20:08:07 +00:00
7c266b85e2 added: winix function 'account'
code for activating an account has been moved here from Pw
changed: the form for reseting a user's password has been moved
         to 'passwd' winix function (it was in Pw before)




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@926 e52654a7-88a9-db11-a3e9-0013d4bc506e
2013-05-16 19:26:44 +00:00
48cdca7549 changed: in fun_gallery.html: added js code to get the proper image id from url
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@925 e52654a7-88a9-db11-a3e9-0013d4bc506e
2013-05-14 08:37:22 +00:00
1c401eae3b added: to Rm function:
bool Rm::RemoveFileOrSymlink(long item_id, bool check_access)
added: in ticket plugin: possibility to remove a file/image
       (not finished yet)




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@924 e52654a7-88a9-db11-a3e9-0013d4bc506e
2013-05-06 07:23:44 +00:00
0e9eb30b5d added: some ezc function to ticket plugin:
ticket_param_value_for_param_id
       tickets_tab_param_value_for_param_id
       tickets_tab_conf_tab_param_name
       tickets_tab_conf_tab_file_tab
       tickets_tab_conf_tab_file_tab_index
       tickets_tab_conf_tab_file_tab_path
       tickets_tab_conf_tab_file_tab_itemid
       tickets_tab_conf_tab_file_tab_meta




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@923 e52654a7-88a9-db11-a3e9-0013d4bc506e
2013-04-24 01:21:19 +00:00
c10c9393c0 changed: plugin 'export': export winix function
the checkbox is now selected when we want to export static files too 
         (default it is not checked)
         



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@922 e52654a7-88a9-db11-a3e9-0013d4bc506e
2013-04-17 00:37:39 +00:00
8705b3437c fixed: imgcrop winix function should load only images
(when called in a directory)
added: to reload winix function:
       reloading (clearing) the cache from 'menu' plugin
added: to 'menu' plugin
       possibility to read 'meta' information from files 
       third argument 'withmeta' to menu_dir_tab ezc function
       e.g. [for menu_dir_tab "/directory" "..." "withmeta"]...[end]
       and some ezc functions to retrieve the meta values




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@921 e52654a7-88a9-db11-a3e9-0013d4bc506e
2013-04-16 09:51:36 +00:00
aed891764a added: to config: HasValue() methods
for checking if a value exists (useful for checking lists -- they don't have to be copied out)




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@920 e52654a7-88a9-db11-a3e9-0013d4bc506e
2013-04-02 22:24:30 +00:00
495499d12f added: a new winix function: imgcrop
for cropping images (and thumbnails)
       www.domain.com/dir/file.jpg/imgcrop  -- crop an image
       www.domain.com/dir/file.jpg/imgcrop/thumb  -- crop an image's thumbnail
       www.domain.com/dir/file.jpg/imgcrop/newthumb  -- crop and create a new thumbnail (from an original image)
       www.domain.com/dir/imgcrop -- show images' list with above options
added: to Image class: some methods for cropping




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@919 e52654a7-88a9-db11-a3e9-0013d4bc506e
2013-03-29 22:03:28 +00:00
8d9a021eab changed: when there is reqtype:json parameter and there is not set request.ajax_serializer
then we are using a generic json serializer
changed: we are sending the application/json header when returning an json string
added:   to config: log_server_answer (default false)
         when true we put the whole string (server's answer) to the log file
added:   to Request: use_200_status_for_not_found_and_permission_denied
         if this is true then if the server http code would be 403 or 404
         then we return 200 OK (useful when using ajax)
changed: System::RedirectTo() methods take as the last parameter: use_reqtype
         if this is true (default) then reqtype:type parameter is automatically added to the redirecting path
         




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@918 e52654a7-88a9-db11-a3e9-0013d4bc506e
2013-03-26 00:04:01 +00:00
be6e09c5af added: some ezc functions (item_tab_meta*)
added: some ezc functions (gallery_tab_meta*) to gallery plugin
added: to gallery plugin: a new gallery: Gallery version 1.2.9



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@917 e52654a7-88a9-db11-a3e9-0013d4bc506e
2013-02-26 11:49:22 +00:00
293e426ed4 fixed: plugin 'group'
Groups::ReindexGroups incorrectly read a field from a PT::Space (it used 'table' object directly)
       but the value was in 'table_single' 
       now we are using GetValue method



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@916 e52654a7-88a9-db11-a3e9-0013d4bc506e
2013-02-01 21:14:56 +00:00
60f2337b73 updated: paths in Makefile (prog subdirectory)
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@915 e52654a7-88a9-db11-a3e9-0013d4bc506e
2013-01-19 16:31:15 +00:00
ce8152de2f changed: added 'logsave' when we are waiting for the database to be ready
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@913 e52654a7-88a9-db11-a3e9-0013d4bc506e
2013-01-19 10:10:17 +00:00
496a1979d2 fixed: in ticket plugin: editticket incorrectly used ticket_info->Clear() method
it was called after some objects were set consequently we were not allowed to edit a ticket



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@912 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-12-30 15:33:08 +00:00
fd698ca7b9 added: put the rebus answer into the log (when user has entered an incorrect answer)
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@911 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-12-26 23:08:57 +00:00
b4b368d324 changed: Makefile dep
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@910 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-11-17 01:10:00 +00:00
825694c880 changed: in editticket: closing ticket is better to do via POST request
added:   a new message sent by editticket when closing a ticket:
         #define WINIX_PL_TICKET_CLOSED                                 4105
         // a ticket has been closed (closed button pressed)
         // in p1 you have a pointer to the Item struct
         // in p2 you have a pointer to the Ticket struct





git-svn-id: svn://ttmath.org/publicrep/winix/trunk@909 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-11-05 23:13:52 +00:00
32750a7d50 changed: ticket plugin: redirect type in editticket winix function (when there is 'close' parameter)
fixed:   prototype doesn't work with jquery (in ticket winix function)
         (prototype was loaded for lightbox)



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@908 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-11-04 22:39:02 +00:00
0045c6c72c added: to Item struct: ameta (PT::Space)
admin meta information
added: option "a" to meta winix function
       editing admin meta information
changed: now if you don't have write access to an item
         you can't see the meta information
         previous if you had read access you could have seen them
added: in plugin ticket and thread
       support for 'closing' (ticket, thread)
       (this is only logic, we need some html yet)
added: some ezc function for getting meta/admin meta information
       (for the current item and the last directory)




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@907 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-11-04 21:01:02 +00:00
4809016b78 changed: html (slog.html)
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@906 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-11-01 17:56:00 +00:00
6e2ba65524 changed: added 'check_abuse' parameter to Login::LoginUser
bool Login::LoginUser(const std::wstring & login, const std::wstring & password, bool remember_me,
                               bool use_ses_log, bool check_abuse)
         default 'false' -- it test the time between GET and POST and the rebus (if exists)



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@905 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-10-27 11:17:52 +00:00
8033ac66c4 added: locales to fun_ipban.html
changed: cosmetic changes in IPBanContainer




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@904 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-10-27 10:14:07 +00:00
9ef3736989 added: to 'ipban' winix function:
possibility to remove a ban (or all bans)
added: to SessionManager: sorting of the ban list (in the second thread)



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@903 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-10-27 09:03:49 +00:00
099dd55d0c added: IP ban mechanism (not finished yet -- we need a winix function to remove a ban)
now after some incorrent login attempts your IP can be banned or blocked
       (see new config variables)


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@902 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-10-27 07:44:26 +00:00
53b4175d00 added: plugin message: WINIX_CHECK_PLUGIN_ACCESS
this message is sent before calling MakePost() or MakeGet()
       if you return false (which is default) you can prevent the access
       to the resource
       



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@901 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-10-17 19:52:55 +00:00
8aa6f08e08 updated: html (login and passwd)
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@900 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-10-17 06:48:48 +00:00
c5024598cb updated: html/css (added div.winix to templates)
now we have winix.css in common/winix directory
         it is automatically loaded by index_head_functions_add.html


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@898 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-10-17 06:00:00 +00:00
dfcf6b29c0 added: to misc:
bool IsWhite(const wchar_t * str, bool treat_new_line_as_white)
       bool IsWhite(const std::wstring & str, bool treat_new_line_as_white)
       return true if the whole string is white (or an empty string)
added: global variable in admin environment for an user: "display_name"
       if defined it is used to display an user's name instead of its login
       it is used in: void print_user_name(Info & i, User & user);
       (tickets, threads, cat function etc)





git-svn-id: svn://ttmath.org/publicrep/winix/trunk@895 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-09-26 07:18:32 +00:00
7f48d1eb2e fixed: the way we check whether we need make the redirect from SSL to non SSL (or vice versa)
beforehand we didn't take into accout default winix functions



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@894 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-09-24 20:31:01 +00:00
eaa97995d2 fixed: we should check cur.request->function is not null (in5D app when testing ssl/nossl redirect)
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@893 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-09-24 18:59:08 +00:00
14f997b844 added: need_ssl flag to FunctionBase
// try to use SSL
       // if in the config 'use_ssl' is true and 'use_ssl_only_for_logged_users' is true
       // then ssl is used only for logged users but sometimes there is a need to use
       // SSL even if noone is logged (for example for such functions like 'login' or 'adduser')
       // default: false
       // (this option is ignored if 'use_ssl' in the config is false)
       bool need_ssl;




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@892 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-09-24 18:38:35 +00:00
26e87b20b1 changed: in Crypt:
renamed Hash() -> HashBin()
         HashBin() is using a binary output from OpenSSL now
	 previously we are using the hex output and with the new OpenSSL version
         the text has additional characters and causes some problems
	 added: HashHex() - it is using the HashBin() and then converts the output
	 to hex format itself
	 



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@891 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-09-19 23:17:10 +00:00
5cdf6eff36 added: to ticket plugin:
some messges:
// 
#define WINIX_PL_TICKET_PREPARE_TO_ADD_TICKET  4103

// a next ticket will be displayed
// in p1 you have a pointer to the Item struct
// this is call from tickets_tab ezc function
#define WINIX_PL_TICKET_TICKETS_TAB_IS_NEXT            4104

methods:
void ticket_meta_value(Info & i)
void tickets_tab_meta_value(Info & i)






git-svn-id: svn://ttmath.org/publicrep/winix/trunk@890 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-09-15 23:34:25 +00:00
4ed535a3b7 added: to plugin ticket: message WINIX_PL_TICKET_LOAD_TICKETS
someone can send this message with a directory id
       and tickets will be loaded from the directory
       (and to display them you can use ezc functions)



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@889 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-09-14 23:48:39 +00:00
da15323c2f added: to plugin thread: message WINIX_PL_THREAD_CAN_MAKE_REDIRECT
(similar as for ticket)



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@888 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-09-14 07:14:54 +00:00
bd1f717b4c added: some methods in Dystem::Dirs (takes wchar_t * as an argument, now only std::wstring were)
changed: in plugin ticket: added message: WINIX_PL_TICKET_CAN_MAKE_REDIRECT
         it is sent at the end of POST request (editticket, createticket)
         if we can make a redirect (useful with AJAX)





git-svn-id: svn://ttmath.org/publicrep/winix/trunk@887 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-09-13 23:12:48 +00:00
72013046fc added: Lock class -- locking resources by using Synchro object
the destructor automatically calls Unlock()



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@886 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-09-11 23:46:00 +00:00
14ae19143f added: new ezc filter: fil_new_line_to_br
added: PutChar() methods to HtmlTextFilter and TexTextFilter



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@885 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-09-11 21:41:10 +00:00
d8260d8383 added: a new way: HEX format to saving/reading from PostgreSQL bytea columns
added: to Request:
       // binary page
       BinaryPage binary_page;

       // a compressed page ready to send to the client
       BinaryPage compressed_page;

       // if true then either page or ajaxpage will be sent to the client
       // if false then binary_page is sent
       // default: true
       bool use_text_page;

       BinaryPage is defined as (in requesttypes.h):
       typedef PT::TextStreamBase<char, 1, 4096> BinaryPage;

added: to Compress: now it can gets BinaryPage as arguments (input, output)
changed: winix version to: 0.5.0
added: in templates: TexTextStream class
       for taking input to the TeX typesetting system





git-svn-id: svn://ttmath.org/publicrep/winix/trunk@884 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-09-11 05:19:45 +00:00
9174555ff8 added: to config: log_time_zone_id (size_t) identifier
this is the time zone identifier used in log messages



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@882 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-09-06 17:50:14 +00:00
0c6ddc2218 added: 'subject' winix function is using WINIX_FILE_CHANGED message now (when changing a file's subject)
added: 'postredirect' global parameter (it can be a param or post value)
       you can use this parameter in a html POST form
       after processing the POST request winix will make a redirect to the value



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@881 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-09-04 20:24:42 +00:00
43b4075b16 added: ezc functions:
void dir_tab_subject(Info & i);
       void dir_tab_is_root(Info & i);
changed: in dir_tab_link:
         now it doesn't print the proto and base address - you should use [doc_base_url]




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@879 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-09-02 01:27:41 +00:00
8f8e44fee5 added: ezc functions:
void dir_is_no(Info & i)
       void dir_level_is(Info & i)
       void dir_last_url_is_no(Info & i)
       void item_no_is(Info & i)
       void item_url_is_no(Info & i)




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@878 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-08-26 22:30:25 +00:00
260c12894d added: to Request options used by ezc generators:
bool gen_trim_white;
       bool gen_skip_new_line;
       bool gen_use_special_chars;
added: new ezc filter: fil_csv_escape
       for escaping csv fields





git-svn-id: svn://ttmath.org/publicrep/winix/trunk@877 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-08-26 19:53:47 +00:00
adf273479a fixed: WINIX_RAW_POST_STRING should have a different id
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@876 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-08-19 14:25:43 +00:00
54480da405 added: WINIX_RAW_POST_STRING plugin message
this is the raw string sent in POST method (in p1 pointer there is a pointer to std::string object)



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@875 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-08-19 14:24:24 +00:00
90261b2005 added: a new plugin message: WINIX_POST_PARAMS
raw POST parameters
       in p1 there is a pointer to std::string meaning a parameter's name
       in p2 there is a pointer to std::string value
       this is sent only from PostParser
       PostMultiParser (multipart/form-data html forms) doesn't send this messsage
       there is no a session set (session pointer is null)




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@874 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-08-19 13:50:58 +00:00
cc71c225a3 added: to DbBase:
bool EndTrans(bool everything_ok);



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@873 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-08-15 19:33:20 +00:00
e739f30088 fixed: when using Request::ajax_serializer then we should not use html filter
(the filter can be used before we make the json answer -- not implemented yet)



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@872 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-08-12 18:23:48 +00:00
51d95b49a0 added: to Request:
// used as a JSON output (when ajax_serializer is defined)
       // it will be serialized and have at least:
       // 'content' string - the whole html content
       // 'http_status' integer - http status code (e.g. 200)
       PT::Space ajax;
 
       // if not null then the request will have a JSON as an output
       PT::SpaceToJSON * ajax_serializer;




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@871 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-08-08 16:04:48 +00:00
b5c155b927 added: export plugin
the possibility to export only non static files in a directory



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@870 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-08-03 10:55:14 +00:00
5a5fe1b0cc fixed: export plugin
I forgotten to add exporting a directory



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@869 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-08-03 10:24:24 +00:00
1c4e010fc1 I have forgotten to add: html/fun_export.html
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@868 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-08-03 09:39:25 +00:00
d8d523d983 added: 'export' winix function (export plugin)
exporting an item or the whole directory



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@867 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-08-03 09:25:17 +00:00
1c2589a2f2 added: to Log:
void LogBinary(const char * blob, size_t blob_len);
       void LogBinary(const std::string & blob);
       int LogLevel();



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@866 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-07-31 03:29:16 +00:00
1ec61ffa11 added: to Log:
operator<<(const PT::TextStreamBase<>())



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@865 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-07-25 10:28:41 +00:00
ca0a5c9cbe changed: upload html
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@864 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-07-15 18:20:22 +00:00
8dd31e737f changed: css
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@862 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-07-15 15:57:45 +00:00
e98cca7fbc updated: jquery upload plugin (upload winix function)
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@861 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-07-15 15:49:48 +00:00
9830b0a50f added: to misc: UrlEncode which takes PT::TextStreamBase as an argument
added: to misc: QEncode which takes PT::TextStreamBase as an argument
added: to Locale: methods: IsKey, Get which takes PT::TextStreamBase as an argument




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@860 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-07-10 16:50:59 +00:00
f76a0ca3e9 added: some ezc functions in menu plugin
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@859 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-07-02 19:15:50 +00:00
5a6d1991ac changed: config.space is available public now
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@858 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-06-30 23:20:18 +00:00
329e2d8001 fixed: when there is no option "locale_files" in the config
the "en" should be loaded by default
added: LDFLAGS option to Makefiles
added: compilation with CLANG (some const objects should have been created with default cctor)




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@856 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-06-30 18:37:52 +00:00
403cca5aad rewritten: public interface in TemplatesFunctions::Locale
added a default parameter bool try_default_too = true to some methods: Get(), IsKey()
           added more methods for accessing by an internal index



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@854 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-06-27 23:21:43 +00:00
b8ff5d4cfc added: winix functions: locale, timezone
changed: time zones -- now we have the daylight saving time
       different for each year (start, end)
added: config option: time_zone_id (size_t)
       time zone identifier for not logged users
       or for newly created accounts
       those identifiers you can see in etc/time_zones.conf file
       or by using timezone winix function with 'a' parameter (timezone/a) (!!IMPROVE ME NOT IMPLEMENTED YET)
       default: 34 (Coordinated Universal Time UTC+00:00)
added: config option: locale_default_id (size_t)
       locale for not logged users
       or for newly created accounts
added: config option: locale_max_id (size_t)
       a maximum value of a locale identifier
       default: 100 (maximum: 1000)
       each locale files should have its own identifier (in "winix_locale_id" field)
       from zero to this value
added: config option: time_zone_max_id (size_t)
       maximum value of a time zone identifier
       time zones with an id greater than this will be skipped
       default: 130 (maximum: 1000)
removed: config option: locale_default



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@852 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-06-26 23:19:19 +00:00
54e6c07efc added: etc directory to Makefile install
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@850 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-06-22 23:41:12 +00:00
d11cda3577 added: a new directory "etc"
there'll be some generic config files for winix
added: a new file in etc directory: time_zones_file
       list of time zones (not finished yet -- daylight saving time is needed)
added: option to config: etc_dir
       a directory in which there are some config files
       used mainly when winix starts
       default: empty (means not for using)
added: option to config: time_zones_file
       a file in etc_dir with time zones info
       default: time_zones.conf
       this is a Space structure with all time zones
added: to system: TimeZones struct
       list of time zones read from etc/time_zones.conf



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@849 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-06-22 23:34:33 +00:00
abafb80caf added: time zone's names to locales
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@848 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-06-22 19:18:03 +00:00
e0dd85ca99 changed: making a redirect from SSL connection to non SSL
if either use_ssl in the config if false
         or if use_ssl_only_for_logged_users is true
         and a user is not logged
added:   base url redirect HTTP codes to the config
         // if current connection is without SSL and should be made through SSL
         // or if is via SSL and should be done in plain text
         // then we make a redirect
         // default: 303
         int use_ssl_redirect_code;

         // when the HOST_HTTP environment variable is not equal to 'base_url'
         // (the part 'http://' and the last slash is removed)
         // the server will redirect into base_url + 'REQUEST_URI'
         // it's useful when you want to redirect from 'mydomain.tld' into 'www.mydomain.tld' etc.
         // set this option to false if you have multiple subdomains
         // default: false
         bool base_url_redirect;




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@847 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-06-07 00:26:37 +00:00
2c38fe180e added: new function for ezc templating:
void space_value_noescape(Info & i, PT::Space & space)



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@846 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-06-05 21:31:12 +00:00
0d0f12b394 added: to Requst:
std::wstring * PostVarp(const std::wstring & var);
added: to misc:
       template<class CharType>
       bool Toa(unsigned/signed long/int value, CharType * buffer);
       some Toa methods which don't get the buffer len
       (the buffer has to be sufficient big)




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@845 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-06-04 17:51:43 +00:00
86d6c96aeb fixed: winix_subdomain ezc function
didn't print the subdomain
added: to rm winix function:
       bool Rm::RemoveItemByPath(const std::wstring & path, bool check_access)
fixed: in Upload winix function
       when uploading an image we have to get
       a mount point where the image is placed (parent dir)
       (it was cur->mount beforehand)



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@844 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-06-03 02:14:33 +00:00
b605fb0a77 added: some ezc functions for subdomains:
void winix_subdomain(Info & i);
       void winix_subdomain_is_empty(Info & i);
       void winix_subdomain_is_not_empty(Info & i);
       void winix_subdomain_is(Info & i);




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@843 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-05-30 21:14:03 +00:00
ec773e5f29 added: TimeZone struct (core)
this class has information about a time zone (utf offset, daylight saving time)
       and methods for converting between UTC and local time
       structs User and Config has a TimeZone object
       System::ToLocal() and System::ToUTC() uses it for converting
       (depending whether a user is logged or not)


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@842 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-05-30 19:04:18 +00:00
9d5d088b4a removed: in some places a dependencies to tm struct has left
removed: operator<<(tm&) from streams: textstream, log, dbtextstream, htmltextstream



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@840 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-05-27 18:11:34 +00:00
1b858f5782 removed: dependencies to 'tz' system structure
now we are using PT::Date from pikotools



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@839 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-05-26 23:04:49 +00:00
5b845f1d03 changed: in Request:
removed start_tm
         added start_date (PT::Date)
changed: in Session:
         removed: tm_time
         added: start_date (PT::Date)
         renamed: time -> start_time
         the same is for last_time
         now we have (last_time and last_date)



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@838 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-05-24 21:09:37 +00:00
db9d381a43 added: to thread manager: names of the threads
the names are shown in the log file


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@837 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-05-19 17:04:33 +00:00
0df088e1e2 fixed: when demonizing there were some logs info put twice in the log file
now we first demonize (fork) and then open the log file
added: start adding support for PT::Date 
       we are using instead of tz system structure



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@836 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-05-19 15:14:35 +00:00
67099d5d06 changed: misc::OnlyDigit()
a comma is changed to a dot


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@835 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-05-12 20:30:34 +00:00
07e8e0c63c updated: to the new Space API (pikotools)
changed: in locale txt files:
         the '(' and ')' characters should be escaped '\(' and '\)'
         or the whole string should be quoted
added:   when parsing locale files we print the line number where there was a syntax error



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@833 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-05-12 16:37:44 +00:00
ecc89d8596 added: two plugin's messages
// a session is going to be removed
// it is called from session manager's thread (with lock/unlock)
#define WINIX_PREPARE_SESSION_TO_REMOVE          30027

// a session has been removed
// it is called from session manager's thread (with lock/unlock)
// in l1 you have the old session id
#define WINIX_SESSION_REMOVED                    30029




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@832 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-05-01 17:58:42 +00:00
c94b0311b6 updated: to the new Pikotools API
ConfParser is now SpaceParser
added:   to SessionManager
         Session * SessionManager::FindSession(long id)



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@831 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-04-30 22:53:54 +00:00
fc33b4f882 added: a deadlock counter to Synchro class
now we can use Lock() more than one in the same thread
       and next Unlock() will recognize it
       sample:
       Lock(); // first lock -- resources locked
       Lock(); // second lock -- skipped (counter incremented)
       ...
       Unlock(); // first unlock -- skipped (because counter greater than zero)
       Unlock(); // second unlock -- actually unlocking


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@830 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-04-28 20:57:57 +00:00
1da1eef768 fixed: ThreadMenager should use Lock/Unlock in StartAll() method
added: Job class (system->job object)
       a general mechanism for jobs (by using PT::Space as a job structure)
       WINIX_JOB plugin message will be sent with a pointer to PT::Space



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@829 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-04-25 22:24:37 +00:00
baf10a9ba9 added: std::wstring Request::subdomain
support for subdomains



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@828 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-04-22 18:23:44 +00:00
bcea4f9464 fixed: base_url_redirect config option was not read from the config file
and was not used when checking for base url redirect
fixed: return values from plugins should be given in a special structure
       they were remembered in plugin object (ret_false, ret_true)
       and consequently were not thread safe
       now all plugin.Call() methods return PluginRes structure 
       in which there are ret_false and ret_true variables       
changed: small refactoring in AddUser winix function



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@827 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-04-22 13:30:07 +00:00
920290e9dc changed: permission to winix function 'who' and 'last'
(only logged users can use these functions)


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@826 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-04-06 08:11:25 +00:00
1d83cf42a1 fixed: passwd winix funtion always changed a password for current user
(even if it was an administrator and has selected other people)


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@825 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-03-30 06:44:38 +00:00
09bfdf9e77 added: two ezc functions:
void winix_postvar_value_is(Info & i);
       void winix_postvar_value_is_not(Info & i);



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@824 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-03-28 00:09:27 +00:00
e83fd91423 rewritten: sessions management
(Session, SessionContainer, SessionManager)
           now a Session object don't copy all fields in its copy constructor (only id)
           the rest fields are set after the object is inserted in SessionContainer
added:     after successfully login a session id is changed
added:     plugin.Call() methods with a first argument a pointer to a Session object



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@823 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-03-17 05:11:23 +00:00
70421b7bd1 reverted last commit (secure flag to cookie) with some info
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@822 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-03-15 17:50:19 +00:00
71ae70f670 added: to cookies: flag "; secure" if a connection is through SSL
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@821 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-03-15 10:43:29 +00:00
b1b3cea64e added: new plugin message: WINIX_PREPARE_USER_TO_LOGIN
a user will be logged in
        set PluginInfo::res to false (it is by default) to prevent logging the user
        directly after this message (if you do not return false)
        a WINIX_USER_LOGGED is sent
        in p1 you have a pointer to User struct
        (if at least one plugin returns false then the user will not be logged)



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@820 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-03-14 20:25:30 +00:00
2712c57f15 changed: Makefile dep (dependencies from pikotools and tito were missing)
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@819 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-03-12 20:30:36 +00:00
0b528c7225 added: to misc:
void OnlyDigit(StringType & s, bool allow_comma = true)
       removes all non-digit characters from a string


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@818 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-03-11 16:21:52 +00:00
b7007da5a9 fixed: misc: ValidateEmail() buffer overflow
added: notifications for resetting a user's password
       (there is no a winix function for this yet)



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@817 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-03-09 22:56:54 +00:00
489310ba1c added: winix function: rmuser
changed: UGContainer<> now uses std::list as a storage
         (previously it was using std::vector with pointers)
removed: now we don't have the operator[] for UGContainer<>



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@816 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-03-09 02:36:25 +00:00
6c2c12fe5e added: html/fun_pw.html
default view for pw winix function


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@815 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-03-03 21:00:48 +00:00
e61f0db57e changed: export plugin:
password is stored as a string (in database)


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@814 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-03-01 15:39:13 +00:00
3e3546a2fd fixed: plugin 'menu' incorrectly read directory items when the directory was en empty string
(the current directory should be used)


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@813 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-03-01 15:14:46 +00:00
d2fa3b7171 corrected: in some places declarations of classes where mixed with struct (class/struct)
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@812 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-02-29 22:52:55 +00:00
0e9f587591 added: to IsWhite (core/misc)
other unicode white characters
       25 characters -- without a new line character (10)
added: config option: account_need_email_verification
       if true then when creating an account a user has to provide
       his email address and a message with an activation link will be sent 
       back to him
added: 'pw' winix function (not finished yet)
       at the moment only one parameter 'activate'



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@810 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-02-28 21:09:44 +00:00
9208b15167 fixed: in winix function 'mv':
a recurrence loop - incorrect function was called (typo)
updated: to the new EZC api:
         templates from plugin menu
         templates from 'man' winix function


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@809 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-02-27 17:43:59 +00:00
a45fb30e0a rewritten: plugin 'menu'
now we have a cache for the plugin
           (this limits the number of database requests)
added:     to plugin 'menu'
           menu_dir_tab can have a 'current' parameter (first argument)
           (it uses the last path from the previous menu_dir_tab) 
changed:   updated to the new EZC api
added:     new message to plugins: WINIX_DIR_ADDED


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@808 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-02-24 12:09:38 +00:00
97c7edafd6 added: to misc:
UrlEncode() for char->wstring
         UrlEncode() for wstring->wstring
removed: Request::redirect_url_encoded flag
         the Request::redirect_to string should always be url-encoded
changed: in UrnEncode()
         now characters like '#' and '/' are not allowed in an url
         (will be url-encoded)
         


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@807 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-02-19 00:59:08 +00:00
1a51b1adc7 added: to config:
parameter: ezc_max_elements
          maximum number for elements through the whole template (ezc)
          default: 50000
       parameter: ezc_max_loop_elements
          maximum number of each [for] loop
          default: 5000 (from ezc generator)
added: to Request class:
       time_t start_time;
       tm start_tm;
       they are set when a request starts
       


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@806 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-02-17 05:19:24 +00:00
9d2be5c50d added: to misc:
void MaxSize(StringType & str, size_t max_size)
       if a string is larger than max_size then it is truncated to max_size characters


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@805 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-02-14 20:35:35 +00:00
f381f24402 fixed: in DbBase: removed:
DbBase::AssertQuery(const std::wstring & q)
       there was a recurrence calling (the method called itself)
       we don't need a method which get a wstring as an argument
added: DbBase::AssertQuery(const char * q, ExecStatusType t)
       DbBase::AssertQuery(const DbTextStream & query, ExecStatusType t)
       (AssertQuery with a second argument -- the same as to AssertResult)
       we don't have to use AssertQuery and AssertResult
       only one AssertQuery now
added: to plugins: two messages:
       // preparing a current user to logout
       // send from 'logout' winix function
       // !! IMPROVE ME this message can be sent when winix is making the shutdown
       // (for sessions which are not mark as 'remember me')
       // and when the SessionManager deletes a session (from the special thread)
       #define WINIX_PREPARE_USER_LOGGED_OUT          30610

       // a user has been logged out
       // send from 'logout' winix function
       // in l1 you have the old user_id
       // !! IMPROVE ME this message can be sent when winix is making the shutdown
       // (for sessions which are not mark as 'remember me')
       // and when the SessionManager deletes a session (from the special thread)
       #define WINIX_USER_LOGGED_OUT                          30620



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@804 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-02-12 14:52:52 +00:00
f6db85fcdb fixed: uninitialized variable in 'rm' winix function (in HasAccess method)
sometimes for directories the rm function could return 'access true' (even without 'r' parameter)



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@803 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-02-10 00:50:05 +00:00
9687d5cd66 removed: operator<<(const PT::Space * space)
from textstream, log, dbtextstream, htmltextstream
added: compile option: -pthread



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@802 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-02-10 00:29:54 +00:00
6e2d00bc5b added: now we have a fourth part in permissions (guests)
e.g.: 07555 means:
           7 for owner
           5 for group
           5 for others
           5 for guests (not logged users)
added:     the sticky bit for directories
           e.g. permissions to a directory with a sticky bit set
           can be set to: 017555
rewritten: rm/mv winix functions to correctly understand the sticky bit
added:     Dir::FollowLink() recognizes ".." and "." now
           consequently System::FollowAllLinks recognizes it too
added:     umask -- calculating privileges for new files/directories
           all users have their own umask (in meta)
           and there is one in the config
           (for guests and when a user has not definied its own one)
removed:   mount option: only_root_remove



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@801 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-01-24 23:03:36 +00:00
5aaab89cd8 added: to locale: comparing lexicographically two characters/strings
int Compare(wchar_t c1, wchar_t c2);
       int Compare(const std::wstring & str1, const std::wstring & str2);
       
	   


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@800 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-01-21 20:51:13 +00:00
7407d24586 added: new ezc filter: fil_first_wordup
first character in a word is capitalized


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@799 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-01-21 17:13:00 +00:00
c9931da5ba fixed: plugin ticket: when a session expires all files from editticket were removed
it should be removed only those new added


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@798 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-01-21 12:29:44 +00:00
4311f06ade added: to TextStream<> and Log:
operator<<(const tm & tm_)



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@797 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-01-19 20:50:42 +00:00
8b64b5d372 updated plugins/ticket templates functions
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@796 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-01-18 17:55:28 +00:00
631ca4f8a3 plugin ticket: rewritten templates ezc functions
(now images/files are working fine)


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@795 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-01-17 22:54:41 +00:00
424618de38 added: to templates: an interface for getting information from Space
miscspace.h, miscspace.cpp
changed: plugin ticket
         now as a config we use a PT::Space struct
         (not finished yet, only 'integer', 'select' and 'progress' are done)


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@794 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-01-16 10:12:38 +00:00
b2d3ca9543 now winix is using 'pikotools' (confparser, utf8, mainparser)
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@792 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-01-12 02:24:08 +00:00
cb33f20a24 removing: confparser.h confparser.cpp
(moving to pikotools)


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@791 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-01-11 11:32:01 +00:00
973d804db2 added: TextStream<> DbTextStream<> and HtmlTextStream<> have operator<<(Space&) now
added: to db: bool DbBase::AssertValueSpace(PGresult * r, int row, int col, Space & space, bool split_single)
added: environment variables for users
       User::env (of type Space) and
       User::aenv (of type Space) for admin variables (can be changed only by a super user)
added: winix function 'env'
       for changing User::env and User::aenv ('env' winix function with a 'a' parameter)



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@790 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-01-08 03:59:51 +00:00
84eaa6b7b6 changed: rewritten templates/man
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@789 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-01-06 12:55:08 +00:00
f967a428ce added: winix function 'man'
displaying all winix functions and ezc templates functions


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@787 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-01-06 12:07:23 +00:00
543d464cbc changed: plugin 'menu': ezc funtion: menu_dir_tab
now we have two parameters: first is a path and second is: "images", "dirs", "files" or empty
          


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@786 e52654a7-88a9-db11-a3e9-0013d4bc506e
2012-01-02 02:05:12 +00:00
43470b2a41 forgotten to add html/index_rawcontent.html
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@785 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-12-17 22:02:49 +00:00
fa05e25a9d added: to config: 'content_type_header' parameter
the kind of "Content-Type" header send to the client
       if utf8 is enabled then 'charset=UTF-8' will also be appended
added: to templates: an index pattern for 'rawcontent'
       used when 'rawcontent' parameter is present
       by default the template has only one [content] ezc function
       useful in AJAX requests       


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@784 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-12-17 21:59:22 +00:00
fe2f1605f1 changed: core/misc: date format in Time() methods
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@783 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-12-14 20:35:19 +00:00
48b5c167bf added to db stream: DbTextStream::operator<<(const std::vector<long> & tabid)
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@782 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-12-08 22:01:19 +00:00
08a0a36dfd changed: html (upload winix function)
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@781 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-12-05 18:20:48 +00:00
d135c31ca0 added: to htmlfilter: html "col" tag is a 'simple' tag
added: ezc functions: winix_function_param_value_is and winix_function_param_value_is_not
       they take two arguments: param_name and param_value



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@780 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-12-04 19:34:39 +00:00
dce68221ad changed: plugin 'export'
rewritten changing of strings in html output
         (added support for https:// prefix)


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@779 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-12-03 19:34:58 +00:00
93273bd470 changed: upload template
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@778 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-12-02 14:38:26 +00:00
92f7c11999 added: 'export' plugin can make use of some meta informations (from items)
additional export currently


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@777 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-12-01 20:45:06 +00:00
024ce8e73c added: a new index template: index_fullscreen.html
is chosen automatically when 'fullscreen' parameter is passed


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@776 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-12-01 18:54:09 +00:00
7902389ef1 changed: in plugin 'menu'
menu_dir_tab ezc functions can be nested now
         (not finished yet)
added:   'meta' winix function
         additional meta information for files and directories
         (not finished yet)



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@775 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-11-25 04:51:55 +00:00
1e9ab2f805 added: to 'group' plugin: new ezc function: group_tab_is_current_link
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@774 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-10-30 23:47:43 +00:00
0550212b64 changed: GroupItem plugin has been renamed to Group
it's nearly finished
         now we are using three levels from Space (ConfParser)
         - group set
         - group
         - values
         


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@773 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-10-16 21:33:45 +00:00
c7b6ca67a2 changed: plugin messages:
WINIX_FILE_REMOVED and WINIX_DIR_PREPARE_TO_REMOVE
         now as a parameter we have a pointer to the Item struct
changed: export plugin now exports all files from a directory
         (in the future there'll be an option how the plugin should behave)



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@772 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-09-30 01:33:42 +00:00
9dae2de2fa fixed: FunctionParser skipped a function name after an item (file) if the name was not a name for a function
it should report a 404 in such a case


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@771 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-09-28 22:24:24 +00:00
968593106e fixed: menu plugin: static files were not correctly skipped
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@770 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-09-26 06:56:35 +00:00
302cb0130d changed: menu plugin (static files are skipped)
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@769 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-09-26 06:39:05 +00:00
89efaa790f changed: ConfParser -- now we can have a tree (spaces can have more than one level)
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@768 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-09-26 05:40:26 +00:00
60f0e62c23 changed: we do not make a 'base redirect' when the request method is POST
changed: ConfParser -- now we have spaces (only one level)



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@767 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-09-16 22:46:42 +00:00
f113e2ef31 changed: we should use SSL connection for such functions as:
adduser, login


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@766 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-09-14 09:56:00 +00:00
39923d6617 fixed: UGContainer<Type> used a std::vector<Type> and when a new item was inserted
then current iterators (and pointers) were invalidated
         now we are using std::vector<Type*>
         this caused some crashes when a new user was added by 'adduser' winix function
added:   plugin 'export' is able to upload files on a remote server now
         (not finished yet)
changed: Thumb class is now called: Image
         and we are able to resize images too
         (some new options in the config and in mount points)
added:   some new plugin messages



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@764 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-09-13 06:08:34 +00:00
72be443414 added: new flag: Request::using_ssl
true if the connections is encrypted by using SSL
changed: in BaseUrlRedirect
         we also check if the connection should use SSL 
         and if so then we make a redirect to "https://.."
changed: in 'static' mount points:
         if the request was e.g. "/styles/default.js?t=B49E5BQ"
         we should return a file "/styles/default.js" (without the "?..." part)
         additionally '#' character is checked



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@762 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-09-06 22:46:15 +00:00
392e8060ba added: some work in Export plugin
changed: in base redirect we are using 301 moved permanently status code now (was 303)


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@761 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-09-05 15:38:09 +00:00
8c01b0f6c0 added: two tables to locales/substitute: smallleters, capitalics
added: locale.ToSmall(wchar_t), locale.ToCapital(wchar_t)
       now we are able to recognize other than ASCII characters
added: static/basic/winix.css with basic styles
removed: [include "item_options.html"] from html templates (fun_cat.html and others)




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@760 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-08-29 22:23:54 +00:00
b984475e49 fixed: index templates and 'change' templates were not cleared when 'reload' function was called
so wrong indexes have been assigned


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@759 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-08-27 03:12:33 +00:00
4f114ea33c added: ezc function: dir_has_parents
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@758 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-08-26 20:45:58 +00:00
5b8a9c0108 added: Patterns class (in templates)
ezc patterns are managed by this class
added: some work in groupitem plugin (not finished yet)
changed: ConfParser can read a string from memory now
         (need some testing yet)



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@757 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-08-25 23:53:49 +00:00
ee6500ac65 added: some more orphans to polish default locale
added: new options to the config:
  url_proto: default: http://
  url_ssl_proto: default: https://
  use_ssl, use_ssl_static, use_ssl_common (whether or not to use SSL protocol)
  use_ssl_only_for_logged_users
  now we are able to use SSL encryption (https) together with normal connections
removed: config option: base_server




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@755 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-08-17 23:09:47 +00:00
3b2a1c3f25 added: new winix function: "sort"
sorting items in a directory (Item::sort_index is used)


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@754 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-08-02 00:10:45 +00:00
4d87359aca added: Export plugin (not finished yet)
added:   ThreadManager
         all threads are connected to the ThreadManager
         they are started/stopped by the manager
changed: FunctionParser
         now we are parsing directly what is in URI
         (we were using GetParser beforehand)
         we are able to recognize ordinary URI scheme (with '?' and '#' characters)
         sample:
         http://domain.com/dir1/dir2/item/function?par1=val2&par2=val2#htmlanchor
         is the same as:
         http://domain.com/dir1/dir2/item/function/par1:val2/par2:val2#htmlanchor
         'htmlanchor' is put in Request::anchor field,
         and the default function can be used like this:
         http://domain.com/dir1/dir2/item?par1=val2&par2=val2#htmlanchor
         but there is not an equivalent in winix form
         e.g. http://domain.com/dir1/dir2/item/par1:val2/par2:val2#htmlanchor
         because 'par1:val2' would be treated as a function name
removed: GetParser
         now we don't have Request::get_tab structure
removed: CKEditorGetParser
         it is not needed now



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@752 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-07-28 22:18:10 +00:00
c37c1ff812 fixed: as we have insert_page ezc function now
we cannot delete ezc patterns when PatternCacher::GetPattern() method is called
       because we can delete a pattern which is in use
       now deleting is performed at the end of a request


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@751 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-07-15 02:09:02 +00:00
1812a2e9ad added: new plugin: menu
fixed: System::FollowAllLinks didn't check permissions to a file (only to a simlink or a directory)
added: new ezc function: insert_page
       now we are able to nest pages in pages



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@750 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-07-13 23:14:10 +00:00
ccc02f41bf added: we can use different redirect codes now
(int Request::redirect_type variable)
       we can set following integer values:
       300 - Multiple Choices
       301 - Moved Permanently
       302 - Found
       307 - Temporary Redirect
       303 - See Other
       default is 303 for all redirects



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@749 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-07-07 17:02:14 +00:00
eaf10c70b7 added: a new winix function: passwd
for changing your password
       or if you are a super user you can
       change a password for anyone
added: uname prints available plugins now



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@748 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-06-27 21:38:19 +00:00
06f42dd9cb changed: winix 'upload' function is a file manager now
we're using an jquery upload plugin
added:   Item struct has new rows: hash, hash_type, file_size, sort_index
added:   css mount parameter
         you can specify css files there, and javascript wysiwyg editors
         (ckeditor, tinymce) can make use of it
changed: post parsers can parse post variables with the same name
         (a postfix is added in such a case)
added:   common_dir parameter to the config
         this is a path to common directory (directory with common static files)
         it is needed to the 'css' mount parameter
         


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@746 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-06-24 20:53:21 +00:00
1d6ff73aad added: new winix function: mount
displaying all mount points
changed: struct Cur has now 'mount' pointer
         we should not use system->mounts.pmount now
         (it will be removed in the future)
changed: all mount point parameters are now propagated to childs mount points
         (if not defined there)



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@745 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-06-21 21:24:49 +00:00
700a6fe643 updated index.html
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@742 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-06-19 21:07:23 +00:00
0a7432b059 added: SLog class -- session logger
messages are displayed in the browser (with locales)
changed: MountParser
         now if there is an error in a line -- the line is simply skipped
         


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@741 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-06-19 20:59:58 +00:00
b369fda1d9 deleted some log info
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@740 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-06-19 10:40:09 +00:00
c49c35cfbd added: a new mount type: static
some path in winix can be redirected to a specified static directory


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@738 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-06-14 23:45:42 +00:00
fb4742e165 added: nicedit: a new wysiwyg javascript editor
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@737 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-06-13 01:06:10 +00:00
fce45b93a2 fixed: users: flag 'super_user' was not correctly read ftom the database
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@736 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-06-09 23:00:00 +00:00
18ecd46a01 changed: when winix demonizes it creates a three new descriptors (0, 1 and 3)
pointing to /dev/null
added:   DbBase::AssertValueBin(PGresult * r, int row, int col, std::string & result)
         it reads binary (bytea) data
added:   DbTextStream can handle 'bool' types now
         (is puts 'true' of 'false' to the stream)
changed: now passwords can be stored either as plain text, a hash or can be encrypted
         with RSA
         currently we have following hashes:
         md4, md5, sha1, sha224, sha256, sha384, sha512
         we are using openssl to manage them
         (look at config options for more info)
changed: winix version to 0.4.7         
added:   class Run - you can run any program from os and send a buffer to its standard input
         and read what the program put on its standard output
added:   class Crypt (in System) - calculating hashes, and crypting/decrypting




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@734 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-06-09 21:22:08 +00:00
af8fbdae72 added: now winix will not log post parameters with 'pass' in names (at the beginning)
changed: only first few characters are logged (from POST)


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@733 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-06-06 22:47:34 +00:00
c84997be30 small changes in Makefiles
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@731 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-06-06 20:35:56 +00:00
06551d6084 added: "str" "strnc" ezc functions
changed: ezc functions:
         "winix_false" to "false"
         "winix_true"  to "true"


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@730 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-04-26 17:19:08 +00:00
84145d7cc8 fixed: BBCODEParser incorrectly worked with the latest changes in HTMLFilter
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@729 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-04-16 11:27:54 +00:00
426beae796 renamed: config option 'html_filter_break_lines' to 'html_filter_break_word'
added:   config option 'html_filter_wrap_line'
         this wraps the whole line (line calculated with html tags as well)
changed: orphans (for html filter) are read from locale files now
         ('language_orphans' value )



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@728 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-04-16 08:42:22 +00:00
aadf12c7b3 added support for gzip compression
new config option: compression_encoding (integer)
 1  - use deflate if available (or raw deflate for Internet Explorer) or don't compress
 2  - use gzip if available or don't compress
 10 - prefer deflate -- use deflate (or raw deflate for IE) if both deflate and gzip are available
 20 - prefer gzip    -- use gzip if both deflate and gzip are available
 default: 20

		   


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@727 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-04-02 00:10:16 +00:00
1b60935d08 updated 'galleria' js plugin
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@726 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-04-01 16:30:14 +00:00
d68731fd55 fixed: thread plugin didn't correctly set the last item and replies (in 'thread' table)
when deleting an answer
added: ThreadInfo::Repair() method
       will be used by 'fsck' winix function       
added: plugins/groupitem 
       directory for a new plugin: 'groupitem'
       


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@725 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-03-23 17:54:53 +00:00
ba63c8c661 changed: removed Languages::Land enum
now we set the languages in the config file: option locale_files, sample:
  locale_files = ( en, pl )
it represents the name of locale files (those from locale_dir directory)
renamed config option: locale to locale_default


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@722 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-02-24 17:06:12 +00:00
15487b347f added ezc function: winix_function_param_is_not
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@721 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-02-22 04:14:26 +00:00
e7e90c6527 txt templates (a new line was missing)
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@720 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-02-18 09:35:35 +00:00
ca5421347a fixed: a new created session doesn't have a correct time set
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@719 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-02-18 09:33:15 +00:00
c8a57f2046 added: to gallery plugin: gallery_theme() mount option
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@718 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-02-15 23:20:12 +00:00
583df13139 added: mount options: thumb_size(cx, cy)
size of a generated thumbnail (size in pixels)
added: plugin gallery: mount option gallery_type
       it can be:
       "lightbox"
       "galleria"
       "galleriathumb"


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@717 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-02-11 21:37:28 +00:00
5049961e17 added a new plugin: "gallery"
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@716 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-01-31 15:51:53 +00:00
18492e5d61 changed templates
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@715 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-01-27 14:35:25 +00:00
d4d9f89d1d changed: ticket templates
added: new plugin message (WINIX_END_REQUEST)


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@714 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-01-27 12:24:45 +00:00
ecf19034ae added: winix uses now [filter] statement from ezc
added: notifications to threads (were temporarily disabled)
changed: templates in notifications



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@712 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-01-26 12:45:38 +00:00
00521c490e added: Q encoding in misc: QEncode()
for mails headers encoding



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@711 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-01-25 11:54:46 +00:00
3071df227a fixed: find_ticket_value (in plugins/ticket/templates.cpp)
should find the first item (can be more than one item with the same 'param')

fixed: added sorting tickets params in ReadTicketParams() (in plugins/ticket/ticketinfo.cpp)

fixed: plugin should have its own 'PluginInfo info' struct
a plugin's function can call another plugin's functions

added: removing tickets files/images

added: removing threads

changed: rm function will call WINIX_FILE_REMOVED now when deleting directories





git-svn-id: svn://ttmath.org/publicrep/winix/trunk@710 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-01-23 23:23:24 +00:00
915cabdf97 changed: added Cur structure
we have there two pointers: 
 Request * request;
 Session * session;
these are the current request and the current session


the session GC was moved to SessionManager (was in SessionContainer)



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@708 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-01-23 14:15:30 +00:00
61ac29b2de added in ticket/templates.cpp binary search for tickets and tickets parameters
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@707 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-01-21 16:16:52 +00:00
ab84a5169e 'tickets' can use 'threads' now
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@706 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-01-20 18:37:51 +00:00
3fad25b8c8 moved some thread files to plugins/thread
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@705 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-01-05 21:44:19 +00:00
8154c403d8 we can create links (hard links, symbolic links) now
added winix functions: ln

winix function 'default' can be used without redirecting now

added new tickets types: TypeProgress, TypeString, TypeMultistring, TypeImages, TypeFiles
now tickets are combined with files
added winix functions: showtickets

fixed mountpoints:
when the default root mount was created its parameter table was empty
and it caused accessing to a non-existing objects

fixed logger:
modifiers (log1, log2, log3) were incorrectly treated
added modifier: log4 (debug info)

now we are moving threads to a new plugin 'thread'
created directory: plugins/thread
(not finished yet)




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@704 e52654a7-88a9-db11-a3e9-0013d4bc506e
2011-01-05 21:24:11 +00:00
bb83aed20d changed cat template
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@703 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-12-12 09:41:20 +00:00
600c9fc907 Thumb thread should check the exit signal
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@701 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-12-12 09:25:36 +00:00
5d09eb149c added a special thread for making thumbnails (thumb.h thumb.cpp)
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@700 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-12-11 22:55:48 +00:00
e854fe3681 changed makefile
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@698 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-12-10 21:20:01 +00:00
36c8822e6c changed organization of static files
removed: item.auth item.auth_path
added:   item.file_path, item.file_fs, item.file_type
now the path to a static file is a relative path
added: thumbnails (not finished yet)
fixed: db didn't correctly return the number of deleted items /DelItem() method/




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@696 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-12-10 21:07:01 +00:00
9b29cce1a4 added a special default function: "-"
the proper default function will be selected automatically


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@695 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-12-07 18:18:45 +00:00
508f06339e added to config: session_max
how many sessions can be: default 1000000 (one milion)


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@694 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-12-07 17:41:28 +00:00
0a9cdd2f15 added: gc for sessions (another thread)
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@693 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-12-07 12:52:52 +00:00
7f77b6e3ec added ezc function: user_is_in_all_groups
changed: ezc function user_is_in_group (we can provide more than one group now)


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@691 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-12-06 01:37:30 +00:00
9507b0b1ba changed Makefile
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@690 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-12-06 00:32:12 +00:00
ad9d6f4301 db: core/user table has only 'notify' column now (previous was cms_notify, thread_notify)
added: notifications for tickets (not finished yet)


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@688 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-12-06 00:25:46 +00:00
b721fb6860 changed path templatesnotifiy/ to notify/
i forgot to add a file: notify/notify.cpp


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@687 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-12-02 02:36:49 +00:00
5f46cd2ea5 moved: templatesnotify -> notify
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@686 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-12-02 02:16:11 +00:00
35efed9fef - now the mess with threads has gone away
- we have a class BaseThread -- this is a base class -- we can inherit from it when
  creating a new thread
- others treads are correctly stopped (when signal comes) -- pthread_join
- we have a special thread only for signals



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@685 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-12-02 01:02:02 +00:00
08e53919e2 changed: updated to the new ezc api, this with O(1) when looking for a specific ezc function
changed: sessions are deleted at the end of a request (and only a few sessions)
         other sessions will be deleted after a next request


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@684 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-11-25 22:42:24 +00:00
933c8841ff added: uptime winix function prints how many sessions there are
changed: functions for text/numbers conversions
         int Toi(const std::string & str,  int base = 10);
         int Toi(const std::wstring & str, int base = 10);
         int Toi(const char * str,         int base = 10);
         int Toi(const wchar_t * str,      int base = 10);

         long Tol(const std::string & str,  int base = 10);
         long Tol(const std::wstring & str, int base = 10);
         long Tol(const char * str,         int base = 10);
         long Tol(const wchar_t * str,      int base = 10);

         template<class CharType>
         bool Toa(unsigned long value, CharType * buffer, size_t buf_len, int base = 10);

         template<class CharType>
         bool Toa(long value, CharType * buffer, size_t buf_len, int base = 10);

         template<class CharType>
         bool Toa(unsigned int value, CharType * buffer, size_t buf_len, int base = 10);

         template<class CharType>
         bool Toa(int value, CharType * buffer, size_t buf_len, int base = 10);

         const wchar_t * Toa(unsigned int value,  int base = 10);
         const wchar_t * Toa(unsigned long value, int base = 10);
         const wchar_t * Toa(int value,  int base = 10);
         const wchar_t * Toa(long value, int base = 10);

         void Toa(int  value, std::string & res,  int base = 10, bool clear = true);
         void Toa(long value, std::string & res,  int base = 10, bool clear = true);
         void Toa(int  value, std::wstring & res, int base = 10, bool clear = true);
         void Toa(long value, std::wstring & res, int base = 10, bool clear = true);

added:   HtmlTextStream class (files htmltextstream.cpp htmltextstream.h in templates)
         this is a special stream for automatically escaping html tags
	     



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@682 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-11-25 01:34:46 +00:00
518281e101 fixed: when signal comes winix properly exits
fixed:   when winix exits the session data were not properly destroyed (memory leak)
         we should set request.session pointer to each session when deleting sessions
         from session_container
         the session data were not properly destroyed when winix checked for 
         outdated sessions (and when it was removing them)
fixed:   performance (memcpy used too often)
         in some places there were reserve method used (on std::wstring/std::string objects)
         especially in AssignString() method and TextStream<> object
         if we add a new string we should check the new size
         and only call reserve() if the new size will be greater than existing one
         (plus some constant)
changed: fcgi objects moved to App class (from Request)
         now we use thread safe methods (e.g. FCGX_Accept_r)
added:   log_plugin_call option to the config
         default: false
         when true winix log when a plugin function is called
added:   winix parameter 'nostat' for not calculating statistics
         (useful when making performance tests)


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@680 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-11-23 21:52:25 +00:00
515d4bab0d added ezc functions: winix_false, winix_true
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@679 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-11-22 01:12:46 +00:00
8e72a820dd added support for UTF-8
now the UTF-8 is a default charset


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@677 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-11-21 00:19:17 +00:00
f1f0fa34cb fixed: didn't compile
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@676 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-11-04 17:13:13 +00:00
5010ef93e8 added temporary debug info to Notify::ItemChanged() method
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@674 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-11-04 17:05:59 +00:00
e6679a3192 added a new winix function "vim" - an editor based on the WYMeditor
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@673 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-11-04 16:46:19 +00:00
7cf8d5d2d3 added: to htmlfilter: param tag has not an ending tag
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@672 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-10-25 18:00:23 +00:00
14198eca41 fixed: some log problems
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@671 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-10-24 19:31:43 +00:00
c6473f20dc now winix can demonize itself
parameter in the config: demonize (default: true)
 


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@669 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-10-24 19:26:54 +00:00
9c34cb5862 winix can drop privileges now (if started as the root)
added parameters to the config:
 user (string)
 group (string)
 additional_groups (bool)



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@668 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-10-24 17:49:38 +00:00
149fd1629f rm function can remove tickets now
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@667 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-10-23 23:51:44 +00:00
c48241f78a fixed: there were mktime() used on some dirs Items
so sometimes the time of the dir was changed

now for converting tm into time_t use:
time_t Time(const tm & par);
time_t Time(const tm * par);
tm     Time(time_t par);
from core/misc.h

now winix internally use GMT time
only when printing it is converted to local user time
temporarily all users use the same local time (config: time_zone_offset)
(only logs are genereted with local system time)

added to system:
time_t LocalTime(time_t gmt_time);
tm     LocalTime(const tm * ptm);
tm     LocalTime(const tm & ptm);
they convert GMT time to local user time




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@666 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-10-23 23:12:47 +00:00
a1bee81a5b added 'stat' winix function
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@665 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-10-23 14:54:44 +00:00
1b053c03ba added: now plugin ticket uses a new horizontal table (plugins.ticket)
columns: dir_id, param, value
we are able to build complicated tickets 



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@664 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-10-19 00:31:20 +00:00
33057acd62 added ticket parser: plugins/ticket/ticketparser.h plugins/ticket/ticketparser.cpp
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@663 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-10-11 20:42:49 +00:00
07511a2eb0 fixed: DbBase::ConvertTime(tm) should not have been used in this way as it was
(it uses a static buffer)
       now DbTextStream can get tm struct so you don't have to use ConvertTime 


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@662 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-10-09 20:27:45 +00:00
69c634d53f added to core/misc:
bool EqualNoCase(const std::string & str1, const std::string & str2)


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@660 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-10-01 23:20:03 +00:00
7bc17a9202 fixed: ticket sets a default function only for directories
fixed: reading a new url and subject in Functions::ReadItem()
added: tickets are sorted now (by date)



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@659 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-09-30 20:58:20 +00:00
d94a08b991 moved: plugins/ticket/ticket.cpp -> plugins/ticket/templates.cpp
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@658 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-09-29 22:41:34 +00:00
a8b8c1feec tickets has been moved to a new plugin 'ticket'
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@657 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-09-29 21:24:34 +00:00
a589e5a090 added: TextStream a class similar to std::ostringstream
but with a Clear() method
       the dynamic allocated buffer can be easily reused
added: DbTextStream a special version of a stream
       used to create a database string query
       everything is escaped by default
added: DbBase a base class with some basic methods for communicating
       with the database
added: DbConn a class for managing connection to the database
changed: some refactoring in Db class       



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@655 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-09-18 00:51:12 +00:00
8b1db3304f creating winix/db directory (for the database class)
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@654 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-09-16 10:20:20 +00:00
23aedd68b0 changed: mount points
mount type and mount fs are of type 'int' now
they can be added by plugins


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@652 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-09-12 23:33:27 +00:00
f48f08a98b changed: notification's template
added: notifications in tickets


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@650 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-09-07 23:54:01 +00:00
81dd88d25a fixed: there was missing html/fun_editticket.html template
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@649 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-09-05 18:58:24 +00:00
c92081d6e1 added: to stats plugin: microsoft bing searcher
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@648 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-08-28 21:19:30 +00:00
d6e80f5a23 fixed: plugins path
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@647 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-08-17 23:48:42 +00:00
37cf71234c changed makefile
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@645 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-08-17 23:33:27 +00:00
3b655f39e1 added: plugins_dir to config
small changes in makefiles


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@643 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-08-17 22:32:47 +00:00
eec0ddf466 added: method ConfParser::UseEscapeChar(bool escape)
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@642 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-08-16 14:15:37 +00:00
ca4e53bb0f html code in editors (emacs, ckeditor...) is filtered now for normal users
(root is allowed to use any html code)


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@641 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-08-14 17:56:07 +00:00
d9f2e91806 removed some debug logs from emacs
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@640 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-08-14 17:07:13 +00:00
7bfed62526 emacs didn't correctly report errors from db
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@639 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-08-14 16:55:16 +00:00
b63ac98f40 now winix waites for the database to be ready (when the operating system starts)
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@638 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-08-14 16:23:18 +00:00
1e7d297c0e small changes in template winix function
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@637 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-08-14 14:45:25 +00:00
f3cd3b88b9 some improvement in templates
(now we have O(1) time for selecting the right html template)
added: winix function: template
for selecting a template for an item (file or dir)



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@636 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-08-13 20:04:57 +00:00
9a199cd834 part II of rewriting
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@635 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-08-12 19:10:12 +00:00
c3fac2e83f changed method: void PostMultiParser::ReadContentToFileLoop()
previous version was not clean


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@634 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-08-11 15:47:44 +00:00
c7f6d2727c fixed: PostMultiParser incorrectly logged the size of input items (those which were not files)
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@633 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-08-11 10:00:23 +00:00
9901c63ede removed some thread and ticket information from request
they are in FunThread and FunTicket classes now
added funtion FunUptime (I forgot about it)



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@631 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-08-10 20:43:38 +00:00
76897b8a83 I have forgotten to create classes: Ckeditor and Tinymce (in functions)
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@630 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-08-10 17:05:19 +00:00
217cf1420b the first part of reimplementing has been done
now we have app object and singletons are only: log logn plugin and app



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@628 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-08-10 16:12:50 +00:00
6897192364 added: [dir_last_url_is] to templates
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@626 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-08-02 18:36:17 +00:00
031ace3fe5 changed: the way how plugins work
all your plugin functions can have signature either:
void my_function(PluginInfo & info); or
void my_function();
only the main Init should have:
extern "C" void Init(PluginFunction & info);

added: directory 'plugins' for plugins
added: 'stats' plugin
		  


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@624 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-07-27 20:41:56 +00:00
e4683b9a05 fixed: in htmlfilter: <area> should be treated as single tag
changed: ConfParser is abble to recognize lists


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@623 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-07-21 17:24:16 +00:00
93da32cfb3 updated to the new version of ezc
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@621 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-07-19 23:07:34 +00:00
62a0e52092 added: progress bar (image) to tickets table
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@620 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-07-05 17:22:30 +00:00
262ba10443 small refactoring
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@619 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-07-05 15:21:06 +00:00
50cb88c5ed added: parameters consist of a name and a value now
sample: /dir/dir2/function/paramname:paramvalue
removed: TemplatesMisc namespace



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@618 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-07-04 20:27:14 +00:00
76e32703ac fixed: a mount parameter html_template() was not properly read when mountpoints were reloaded
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@617 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-07-01 15:40:18 +00:00
d9f5fbaf04 added: "edit" button on threads
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@616 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-06-30 19:56:32 +00:00
16bb238518 added: bbcode
files: core/bbcodeparser.h core/bbcodeparser.cpp


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@615 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-06-30 18:42:50 +00:00
759135fd7d struct Item has modification_user_id (long) now
this is the id of a user who has modified the item recently
this is only for information, persmissions don't use it


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@614 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-06-22 21:09:37 +00:00
56075857f2 debug
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@613 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-06-22 13:05:49 +00:00
8d3c7500d8 debugging info
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@612 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-06-22 13:01:56 +00:00
1e3f5e8695 added: mount option: html_template(file.html)
files: indexpatterns.h indexpatterns.cpp
removed: templates/index_root.html
        its content was moved to index.html


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@611 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-06-21 23:53:19 +00:00
08f5865c72 html templates
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@610 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-06-21 13:10:53 +00:00
ff3c141138 added: a new editor: tinymce (function tinymce)
added: html filter can check orphans: "i", "a", "o" ... in a text


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@607 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-06-20 22:47:24 +00:00
fe31e0e849 added: cp function for directories
added: emacs/mkdir uses group_id of the parent directory when creating new items
added: parameter 'dirls' to ls function


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@606 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-06-05 19:44:49 +00:00
2a26968c6c added: function cp (only for files)
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@605 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-06-03 17:38:18 +00:00
fe8774953a changed html templates
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@604 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-05-31 20:42:13 +00:00
4a7f036561 updated to new version of Ezc
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@602 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-05-30 21:07:46 +00:00
612f260938 added function: uname
added function: subject - for changing a subject


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@600 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-05-20 18:28:19 +00:00
2ad666d221 added: sessions data for plugins (plugindata.h plugindata.cpp)
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@598 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-05-04 21:58:22 +00:00
aff4cc516e added: 'rm' function can remove auth content now
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@597 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-03-15 17:09:45 +00:00
6fbcffe63b added: to the Item: auth_path - a path to a static file (if auth is different from auth_none)
added: function 'mv' (move)



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@596 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-03-15 01:47:26 +00:00
ebd868fa33 removed: Done class (core/done.h, core/done.cpp)
removed: from Session: done, done_status, timers



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@594 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-02-28 21:33:06 +00:00
71a63cc70e added: function adduser
changed: errors (removed enum, there are macros now)
added: error messages to locales (winix_err_NN)
removed: templates: err_abuse.html err_others.html


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@593 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-02-28 00:08:10 +00:00
3702efc5be added: parameter 'l' to 'ls' function
added: Db::ItemQuery struct for querying items
changed: some refactoring (renamed some config variables)




git-svn-id: svn://ttmath.org/publicrep/winix/trunk@589 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-02-22 22:52:09 +00:00
16e51cd4e5 added: to mount points: file systems
we have two file systems now:
       - simplefs - the files stored on the hard drive have the same structure as in the database (dir1/dir2/file)
       - hashfs - files are stored in special directories
extented: the mountparser can read file system 
added: function download
       this is a default function for items which have static content
  


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@588 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-02-18 23:30:22 +00:00
87747fab06 added: functions: chmod, chown
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@587 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-02-16 18:34:41 +00:00
4fe3d4339f added: parameter 'r' to priv function
all directories and files can be changed


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@586 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-02-16 00:37:00 +00:00
a276fb6b79 modified templates
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@585 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-02-15 18:22:16 +00:00
fa8d8f9ea0 fixed: Config::Text() returned a reference to a local variable (std::string)
added: 'static' directory with *.css and images
       we have a default layout
moved: locale from data to templates       
       notification templates have its own locale object
added: reload function reloades locale now too
added: 'nice' form of item_info in templates



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@582 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-02-15 00:31:14 +00:00
c58031cbf4 added static dir
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@581 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-02-14 14:28:43 +00:00
4aae12fc63 I forgot to commit loadavg.h and loadavg.cpp
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@579 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-02-13 20:14:44 +00:00
256a8fb5c5 added: calculation of load averages and requests per second
(uptime function shows it)


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@577 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-02-13 20:12:15 +00:00
3c5a7cd664 changed: upload function
select file type by the extension
         param: multi
fixed:   uptime function
         it showed incorrect uptime time (minuts were badly calculated)


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@575 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-02-12 23:16:13 +00:00
796985472a added to config: parameter static_auth_dir_tmp
with a path to directory for tmp files (for upload functino)



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@572 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-02-12 17:05:32 +00:00
7e0014865e added: loggin to upload.cpp
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@571 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-02-12 16:39:09 +00:00
cd74d1887a fixed: sprintf %d in uptime function
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@569 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-02-11 21:04:53 +00:00
adf36e71ce added: functions: ckeditor, uptime
added: for function: login - a html pattern for GET request


git-svn-id: svn://ttmath.org/publicrep/winix/trunk@567 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-02-11 20:56:52 +00:00
fc3c303d30 added: to templates: item_url_is and dir_last_url
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@566 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-02-08 20:02:16 +00:00
0e50977779 added: 'rm' function can work with tickets
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@565 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-02-06 14:08:44 +00:00
ed9feaf542 changed: log is saved after some requests (config: log_request value) (performance)
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@563 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-01-28 21:09:48 +00:00
09d427b4ba changed: rename cmslu to winix
changed: html templates are a part of winix now
         and the user can provide special html templates for its site
added:   locales
added:   html templates are using HtmlFilter now (locales)
changed: now we have html templates for each language



git-svn-id: svn://ttmath.org/publicrep/winix/trunk@560 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-01-28 15:39:01 +00:00
5dac8af300 renaming cmslu to winix
git-svn-id: svn://ttmath.org/publicrep/winix/trunk@559 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-01-26 19:07:40 +00:00
1493a6180a moving html templates to cmslu
git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@558 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-01-26 19:02:21 +00:00
848ddcebd7 fixed: not logged users cannot edit a ticket
git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@557 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-01-25 07:27:18 +00:00
71763d340e fixed: not logged users are not allowed to remove anything
(temporarily - we're waiting for the sticky bit)


git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@556 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-01-25 07:04:34 +00:00
89daf6489d added: issues ticket system
added functions: ticket, createticket, editticket
         (there is no 'rm' function working for tickets yet)
changed: mount parser and mount points
         now we have more parameters (arguments in parameters)
some refactoring in functions 'emacs' and 'mkdir'



git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@554 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-01-25 04:52:17 +00:00
356e93914b fixed: there was a wrong template used for 404 header
git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@553 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-01-11 16:41:23 +00:00
5523d0c27a fixed: access to content type should not be checked when generating a page
git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@552 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-01-11 15:09:31 +00:00
590a94523e fixed: content type was always 'formatted text' (in emacs when creating a new item)
git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@551 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-01-11 14:59:19 +00:00
3c95b84633 added: item content type: raw
git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@549 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-01-11 14:47:52 +00:00
59943c87cd added: default values for variables read from the config file
git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@547 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-01-07 14:45:00 +00:00
3f9a46b1f7 added: static_auth_dir to config
git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@545 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-01-06 19:36:29 +00:00
81faca041a added: parser for multipart forms, files: postmultiparser.h postmultiparser.cpp
added: function: upload




git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@543 e52654a7-88a9-db11-a3e9-0013d4bc506e
2010-01-06 19:17:53 +00:00
60fccea703 fixed: dots in url-es (now only one dot is available in the whole name and it cannot be only one dot ".")
added:   cmslu can act as an authorizer (fast cgi authorize role)
added:   Item::static_auth we can have additional static content on the file system
         this content is authorized through cmslu (fastcgi authorizer mode)
changed: some changes in config
changed: the way how the www server is using cmslu
         added new virtuals: static static_auth
changed: cmslu returns correct http headers (200, 404, 403)
changed: in cookie parser: we get the last cookie (if the server has more than one cookie with the same name)



git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@540 e52654a7-88a9-db11-a3e9-0013d4bc506e
2009-12-30 20:46:12 +00:00
118bf1fc65 added: exception for the Konqueror browser
it has a problem with deflate compression


git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@539 e52654a7-88a9-db11-a3e9-0013d4bc506e
2009-12-19 19:46:15 +00:00
ce7ae3edd4 changed: notification times
git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@536 e52654a7-88a9-db11-a3e9-0013d4bc506e
2009-12-09 00:52:00 +00:00
717eb526fb * added: class HTMLFilter
files: htmlfilter.h htmlfilter.cpp
         this is an html filter used to make the html output looking better
         this is a very lightweight filter
         (without using any dynamic memory - some memory is allocated only at the beginning - in ctors)
         this filter has O(n) complexity over the whole html string
* added: antyspamming method
         if the POST request is sent too fast after the GET
         it is treated as a spam
         only for no logged users and only in 'emacs' and 'createthread' functions
       


git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@534 e52654a7-88a9-db11-a3e9-0013d4bc506e
2009-12-09 00:42:40 +00:00
9241fddb1e small changes in Makefile
now the binaries are in local 'bin' directory
(use make install)


git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@532 e52654a7-88a9-db11-a3e9-0013d4bc506e
2009-12-04 05:03:44 +00:00
2dff0bed72 changed: SessionParser::ReadLong() can read negative values
git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@531 e52654a7-88a9-db11-a3e9-0013d4bc506e
2009-11-21 00:08:08 +00:00
4827c116f0 added: 'remember me' flag when logging
added: the session file
       sessions can still be available between starting and stopping the cmslu system


git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@529 e52654a7-88a9-db11-a3e9-0013d4bc506e
2009-11-20 23:09:52 +00:00
848afac803 removed: hidden variable 'old_url' in emacs template
git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@527 e52654a7-88a9-db11-a3e9-0013d4bc506e
2009-11-18 01:58:38 +00:00
13b0204427 I have forgotten to add templates/rebus.cpp to the repository
git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@525 e52654a7-88a9-db11-a3e9-0013d4bc506e
2009-11-17 01:07:29 +00:00
dc5f002de3 refactoring
git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@523 e52654a7-88a9-db11-a3e9-0013d4bc506e
2009-11-17 01:04:01 +00:00
2ca44ec361 added: Rebus
(when no logged user wants to send a message then he is asked a question)


git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@521 e52654a7-88a9-db11-a3e9-0013d4bc506e
2009-11-16 23:36:38 +00:00
c62d48160a fixed: the core didn't test for special folder when system was running
(now mkdir addes correctly special folders)
added: function 'reload'
       param: 'templates' - reloading templates


git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@519 e52654a7-88a9-db11-a3e9-0013d4bc506e
2009-11-16 17:43:23 +00:00
9129f1b82a added: mount points are read from db: /etc/fstab
changed: mount points parser allows empty lines (with some white characters)


git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@518 e52654a7-88a9-db11-a3e9-0013d4bc506e
2009-11-15 23:55:11 +00:00
378cfc0c3d added: plugin mechanism
files: core/plugin.h core/plugin.cpp core/pluginmsg.h
added: directory 'main' with main.cpp (moved from 'core' directory)
changed: the way of building
       nearly everything is in cmslu.so
       only main() is in cmslu and is dynamically linked with cmslu.so



git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@516 e52654a7-88a9-db11-a3e9-0013d4bc506e
2009-11-13 20:40:11 +00:00
7db71d43e0 added: acceptbaseparser.h acceptbaseparser.cpp
class AcceptBaseParser for parsing http accept* headers
added: acceptencodingparser.h
       class AcceptEncodingParser for parsing HTTP_ACCEPT_ENCODING header
added: compresion only when HTTP_ACCEPT_ENCODING has 'deflate'
       and the browser is not the Internet Explorer


git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@515 e52654a7-88a9-db11-a3e9-0013d4bc506e
2009-10-08 17:59:10 +00:00
85b678a8fb added: notifications to users' emails
(core/notify.h core/notify.cpp)
       templatesnotify directory
       all notifications are managed by a second thread


git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@512 e52654a7-88a9-db11-a3e9-0013d4bc506e
2009-09-30 22:31:20 +00:00
9902ce2b78 added: support for output compression
git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@511 e52654a7-88a9-db11-a3e9-0013d4bc506e
2009-09-21 23:05:05 +00:00
394c7b22a2 changed: mount points
git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@508 e52654a7-88a9-db11-a3e9-0013d4bc506e
2009-06-07 22:17:07 +00:00
f99c993d96 added: column 'guest_name' to 'item' table
used when user_id is -1
added: mount parameters: thread_with_info, thread_with_header
added: function rm can remove threads



git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@506 e52654a7-88a9-db11-a3e9-0013d4bc506e
2009-06-07 02:40:27 +00:00
1eb42446f8 added: forum
added: mount params can have arguments (in parentheses)
added: mount params: withheader, withinfo, restrictcreatethread, only_root_can_remove,
       can_use_emacs_on(level), can_use_mkdir_on(level), 
added: table Item has 'subject' column now
removed: column 'subject' from table Content




git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@505 e52654a7-88a9-db11-a3e9-0013d4bc506e
2009-06-05 20:29:06 +00:00
3d001e7458 added: macro APPPREPARE
void AppFunction(int code);



git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@503 e52654a7-88a9-db11-a3e9-0013d4bc506e
2009-05-21 19:27:16 +00:00
2dd3fc7df8 changed: the way of building
core.a content.a templates.a confparser.a have gone away
	 there is only: cmslu.a now (in the global directory 'cmslu')
changed: the way of building
         in Makefile(s) we dont longer use explicitly a variable 'o = file1.o file2.o...'
	 it was put into Makefile.o.dep and is generated automatically 
         when 'make depend' is invoked
changed: some #include "..." directives were put from *.h to *.cpp files
         fewer dependences


git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@501 e52654a7-88a9-db11-a3e9-0013d4bc506e
2009-04-21 20:50:55 +00:00
f46677dfc0 added: mount points have parameters now
added: to the database: table 'thread'



git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@499 e52654a7-88a9-db11-a3e9-0013d4bc506e
2009-04-20 23:49:28 +00:00
e94ccc86f8 fixed: a small problem in mountparser (it coused core dumped when there was a wrong mount point supplied)
fixed: 'default' funtion can take a directory now (there was an error early)


git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@497 e52654a7-88a9-db11-a3e9-0013d4bc506e
2009-04-20 21:10:31 +00:00
e778903dab added: put info about logging out a user (to 'last' table) (when a session expires)
git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@496 e52654a7-88a9-db11-a3e9-0013d4bc506e
2009-04-20 20:22:35 +00:00
a1ea298a43 added: mount points
(reading /etc/fstab from db not working yet)
       core/mount.h
       core/mountparser.h
       core/mountparser.cpp
       core/mounts.h
       core/mounts.cpp
       content/thread.cpp
       content/createthread.cpp
       templates/thread.cpp       



git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@495 e52654a7-88a9-db11-a3e9-0013d4bc506e
2009-04-19 22:13:21 +00:00
7a4a8e0fe2 added: container LastContainer (lastcontainer.h lastcontainer.cpp)
it consists of last logged users
added: function 'last'


git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@492 e52654a7-88a9-db11-a3e9-0013d4bc506e
2009-04-16 01:59:42 +00:00
bbaefd0f77 added: date_creation and date_modification to items
changed: function 'run' is using a template: fun_run.html
         there is: [item_run] called from this template


git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@489 e52654a7-88a9-db11-a3e9-0013d4bc506e
2009-03-22 23:54:15 +00:00
951d0e8653 changed: DirContainer - uses std::list instead of std::vector as the main container
we do not have to rebuild indexes after deleting some items
added:   DirContainer::DelById(long id)
changed: Dirs::CheckRootDir() addes the root dir if there is no one
added:   Dirs::DeleteDir(long id) - deletes specified directory (and its contents)
         (from the cache and the database)
added:   Db::DelDirById(long id) - deletes a dir from the database 
         and its first children
added:   standard function rm can delete directories


git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@487 e52654a7-88a9-db11-a3e9-0013d4bc506e
2009-02-06 13:12:03 +00:00
7d73d048c8 added: SessionContainer special container used by SessionManager
sessions are indexed by id and time (last used time)
changed: old sessions are deleted
       parameter: session_max_iddle in the config file
added: function 'who'


git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@483 e52654a7-88a9-db11-a3e9-0013d4bc506e
2009-01-31 06:53:36 +00:00
a48766871d fixed: the way AppDb works (pg_conn and Connect method)
git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@482 e52654a7-88a9-db11-a3e9-0013d4bc506e
2009-01-27 18:43:44 +00:00
406cb4a619 changed: not logging (headers and body)
git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@480 e52654a7-88a9-db11-a3e9-0013d4bc506e
2009-01-26 21:21:07 +00:00
9418cc7a69 default.item has to be default.cpp
git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@479 e52654a7-88a9-db11-a3e9-0013d4bc506e
2009-01-26 21:08:42 +00:00
20f6fbcf84 changed: the way of building the cmslu
main Makefile is in an application directory
         in cmslu/ there are only libraries:
         core.a content.a confparser.a templates.a
added:   macros APPTEMPLATES APPFUNCTIONS
         defined in the application's Makefile
added:   PatternCacher
added:   cmslu function 'run'
         files which have exec permissions
         can be run (run is a default function)
         after read from the database the content is parsed
         into Ezc::Pattern object, this object is then cached
         in PatternCacher
added:   FunctionCodeParser - will be used to parse the code
         from standard functions (ls/cat/...)


git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@475 e52654a7-88a9-db11-a3e9-0013d4bc506e
2009-01-26 20:49:28 +00:00
327f18525c changed: cmslu building
Makefile from cmslu/ builds only: confparser.a content.a core.a templates.a
         the proper *.fcgi file is created from an application
changed: all cmslu functions have english names (ls, emacs, etc)
fixed:   function: login/logout are placed where there are permissions


git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@474 e52654a7-88a9-db11-a3e9-0013d4bc506e
2009-01-14 20:11:12 +00:00
8a0ea59c77 added: function: default
changes the default item in a directory


git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@473 e52654a7-88a9-db11-a3e9-0013d4bc506e
2008-12-31 18:28:12 +00:00
f6ad846927 I forgot to commit content/mkdir.cpp
git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@472 e52654a7-88a9-db11-a3e9-0013d4bc506e
2008-12-31 13:40:23 +00:00
114b5724f8 added: function: mkdir
git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@471 e52654a7-88a9-db11-a3e9-0013d4bc506e
2008-12-31 13:36:46 +00:00
3e328932fc added: created directory 'content' which has Content:: files
added:   created directory 'templates' which has Templates:: and TemplatesFunctions:: files
changed: content.cpp split into many files (directory 'content')
changed: templates.cpp split into many files (directory 'templates')
added:   full permissions
changed: building of the program (GNU make is used now)
         Makefile and Makefile.dep added into directories
added:   a parser 'FunctionParser'
         is used to parse the GET string
         it recognizes directories, items, functions, functions parameters
added:   other classes: Function, Functions 
added:   function: ls, privileges
changed: function 'id' to 'node'
changed: version: to 0.2.0
added/changed: a lot of work have been done


git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@469 e52654a7-88a9-db11-a3e9-0013d4bc506e
2008-12-30 01:05:03 +00:00
fac60a197b changed: there is one dir called root (has parent_id -1)
(we have an owner, group, privileges etc of the root dir)
         the root.id of course is not -1 


git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@468 e52654a7-88a9-db11-a3e9-0013d4bc506e
2008-12-22 16:03:03 +00:00
55cd813141 added: privileges (user, groups, permissions)
(not finished yet)
       classes: User, Group, Users, Groups, UGContainer
changed: Dir class into Dirs


git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@467 e52654a7-88a9-db11-a3e9-0013d4bc506e
2008-12-21 21:17:09 +00:00
86f28faf8d changed: db: table item: url_subject into url
changed: item.url_subject into item.url
changed: a new table: content
         with: id, subject, content, content_type
         (those from the item table)
         it helps to create hard links


git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@466 e52654a7-88a9-db11-a3e9-0013d4bc506e
2008-12-14 05:28:28 +00:00
023faa66fc added: config: base_url_redirect
when true the server checks whether HTTP_HOST environment variable
       is the same as base_url from the config (of course without the 'http://' part
       and the last slash) - if it's not the same then the server
       redirects you into a new location base_url+REQUEST_URI
changed: variables env_* from Request are never null (after Request::Read())
       if the server didn't set such a variable it will be pointing into an empty string "\0"


git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@465 e52654a7-88a9-db11-a3e9-0013d4bc506e
2008-12-12 03:11:29 +00:00
3462cdf827 I forgot to add config.h and config.cpp into the repository
git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@464 e52654a7-88a9-db11-a3e9-0013d4bc506e
2008-12-11 02:48:25 +00:00
8aab988752 added: program reads its configuration from a config file
added: confparser directory and confparser.h and confparser.cpp
       class ConfParser used to parse a config file
       this is a generic parser, can be used by another project
added: config.h, config.cpp
       class Config used for assigning values from 
       a config file into the data object
added: function for signals: SIGINT, SIGHUP
       after receiving SIGHUP the program will read
       its config file again


git-svn-id: svn://ttmath.org/publicrep/cmslu/trunk@463 e52654a7-88a9-db11-a3e9-0013d4bc506e
2008-12-11 02:46:16 +00:00
526 changed files with 101890 additions and 4944 deletions

6
.gitignore vendored Normal file
View File

@@ -0,0 +1,6 @@
.cproject
.project
.settings/
*.o
*.so
winixd/winix

View File

@@ -1,46 +0,0 @@
CC = g++
o = templates.o log.o requestcontroller.o main.o misc.o db.o session.o request.o content.o sessionmanager.o httpsimpleparser.o data.o dir.o error.o done.o dircontainer.o ezc.o
CFLAGS = -Wall -pedantic -g -I/usr/local/include -L/usr/local/lib
name = cmslu.fcgi
all: $(name) $(mod_cms)
$(name): $(o)
g++ -o $(name) $(CFLAGS) $(o) -lfcgi -lpq
.SUFFIXES: .cpp .o
.cpp.o:
$(CC) -c $(CFLAGS) $<
templates.o: core/templates.cpp core/templates.h core/../../ezc/src/ezc.h core/data.h core/misc.h core/log.h core/item.h core/error.h core/dir.h core/db.h core/dircontainer.h core/request.h core/requesttypes.h core/session.h core/done.h core/getparser.h core/httpsimpleparser.h core/postparser.h core/cookieparser.h
log.o: core/log.cpp core/log.h
requestcontroller.o: core/requestcontroller.cpp core/requestcontroller.h core/data.h core/misc.h core/log.h core/item.h core/error.h core/dir.h core/db.h core/dircontainer.h core/request.h core/requesttypes.h core/session.h core/done.h core/getparser.h core/httpsimpleparser.h core/postparser.h core/cookieparser.h core/content.h core/templates.h core/../../ezc/src/ezc.h core/sessionmanager.h
main.o: core/main.cpp core/requestcontroller.h core/data.h core/misc.h core/log.h core/item.h core/error.h core/dir.h core/db.h core/dircontainer.h core/request.h core/requesttypes.h core/session.h core/done.h core/getparser.h core/httpsimpleparser.h core/postparser.h core/cookieparser.h core/content.h core/templates.h core/../../ezc/src/ezc.h core/sessionmanager.h
misc.o: core/misc.cpp core/misc.h core/log.h core/item.h
db.o: core/db.cpp core/db.h core/log.h core/item.h core/misc.h core/error.h core/dircontainer.h
session.o: core/session.cpp core/session.h core/requesttypes.h core/error.h core/log.h core/item.h core/done.h
request.o: core/request.cpp core/request.h core/requesttypes.h core/log.h core/session.h core/error.h core/item.h core/done.h core/getparser.h core/httpsimpleparser.h core/postparser.h core/cookieparser.h
content.o: core/content.cpp core/content.h core/templates.h core/../../ezc/src/ezc.h core/data.h core/misc.h core/log.h core/item.h core/error.h core/dir.h core/db.h core/dircontainer.h core/request.h core/requesttypes.h core/session.h core/done.h core/getparser.h core/httpsimpleparser.h core/postparser.h core/cookieparser.h
sessionmanager.o: core/sessionmanager.cpp core/sessionmanager.h core/request.h core/requesttypes.h core/log.h core/session.h core/error.h core/item.h core/done.h core/getparser.h core/httpsimpleparser.h core/postparser.h core/cookieparser.h core/data.h core/misc.h core/dir.h core/db.h core/dircontainer.h
httpsimpleparser.o: core/httpsimpleparser.cpp core/httpsimpleparser.h
data.o: core/data.cpp core/data.h core/misc.h core/log.h core/item.h core/error.h core/dir.h core/db.h core/dircontainer.h
dir.o: core/dir.cpp core/dir.h core/item.h core/error.h core/log.h core/db.h core/misc.h core/dircontainer.h
error.o: core/error.cpp core/error.h core/log.h
done.o: core/done.cpp core/done.h
dircontainer.o: core/dircontainer.cpp core/dircontainer.h core/item.h core/log.h
ezc.o: ../ezc/src/ezc.cpp ../ezc/src/ezc.h
clean:
rm -f *.o
rm -f $(name)

View File

@@ -1,477 +0,0 @@
/*
* This file is a part of CMSLU -- Content Management System like Unix
* and is not publicly distributed
*
* Copyright (c) 2008, Tomasz Sowa
* All rights reserved.
*
*/
#include "content.h"
bool Content::Init()
{
templates.Read();
return true;
}
void Content::AddItem()
{
if( !request.session->is_logged )
return;
try
{
request.session->done = Done::added_item;
// request.item_table.resize(1);
// Item & item = request.item_table[0];
request.item.subject = request.PostVar("subject");
request.item.content = request.PostVar("content");
request.item.parent_id = data.dir.GetDirId( request.PostVar("directory") );
request.item.type = Item::file;
PrepareUrlSubject(request.item);
request.session->done_status = db.AddItem(request.item);
request.session->done_timer = 1;
// if( request.session->done_status != Request::added_item )
//request.item_table.resize(1);
//request.item_table[0] = request.item;
}
catch(const Error & e)
{
request.session->done_status = e;
}
}
void Content::EditItem()
{
if( !request.session->is_logged )
return;
try
{
request.session->done = Done::edited_item;
// request.item_table.resize(1);
// Item & item = request.item_table[0];
request.item.subject = request.PostVar("subject");
request.item.content = request.PostVar("content");
request.item.id = atol( request.PostVar("id").c_str() );
bool with_subject = false;
if( request.PostVar("old_subject") != request.item.subject )
with_subject = true;
request.item.parent_id = data.dir.GetDirId( request.PostVar("directory") );
request.item.type = Item::file;
PrepareUrlSubject(request.item);
request.session->done_status = db.EditItem(request.item, with_subject);
request.session->done_timer = 1;
}
catch(const Error & e)
{
request.session->done_status = e;
}
}
void Content::LogUser()
{
try
{
std::string & login = request.PostVar("login");
std::string & pass = request.PostVar("password");
long user_id;
if( db.CheckUser(login, pass, user_id) )
{
request.session->is_logged = true;
request.session->user_id = user_id;
request.session->user = login;
log << log2 << "User " << login << " (id: " << user_id << ") logged" << logend;
}
}
catch(const Error &)
{
}
}
void Content::MakeDirectoryStructure()
{
GetTable::size_type get_table_len = request.get_table.size();
long parent = -1;
for( get_index = 0 ; get_index < get_table_len ; ++get_index)
{
Item * pdir;
if( !data.dir.GetDir(request.get_table[get_index], parent, &pdir) )
break;
parent = pdir->id;
request.cur_dir_table.push_back( *pdir );
}
// parent - last directory (or -1 if none)
request.dir = parent;
data.dir.GetDirChilds(parent, request.dir_table);
}
Request::Result Content::StandardFunction(std::string & name)
{
Request::Result res = Request::err404;
// language polish
// in the future there'll be something here
// names of functions should not begin with an underscore '_'
if( name == "dodaj" )
res = Request::add_item;
else
if( name == "edytuj" )
res = Request::edit_item;
else
if( name == "id" )
res = Request::show_item_by_id;
else
if( name == "usun" )
res = Request::del_item;
else
if( name == "potwierdz" )
res = Request::confirm;
else
if( name == "wyloguj" )
res = Request::logout;
return res;
}
void Content::PrepareUrlSubject(Item & item)
{
SetUrlSubjectFromSubject(item);
if( StandardFunction(item.url_subject) != Request::err404 )
{
// names of functions should not begin with an underscore '_'
// and we can simply add one '_' at the beginning
// and the name will be unique
item.url_subject.insert(item.url_subject.begin(), '_');
}
}
bool Content::MakeGetCheckDir()
{
if( get_index == request.get_table.size() )
{
// request was for a directory
db.GetItems(request.item_table, item);
// !! temporarily
long default_id = -1;
if( request.cur_dir_table.empty() )
{
default_id = data.dir.root.default_item;
}
else
{
default_id = request.cur_dir_table.back().default_item;
}
if( default_id != -1 )
{
request.result = Request::show_item;
std::vector<Item>::iterator i;
for(i = request.item_table.begin() ; i != request.item_table.end() ; ++i)
{
if( i->id == default_id )
request.item_table[0] = *i;
}
request.item_table.resize(1);
}
else
if( data.one_item_is_showed &&
request.item_table.size() == 1 &&
request.item_table[0].type == Item::file )
{
request.result = Request::show_item;
}
else
{
request.result = Request::show_dir;
}
return true;
}
return false;
}
// zrobic tak ze gdzie podajemy cala liste aby nie ladowac contentu z bazy danych do itemow
void Content::MakeGet()
{
MakeDirectoryStructure();
item.Clear();
// request.dir is set by MakeDirectoryStructure()
item.parent_id = request.dir;
if( MakeGetCheckDir() )
return;
// request was for an item or a standard function
request.result = StandardFunction( request.get_table[get_index] );
if( request.result != Request::err404 )
{
// request for a standard function
++get_index;
return;
}
if( request.get_table[get_index].empty() )
// we do not have an empty url_subject
// err404 at the end
return;
// if we want to search by url_subject then request.get_table[get_index] should not be empty
item.url_subject = request.get_table[get_index++];
db.GetItems(request.item_table, item);
if( request.item_table.empty() )
// err404 at the end
return;
if( get_index == request.get_table.size() )
{
request.result = Request::show_item;
return;
}
// there is a standard function at the end
request.result = StandardFunction( request.get_table[get_index++] );
}
void Content::MakeEditItem()
{
if( !request.item_table.empty() )
request.item = request.item_table[0];
else
{
log << log1 << "Content: request.item_table should not be empty" << logend;
request.result = Request::err404;
}
}
void Content::AppendCurDir(std::string & dir)
{
std::vector<Item>::size_type a;
for(a=0 ; a<request.cur_dir_table.size() ; ++a)
{
dir += request.cur_dir_table[a].url_subject;
dir += '/';
}
}
void Content::MakeShowItemById()
{
if( get_index == request.get_table.size() )
{
request.result = Request::err404;
}
else
{
long id = atol( request.get_table[get_index++].c_str() );
db.GetItem(request.item_table, id);
if( request.item_table.empty() )
request.result = Request::err404;
else
{
request.result = Request::redirect;
std::string path;
data.dir.MakePath(request.item_table[0].parent_id, path);
request.str = data.base_url + path + request.item_table[0].url_subject;
}
}
}
void Content::MakeDelItem()
{
if( !request.session->is_logged )
return;
if( request.item_table.empty() )
{
request.result = Request::err404;
return;
}
if( get_index == request.get_table.size() )
{
request.CopyFirstItem();
request.session->item = request.item;
if( db.DelItem( request.item.id ) )
{
request.session->done = Done::deleted_item;
request.session->done_status = Error::ok;
log << log2 << "Content: deleted item: subject: " << request.item.subject << ", id: " << request.item.id << logend;
}
else
{
request.session->done = Done::deleted_item;
request.session->done_status = Error::db_no_item;
}
request.result = Request::redirect;
request.str = data.base_url;
AppendCurDir(request.str);
request.session->done_timer = 2;
}
else
{
if( StandardFunction( request.get_table[get_index++] ) == Request::confirm )
{
request.result = Request::del_item_confirm;
request.CopyFirstItem();
}
else
request.result = Request::err404;
}
}
void Content::MakeLogout()
{
if( request.session->is_logged )
{
log << log2 << "User " << request.session->user << " (id: " << request.session->user_id << ") logged out" << logend;
request.session->is_logged = false;
request.session->user.clear();
request.session->user_id = 0;
}
request.result = Request::redirect;
std::string path;
data.dir.MakePath(request.dir, path);
request.str = data.base_url + path;
if( !request.item_table.empty() )
request.str += request.item_table[0].url_subject;
request.session->done = Done::loggedout;
request.session->done_timer = 2;
}
void Content::MakeStandardFunction()
{
if( request.result == Request::edit_item )
{
MakeEditItem();
}
else
if( request.result == Request::show_item_by_id )
{
MakeShowItemById();
}
else
if( request.result == Request::del_item )
{
MakeDelItem();
}
else
if( request.result == Request::logout )
{
MakeLogout();
}
}
void Content::MakePost()
{
if( request.IsPostVar("add_item") )
AddItem();
else
if( request.IsPostVar("edit_item") )
EditItem();
else
if( request.IsPostVar("logging") )
LogUser();
}
void Content::Make()
{
MakePost();
MakeGet();
MakeStandardFunction();
templates.Generate();
// request.PrintGetTable();
//request.PrintEnv();
// request.PrintIn();
}

View File

@@ -1,73 +0,0 @@
/*
* This file is a part of CMSLU -- Content Management System like Unix
* and is not publicly distributed
*
* Copyright (c) 2008, Tomasz Sowa
* All rights reserved.
*
*/
#ifndef headerfilecontent
#define headerfilecontent
#include <cstdlib>
#include <fcgiapp.h>
#include "templates.h"
#include "request.h"
#include "error.h"
#include "misc.h"
#include "db.h"
class Content
{
// index to request.get_table
// set after calling MakeDirectoryStructure()
// index of the last item which is not a directory (or is equal get_table.size())
GetTable::size_type get_index;
// temporarily object used for some purposes
Item item;
Templates templates;
void AddItem();
void EditItem();
void LogUser();
void MakeDirectoryStructure();
Request::Result StandardFunction(std::string & name);
void PrepareUrlSubject(Item & item);
bool MakeGetCheckDir();
void MakeEditItem();
void MakeShowItemById();
void MakeDelItem();
void MakeLogout();
void MakeStandardFunction();
void AppendCurDir(std::string & dir);
void MakePost();
void MakeGet();
public:
bool Init();
void Make();
};
#endif

View File

@@ -1,70 +0,0 @@
/*
* This file is a part of CMSLU -- Content Management System like Unix
* and is not publicly distributed
*
* Copyright (c) 2008, Tomasz Sowa
* All rights reserved.
*
*/
#ifndef headerfilecookieparser
#define headerfilecookieparser
#include <fcgiapp.h>
#include "httpsimpleparser.h"
#include "requesttypes.h"
class CookieParser : public HttpSimpleParser
{
const char * cookie_string;
CookieTable & cookie_table;
protected:
virtual int GetChar()
{
if( !cookie_string || *cookie_string == 0 )
return -1;
return (int)(unsigned char)*(cookie_string++);
}
virtual void Parameter(std::string & name, std::string & value)
{
// Cookie names are case insensitive according to section 3.1 of RFC 2965
ToLower(name);
std::pair<CookieTable::iterator, bool> res = cookie_table.insert( std::make_pair(name, value) );
log << log2 << "Cookie, name: \"" << name << "\", value: \"" << value << "\"";
if( res.second == false )
log << log2 << " (skipped)";
log << log2 << logend;
}
public:
CookieParser(const char * cookie_string_, CookieTable & cookie_table_) : cookie_string(cookie_string_), cookie_table(cookie_table_)
{
HttpSimpleParser::separator = ';';
HttpSimpleParser::value_can_be_quoted = true;
HttpSimpleParser::skip_white_chars = true;
HttpSimpleParser::recognize_special_chars = false;
}
};
#endif

View File

@@ -1,46 +0,0 @@
/*
* This file is a part of CMSLU -- Content Management System like Unix
* and is not publicly distributed
*
* Copyright (c) 2008, Tomasz Sowa
* All rights reserved.
*
*/
#include "data.h"
Data::Data()
{
// all these data will be reading from a config file
log_file = "cmslu.log";
fcgi_socket = "/var/cmslu/s1";
fcgi_socket_chmod = 0770;
fcgi_socket_user = "tomek";
fcgi_socket_group = "www";
log_level = 2;
log_stdout = true;
templates = "../httpd/templates"; // templates dir
default_index = "index.html";
http_session_id_name = "slimaczek_sid";
db_database = "tomek";
db_user = "tomek";
db_pass = "monitorekasd";
// !! add a method which will be adding a slash at the end of url-es
base_url = "http://s10.slimaczek.pl/"; // with a slash at the end
one_item_is_showed = true;
dir.root.default_item = 134;
}

View File

@@ -1,88 +0,0 @@
/*
* This file is a part of CMSLU -- Content Management System like Unix
* and is not publicly distributed
*
* Copyright (c) 2008, Tomasz Sowa
* All rights reserved.
*
*/
#ifndef headerfiledata
#define headerfiledata
#include <string>
#include <vector>
#include <map>
#include "misc.h"
#include "item.h"
#include "error.h"
#include "dir.h"
class Data
{
public:
// log file name
std::string log_file;
// 1 - minimum
// 2 - (default)
// 3 - maximum - all logs
int log_level;
// logging to stdout too
bool log_stdout;
// fast cgi: socket (unix domain)
std::string fcgi_socket;
// fast cgi: socket permissions
int fcgi_socket_chmod;
// fast cgi: owner of the socket
std::string fcgi_socket_user;
// fast cgi: group of the socket
std::string fcgi_socket_group;
std::string templates;
std::string default_index;
std::string db_database;
std::string db_user;
std::string db_pass;
std::string base_url;
std::string http_session_id_name;
Dir dir;
// if there is one item in a directory
// it will be showed
// (instead of showing directory contents)
bool one_item_is_showed;
Data();
};
extern Data data;
#endif

View File

@@ -1,668 +0,0 @@
/*
* This file is a part of CMSLU -- Content Management System like Unix
* and is not publicly distributed
*
* Copyright (c) 2008, Tomasz Sowa
* All rights reserved.
*
*/
#include "db.h"
Db::Db()
{
pg_conn = 0;
}
Db::~Db()
{
Close();
}
void Db::Init(const std::string & d, const std::string & u, const std::string & p)
{
db_database = d;
db_user = u;
db_pass = p;
Connect();
}
void Db::Connect()
{
std::ostringstream buf;
buf << "dbname=" << db_database << " user=" << db_user << " password=" << db_pass;
pg_conn = PQconnectdb(buf.str().c_str());
if( !pg_conn )
log << log1 << "Db: Fatal error during connecting" << logend;
if( PQsetClientEncoding(pg_conn, "LATIN2") == -1 )
log << log1 << "Db: Can't set the proper client encoding" << logend;
}
void Db::Close()
{
if( pg_conn )
{
PQfinish(pg_conn);
pg_conn = 0;
}
}
void Db::AssertConnection()
{
if( !pg_conn )
{
log << log1 << "Db: Trying to connect into the database...";
Connect();
if( !pg_conn )
// logend from Connect()
throw Error(Error::db_fatal_error_during_connecting);
log << log1 << "ok" << logend;
}
if( PQstatus(pg_conn) != CONNECTION_OK )
{
log << log2 << "Db: connection into the database is lost, trying to recover..." << logend;
PQreset(pg_conn);
if( PQstatus(pg_conn) != CONNECTION_OK )
{
log << log2 << "no" << logend;
throw Error(Error::db_fatal_error_during_connecting);
}
else
{
log << log2 << "ok" << logend;
}
}
}
std::string Db::Escape(const std::string & s)
{
std::string result;
result.resize(s.length() * 2 + 1);
size_t len = PQescapeStringConn(pg_conn, const_cast<char*>( result.c_str() ), s.c_str(), s.length(), 0);
result.resize(len);
return result;
}
std::string Db::Escape(const char * s)
{
std::string result;
int len;
for(len=0 ; s[len] != 0 ; ++len);
result.resize(len * 2 + 1);
size_t len_new = PQescapeStringConn(pg_conn, const_cast<char*>( result.c_str() ), s, len, 0);
result.resize(len_new);
return result;
}
// ------------------
PGresult * Db::AssertQuery(const std::string & q)
{
PGresult * r = PQexec(pg_conn, q.c_str());
if( !r )
{
log << log1 << "Db: Problem with query: " << PQerrorMessage(pg_conn) << logend;
throw Error(Error::db_incorrect_query);
}
return r;
}
void Db::AssertResultStatus(PGresult * r, ExecStatusType t)
{
if( PQresultStatus(r) != t )
{
log << "Db: Incorrect result status: " << PQerrorMessage(pg_conn) << logend;
throw Error(Error::db_incorrent_result_status);
}
}
int Db::AssertColumn(PGresult * r, const char * column_name)
{
int c = PQfnumber(r, column_name);
if( c == -1 )
{
log << log1 << "Db: there is no column: " << column_name << logend;
throw Error(Error::db_no_column);
}
return c;
}
const char * Db::AssertValue(PGresult * r, int row, int col)
{
const char * res = PQgetvalue(r, row, col);
if( !res )
{
log << log1 << "Db: there is no such an item in the result, row:" << row << ", col:" << col << logend;
throw Error(Error::db_no_item);
}
return res;
}
void Db::ClearResult(PGresult * r)
{
if( r )
PQclear(r);
}
bool Db::CheckUser(std::string & login, std::string & password, long & user_id)
{
PGresult * r = 0;
bool user_ok = false;
try
{
AssertConnection();
std::ostringstream query;
query << "select id from core.user where login='" << Escape(login) << "' and password='" << Escape(password) << "';";
r = AssertQuery( query.str() );
AssertResultStatus(r, PGRES_TUPLES_OK);
int rows = PQntuples(r);
if( rows == 0 )
throw Error(Error::db_incorrect_login);
if( rows > 1 )
{
log << log1 << "Db: there is more than one user: " << login << " (with the same password)" << logend;
throw Error(Error::db_more_than_one_login);
}
int cuser_id = AssertColumn(r, "id");
const char * fuser_id = AssertValue(r, 0, cuser_id);
user_id = atol( fuser_id );
user_ok = true;
}
catch(const Error &)
{
}
ClearResult(r);
return user_ok;
}
bool Db::AddItemCreateUrlSubject(Item & item)
{
bool is_that_url;
PGresult * r = 0;
int index = 1;
const int max_index = 100;
char appendix[20];
appendix[0] = 0;
try
{
do
{
std::ostringstream query;
// this Escape can be put at the beginning (performance)
query << "select id from core.item where url_subject='" << Escape(item.url_subject) << appendix << "' and parent_id='" << item.parent_id << "';";
r = AssertQuery(query.str());
AssertResultStatus(r, PGRES_TUPLES_OK);
if( PQntuples(r) != 0 )
{
sprintf(appendix, "_(%d)", ++index);
is_that_url = true;
}
else
{
item.url_subject += appendix;
is_that_url = false;
}
ClearResult(r);
r = 0;
}
while( is_that_url && index <= max_index );
}
catch(const Error &)
{
is_that_url = true; // for return false
}
ClearResult(r);
return !is_that_url;
}
// for testing consistency
void Db::CheckAllUrlSubjectModifyItem(Item & item)
{
PGresult * r = 0;
try
{
std::ostringstream query;
query << "update core.item set url_subject=";
// url_subject
if( AddItemCreateUrlSubject(item) )
query << '\'' << Escape(item.url_subject) << '\'';
else
{
query << '\'' << item.id << '\'';
item.url_subject.clear();
}
query << " where id='" << item.id << "';";
r = AssertQuery(query.str());
AssertResultStatus(r, PGRES_COMMAND_OK);
}
catch(const Error &)
{
}
ClearResult(r);
}
// for checking consistency
void Db::CheckAllUrlSubject()
{
PGresult * r = 0;
Item item;
try
{
AssertConnection();
std::ostringstream query, query2;
query << "select id, subject from core.item where url_subject is null or url_subject=''";
r = AssertQuery(query.str());
AssertResultStatus(r, PGRES_TUPLES_OK);
int rows = PQntuples(r);
int cid = AssertColumn(r, "id");
int csubject = AssertColumn(r, "subject");
for(int i = 0 ; i<rows ; ++i)
{
item.id = atol( AssertValue(r, i, cid) );
item.subject = AssertValue(r, i, csubject);
CheckAllUrlSubjectModifyItem(item);
}
}
catch(const Error &)
{
}
ClearResult(r);
}
long Db::AssertCurrval(const char * table)
{
PGresult * r;
std::ostringstream query;
query << "select currval('" << table << "');";
r = AssertQuery(query.str());
AssertResultStatus(r, PGRES_TUPLES_OK);
if( PQntuples(r) != 1 )
{
log << log1 << "Db: error (currval) for table: " << table << ", " << PQerrorMessage(pg_conn) << logend;
throw Error(Error::db_err_currval);
}
long res = strtol( AssertValue(r, 0, 0), 0, 10 );
return res;
}
Error Db::AddItem(Item & item)
{
PGresult * r = 0;
Error result = Error::ok;
bool url_without_id = false;
try
{
AssertConnection();
std::ostringstream query;
query << "insert into core.item (subject, content, url_subject, type, parent_id) values (";
query << '\'' << Escape(item.subject) << "', ";
query << '\'' << Escape(item.content) << "', ";
// url_subject
url_without_id = AddItemCreateUrlSubject(item);
if( url_without_id )
{
query << '\'' << Escape(item.url_subject) << "', ";
}
else
{
query << "currval('core.item_id_seq')" << ", ";
}
query << '\'' << static_cast<int>(item.type) << "', ";
query << '\'' << item.parent_id << "' ";
query << ");";
r = AssertQuery(query.str());
AssertResultStatus(r, PGRES_COMMAND_OK);
item.id = AssertCurrval("core.item_id_seq");
if( !url_without_id )
ToString(item.url_subject, item.id);
}
catch(const Error & e)
{
result = e;
}
ClearResult(r);
return result;
}
Error Db::EditItem(Item & item, bool with_subject)
{
PGresult * r = 0;
Error result = Error::ok;
bool url_without_id = false;
try
{
AssertConnection();
std::ostringstream query;
query << "update core.item set (";
if( with_subject )
query << "subject, url_subject, ";
query << "content, type, parent_id) = (";
if( with_subject )
{
query << '\'' << Escape(item.subject) << "', ";
// url_subject
url_without_id = AddItemCreateUrlSubject(item);
if( url_without_id )
{
query << '\'' << Escape(item.url_subject) << "', ";
}
else
{
query << '\'' << item.id << "', ";
}
}
query << '\'' << Escape(item.content) << "', ";
query << '\'' << static_cast<int>(item.type) << "', ";
query << '\'' << item.parent_id << "' ";
query << ") where id='" << item.id << "';";
r = AssertQuery(query.str());
AssertResultStatus(r, PGRES_COMMAND_OK);
if( with_subject && !url_without_id )
ToString(item.url_subject, item.id);
}
catch(const Error & e)
{
result = e;
}
ClearResult(r);
return result;
}
PGresult * Db::GetItemsQuery(Item & item_ref)
{
std::ostringstream query;
query << "select * from core.item where type!='0' and parent_id='" << item_ref.parent_id << "'";
if( item_ref.id != -1 )
query << " and id='" << item_ref.id << "'";
if( !item_ref.url_subject.empty() )
query << " and url_subject='" << Escape(item_ref.url_subject) << "'";
query << ';';
return AssertQuery(query.str());
}
void Db::GetItems(std::vector<Item> & item_table, Item & item_ref)
{
item_table.clear();
PGresult * r = 0;
try
{
AssertConnection();
r = GetItemsQuery(item_ref);
AssertResultStatus(r, PGRES_TUPLES_OK);
Item item;
int rows = PQntuples(r);
ItemColumns col;
col.SetColumns(r);
for(int i = 0 ; i<rows ; ++i)
{
col.SetItem(r, i, item);
item_table.push_back(item);
}
}
catch(const Error &)
{
}
ClearResult(r);
}
void Db::GetItem(std::vector<Item> & item_table, long id)
{
PGresult * r = 0;
try
{
AssertConnection();
std::ostringstream query;
query << "select * from core.item where type='1' and id='" << id << "';";
r = AssertQuery( query.str() );
AssertResultStatus(r, PGRES_TUPLES_OK);
Item item;
int rows = PQntuples(r);
if( rows > 1 )
log << log1 << "Db: we have more than one item with id: " << id << logend;
ItemColumns col;
col.SetColumns(r);
for(int i = 0 ; i<rows ; ++i)
{
col.SetItem(r, i, item);
item_table.push_back(item);
}
}
catch(const Error &)
{
}
ClearResult(r);
}
bool Db::DelItem(long id)
{
long rows = 0;
PGresult * r = 0;
try
{
AssertConnection();
std::ostringstream query;
query << "delete from core.item where type='1' and id='" << id << "';";
r = AssertQuery( query.str() );
AssertResultStatus(r, PGRES_COMMAND_OK);
const char * crows = PQcmdTuples(r);
if( crows )
{
rows = atol(crows);
if( rows > 1 )
log << log1 << "Db: more than one item were deleted" << logend;
}
}
catch(const Error &)
{
}
ClearResult(r);
return rows != 0;
}
void Db::GetDirs(DirContainer & dir_table)
{
PGresult * r = 0;
try
{
AssertConnection();
std::ostringstream query;
query << "select * from core.item where type='0';";
r = AssertQuery( query.str() );
AssertResultStatus(r, PGRES_TUPLES_OK);
Item item;
int rows = PQntuples(r);
ItemColumns col;
col.SetColumns(r);
for(int i = 0 ; i<rows ; ++i)
{
col.SetItem(r, i, item);
dir_table.PushBack( item );
}
}
catch(const Error &)
{
}
ClearResult(r);
}

119
core/db.h
View File

@@ -1,119 +0,0 @@
/*
* This file is a part of CMSLU -- Content Management System like Unix
* and is not publicly distributed
*
* Copyright (c) 2008, Tomasz Sowa
* All rights reserved.
*
*/
#ifndef headerfilecoredb
#define headerfilecoredb
#include <string>
#include <vector>
#include <map>
#include <sstream>
#include <libpq-fe.h>
#include <cstdio>
#include "log.h"
#include "item.h"
#include "misc.h"
#include "error.h"
#include "dircontainer.h"
class Db
{
protected:
PGconn * pg_conn;
std::string db_database, db_user, db_pass;
public:
Db();
~Db();
void Init(const std::string & database, const std::string & user, const std::string & pass);
void Connect();
void Close();
void AssertConnection();
std::string Escape(const std::string & s);
std::string Escape(const char * s);
PGresult * AssertQuery(const std::string & q);
void AssertResultStatus(PGresult * r, ExecStatusType t);
static int AssertColumn(PGresult * r, const char * column_name);
static const char * AssertValue(PGresult * r, int row, int col);
void ClearResult(PGresult * r);
bool CheckUser(std::string & login, std::string & password, long & user_id);
long AssertCurrval(const char * table);
bool AddItemCreateUrlSubject(Item & item);
Error AddItem(Item & item);
Error EditItem(Item & item, bool with_subject = true);
void CheckAllUrlSubjectModifyItem(Item & item);
void CheckAllUrlSubject();
PGresult * GetItemsQuery(Item & item_ref);
void GetItems(std::vector<Item> & item_table, Item & item_ref);
void GetItem(std::vector<Item> & item_table, long id);
bool DelItem(long id);
void GetDirs(DirContainer & dir_table);
struct ItemColumns
{
int id, subject, content, url_subject, type, parent_id, default_item;
void SetColumns(PGresult * r)
{
id = Db::AssertColumn(r, "id");
subject = Db::AssertColumn(r, "subject");
content = Db::AssertColumn(r, "content");
url_subject = Db::AssertColumn(r, "url_subject");
type = Db::AssertColumn(r, "type");
parent_id = Db::AssertColumn(r, "parent_id");
default_item = Db::AssertColumn(r, "default_item");
}
void SetItem(PGresult * r, long row, Item & item)
{
item.id = atol( Db::AssertValue(r, row, id) );
item.subject = Db::AssertValue(r, row, subject);
item.content = Db::AssertValue(r, row, content);
item.url_subject = Db::AssertValue(r, row, url_subject);
item.type = static_cast<Item::Type>( atoi( Db::AssertValue(r, row, type) ) );
item.parent_id = atol( Db::AssertValue(r, row, parent_id) );
item.default_item = atol( Db::AssertValue(r, row, default_item) );
}
};
}; // class Db
extern Db db;
#endif

View File

@@ -1,220 +0,0 @@
/*
* This file is a part of CMSLU -- Content Management System like Unix
* and is not publicly distributed
*
* Copyright (c) 2008, Tomasz Sowa
* All rights reserved.
*
*/
#include "dir.h"
void Dir::Clear()
{
dir_table.Clear();
// !! temporarily not clearing
//root.Clear();
root.id = -1;
}
void Dir::ReadDirs()
{
Clear();
db.GetDirs(dir_table);
}
bool Dir::GetDir(const std::string & name, long parent, Item ** item)
{
DirContainer::ParentIterator i = dir_table.FindFirstParent(parent);
for( ; i!=dir_table.ParentEnd() ; i = dir_table.NextParent(i) )
if( i->second->url_subject == name )
{
*item = &(*i->second);
return true;
}
return false;
}
bool Dir::ExtractName(const char * & s, std::string & name)
{
name.clear();
// skipping first slashes (can be more than one)
for( ; *s == '/' ; ++s);
for( ; *s != 0 && *s != '/' ; ++s)
name += *s;
return !name.empty();
}
bool Dir::GetDir(const std::string & path, Item ** item)
{
long parent = -1;
std::string name;
const char * s = path.c_str();
Item * pitem = &root;
while( ExtractName(s, name) )
{
if( !GetDir(name, parent, &pitem) )
return false;
}
*item = pitem;
return true;
}
bool Dir::GetDirId(const std::string & path, long * id)
{
Item * pitem;
if( !GetDir(path, &pitem) )
return false;
*id = pitem->id;
return true;
}
bool Dir::GetDirId(const std::string & name, long parent, long * id)
{
Item * pitem;
if( !GetDir(name, parent, &pitem) )
return false;
*id = pitem->id;
return true;
}
bool Dir::IsDir(long id)
{
if( id == -1 )
// root directory
return true;
DirContainer::Iterator i = dir_table.FindId(id);
if( i == dir_table.End() )
return false;
return true;
}
bool Dir::GetDirChilds(long parent, std::vector<Item> & childs_table)
{
if( !IsDir(parent) )
return false;
DirContainer::ParentIterator i = dir_table.FindFirstParent(parent);
for( ; i != dir_table.ParentEnd() ; i = dir_table.NextParent(i) )
childs_table.push_back( *i->second );
return true;
}
// dodatkowo moze metoda AppendPath dodajaca sciezke do biezacego stringa?
// albo tutaj stringa nie czyscic?
// O(m * log n) (m- how many parts are in 'id')
bool Dir::MakePath(long id, std::string & path)
{
DirContainer::Iterator i;
path.clear();
while( true )
{
if( id == -1 )
return true;
i = dir_table.FindId(id);
if( i == dir_table.End() )
return false;
id = i->parent_id;
path.insert(path.begin(), '/');
path.insert(0, i->url_subject);
}
}
// with exceptions
Item * Dir::GetDir(const std::string & path)
{
Item * pitem;
if( !GetDir(path, &pitem) )
throw Error(Error::incorrect_dir);
return pitem;
}
Item * Dir::GetDir(const std::string & name, long parent)
{
Item * pitem;
if( !GetDir(name, parent, &pitem) )
throw Error(Error::incorrect_dir);
return pitem;
}
long Dir::GetDirId(const std::string & path)
{
long id;
if( !GetDirId(path, &id) )
throw Error(Error::incorrect_dir);
return id;
}
long Dir::GetDirId(const std::string & name, long parent)
{
long id;
if( !GetDirId(name, parent, &id) )
throw Error(Error::incorrect_dir);
return id;
}

View File

@@ -1,80 +0,0 @@
/*
* This file is a part of CMSLU -- Content Management System like Unix
* and is not publicly distributed
*
* Copyright (c) 2008, Tomasz Sowa
* All rights reserved.
*
*/
#ifndef headerfiledir
#define headerfiledir
#include <vector>
#include <map>
#include <string>
#include "item.h"
#include "error.h"
#include "log.h"
#include "db.h"
#include "dircontainer.h"
class Dir
{
private:
public: // !! temporarily
// id = -1;
Item root;
DirContainer dir_table;
// parent (or -1), item
//typedef std::multimap<long, Item> DirTable;
//DirTable dir_table;
bool ExtractName(const char * & s, std::string & name);
public:
void Clear();
void ReadDirs();
// without any exceptions
// these methods return false in a case the path or name (with a specific parent) are invalid
// we do not support '..' in a path (for security reason)
bool IsDir(long id);
bool GetDir(const std::string & path, Item ** item);
bool GetDir(const std::string & name, long parent, Item ** item);
bool GetDirId(const std::string & path, long * id);
bool GetDirId(const std::string & name, long parent, long * id);
bool GetDirChilds(long parent, std::vector<Item> & childs_table); // only returns dir-children
bool MakePath(long id, std::string & path);
// with an Error exception
// if the path or name are invalid these methods throw an exception
Item * GetDir(const std::string & path);
Item * GetDir(const std::string & name, long parent);
long GetDirId(const std::string & path);
long GetDirId(const std::string & name, long parent);
};
#endif

View File

@@ -1,161 +0,0 @@
/*
* This file is a part of CMSLU -- Content Management System like Unix
* and is not publicly distributed
*
* Copyright (c) 2008, Tomasz Sowa
* All rights reserved.
*
*/
#include "dircontainer.h"
// !! tutaj ostatecznie ustawic wartosc np okolo 100
// chwilowo do testow ustawione 2
DirContainer::DirContainer()
{
}
DirContainer::Iterator DirContainer::Begin()
{
return table.begin();
}
DirContainer::Iterator DirContainer::End()
{
return table.end();
}
DirContainer::SizeType DirContainer::Size()
{
return table.size();
}
bool DirContainer::Empty()
{
return table.empty();
}
void DirContainer::PushBack(const Item & item)
{
bool rebuild_indexes = false;
if( table.size() == table.capacity() )
rebuild_indexes = true;
table.push_back(item);
log << log2 << "DirCont: added item, id: " << item.id << ", parent_id: " << item.parent_id << logend;
if( rebuild_indexes )
RebuildIndexes();
else
AddIndexes( --table.end() );
}
void DirContainer::Clear()
{
table.clear();
table_id.clear();
table_parent.clear();
}
DirContainer::Iterator DirContainer::FindId(long id)
{
TableId::iterator i = table_id.find(id);
if( i == table_id.end() )
return table.end();
return i->second;
}
void DirContainer::AddIndexes(Iterator item)
{
table_id.insert( std::make_pair(item->id, item) );
table_parent.insert( std::make_pair(item->parent_id, item) );
log << log2 << "DirCont: added indexes to item, id: " << item->id << ", parent_id: " << item->parent_id << logend;
}
void DirContainer::RebuildIndexes()
{
Iterator i;
log << log2 << "DirCont: rebuilding indexes" << logend;
table_id.clear();
table_parent.clear();
for(i=table.begin() ; i!=table.end() ; ++i)
AddIndexes( i );
log << log2 << "DirCont: indexes rebuilt, table.size: " << table.size() << ", table_id.size: " << table_id.size() << ", table_parent.size: " << table_parent.size() << logend;
}
DirContainer::ParentIterator DirContainer::ParentBegin()
{
return table_parent.begin();
}
DirContainer::ParentIterator DirContainer::ParentEnd()
{
return table_parent.end();
}
DirContainer::ParentSizeType DirContainer::ParentSize()
{
return table_parent.size();
}
bool DirContainer::ParentEmpty()
{
return table_parent.empty();
}
DirContainer::ParentIterator DirContainer::FindFirstParent(long parent)
{
ParentIterator i = table_parent.lower_bound(parent);
if( i == table_parent.end() || i->first != parent )
return table_parent.end();
return i;
}
DirContainer::ParentIterator DirContainer::NextParent(ParentIterator i)
{
if( i == table_parent.end() )
return table_parent.end();
long parent = i->first;
++i;
if( i == table_parent.end() || i->first != parent )
return table_parent.end();
return i;
}

View File

@@ -1,66 +0,0 @@
/*
* This file is a part of CMSLU -- Content Management System like Unix
* and is not publicly distributed
*
* Copyright (c) 2008, Tomasz Sowa
* All rights reserved.
*
*/
#ifndef headerfiledircontainer
#define headerfiledircontainer
#include <vector>
#include <map>
#include "item.h"
#include "log.h"
class DirContainer
{
public:
typedef std::vector<Item> Table;
typedef Table::iterator Iterator;
typedef Table::size_type SizeType;
typedef std::map<long, Iterator> TableId;
typedef std::multimap<long, Iterator> TableParent;
typedef TableParent::iterator ParentIterator;
typedef TableParent::size_type ParentSizeType;
DirContainer();
Iterator Begin();
Iterator End();
SizeType Size();
bool Empty();
void PushBack(const Item & item);
void Clear();
Iterator FindId(long id);
ParentIterator ParentBegin();
ParentIterator ParentEnd();
ParentSizeType ParentSize();
bool ParentEmpty();
ParentIterator FindFirstParent(long parent);
ParentIterator NextParent(ParentIterator pi);
private:
void AddIndexes(Iterator item);
void RebuildIndexes();
// main table with dirs
Table table;
// indexes
TableId table_id;
TableParent table_parent;
};
#endif

View File

@@ -1,42 +0,0 @@
/*
* This file is a part of CMSLU -- Content Management System like Unix
* and is not publicly distributed
*
* Copyright (c) 2008, Tomasz Sowa
* All rights reserved.
*
*/
#include "done.h"
Done::Done()
{
}
Done::Done(Code c) : code(c)
{
}
Done & Done::operator=(Code c)
{
code = c;
return *this;
}
bool Done::operator==(Code c) const
{
return code == c;
}
bool Done::operator!=(Code c) const
{
return code != c;
}

View File

@@ -1,45 +0,0 @@
/*
* This file is a part of CMSLU -- Content Management System like Unix
* and is not publicly distributed
*
* Copyright (c) 2008, Tomasz Sowa
* All rights reserved.
*
*/
#ifndef headerfiledone
#define headerfiledone
// what have been done
class Done
{
public:
enum Code
{
none,
added_item,
edited_item,
deleted_item,
loggedout
};
Done();
Done(Code c);
Done & operator=(Code c);
bool operator==(Code c) const;
bool operator!=(Code c) const;
private:
Code code;
};
#endif

View File

@@ -1,73 +0,0 @@
/*
* This file is a part of CMSLU -- Content Management System like Unix
* and is not publicly distributed
*
* Copyright (c) 2008, Tomasz Sowa
* All rights reserved.
*
*/
#include "error.h"
Error::Error()
{
code = unknown;
}
Error::Error(Code c) : code(c)
{
}
Error::Error(int i)
{
code = static_cast<Code>(i);
}
Error::operator int() const
{
return static_cast<int>(code);
}
Error & Error::operator=(Code c)
{
code = c;
return *this;
}
bool Error::operator==(Code c) const
{
return code == c;
}
bool Error::operator!=(Code c) const
{
return code != c;
}
std::ostream & operator<<(std::ostream & out, const Error & e)
{
out << static_cast<int>(e.code);
return out;
}
Log & operator<<(Log & out, const Error & e)
{
out << static_cast<int>(e.code);
return out;
}

View File

@@ -1,71 +0,0 @@
/*
* This file is a part of CMSLU -- Content Management System like Unix
* and is not publicly distributed
*
* Copyright (c) 2008, Tomasz Sowa
* All rights reserved.
*
*/
#ifndef headerfileerror
#define headerfileerror
#include <iostream>
#include "log.h"
class Error
{
public:
enum Code
{
ok = 0,
incorrect_path,
db_fatal_error_during_connecting,
db_incorrect_query,
db_incorrent_result_status,
db_no_column,
db_no_item,
db_incorrect_login,
db_more_than_one_login,
db_err_currval,
incorrect_dir,
unknown = 1000
};
Error();
Error(Code c);
Error(int i);
Error & operator=(Code c);
operator int() const;
bool operator==(Code c) const;
bool operator!=(Code c) const;
friend std::ostream & operator<<(std::ostream & out, const Error & e);
friend Log & operator<<(Log & out, const Error & e);
private:
Code code;
};
std::ostream & operator<<(std::ostream & out, const Error & e);
Log & operator<<(Log & out, const Error & e);
#endif

View File

@@ -1,57 +0,0 @@
/*
* This file is a part of CMSLU -- Content Management System like Unix
* and is not publicly distributed
*
* Copyright (c) 2008, Tomasz Sowa
* All rights reserved.
*
*/
#ifndef headerfilegetparser
#define headerfilegetparser
#include "httpsimpleparser.h"
#include "requesttypes.h"
class GetParser : public HttpSimpleParser
{
const char * get_string;
GetTable & get_table;
protected:
virtual int GetChar()
{
if( !get_string || *get_string == 0 )
return -1;
return (int)(unsigned char)*(get_string++);
}
virtual void Parameter(std::string &, std::string & value)
{
get_table.push_back(value);
log << log2 << "Get, value: \"" << value << "\"" << logend;
}
public:
GetParser(const char * get_string_, GetTable & get_table_) : get_string(get_string_), get_table(get_table_)
{
HttpSimpleParser::separator = '/';
HttpSimpleParser::read_name = false;
if( get_string && *get_string == separator ) // one '/' at the beginning
++get_string;
}
};
#endif

View File

@@ -1,231 +0,0 @@
/*
* This file is a part of CMSLU -- Content Management System like Unix
* and is not publicly distributed
*
* Copyright (c) 2008, Tomasz Sowa
* All rights reserved.
*
*/
#include "httpsimpleparser.h"
void HttpSimpleParser::ToLower(std::string & s)
{
std::string::iterator i;
for(i=s.begin() ; i!= s.end() ; ++i)
{
if( *i>='A' && *i<='Z' )
*i = *i - 'A' + 'a';
}
}
bool HttpSimpleParser::IsWhite(int c)
{
if( c==' ' || c=='\t' )
return true;
return false;
}
void HttpSimpleParser::SkipWhiteChars()
{
while( IsWhite(last_c) )
last_c = GetChar();
}
void HttpSimpleParser::TrimWhiteChars(std::string & s)
{
if( s.empty() )
return;
std::string::size_type i;
for(i = 0 ; i<s.size() && IsWhite(s[i]) ; ++i);
if( i == s.size() )
{
// all characters are white
s.clear();
return;
}
if( i > 0 )
// there are some white characters at the beginning
s.erase(0, i);
// s is not empty now (i was not equal s.size())
// and we have some non white characters
// we stops at the last non white character
for(i = s.size()-1 ; i>0 && IsWhite(s[i]) ; --i);
if( i != s.size()-1 )
// there are some white characters at the end
// we're starting from i+1 even when i==0 (there are some non white characters)
s.erase(i+1, s.size() - i - 1);
}
int HttpSimpleParser::ParseHalfHex(int c)
{
if( c>='a' && c<='z' )
c += 'A' - 'a'; // to upper case
if( c >= 'A' )
c = c - 'A' + 10;
else
c = c - '0';
c &= 0xf;
return c;
}
void HttpSimpleParser::CheckSpecialChar()
{
if( last_c == '%' )
{
int c1 = GetChar();
int c2 = GetChar();
if( c1==-1 || c2==-1 )
last_c = -1;
c1 = ParseHalfHex(c1);
c2 = ParseHalfHex(c2);
last_c = (c1 << 4) + c2;
}
else
if( last_c == '+' )
{
last_c = ' ';
}
}
void HttpSimpleParser::ReadName()
{
// we're checking 'separator' and '=' because the string is allowed not having '=' (the value is optional)
for( ; last_c!=-1 && last_c!=separator && last_c!='=' ; last_c = GetChar() )
{
if( recognize_special_chars )
CheckSpecialChar();
if( last_c != -1 )
last_name += last_c;
}
if( last_c == '=' )
last_c = GetChar();
}
void HttpSimpleParser::ReadQuotedValue()
{
// skipping '"'
last_c = GetChar();
for( ; last_c!=-1 && last_c!='"' ; last_c = GetChar() )
{
if( recognize_special_chars )
CheckSpecialChar();
if( last_c != -1 )
last_value += last_c;
}
if( last_c == '"' )
last_c = GetChar();
// looking for a separator (skipping)
for( ; last_c!=-1 && last_c!=separator ; last_c = GetChar() );
}
void HttpSimpleParser::ReadValue()
{
if( skip_white_chars )
SkipWhiteChars();
if( value_can_be_quoted && last_c == '"' )
{
ReadQuotedValue();
}
else
{
for( ; last_c!=-1 && last_c!=separator ; last_c = GetChar() )
{
if( recognize_special_chars )
CheckSpecialChar();
if( last_c != -1 )
last_value += last_c;
}
}
if( last_c == separator )
last_c = GetChar();
}
void HttpSimpleParser::Parse()
{
for( last_c = GetChar() ; last_c != -1 ; )
{
last_name.clear();
last_value.clear();
if( read_name )
ReadName();
ReadValue();
if( skip_white_chars )
{
TrimWhiteChars(last_name);
TrimWhiteChars(last_value);
}
Parameter(last_name, last_value); // user definied function
}
}

View File

@@ -1,74 +0,0 @@
/*
* This file is a part of CMSLU -- Content Management System like Unix
* and is not publicly distributed
*
* Copyright (c) 2008, Tomasz Sowa
* All rights reserved.
*
*/
#ifndef headerfilehttpsimpleparser
#define headerfilehttpsimpleparser
#include <string>
class HttpSimpleParser
{
protected:
bool read_name;
bool value_can_be_quoted;
bool skip_white_chars;
bool recognize_special_chars;
int ParseHalfHex(int c);
void ReadName();
void ReadQuotedValue();
void ReadValue();
std::string last_name;
std::string last_value;
int last_c;
int separator;
// '-1' means end (eof)
virtual int GetChar() = 0;
virtual void Parameter(std::string & last_name, std::string & last_value) = 0;
void ToLower(std::string & s);
bool IsWhite(int c);
void SkipWhiteChars();
void TrimWhiteChars(std::string & s);
void CheckSpecialChar();
public:
HttpSimpleParser()
{
separator = '&';
read_name = true;
value_can_be_quoted = false;
skip_white_chars = false;
recognize_special_chars = true;
}
void Parse();
};
#endif

View File

@@ -1,73 +0,0 @@
/*
* This file is a part of CMSLU -- Content Management System like Unix
* and is not publicly distributed
*
* Copyright (c) 2008, Tomasz Sowa
* All rights reserved.
*
*/
#ifndef headerfileitem
#define headerfileitem
#include <string>
struct Item
{
long id;
std::string subject;
std::string content;
std::string url_subject;
enum Type
{
dir = 0,
file = 1,
none = 1000
};
Type type;
//item_type;
long parent_id;
long default_item;
Item()
{
Clear();
}
void Clear()
{
id = -1;
subject.clear();
content.clear();
url_subject.clear();
type = none;
parent_id = -1;
default_item = -1;
}
};
#endif

View File

@@ -1,177 +0,0 @@
/*
* This file is a part of CMSLU -- Content Management System like Unix
* and is not publicly distributed
*
* Copyright (c) 2008, Tomasz Sowa
* All rights reserved.
*
*/
#include "log.h"
Log::Log()
{
log_level = 1;
current_level = 2;
log_file = "cmslu.log";
log_stdout = true;
}
void Log::Init(int log_l, const std::string & log_f, bool log_std)
{
log_level = log_l;
log_file = log_f;
log_stdout = log_std;
}
// zrobic templeta z tych metod
// i dla const char * zrobic specjalizacje
Log & Log::operator<<(const char * s)
{
if( !s )
return *this;
buffer << s;
return *this;
}
Log & Log::operator<<(const std::string & s)
{
buffer << s;
return *this;
}
Log & Log::operator<<(int s)
{
buffer << s;
return *this;
}
Log & Log::operator<<(long s)
{
buffer << s;
return *this;
}
/*
Log & Log::operator<<(void * s)
{
buffer << s;
return *this;
}
*/
Log & Log::operator<<(char s)
{
buffer << s;
return *this;
}
Log & Log::operator<<(size_t s)
{
buffer << s;
return *this;
}
Log & Log::operator<<(Manipulators m)
{
switch(m)
{
case logend:
SaveLog();
buffer.str( "" );
break;
case log1:
current_level = 1;
break;
case log2:
current_level = 2;
break;
case log3:
current_level = 3;
break;
}
return *this;
}
void Log::SaveLog()
{
int attempt = 2;
if( current_level > log_level )
return;
if( log_stdout )
std::cout << buffer.str() << std::endl;
std::ofstream file;
do
{
file.open( log_file.c_str(), std::ios_base::out | std::ios_base::app );
// if( !file )
// sleep(1);
}
while( --attempt > 0 && !file );
if( !file )
return;
file << buffer.str() << std::endl;
}

View File

@@ -1,61 +0,0 @@
/*
* This file is a part of CMSLU -- Content Management System like Unix
* and is not publicly distributed
*
* Copyright (c) 2008, Tomasz Sowa
* All rights reserved.
*
*/
#ifndef headerfilelog
#define headerfilelog
#include <sstream>
#include <fstream>
#include <iostream>
#include <string>
enum Manipulators { logend, log1, log2, log3 };
class Log
{
std::ostringstream buffer;
int log_level, current_level;
std::string log_file;
bool log_stdout;
public:
Log();
void Init(int log_l, const std::string & log_f, bool log_std);
Log & operator<<(const char * s);
Log & operator<<(const std::string & s);
Log & operator<<(int s);
Log & operator<<(long s);
//Log & operator<<(void * s); // ??
Log & operator<<(char s);
Log & operator<<(size_t s);
Log & operator<<(Manipulators m);
void SaveLog();
};
extern Log log;
#endif

View File

@@ -1,73 +0,0 @@
/*
* This file is a part of CMSLU -- Content Management System like Unix
* and is not publicly distributed
*
* Copyright (c) 2008, Tomasz Sowa
* All rights reserved.
*
*/
#include <cstdlib>
#include <ctime>
#include <signal.h>
#include <iostream>
#include "requestcontroller.h"
#include "data.h"
#include "log.h"
#include "request.h"
#include "db.h"
// singletons
// first 'data' then 'log' then 'request'
Data data;
Log log;
Request request;
Db db;
void signal_term(int)
{
log << log1 << "system aborted" << logend;
exit(0);
}
int main()
{
std::srand(std::time(0));
log.Init(data.log_level, data.log_file, data.log_stdout);
RequestController req_controller;
//data.read_from_file();
db.Init(data.db_database, data.db_user, data.db_pass);
if( !req_controller.Init() )
return 1;
log << log1 << "system started" << logend;
signal(SIGTERM, signal_term);
log << log1 << "checking for table consistency...";
db.CheckAllUrlSubject();
log << log1 << "done" << logend;
req_controller.Loop();
log << log1 << "system stopped" << logend;
return 0;
}

View File

@@ -1,138 +0,0 @@
/*
* This file is a part of CMSLU -- Content Management System like Unix
* and is not publicly distributed
*
* Copyright (c) 2008, Tomasz Sowa
* All rights reserved.
*
*/
#include "misc.h"
void ToString(std::string & s, int value)
{
static char buffer[50];
sprintf(buffer, "%d", value);
s = buffer;
}
void ToString(std::string & s, long value)
{
static char buffer[50];
sprintf(buffer, "%ld", value);
s = buffer;
}
void SetUrlSubjectFromSubject(Item & item)
{
std::string::iterator i;
item.url_subject.clear();
for(i = item.subject.begin(); i!=item.subject.end() ; ++i)
{
int c = ChangeLocalChar(*i);
if( (c >= 'a' && c <='z') ||
(c >= 'A' && c <='Z') ||
(c >= '0' && c <='9') ||
(c == '(' || c == ')' || c == '.' || c == ',' || c == '_' )
)
{
item.url_subject += c;
}
else
item.url_subject += '_';
}
if( item.url_subject.empty() )
item.url_subject = "bez_nazwy";
else
if( item.url_subject[0] >= '0' && item.url_subject[0] <= '9' )
// url_subject must begin with a letter
item.url_subject.insert(item.url_subject.begin(), '_');
}
int polish_letters_simple[] =
{ 'a', 'A',
'c', 'C',
's', 'S',
'e', 'E',
'l', 'L',
'o', 'O',
'z', 'Z',
'z', 'Z',
'n', 'N', 0 }; // 0 - terminating
int polish_letters_iso88592[] =
{ 0xb1, 0xa1,
0xe6, 0xc6,
0xb6, 0xa6,
0xea, 0xca,
0xb3, 0xa3,
0xf3, 0xd3,
0xbf, 0xaf,
0xbc, 0xac,
0xf1, 0xd1, 0 };
int ChangeLocalChar(unsigned char c)
{
// if( language == polish_iso88592 )
for(int i = 0 ; polish_letters_iso88592[i] ; ++i)
{
if( polish_letters_simple[i] == 0 )
{
log << log1 << "localization tables don't have the same size" << logend;
return c;
}
if( polish_letters_iso88592[i] == c )
return polish_letters_simple[i];
}
return c;
}
void HtmlSpecial(std::ostringstream & out, const std::string & in)
{
std::string::const_iterator i;
for(i = in.begin() ; i != in.end() ; ++i)
{
if( *i == '<' )
out << "&lt;";
else
if( *i == '>' )
out << "&gt;";
else
out << *i;
}
}
std::string HtmlSpecial(const std::string & in)
{
std::ostringstream out;
HtmlSpecial(out, in);
return out.str();
}

View File

@@ -1,33 +0,0 @@
/*
* This file is a part of CMSLU -- Content Management System like Unix
* and is not publicly distributed
*
* Copyright (c) 2008, Tomasz Sowa
* All rights reserved.
*
*/
#ifndef headerfilemisc
#define headerfilemisc
#include <string>
#include <sstream>
#include "log.h"
#include "item.h"
#define MAJOR_VER 0
#define MINOR_VER 1
#define REVISION_VER 0
void ToString(std::string & s, int value);
void ToString(std::string & s, long value);
void SetUrlSubjectFromSubject(Item & item);
int ChangeLocalChar(unsigned char c);
void HtmlSpecial(std::ostringstream & out, const std::string & in);
std::string HtmlSpecial(const std::string & in);
#endif

View File

@@ -1,56 +0,0 @@
/*
* This file is a part of CMSLU -- Content Management System like Unix
* and is not publicly distributed
*
* Copyright (c) 2008, Tomasz Sowa
* All rights reserved.
*
*/
#ifndef headerfilepostparser
#define headerfilepostparser
#include <fcgiapp.h>
#include <string>
#include "httpsimpleparser.h"
#include "requesttypes.h"
class PostParser : public HttpSimpleParser
{
FCGX_Stream * in;
PostTable & post_table;
protected:
virtual int GetChar()
{
return FCGX_GetChar(in);
}
virtual void Parameter(std::string & name, std::string & value)
{
std::pair<PostTable::iterator, bool> res = post_table.insert( std::make_pair(name, value) );
log << log2 << "Method POST, name: \"" << name << "\", value: \"" << value << "\"";
if( res.second == false )
log << log2 << " (skipped)";
log << log2 << logend;
}
public:
PostParser(FCGX_Stream * in_, PostTable & post_table_) : in(in_), post_table(post_table_)
{
}
};
#endif

View File

@@ -1,374 +0,0 @@
/*
* This file is a part of CMSLU -- Content Management System like Unix
* and is not publicly distributed
*
* Copyright (c) 2008, Tomasz Sowa
* All rights reserved.
*
*/
#include "request.h"
Request::Request()
{
Clear();
}
void Request::Clear()
{
// warning: don't clear in, out, err, env
get_table.clear();
post_table.clear();
cookie_table.clear();
method = none;
headers.str("");
page.str("");
debug.str("");
env_request_method = 0;
env_request_uri = 0;
env_http_cookie = 0;
session = 0;
result = err404; // tutaj moze cos lepszego, cos w stylu 'not implemented'
dir = -1;
cur_dir_table.clear();
item_table.clear();
dir_table.clear();
item.Clear();
str.clear();
}
void Request::CopyFirstItem()
{
if( !request.item_table.empty() )
request.item = request.item_table[0];
else
{
request.item.Clear();
log << log1 << "Request::CopyFirstItem: item_table is empty" << logend;
request.result = err_internal;
}
}
// value can be null
void Request::SetCookie(const char * name, const char * value)
{
request.headers << "Set-Cookie: " << name << "=";
if( value && value[0]!=0 )
request.headers << value;
else
request.headers << "\"\"";
request.headers << "; path=/\r\n";
}
void Request::SetCookie(const char * name, long value)
{
request.headers << "Set-Cookie: " << name << "=" << value << "; path=/\r\n";
}
bool Request::IsPostVar(const char * var)
{
PostTable::iterator p;
p = post_table.find(var);
if( p == post_table.end() )
return false;
return true;
}
std::string & Request::PostVar(const char * var)
{
PostTable::iterator p;
p = post_table.find(var);
if( p == post_table.end() )
throw Error();
return p->second;
}
//
void Request::PrintGetTable()
{
debug << "get_table: " << get_table.size() << "\n";
for(GetTable::iterator i = get_table.begin() ; i != get_table.end() ; ++i)
debug << " \"" << *i << "\"\n";
debug << std::endl;
}
void Request::PrintEnv()
{
char ** e;
debug << "environment variables:\n";
for( e = env ; *e ; ++e )
debug << ' ' << *e << "\n";
debug << std::endl;
}
void Request::PrintIn()
{
char buf[100];
int buf_len = sizeof(buf) / sizeof(char);
int len;
debug << "fcgi input:\n";
do
{
len = FCGX_GetStr(buf, buf_len - 1, in);
if( len != 0 )
{
buf[len] = 0;
debug << buf;
}
}
while( len == buf_len - 1 );
debug << std::endl;
}
void Request::ReadEnvVariables()
{
// we store that values because FCGX_GetParam has O(n) complexity
// with this variables (env_*) we have O(1)
env_request_method = FCGX_GetParam("REQUEST_METHOD", env);
env_request_uri = FCGX_GetParam("REQUEST_URI", env);
env_http_cookie = FCGX_GetParam("HTTP_COOKIE", env);
}
void Request::CheckMethod()
{
method = none;
if( !env_request_method )
return;
if( env_request_method[0] == 'G' )
method = get;
else
if( env_request_method[0] == 'P' )
method = post;
}
void Request::ReadParameters()
{
// some parameters (get) we have always
// if( method == get )
{
GetParser get_parser(env_request_uri, get_table);
get_parser.Parse();
}
if( method == post )
{
PostParser post_parser(in, post_table);
post_parser.Parse();
}
CookieParser cookie_parser(env_http_cookie, cookie_table);
cookie_parser.Parse();
}
// reading everything
void Request::Read()
{
ReadEnvVariables();
CheckMethod();
ReadParameters();
}
void Request::SendAll()
{
if( result == redirect )
{
FCGX_PutS("Status: 301 Moved Permanently\r\n", out);
FCGX_FPrintF(out, "Location: %s\r\n", str.c_str());
log << log2 << "Redirect into: " << str << logend;
}
else
{
FCGX_PutS("Status: 200 OK\r\n", out);
FCGX_PutS("Content-Type: Text/Html\r\n", out);
}
FCGX_PutS(headers.str().c_str(), out);
FCGX_PutS("\r\n", out);
if( result == redirect )
// if there is a redirect we do not send a content
return;
FCGX_PutS(page.str().c_str(), out);
const std::string & d = debug.str();
if( !d.empty() )
{
FCGX_PutS("\n<!--\n", out);
FCGX_PutS(d.c_str(), out);
FCGX_PutS("\n-->\n", out);
}
}
// ----------------
/*
unsigned char Request::tohex(unsigned char polowa)
{
// polowa z zakresu 0-15
polowa = polowa & 0xf;
if(polowa<10)
polowa += '0';
else
polowa = polowa - 10 + 'A';
return polowa;
}
// cala wartosc zapisywana jest w postaci hex
string Request::ToHex(const string & dane)
{
string wynik;
unsigned int i;
for(i=0 ; i<dane.length() ; ++i)
{
wynik += tohex(dane[i] >> 4);
wynik += tohex(dane[i] & 0xf);
}
return wynik;
}
string Request::HexToString(const string & dane)
{
string wynik;
unsigned int i;
unsigned char znak,znak1,znak2;
if(dane.length()==0)
return wynik;
for(i=0 ; i<dane.length()-1 ; i+=2)
{
znak1 = parsujhex(dane[i]);
znak2 = parsujhex(dane[i+1]);
znak = (znak1 << 4) + znak2;
wynik += znak;
}
return wynik;
}
string Request::ToUrl(const string & dane)
{
string wynik;
unsigned int i;
for(i=0 ; i<dane.length() ; ++i)
{
if( (dane[i]>='a' && dane[i]<='z') ||
(dane[i]>='A' && dane[i]<='Z') ||
(dane[i]>='0' && dane[i]<='9') ||
dane[i]=='_' )
{
wynik += dane[i];
}
else
{
wynik += '%';
wynik += tohex(dane[i] >> 4);
wynik += tohex(dane[i] & 0xf);
}
}
return wynik;
}
*/

View File

@@ -1,116 +0,0 @@
/*
* This file is a part of CMSLU -- Content Management System like Unix
* and is not publicly distributed
*
* Copyright (c) 2008, Tomasz Sowa
* All rights reserved.
*
*/
#ifndef headerfilerequest
#define headerfilerequest
#include <fcgiapp.h>
#include <sstream>
#include <vector>
#include "requesttypes.h"
#include "log.h"
#include "session.h"
#include "getparser.h"
#include "postparser.h"
#include "cookieparser.h"
#include "item.h"
#include "error.h"
struct Request
{
FCGX_Stream * in, * out, * err;
FCGX_ParamArray env; // defined as 'char **'
enum Method { get, post, none } method;
// headers, page and debug
std::ostringstream headers, page, debug;
GetTable get_table;
PostTable post_table;
CookieTable cookie_table;
const char * env_request_method;
const char * env_request_uri;
const char * env_http_cookie;
// current session
// is set after calling session_manager.SetSession()
Session * session;
// 'done_status' is set if 'done' is different than 'nothing'
Error done_status;
// what to do
enum Result { err_internal, err404, show_dir, show_item, show_item_by_id, add_item, edit_item, del_item, del_item_confirm, confirm, redirect, logout } result; // zamienic na to_do
//Item item; // bedziemy uzywac tego, item_id i item_url_subject wywalic
// current directory e.g. /foo/bar
std::vector<Item> cur_dir_table;
// id of the last directory (bar) or -1
long dir;
// items in the current directory
// maybe without contents?
std::vector<Item> item_table;
// directories in the current directory
std::vector<Item> dir_table;
// this item is used for many purposes such as editing, adding an item etc.
Item item;
// this string is used for many purposes such as redirecting
std::string str;
// for debugging
void PrintGetTable();
void PrintEnv();
void PrintIn();
Request();
void Clear();
void SetCookie(const char * name, const char * value);
void SetCookie(const char * name, long value);
bool IsPostVar(const char * var);
std::string & PostVar(const char * var); // with a throw
// item_table[0] -> item
void CopyFirstItem();
void ReadEnvVariables();
void CheckMethod();
void ReadParameters();
void Read();
void SendAll();
};
extern Request request;
#endif

View File

@@ -1,137 +0,0 @@
/*
* This file is a part of CMSLU -- Content Management System like Unix
* and is not publicly distributed
*
* Copyright (c) 2008, Tomasz Sowa
* All rights reserved.
*
*/
#include "requestcontroller.h"
RequestController::RequestController()
{
}
bool RequestController::Init()
{
const char * sock = data.fcgi_socket.c_str();
unlink(sock);
int s = FCGX_OpenSocket(sock, 10);
if( s < 0 )
{
log << log1 << "An error during creating a socket" << logend;
return false;
}
chmod(sock, data.fcgi_socket_chmod);
passwd * pw = getpwnam(data.fcgi_socket_user.c_str());
if( !pw )
{
log << log1 << "There is no user: " << data.fcgi_socket_user << logend;
return false;
}
group * gr = getgrnam(data.fcgi_socket_group.c_str());
if( !gr )
{
log << log1 << "There is no group: " << data.fcgi_socket_group << logend;
return false;
}
chown(sock, pw->pw_uid, gr->gr_gid);
if( setuid(pw->pw_uid) < 0 )
{
log << log1 << "I can't change the user into: " << data.fcgi_socket_user << logend;
return false;
}
/*
if( setgid(gr->gr_gid) < 0 )
{
int e = errno;
log << log1 << "I can't change the group into: " << data.fcgi_socket_group << " " << gr->gr_gid << logend;
log << log1 << "errno: " << e << logend;
return false;
}
*/
dup2(s, 0);
if( !data.log_stdout )
close(1);
close(2);
//
data.dir.ReadDirs();
//
if( !content.Init() )
return false;
return true;
}
void RequestController::Loop()
{
while( FCGX_Accept(&request.in, &request.out, &request.err, &request.env) == 0 )
{
log << log2 << "start request" << logend;
try
{
request.Clear();
request.Read();
session_manager.SetSession(); // setting request.session as well
request.session->CheckTimers();
content.Make();
request.SendAll();
}
catch(const std::exception & e)
{
log << log1 << "uncaught std exception: " << e.what() << logend;
}
catch(const Error & e)
{
log << log1 << "uncaught exception: Error: " << e << logend;
}
catch(...)
{
log << log1 << "uncaught exception" << logend;
}
log << log2 << "end request" << logend;
log << log2 << "---------------------------------------------------------------------------------" << logend;
}
}

View File

@@ -1,45 +0,0 @@
/*
* This file is a part of CMSLU -- Content Management System like Unix
* and is not publicly distributed
*
* Copyright (c) 2008, Tomasz Sowa
* All rights reserved.
*
*/
#ifndef headerfilerequestcontroller
#define headerfilerequestcontroller
#include <unistd.h>
#include <sys/stat.h>
#include <iostream>
#include <sys/types.h>
#include <pwd.h>
#include <grp.h>
#include <errno.h>
#include "data.h"
#include "log.h"
#include "request.h"
#include "content.h"
#include "sessionmanager.h"
#include "postparser.h"
#include "cookieparser.h"
class RequestController
{
Content content;
SessionManager session_manager;
public:
RequestController();
bool Init();
void Loop();
};
#endif

View File

@@ -1,26 +0,0 @@
/*
* This file is a part of CMSLU -- Content Management System like Unix
* and is not publicly distributed
*
* Copyright (c) 2008, Tomasz Sowa
* All rights reserved.
*
*/
#ifndef headerfilerequesttypes
#define headerfilerequesttypes
#include <string>
#include <vector>
#include <map>
// some global types used by Request class
typedef std::vector<std::string> GetTable;
typedef std::map<std::string, std::string> PostTable;
typedef std::map<std::string, std::string> CookieTable;
#endif

View File

@@ -1,73 +0,0 @@
/*
* This file is a part of CMSLU -- Content Management System like Unix
* and is not publicly distributed
*
* Copyright (c) 2008, Tomasz Sowa
* All rights reserved.
*
*/
#include "session.h"
Session::Session()
{
Clear();
time = std::time(0);
}
void Session::Clear()
{
id = 0;
time = 0;
is_logged = false;
user_id = 0;
user.clear();
done = Done::none;
done_status = Error::ok;
item.Clear();
done_timer = 0;
}
bool Session::operator==(const Session & s) const
{
return id == s.id;
}
bool Session::operator<(const Session & s) const
{
return id < s.id;
}
bool Session::DecTimer(int & timer)
{
if( timer == 0 )
return false;
--timer;
if( timer == 0 )
return true; // we must clear our variables
return false;
}
void Session::CheckTimers()
{
if( DecTimer(done_timer) )
{
done = Done::none;
done_status = Error::ok;
}
}

View File

@@ -1,63 +0,0 @@
/*
* This file is a part of CMSLU -- Content Management System like Unix
* and is not publicly distributed
*
* Copyright (c) 2008, Tomasz Sowa
* All rights reserved.
*
*/
#ifndef headerfilecoresession
#define headerfilecoresession
#include <ctime>
#include "requesttypes.h"
#include "error.h"
#include "item.h"
#include "done.h"
struct Session
{
// 0 - means that there is no session
long id;
int time;
bool is_logged;
long user_id; // logged user
std::string user; // user name
// what is done
Done done;
Error done_status;
int done_timer;
// used for many purposes, depending on 'done'
Item item;
// -------------------
Session();
virtual void Clear();
bool operator==(const Session & s) const;
bool operator<(const Session & s) const;
bool DecTimer(int & timer);
void CheckTimers();
};
#endif

View File

@@ -1,161 +0,0 @@
/*
* This file is a part of CMSLU -- Content Management System like Unix
* and is not publicly distributed
*
* Copyright (c) 2008, Tomasz Sowa
* All rights reserved.
*
*/
#include "sessionmanager.h"
bool SessionManager::IsSession(long s)
{
SessionTable::iterator i;
Session temp;
temp.id = s;
i = session_table.find(temp);
if( i == session_table.end() )
return false;
return true;
}
long SessionManager::CreateSessionId()
{
long id;
// make sure to call std::srand() somewhere at the beginning
// id must be != 0 (0 is reserved)
do
{
if( sizeof(long) == 8 )
{
id = ((unsigned long)std::rand()) << 32 + std::rand();
}
else
{
id = std::rand();
}
id += std::time(0);
if( id < 0 )
id = -id;
}
while( id == 0 ); // 0 reserved for a temporary session
return id;
}
void SessionManager::CreateTemporarySession()
{
Session s;
s.id = 0;
SessionTable::iterator i = session_table.find( s ); // looking for id=0
if( i == session_table.end() )
{
std::pair<SessionTable::iterator,bool> res = session_table.insert(s);
request.session = const_cast<Session*>( &(*res.first) );
}
else
{
request.session = const_cast<Session*>( &(*i) );
}
}
void SessionManager::CreateSession()
{
Session s;
int attempts = 100;
for( ; attempts > 0 ; --attempts )
{
s.id = CreateSessionId();
std::pair<SessionTable::iterator,bool> res = session_table.insert(s);
if( res.second == true )
{
// the insertion took place
request.session = const_cast<Session*>( &(*res.first) );
request.SetCookie(data.http_session_id_name.c_str(), request.session->id);
log << log1 << "created a new session: " << s.id << logend;
return;
}
}
// there is a problem with generating a new session id
// we do not set a session cookie
CreateTemporarySession();
log << log1 << "cannot create a session id (temporary used: with id 0)" << logend;
}
void SessionManager::SetSession()
{
CookieTable::iterator i = request.cookie_table.find(data.http_session_id_name);
if( i == request.cookie_table.end() )
{
CreateSession();
}
else
{
Session temp;
temp.id = atol(i->second.c_str());
SessionTable::iterator s = session_table.find(temp);
if( s != session_table.end() )
{
// that session is in the table
request.session = const_cast<Session*>( &(*s) );
log << log1 << "session: " << s->id << logend;
}
else
{
// there is no such a session
// deleting the old cookie
request.cookie_table.erase(i);
// and creating a new one
CreateSession();
}
}
// request.session is set now
}

View File

@@ -1,45 +0,0 @@
/*
* This file is a part of CMSLU -- Content Management System like Unix
* and is not publicly distributed
*
* Copyright (c) 2008, Tomasz Sowa
* All rights reserved.
*
*/
#ifndef headerfilesessionmanager
#define headerfilesessionmanager
#include <set>
#include <ctime>
#include "request.h"
#include "log.h"
#include "data.h"
#include "session.h"
#include "db.h"
class SessionManager
{
// !! zamienic na map
typedef std::set<Session> SessionTable;
SessionTable session_table;
bool IsSession(long s);
long CreateSessionId();
void CreateTemporarySession();
void CreateSession();
public:
void SetSession();
};
#endif

View File

@@ -1,542 +0,0 @@
/*
* This file is a part of CMSLU -- Content Management System like Unix
* and is not publicly distributed
*
* Copyright (c) 2008, Tomasz Sowa
* All rights reserved.
*
*/
#include "templates.h"
namespace TemplatesFunctions
{
Pattern pat_index;
Pattern pat_item;
Pattern pat_dir;
Pattern pat_item_add_edit;
Pattern pat_item_del_confirm;
Pattern pat_err_404;
Pattern pat_err_internal;
Functions functions;
void language(Info & i)
{
// at the moment only Polish language
i.out << "pl";
}
void title(Info & i)
{
i.out << "";
}
void charset(Info & i)
{
i.out << "iso-8859-2";
}
void version_major(Info & i)
{
i.out << MAJOR_VER;
}
void version_minor(Info & i)
{
i.out << MINOR_VER;
}
void version_revision(Info & i)
{
i.out << REVISION_VER;
}
void content(Info & i)
{
Pattern * p;
switch( request.result )
{
case Request::add_item:
case Request::edit_item:
p = &pat_item_add_edit;
break;
case Request::show_dir:
p = &pat_dir;
break;
case Request::show_item:
p = &pat_item;
break;
case Request::del_item_confirm:
p = &pat_item_del_confirm;
break;
case Request::err_internal:
p = &pat_err_internal;
break;
case Request::err404:
default:
p = &pat_err_404;
}
Generator gen(i.out, *p, functions);
gen.Generate();
}
void base_url(Info & i)
{
i.out << data.base_url;
}
void current_url(Info & i)
{
if( request.env_request_uri )
i.out << request.env_request_uri;
else
base_url(i);
}
void user_logged(Info & i)
{
i.result = request.session->is_logged;
}
void user(Info & i)
{
i.out << request.session->user;
}
void item_id(Info & i)
{
i.out << request.item.id;
}
void item_subject(Info & i)
{
i.out << HtmlSpecial(request.item.subject);
}
void item_content(Info & i)
{
//i.out << HtmlSpecial(request.item.content);
i.out << request.item.content;
}
void item_url_subject(Info & i)
{
i.out << request.item.url_subject;
}
void item_dir(Info & i)
{
std::string path;
if( data.dir.MakePath(request.item.parent_id, path) )
{
i.out << path;
}
else
{
i.out << "problem with generating a path";
}
}
// ---------
void old_item_id(Info & i)
{
i.out << request.session->item.id;
}
void old_item_subject(Info & i)
{
i.out << HtmlSpecial(request.session->item.subject);
}
void old_item_content(Info & i)
{
//i.out << HtmlSpecial(request.session->item.content);
i.out << request.session->item.content;
}
void old_item_url_subject(Info & i)
{
i.out << request.session->item.url_subject;
}
void old_item_dir(Info & i)
{
std::string path;
if( data.dir.MakePath(request.session->item.parent_id, path) )
{
i.out << path;
}
else
{
i.out << "problem with generating a path";
}
}
// ----
void full_dir(Info & i)
{
std::vector<Item>::size_type a;
for(a=0 ; a<request.cur_dir_table.size() ; ++a)
{
i.out << request.cur_dir_table[a].url_subject << '/';
}
}
std::vector<Item>::size_type item_index, dir_index;
void dir_items(Info & i)
{
if( i.iter >= (int)request.dir_table.size() )
{
i.result = false;
}
else
{
i.result = true;
dir_index = i.iter;
}
}
void dir_subject2(Info & i)
{
if( dir_index < request.dir_table.size() )
{
if( request.dir_table[dir_index].subject.empty() )
i.out << "bez nazwy";
else
HtmlSpecial(i.out, request.dir_table[dir_index].subject);
}
}
void dir_url_subject2(Info & i)
{
if( dir_index < request.dir_table.size() )
{
HtmlSpecial(i.out, request.dir_table[dir_index].url_subject);
}
}
void items(Info & i) // zamienic na fitems !!
{
if( i.iter >= (int)request.item_table.size() )
{
i.result = false;
}
else
{
i.result = true;
item_index = i.iter;
}
}
void item_subject2(Info & i)
{
if( item_index < request.item_table.size() )
{
if( request.item_table[item_index].subject.empty() )
i.out << "bez nazwy";
else
HtmlSpecial(i.out, request.item_table[item_index].subject);
}
}
void item_url_subject2(Info & i)
{
if( item_index < request.item_table.size() )
HtmlSpecial(i.out, request.item_table[item_index].url_subject);
}
void item_content2(Info & i)
{
if( item_index < request.item_table.size() )
//HtmlSpecial(i.out, request.item_table[item_index].content);
i.out << request.item_table[item_index].content;
}
void item_id2(Info & i)
{
if( item_index < request.item_table.size() )
i.out << request.item_table[item_index].id;
}
void incorrect_dir(Info & i)
{
if( request.session->done_status == Error::incorrect_dir )
i.result = true;
else
i.result = false;
}
std::vector<Item>::size_type current_dir_index;
void fcurrent_dir(Info & i)
{
if( i.iter < (int)request.cur_dir_table.size() )
{
current_dir_index = i.iter;
i.result = true;
}
else
i.result = false;
}
void current_dir_part_name(Info & i)
{
if( current_dir_index < request.cur_dir_table.size() )
i.out << request.cur_dir_table[current_dir_index].subject;
}
void current_dir_part_url(Info & i)
{
std::vector<Item>::size_type a;
i.out << data.base_url;
for(a = 0 ; a <= current_dir_index && a < request.cur_dir_table.size() ; ++a)
{
i.out << request.cur_dir_table[a].url_subject << '/';
}
}
void edit_item(Info & i)
{
i.result = request.result == Request::edit_item;
}
void added_item(Info &i)
{
i.result = request.session->done == Done::added_item;
}
void edited_item(Info &i)
{
i.result = request.session->done == Done::edited_item;
}
void deleted_item(Info &i)
{
i.result = request.session->done == Done::deleted_item;
}
// zostawic tylko jedna funkcje done_with_errors (bedzie uzywana do roznych celow) !!
void deleted_item_errors(Info & i)
{
i.result = request.session->done_status != Error::ok;
}
void done_with_errors(Info & i)
{
i.result = request.session->done_status != Error::ok;
}
void done_status(Info & i)
{
i.out << static_cast<int>( request.session->done_status );
}
void fitems_in_dir(Info & i)
{
// i.out << "abc: " << variables["fitems_directory"];
}
void loggedout(Info & i)
{
i.result = request.session->done == Done::loggedout;
}
} // namespace TemplatesFunctions
void Templates::CreateFunctions()
{
using namespace TemplatesFunctions;
functions.Clear();
functions.Insert("language", language);
functions.Insert("title", title);
functions.Insert("charset", charset);
functions.Insert("content", content);
functions.Insert("version_major", version_major);
functions.Insert("version_minor", version_minor);
functions.Insert("version_revision", version_revision);
functions.Insert("base_url", base_url);
functions.Insert("current_url", current_url);
functions.Insert("user_logged", user_logged);
functions.Insert("user", user);
functions.Insert("item_id", item_id);
functions.Insert("item_subject", item_subject);
functions.Insert("item_content", item_content);
functions.Insert("item_url_subject", item_url_subject);
functions.Insert("item_dir", item_dir);
functions.Insert("old_item_id", old_item_id);
functions.Insert("old_item_subject", old_item_subject);
functions.Insert("old_item_content", old_item_content);
functions.Insert("old_item_url_subject", old_item_url_subject);
functions.Insert("old_item_dir", old_item_dir);
functions.Insert("dir_items", dir_items);
functions.Insert("items", items);
functions.Insert("item_subject2", item_subject2);
functions.Insert("dir_subject2", dir_subject2);
functions.Insert("full_dir", full_dir);
functions.Insert("dir_url_subject2", dir_url_subject2);
functions.Insert("item_url_subject2", item_url_subject2);
functions.Insert("item_content2", item_content2);
functions.Insert("item_id2", item_id2);
functions.Insert("edit_item", edit_item);
functions.Insert("incorrect_dir", incorrect_dir);
functions.Insert("fcurrent_dir", fcurrent_dir);
functions.Insert("current_dir_part_name", current_dir_part_name);
functions.Insert("current_dir_part_url", current_dir_part_url);
functions.Insert("added_item", added_item);
functions.Insert("edited_item", edited_item);
functions.Insert("deleted_item", deleted_item);
functions.Insert("loggedout", loggedout);
functions.Insert("deleted_item_errors", deleted_item_errors);
functions.Insert("done_with_errors", done_with_errors);
functions.Insert("done_status", done_status);
functions.Insert("fitems_in_dir", fitems_in_dir);
}
void Templates::Read()
{
using namespace TemplatesFunctions;
pat_index.Directory(data.templates);
pat_index.ParseFile(data.default_index);
pat_item.Directory(data.templates);
pat_item.ParseFile("item.html");
pat_dir.Directory(data.templates);
pat_dir.ParseFile("dir.html");
pat_item_add_edit.Directory(data.templates);
pat_item_add_edit.ParseFile("item_add_edit.html");
pat_err_404.Directory(data.templates);
pat_err_404.ParseFile("err_404.html");
pat_item_del_confirm.Directory(data.templates);
pat_item_del_confirm.ParseFile("item_del_confirm.html");
pat_err_internal.Directory(data.templates);
pat_err_internal.ParseFile("err_internal.html");
CreateFunctions();
}
void Templates::Generate()
{
using namespace TemplatesFunctions;
// clear some variables (indexes for example)
item_index = 0;
current_dir_index = 0;
Generator generator(request.page, pat_index, functions);
generator.Generate();
}

View File

@@ -1,44 +0,0 @@
/*
* This file is a part of CMSLU -- Content Management System like Unix
* and is not publicly distributed
*
* Copyright (c) 2008, Tomasz Sowa
* All rights reserved.
*
*/
#ifndef headerfiletemplates
#define headerfiletemplates
#include "../../ezc/src/ezc.h"
#include "data.h"
#include "request.h"
#include "item.h"
#include "db.h"
#include "error.h"
using namespace Ezc;
class Templates
{
public:
void Read();
void Generate();
void CreateFunctions();
};
#endif

182
winixd/Makefile Normal file
View File

@@ -0,0 +1,182 @@
# Makefile for GNU make
include Makefile.dep
# https://www.gnu.org/software/make/manual/html_node/Flavors.html#Flavors
GLOBAL_WORKING_DIR := $(shell pwd)/../..
current_path := $(shell pwd)
global_relative_working_dir := $(shell relative_path $(current_path) $(GLOBAL_WORKING_DIR))
ifeq ($(CXX), g++)
CXX = g++6
endif
ifndef CXX
ifeq ($(OSTYPE), FreeBSD)
CXX = clang++
else
CXX = g++6
endif
endif
# CXX = g++-4.8
ifndef CXXFLAGS
CXXFLAGS = -Wall -O0 -g -fPIC -pthread -std=c++17 -I/usr/local/include -I/usr/include/postgresql -DEZC_HAS_SPECIAL_STREAM
endif
ifndef AR
AR = ar
endif
winix_include_paths = -I$(global_relative_working_dir)/winix/winixd -I$(global_relative_working_dir)/ezc/src -I$(global_relative_working_dir)/tito/src -I$(global_relative_working_dir)/morm/src -I$(global_relative_working_dir)/pikotools
ifndef LDFLAGS
LDFLAGS = -L/usr/local/lib
endif
# for make install
winix_install_dir = /usr/local/winix
export CXX
export CXXFLAGS
export LDFLAGS
export GLOBAL_WORKING_DIR
all: winix.so plugins winix
winix.so: $(winix.src.files)
@cd core ; $(MAKE) -e
@cd db ; $(MAKE) -e
@cd functions ; $(MAKE) -e
@cd notify ; $(MAKE) -e
@cd templates ; $(MAKE) -e
@cd $(GLOBAL_WORKING_DIR)/ezc/src ; $(MAKE) -e
@cd $(GLOBAL_WORKING_DIR)/tito/src ; $(MAKE) -e
@cd $(GLOBAL_WORKING_DIR)/pikotools ; $(MAKE) -e
@cd $(GLOBAL_WORKING_DIR)/morm/src ; $(MAKE) -e
$(CXX) -shared -rdynamic -Wl,-whole-archive -o winix.so $(CXXFLAGS) $(winix_include_paths) core/*.o db/*.o functions/*.o templates/*.o notify/*.o $(GLOBAL_WORKING_DIR)/ezc/src/ezc.a $(GLOBAL_WORKING_DIR)/tito/src/tito.a $(GLOBAL_WORKING_DIR)/pikotools/convert/convert.a $(GLOBAL_WORKING_DIR)/pikotools/utf8/utf8.a $(GLOBAL_WORKING_DIR)/pikotools/space/space.a $(GLOBAL_WORKING_DIR)/pikotools/mainparser/mainparser.a $(GLOBAL_WORKING_DIR)/pikotools/date/date.a $(GLOBAL_WORKING_DIR)/pikotools/log/log.a $(GLOBAL_WORKING_DIR)/morm/src/morm.a $(LDFLAGS) -lfcgi -lpq -lz -lpthread -lcurl -Wl,-no-whole-archive
winix: winix.so $(winix.src.files)
@cd main ; $(MAKE) -e
$(CXX) -o winix $(CXXFLAGS) $(LDFLAGS) main/*.o winix.so -lfcgi
plugins: FORCE
@cd plugins/stats ; $(MAKE) -e
@cd plugins/thread ; $(MAKE) -e
@cd plugins/ticket ; $(MAKE) -e
@cd plugins/gallery ; $(MAKE) -e
@cd plugins/group ; $(MAKE) -e
@cd plugins/menu ; $(MAKE) -e
@cd plugins/export ; $(MAKE) -e
@cd plugins/mailregister ; $(MAKE) -e
@cd plugins/seo ; $(MAKE) -e
FORCE:
clean:
@cd core ; $(MAKE) -e clean
@cd db ; $(MAKE) -e clean
@cd functions ; $(MAKE) -e clean
@cd templates ; $(MAKE) -e clean
@cd notify ; $(MAKE) -e clean
@cd plugins/stats ; $(MAKE) -e clean
@cd plugins/thread ; $(MAKE) -e clean
@cd plugins/ticket ; $(MAKE) -e clean
@cd plugins/gallery ; $(MAKE) -e clean
@cd plugins/group ; $(MAKE) -e clean
@cd plugins/menu ; $(MAKE) -e clean
@cd plugins/export ; $(MAKE) -e clean
@cd plugins/mailregister ; $(MAKE) -e clean
@cd plugins/seo ; $(MAKE) -e clean
@cd $(GLOBAL_WORKING_DIR)/ezc/src ; $(MAKE) -e clean
@cd $(GLOBAL_WORKING_DIR)/tito/src ; $(MAKE) -e clean
@cd $(GLOBAL_WORKING_DIR)/pikotools ; $(MAKE) -e clean
@cd $(GLOBAL_WORKING_DIR)/morm/src ; $(MAKE) -e clean
@cd main ; $(MAKE) -e clean
rm -f winix.so
rm -f winix
depend:
@cd core ; $(MAKE) -e depend
@cd db ; $(MAKE) -e depend
@cd functions ; $(MAKE) -e depend
@cd templates ; $(MAKE) -e depend
@cd notify ; $(MAKE) -e depend
@cd plugins/stats ; $(MAKE) -e depend
@cd plugins/thread ; $(MAKE) -e depend
@cd plugins/ticket ; $(MAKE) -e depend
@cd plugins/gallery ; $(MAKE) -e depend
@cd plugins/group ; $(MAKE) -e depend
@cd plugins/menu ; $(MAKE) -e depend
@cd plugins/export ; $(MAKE) -e depend
@cd plugins/mailregister ; $(MAKE) -e depend
@cd plugins/seo ; $(MAKE) -e depend
@cd $(GLOBAL_WORKING_DIR)/ezc/src ; $(MAKE) -e depend
@cd $(GLOBAL_WORKING_DIR)/tito/src ; $(MAKE) -e depend
@cd $(GLOBAL_WORKING_DIR)/pikotools ; $(MAKE) -e depend
@cd main ; $(MAKE) -e depend
echo -n "winix.src.files = " > Makefile.dep
find -E . -type f -regex ".*\.h|.*\.cpp" | xargs -I foo echo -n foo " " >> Makefile.dep
# use $(global_relative_working_dir) here to put relative paths to Makefile.dep
find -E $(global_relative_working_dir)/ezc/src -type f -regex ".*\.h|.*\.cpp" | xargs -I foo echo -n foo " " >> Makefile.dep
find -E $(global_relative_working_dir)/tito/src -type f -regex ".*\.h|.*\.cpp" | xargs -I foo echo -n foo " " >> Makefile.dep
find -E $(global_relative_working_dir)/pikotools -type f -regex ".*\.h|.*\.cpp" | xargs -I foo echo -n foo " " >> Makefile.dep
find -E $(global_relative_working_dir)/morm/src -type f -regex ".*\.h|.*\.cpp" | xargs -I foo echo -n foo " " >> Makefile.dep
install: all
# installing binaries
rm -Rf $(winix_install_dir)/bin
mkdir -p $(winix_install_dir)/bin
cp winix $(winix_install_dir)/bin
cp winix.so $(winix_install_dir)/bin
# etc configs
rm -Rf $(winix_install_dir)/etc
mkdir -p $(winix_install_dir)/etc
cp -rf etc/* $(winix_install_dir)/etc/
# html templates
rm -Rf $(winix_install_dir)/html
mkdir -p $(winix_install_dir)/html
cp -rf html/* $(winix_install_dir)/html/
# txt templates
rm -Rf $(winix_install_dir)/txt
mkdir -p $(winix_install_dir)/txt
cp -rf txt/* $(winix_install_dir)/txt/
# locales
rm -Rf $(winix_install_dir)/locale
mkdir -p $(winix_install_dir)/locale
cp -rf locale/* $(winix_install_dir)/locale/
# plugins
rm -Rf $(winix_install_dir)/plugins
mkdir -p $(winix_install_dir)/plugins
find plugins/ -name "*.so" | xargs -I foo cp foo $(winix_install_dir)/plugins/
# deleting subversion directories
find $(winix_install_dir) -type d -name ".svn" | xargs -I foo rm -fr foo
# removing privileges for others
find $(winix_install_dir) -exec chmod o-r,o-x,o-w "{}" "+"

1
winixd/Makefile.dep Normal file

File diff suppressed because one or more lines are too long

24
winixd/core/Makefile Normal file
View File

@@ -0,0 +1,24 @@
include Makefile.o.dep
current_path := $(shell pwd)
global_relative_working_dir := $(shell relative_path $(current_path) $(GLOBAL_WORKING_DIR))
winix_include_paths = -I$(global_relative_working_dir)/winix/winixd -I$(global_relative_working_dir)/ezc/src -I$(global_relative_working_dir)/tito/src -I$(global_relative_working_dir)/morm/src -I$(global_relative_working_dir)/pikotools
all: $(o)
%.o: %.cpp
$(CXX) -c $(CXXFLAGS) $(winix_include_paths) $<
depend:
makedepend -Y. $(winix_include_paths) -f- *.cpp > Makefile.dep
echo -n "o = " > Makefile.o.dep
ls -1 *.cpp | xargs -I foo echo -n foo " " | sed -E "s/([^\.]*)\.cpp[ ]/\1\.o/g" >> Makefile.o.dep
clean:
rm -f *.o
include Makefile.dep

1593
winixd/core/Makefile.dep Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1 @@
o = acceptbaseparser.o app.o basethread.o bbcodeparser.o compress.o config.o crypt.o dircontainer.o dirs.o filelog.o groups.o htmlfilter.o httpsimpleparser.o image.o ipbancontainer.o item.o job.o lastcontainer.o loadavg.o lock.o log.o misc.o mount.o mountparser.o mounts.o plugin.o plugindata.o postmultiparser.o rebus.o request.o run.o session.o sessioncontainer.o sessionidmanager.o sessionmanager.o sessionparser.o slog.o synchro.o system.o threadmanager.o timezone.o timezones.o user.o users.o winixbase.o winixmodel.o winixrequest.o winixsystem.o

View File

@@ -0,0 +1,138 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2008-2014, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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.
*
*/
#include <wchar.h>
#include "acceptbaseparser.h"
#include "misc.h"
namespace Winix
{
bool AcceptBaseParser::IsWhite(int c)
{
if( c==' ' || c=='\t' )
return true;
return false;
}
void AcceptBaseParser::SkipWhite()
{
while( IsWhite(*text) )
++text;
}
void AcceptBaseParser::ReadParameter()
{
param.clear();
SkipWhite();
while( *text!=0 && *text!=',' && *text!=';' )
{
param += *text;
++text;
}
TrimWhite(param);
}
void AcceptBaseParser::ReadQ()
{
q = 1.0;
SkipWhite();
if( *text != ';' )
return;
++text; // skipping a semicolon
while( *text!=0 && *text!=',' && *text!='=' )
// skipping until ',' or '='
++text;
if( *text==0 || *text==',' )
return;
++text; // skipping '='
SkipWhite();
q = wcstod(text, (wchar_t**)&text);
}
void AcceptBaseParser::SkipParam()
{
SkipWhite();
if( *text == ',' )
++text;
}
void AcceptBaseParser::Parse(const wchar_t * str)
{
text = str;
Init();
while( *text != 0 )
{
ReadParameter();
ReadQ();
SkipParam();
Param(param, q);
}
}
void AcceptBaseParser::Parse(const std::wstring & str)
{
Parse(str.c_str());
}
} // namespace Winix

View File

@@ -0,0 +1,81 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2008-2018, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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 headerfile_winix_core_acceptbaseparser
#define headerfile_winix_core_acceptbaseparser
#include <string>
#include "winixbase.h"
namespace Winix
{
// sample (you must create your own class derived from this one):
// object.Parse(L" text/html ; , ; q = 45, application / xhtml+xml ; q = 0.4 , application/xml ; q = 0.9 , */* ; q = 0.8 ");
class AcceptBaseParser : public WinixBase
{
public:
void Parse(const wchar_t * str);
void Parse(const std::wstring & str);
private:
virtual void Init() {} ;
virtual void Param(const std::wstring & param, double q) = 0;
bool IsWhite(int c);
void SkipWhite();
void ReadParameter();
void ReadQ();
void SkipParam();
const wchar_t * text;
std::wstring param;
double q;
};
} // namespace Winix
#endif

View File

@@ -0,0 +1,124 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2008-2014, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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 headerfile_winix_core_acceptencodingparser
#define headerfile_winix_core_acceptencodingparser
#include "acceptbaseparser.h"
#include "log.h"
namespace Winix
{
class AcceptEncodingParser : public AcceptBaseParser
{
public:
bool AcceptDeflate()
{
return accept_deflate;
}
bool AcceptGzip()
{
return accept_gzip;
}
void ParseAndLog(const wchar_t * str)
{
Parse(str);
if( accept_deflate || accept_gzip )
{
log << log3 << "AEP: ";
if( accept_deflate )
{
log << "accept deflate";
if( accept_gzip )
log << ", ";
}
if( accept_gzip )
log << "accept gzip";
log << logend;
}
}
void ParseAndLog(const std::wstring & str)
{
ParseAndLog(str.c_str());
}
private:
void Init()
{
accept_deflate = false;
accept_gzip = false;
}
void Param(const std::wstring & param, double q)
{
if( param == L"deflate" && q!=0.0 )
{
accept_deflate = true;
}
if( param == L"gzip" && q!=0.0 )
{
accept_gzip = true;
}
}
bool accept_deflate;
bool accept_gzip;
};
} // namespace Winix
#endif

2255
winixd/core/app.cpp Normal file

File diff suppressed because it is too large Load Diff

281
winixd/core/app.h Normal file
View File

@@ -0,0 +1,281 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2010-2018, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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 headerfile_winix_core_app
#define headerfile_winix_core_app
#include <iostream>
#include <ctime>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <pwd.h>
#include <grp.h>
#include <errno.h>
#include <fcgiapp.h>
#include "sessionmanager.h"
#include "db/db.h"
#include "functions/functions.h"
#include "templates/templates.h"
#include "compress.h"
#include "postparser.h"
#include "cookieparser.h"
#include "postmultiparser.h"
#include "acceptencodingparser.h"
#include "space/jsontospaceparser.h"
#include "winixrequest.h"
#include "log/log.h"
#include "filelog.h"
namespace Winix
{
class App
{
public:
App();
bool InitFCGI();
bool DropPrivileges();
void InitLoggers();
Log & GetMainLog();
void InitPlugins();
bool Init();
void Start();
void Close();
void LogUserGroups();
bool Demonize();
void SetStopSignal();
bool WasStopSignal();
bool Lock();
void Unlock();
void StartThreads();
void WaitForThreads();
// configuration read from a config file
Config config;
// pointers to the current request and a session
Cur cur;
// temporary one request object
// current request
Request req;
// users sessions
SessionManager session_manager;
// database (DEPRACATED)
Db db;
DbConn db_conn;
/*
model
*/
// ...
System system;
// functions (ls, cat, emacs, ...)
Functions functions;
// false at the beginning
// !! IMPROVE ME moze to do loggera dac?
bool stdout_is_closed;
/*
view
*/
Templates templates;
private:
enum Header
{
h_200,
h_404,
h_403
};
PostParser post_parser;
PostMultiParser post_multi_parser;
PT::JSONToSpaceParser post_json_parser;
std::string post_buffer;
CookieParser cookie_parser;
AcceptEncodingParser accept_encoding_parser;
Compress compress;
FCGX_Request fcgi_request;
int fcgi_socket;
Synchro synchro;
pthread_t signal_thread;
std::string socket_to_send_on_exit;
std::string send_data_buf;
PT::SpaceToJSON json_generic_serializer;
TextStream<std::wstring> json_out_stream;
std::string aheader_name, aheader_value;
std::wstring html_filtered;
std::string output_8bit;
BinaryPage compressed_output;
std::wstring cookie_id_string;
std::wstring http_header;
std::string http_header_8bit;
morm::ModelConnector model_connector; // main thread model connector, each thread has its own connector
morm::JSONConnector json_connector;
morm::PostgreSQLConnector postgresql_connector;
// objects for main thread
WinixBase winix_base;
WinixModel winix_model;
WinixSystem winix_system;
WinixRequest winix_request;
// ///////////////////////
Plugin plugin;
//////////////////////////
// log_buffer for the main thread
PT::WTextStream log_buffer;
// logger only for App object
Log log;
// file logger, one object for every Log objects
FileLog file_log;
bool InitFCGI(char * sock, char * sock_user, char * sock_group);
bool InitFCGIChmodChownSocket(char * sock, char * sock_user, char * sock_group);
bool DropPrivileges(char * user, char * group);
bool DropPrivileges(const char * user, uid_t uid, gid_t gid, bool additional_groups);
bool CheckAccessFromPlugins();
void ProcessRequestThrow();
void ProcessRequest();
void BaseUrlRedirect(int code, bool add_subdomain);
bool BaseUrlRedirect();
void CheckIfNeedSSLredirect();
void SetLocale();
void CheckPostRedirect();
void MakePage();
void Make();
void SaveSessionsIfNeeded(); // !! IMPROVE ME wywalic do menagera sesji??
void LogAccess();
void SendData(const BinaryPage & page, FCGX_Stream * out);
void CreateJSONAnswer();
void ReadRequest();
void SendTextAnswer();
void SendBinaryAnswer();
void SendAnswer();
void LogEnvironmentVariables();
void LogEnvironmentHTTPVariables();
void SetEnv(const char * name, std::wstring & env);
void ReadEnvVariables();
void ReadEnvHTTPVariables();
bool SaveEnvHTTPVariable(const char * env);
void ReadEnvRemoteIP();
void ReadPostJson();
void ReadPostVars();
void CheckIE();
void CheckKonqueror();
void CheckRequestMethod();
void CheckSSL();
void SetSubdomain();
Header GetHTTPStatusCode();
void PrepareSessionCookie();
void FilterContent();
void SendHeaders();
void SendCookies();
bool AddHeader(const wchar_t * name, const wchar_t * value);
bool AddHeader(const std::wstring & name, const std::wstring & value);
bool AddHeader(const wchar_t * name, const PT::WTextStream & value);
bool AddHeader(const std::wstring & name, const PT::WTextStream & value);
bool PrepareHeadersStaticCreateResource(PT::WTextStream & out_path);
void PrepareHeadersStatic();
void PrepareHeaderContentType();
void PrepareHeadersForbidden();
void PrepareHeadersRedirect();
void PrepareHeadersSendFile();
void PrepareHeadersCompression(int compress_encoding);
void PrepareHeadersNormal(Header header, size_t output_size);
void PrepareHeaders(bool compressing, int compress_encoding, Header header, size_t output_size);
void PrepareStandardJSONFields();
int SelectDeflateVersion();
void SelectCompression(size_t source_len, bool & compression_allowed, int & compression_encoding);
bool CanSendContent();
void ClearAfterRequest();
void LogUser(const char * msg, uid_t id);
void LogGroup(const char * msg, gid_t id, bool put_logend = true);
void LogUsers();
void LogEffectiveGroups(std::vector<gid_t> & tab);
void LogGroups();
static void * SpecialThreadForSignals(void*);
void SendEmptyFastCGIPacket();
void CreateStaticTree();
// !! IMPROVE ME
// !! move to the session manager?
time_t last_sessions_save;
};
} // namespace Winix
#endif

280
winixd/core/basethread.cpp Normal file
View File

@@ -0,0 +1,280 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2010-2019, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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.
*
*/
#include <errno.h>
#include "basethread.h"
namespace Winix
{
BaseThread::BaseThread() : thread_signal(PTHREAD_COND_INITIALIZER)
{
synchro = 0;
thread_id = 0;
work_mode = 0;
wake_up_was_called = false;
}
BaseThread::~BaseThread()
{
}
void BaseThread::set_main_log_buffer(PT::WTextStream * log_buffer)
{
main_log.SetLogBuffer(log_buffer);
}
void BaseThread::set_main_file_log(PT::FileLog * file_log)
{
main_log.SetFileLog(file_log);
}
void BaseThread::Mode(int mode)
{
work_mode = mode;
}
pthread_t BaseThread::ThreadId()
{
return thread_id;
}
bool BaseThread::Lock()
{
return synchro->Lock();
}
void BaseThread::Unlock()
{
synchro->Unlock();
}
bool BaseThread::IsExitSignal()
{
bool res = true;
if( Lock() )
{
res = synchro->was_stop_signal;
Unlock();
}
return res;
}
bool BaseThread::BaseInit()
{
bool init_status = false;
if( Lock() )
{
init_status = Init(); // your virtual method
Unlock();
}
return init_status;
}
void BaseThread::BaseUninit()
{
if( Lock() )
{
Uninit(); // your virtual method
Unlock();
}
}
bool BaseThread::BaseSignalReceived()
{
bool make_do = false;
wake_up_was_called = false;
try
{
make_do = SignalReceived(); // your short-time virtual method (objects are locked)
}
catch(...)
{
}
return make_do;
}
// this is called only if your SignalReceived() returned true
void BaseThread::BaseDo()
{
try
{
Do(); // your long-time virtual method (objects are *not* locked)
}
catch(...)
{
}
}
// use it with Lock and Unlock
bool BaseThread::WaitForSignal()
{
if( synchro->was_stop_signal || wake_up_was_called )
return true;
return pthread_cond_wait(&thread_signal, &synchro->mutex) == 0;
}
// you should use this method with: synchro->Lock() and Unlock()
void BaseThread::WakeUpThread()
{
wake_up_was_called = true;
pthread_cond_signal(&thread_signal);
}
// use it with Lock and Unlock
// it breaks only if there was a stop signal or the time has expired
bool BaseThread::WaitForSignalSleep(time_t second)
{
timespec t;
int res;
if( synchro->was_stop_signal )
return true;
t.tv_sec = time(0) + second;
t.tv_nsec = 0;
do
{
res = pthread_cond_timedwait(&thread_signal, &synchro->mutex, &t);
}
while( res == 0 && !synchro->was_stop_signal );
// above condition means there was a signal
// but it was not a stop signal so we should still wait
return res == 0 || res == ETIMEDOUT;
}
void BaseThread::WaitForThread()
{
pthread_join(thread_id, 0);
}
void BaseThread::SignalLoop()
{
bool make_do;
do
{
if( Lock() )
{
make_do = false;
if( WaitForSignal() ) // automatically unlock, wait and lock again when signal comes
if( !synchro->was_stop_signal )
make_do = BaseSignalReceived(); // your short-time virtual method will be called (objects locked)
Unlock(); // unlocking from WaitForSignal()
if( make_do )
BaseDo(); // your long-time virtual method will be called (objects *not* locked)
}
}
while( !IsExitSignal() );
}
void * BaseThread::StartRoutine(void * this_object)
{
BaseThread * base = reinterpret_cast<BaseThread*>(this_object);
if( base->synchro )
{
if( base->BaseInit() )
{
if( base->work_mode == 0 )
base->SignalLoop();
else
base->Work();
base->BaseUninit();
}
}
pthread_exit(0);
return 0;
}
bool BaseThread::StartThread()
{
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
int res = pthread_create(&thread_id, &attr, StartRoutine, this);
pthread_attr_destroy(&attr);
return res == 0;
}
} // namespace Winix

168
winixd/core/basethread.h Normal file
View File

@@ -0,0 +1,168 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2010-2019, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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 headerfile_winix_core_basethread
#define headerfile_winix_core_basethread
#include <pthread.h>
#include "synchro.h"
#include "winixmodel.h"
namespace Winix
{
class BaseThread : public WinixModel
{
public:
BaseThread();
virtual ~BaseThread();
void set_main_log_buffer(PT::WTextStream * log_buffer);
void set_main_file_log(PT::FileLog * file_log);
// work mode
// we have two modes:
// 0 - there is a loop with SignalReceived() and Do()
// if SignalReceived() returns true then Do() is called
// 1 - only Work() method is called
// the thread exits after Work() has finished
// default: 0
void Mode(int mode);
// starting the second thread
bool StartThread();
// virtual methods which should/can be inherited by your class
// the methods will be called from the other thread
// wake up the second thread
// (if it waits for the signal)
// you should use it with: synchro->Lock() and Unlock()
// if the thread doesn't wait on a signal then nothing is done
virtual void WakeUpThread();
// waiting until the thread exits
// you should call WakeUpThread() before
virtual void WaitForThread();
// initialize the thread
// (global objects are locked)
// if it returns false then the thread immediately exits
// default: true
virtual bool Init() { return true; }
// uninitialize the thread
// this is called before the thread is prepare to detach
// (global objects are locked)
// it's called only if Init() returned true
virtual void Uninit() {}
// returns the thread id
// this identifier is set by StartThread() metdhod
pthread_t ThreadId();
protected:
// logger for the main thread
Log main_log;
// log from WinixBase is meant to be used by the other thread
protected:
// signal came (work mode = 0 - default)
// signal comes when an other thread calls WakeUpThread() method
// check specific job and return true to call Do() next
// (global objects are locked -- copy some global objects to local variables)
virtual bool SignalReceived() { return false; };
// if SignalReceived() returned true then this method is called
// global objects are *not* locked -- use only your local variables
// if you have to do something on global objects use synchro->Lock() and synchro->Unlock()
virtual void Do() {}
// this method is called after Init() when Mode(1) is used
// this is for long-time job
// this method is called only once
// global objects are *not* locked
virtual void Work() {}
protected:
pthread_t thread_id; // thread id - set by StartThread()
pthread_cond_t thread_signal;
int work_mode;
bool wake_up_was_called;
void SignalLoop();
static void * StartRoutine(void *);
bool BaseInit();
void BaseUninit();
bool BaseSignalReceived();
void BaseDo();
bool WaitForSignal();
bool WaitForSignalSleep(time_t second);
bool Lock();
void Unlock();
// if the work done by Do() is long time consuming you should periodically check
// wheter there was a signal for exiting, and if it was just simply return from Do()
// (it's checking with locking and unlocking)
bool IsExitSignal();
};
} // namespace Winix
#endif

View File

@@ -0,0 +1,636 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2008-2018, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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.
*
*/
#include "bbcodeparser.h"
namespace Winix
{
bool BBCODEParser::Equal(const wchar_t * str1, const wchar_t * str2)
{
while( *str1 == *str2 && *str1 != 0 )
{
str1 += 1;
str2 += 1;
}
return *str1 == *str2;
}
bool BBCODEParser::IsValidCharForName(int c)
{
if( (c>='a' && c<='z') ||
(c>='A' && c<='Z') ||
c=='*' || c=='_')
return true;
return false;
}
bool BBCODEParser::IsOpeningTagMark(wchar_t c)
{
return (c == '[');
}
bool BBCODEParser::IsClosingTagMark(wchar_t c)
{
return (c == ']');
}
bool BBCODEParser::IsClosingXmlSimpleTagMark(wchar_t c)
{
return false;
}
// there are no commentaries in bbcode
bool BBCODEParser::IsOpeningCommentaryTagMark(const wchar_t *)
{
return false;
}
size_t BBCODEParser::OpeningCommentaryTagMarkSize()
{
return 0;
}
bool BBCODEParser::SkipCommentaryTagIfExists()
{
return false;
}
// one enter will generate one <br>
// two enters or more will generate only two br (<br><br>)
void BBCODEParser::PutNormalText(const wchar_t * str, const wchar_t * end)
{
int br_len;
if( *pchar == 0 )
{
// trimming last white characters at end of the user text
while( str<end && (IsWhite(*(end-1)) || *(end-1)==10) )
--end;
}
while( str < end )
{
if( *str == 10 )
{
++str;
br_len = 1;
// skipping white characters without a new line character
while( str < end && IsWhite(*str) )
++str;
if( str < end && *str == 10 )
{
br_len = 2;
// skipping white characters with new line characters
while( str < end && (IsWhite(*str) || *str==10) )
++str;
}
if( !has_open_ol_tag && !has_open_ul_tag && !has_open_li_tag )
{
for(int i=0 ; i < br_len ; ++i)
(*out_string) += L"<br>\n";
}
}
else
{
PrintEscape(*str);
++str;
}
}
}
void BBCODEParser::ReadNormalTextSkipWhite(const wchar_t * & start, const wchar_t * & last_non_white)
{
}
void BBCODEParser::CheckExceptions()
{
if( stack_len >= 2 )
{
if( pstack[stack_len-1].type == Item::opening &&
pstack[stack_len-2].type == Item::opening &&
IsNameEqual(L"*", pstack[stack_len-1].name) &&
IsNameEqual(L"*", pstack[stack_len-2].name) )
{
// removing the last [*] from the stack
// </li> was put automatically
PopStack();
}
}
}
/*
bbcode format:
[bbcodetag=value]some text[/bbcodetag]
the value can be quoted, e.g.
[bbcodetag="value"]some text[/bbcodetag], or
[bbcodetag='value']some text[/bbcodetag]
the third string below (in tags table) is 'html_argument' from Tags,
it can contain a special character % followed by a string which means:
%1 - "value" escaped as for html
%2 - "some text" escaped as for html
%u1 - "value" trimmed and escaped as for url-es
%u2 - "some text" trimmed and escaped as for url-es
%% - one %
if you are using %2 or %u2 then "some text" is not treated as bbcode, e.g.
[bbcodetag=value]some [b]text[/b][/bbcodetag] will produce:
<htmltag arg="value">some [b]text[/b]</htmltag> (the inner tags [b][/b] were not parsed)
also when using %2 or %u2 the closing bbcode tag is skipped
(if you want this tag then you can put it in 'html_argument')
and when using u (%u1 or %u2) the argument is trimmed from whitespaces and new lines
at the beginning and at the end
(because otherwise a space would be changed to %20 and this were probably not what you really wanted)
*/
const BBCODEParser::Tags * BBCODEParser::FindTag(const wchar_t * tag)
{
static Tags tags[] = {
{L"*", L"li", L">", false},
{L"b", L"em", L">", true},
{L"i", L"span", L" class=\"bbitalic\">", true},
{L"u", L"span", L" class=\"bbunderline\">", true},
{L"s", L"span", L" class=\"bbstrike\">", true},
{L"code", L"code", L" class=\"bbcode\">", false},
{L"list", L"ul", L" class=\"bblist\">", false},
{L"color", L"span", L" class=\"bbcol%1\">", true},
{L"url", L"a", L" href=\"%u1\">", true},
{L"img", L"img", L" alt=\"%1\" src=\"%u2\">", true},
{L"quote", L"div", L" class=\"bbquote\">\n<span class=\"bbquotewho\">%1</span><br>\n", false},
};
size_t i;
size_t len = sizeof(tags) / sizeof(Tags);
for(i=0 ; i<len ; ++i)
{
if( Equal(tag, tags[i].bbcode) )
return &tags[i];
}
return 0;
}
const BBCODEParser::Tags * BBCODEParser::FindTag(const std::wstring & tag)
{
return FindTag(tag.c_str());
}
void BBCODEParser::PrintArgumentCheckQuotes(const wchar_t * & start, const wchar_t * & end)
{
// skipping white characters from the argument
while( start<end && IsWhite(*start) )
++start;
// skipping first '=' character if exists
if( start<end && *start == '=' )
++start;
// skipping white characters from the argument
// at the beginning
while( start<end && IsWhite(*start) )
++start;
// and at the end
while( start<end && IsWhite(*(end-1)) )
--end;
if( start<end && (*start=='\'' || *start=='\"') )
{
++start;
if( start<end && *(start-1) == *(end-1) )
--end;
// skipping white characters after a first quote char [url = " ww...."]
while( start<end && IsWhite(*start) )
++start;
}
}
void BBCODEParser::PrintEncode(int c)
{
if( c == '&' )
{
(*out_string) += L"&amp;";
}
else
if( (c>='a' && c<='z') ||
(c>='A' && c<='Z') ||
(c>='0' && c<='9') ||
(c=='_' || c=='?' || c=='.' || c==',' || c=='/' || c=='-' ||
c=='+' || c=='*' || c=='(' || c==')' || c=='=' || c==':')
)
{
(*out_string) += c;
}
else
{
wchar_t buffer[20];
swprintf(buffer, 20, L"%02X", c);
(*out_string) += '%';
(*out_string) += buffer;
}
}
void BBCODEParser::PrintEscape(int c, bool change_quote)
{
if( c == '<' )
{
(*out_string) += L"&lt;";
}
else
if( c == '>' )
{
(*out_string) += L"&gt;";
}
else
if( c == '&' )
{
(*out_string) += L"&amp;";
}
else
if( c == '\"' && change_quote )
{
(*out_string) += L"&quot;";
}
else
{
(*out_string) += c;
}
}
void BBCODEParser::PrintArgumentEncode(const wchar_t * start, const wchar_t * end)
{
PrintArgumentCheckQuotes(start, end);
TrimWhiteWithNewLines(start, end);
for( ; start<end ; ++start )
PrintEncode(*start);
}
void BBCODEParser::PrintArgumentEscape(const wchar_t * start, const wchar_t * end)
{
PrintArgumentCheckQuotes(start, end);
for( ; start<end ; ++start )
PrintEscape(*start, true); // quotes are escaped as well here
}
void BBCODEParser::CheckOpeningTag(const Tags * tag, const wchar_t * tag_name, bool & condition)
{
if( Equal(tag->html_tag, tag_name) )
{
if( condition )
{
PutClosingTag(tag);
(*out_string) += '\n';
}
condition = true;
}
}
void BBCODEParser::CheckOpeningTag(const Tags * tag)
{
bool has_list_tag = has_open_ul_tag || has_open_ol_tag;
CheckOpeningTag(tag, L"li", has_open_li_tag);
CheckOpeningTag(tag, L"ul", has_open_ul_tag);
CheckOpeningTag(tag, L"ol", has_open_ol_tag);
if( has_open_li_tag && !has_list_tag )
{
(*out_string) += L"<ul>\n";
has_open_ul_tag = true;
}
}
void BBCODEParser::PrintEscape(const wchar_t * start, const wchar_t * end, bool change_quote)
{
for( ; start < end ; ++start)
PrintEscape(*start, change_quote);
}
void BBCODEParser::PrintEncode(const wchar_t * start, const wchar_t * end)
{
for( ; start < end ; ++start)
PrintEncode(*start);
}
void BBCODEParser::PutOpeningTagFromEzc()
{
// this can be a tag from Ezc templates system
(*out_string) += '[';
(*out_string) += LastItem().name;
const wchar_t * start = pchar;
while( *pchar && *pchar!=']' )
++pchar;
if( *pchar == ']' )
++pchar;
Put(start, pchar);
}
void BBCODEParser::PutHtmlArgument1(const wchar_t * arg_start, const wchar_t * arg_end, bool has_u)
{
if( has_u )
PrintArgumentEncode(arg_start, arg_end);
else
PrintArgumentEscape(arg_start, arg_end);
}
void BBCODEParser::TrimWhiteWithNewLines(const wchar_t * & start, const wchar_t * & end)
{
while( start < end && (IsWhite(*start) || *start==10) )
++start;
while( start < end && (IsWhite(*(end-1)) || *(end-1)==10) )
--end;
}
void BBCODEParser::PutHtmlArgument2(const Tags * tag, bool has_u)
{
const wchar_t * start = pchar;
const wchar_t * end = pchar;
bool first_tag_removed = false;
while( *pchar != 0 )
{
if( IsOpeningTagMark(*pchar) )
{
if( IsClosingTagForLastItem() )
{
// the last tag is skipped when using patterns with %2 or %u2
PopStack(); // removing opening tag from the stack
first_tag_removed = true;
break;
}
}
else
{
pchar += 1;
end = pchar;
}
}
if( !first_tag_removed )
PopStack(); // user has forgotten to close the tag
if( has_u )
{
TrimWhiteWithNewLines(start, end);
PrintEncode(start, end);
}
else
{
PrintEscape(start, end);
}
}
void BBCODEParser::PutHtmlArgument(const Tags * tag, const wchar_t * arg_start, const wchar_t * arg_end)
{
const wchar_t * pattern = tag->html_argument;
bool has_u;
while( *pattern )
{
if( *pattern == '%' )
{
++pattern;
has_u = false;
if( *pattern == 'u' )
{
++pattern;
has_u = true;
}
if( *pattern == '1' )
{
++pattern;
PutHtmlArgument1(arg_start, arg_end, has_u);
}
else
if( *pattern == '2' )
{
++pattern;
PutHtmlArgument2(tag, has_u);
}
else
if( *pattern == '%' )
{
(*out_string) += '%';
++pattern;
}
// else unrecognized, will be printed next time as a normal character
}
else
{
(*out_string) += *pattern;
++pattern;
}
}
}
void BBCODEParser::PutOpeningTagFromBBCode(const Tags * tag)
{
CheckOpeningTag(tag);
PutOpeningTagMark();
Put(tag->html_tag);
const wchar_t * start = pchar;
while( *pchar && *pchar != ']' )
++pchar;
PutHtmlArgument(tag, start, pchar);
if( *pchar == ']' )
++pchar;
if( !tag->inline_tag )
{
Put(10);
SkipWhiteLines();
}
}
bool BBCODEParser::PutOpeningTag()
{
const Tags * tag = FindTag(LastItem().name);
if( !tag )
PutOpeningTagFromEzc();
else
PutOpeningTagFromBBCode(tag);
return false;
}
void BBCODEParser::PutClosingTag(const Tags * tag)
{
if( !tag )
return; // skipping the tag
PutOpeningTagMark();
(*out_string) += '/';
(*out_string) += tag->html_tag;
PutClosingTagMark();
if( !tag->inline_tag )
{
(*out_string) += L"\n";
SkipWhiteLines();
}
if( Equal(tag->html_tag, L"li") )
has_open_li_tag = false;
if( Equal(tag->html_tag, L"ol") )
has_open_ol_tag = false;
if( Equal(tag->html_tag, L"ul") )
has_open_ul_tag = false;
}
void BBCODEParser::PutClosingTag(const wchar_t * tag_name)
{
const Tags * tag = FindTag(tag_name);
PutClosingTag(tag);
}
void BBCODEParser::Init()
{
has_open_li_tag = false;
has_open_ol_tag = false;
has_open_ul_tag = false;
SkipWhiteLines();
}
void BBCODEParser::Uninit()
{
if( has_open_li_tag )
(*out_string) += L"</li>\n";
if( has_open_ol_tag )
(*out_string) += L"</ol>\n";
if( has_open_ul_tag )
(*out_string) += L"</ul>\n";
}
} // namespace Winix

127
winixd/core/bbcodeparser.h Normal file
View File

@@ -0,0 +1,127 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2008-2018, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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 headerfile_winix_core_bbcodeparser
#define headerfile_winix_core_bbcodeparser
#include "htmlfilter.h"
namespace Winix
{
class BBCODEParser : public HTMLFilter
{
struct Tags
{
const wchar_t * bbcode;
const wchar_t * html_tag;
const wchar_t * html_argument; // with closing '>'
bool inline_tag;
};
/*
virtual methods
(from HTMLFilter class)
*/
virtual void Init();
virtual void Uninit();
virtual bool IsOpeningTagMark(wchar_t c);
virtual bool IsClosingTagMark(wchar_t c);
virtual bool IsClosingXmlSimpleTagMark(wchar_t c);
virtual bool IsOpeningCommentaryTagMark(const wchar_t *);
virtual size_t OpeningCommentaryTagMarkSize();
virtual bool IsValidCharForName(int c);
virtual void CheckExceptions();
virtual bool SkipCommentaryTagIfExists();
virtual bool PutOpeningTag();
virtual void PutClosingTag(const wchar_t * tag);
virtual void PutNormalText(const wchar_t * str, const wchar_t * end);
virtual void ReadNormalTextSkipWhite(const wchar_t * & start, const wchar_t * & last_non_white);
/*
others
*/
bool Equal(const wchar_t * str1, const wchar_t * str2);
void PutHtmlArgument1(const wchar_t * arg_start, const wchar_t * arg_end, bool has_u);
void PutHtmlArgument2(const Tags * tag, bool has_u);
void PutHtmlArgument(const Tags * tag, const wchar_t * arg_start, const wchar_t * arg_end);
void PutOpeningTagFromEzc();
void PutOpeningTagFromBBCode(const Tags * tag);
const Tags * FindTag(const wchar_t * tag);
const Tags * FindTag(const std::wstring & tag);
void PrintArgumentCheckQuotes(const wchar_t * & start, const wchar_t * & end);
void PrintEscape(int c, bool change_quote = false);
void PrintEncode(int c);
void PrintEscape(const wchar_t * start, const wchar_t * end, bool change_quote = false);
void PrintEncode(const wchar_t * start, const wchar_t * end);
void PrintArgumentEncode(const wchar_t * start, const wchar_t * end);
void PrintArgumentEscape(const wchar_t * start, const wchar_t * end);
void PutClosingTag(const Tags * tag);
void CheckOpeningTag(const Tags * tag, const wchar_t * tag_name, bool & condition);
void CheckOpeningTag(const Tags * tag);
void TrimWhiteWithNewLines(const wchar_t * & start, const wchar_t * & end);
bool has_open_ol_tag; // has open html <ol> tag
bool has_open_ul_tag; // has open html <ul> tag
bool has_open_li_tag; // has open html <li> tag
};
} // namespace Winix
#endif

433
winixd/core/compress.cpp Normal file
View File

@@ -0,0 +1,433 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2008-2014, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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.
*
*/
#include "compress.h"
#include "log.h"
namespace Winix
{
Compress::Compress()
{
buffer_in = 0;
buffer_out = 0;
buffer_max_len = 65536; // 64KB
ready_for_compress = false;
compress_level = 6;
raw_deflate_inited = false;
deflate_inited = false;
gzip_inited = false;
}
Compress::~Compress()
{
delete [] buffer_in;
delete [] buffer_out;
if( raw_deflate_inited )
deflateEnd(&strm_raw_deflate);
if( deflate_inited )
deflateEnd(&strm_deflate);
if( gzip_inited )
deflateEnd(&strm_gzip);
}
bool Compress::AllocateMemory()
{
if( buffer_in )
delete [] buffer_in;
if( buffer_out )
delete [] buffer_out;
buffer_in = 0;
buffer_out = 0;
try
{
buffer_in = new char[buffer_max_len];
buffer_out = new char[buffer_max_len];
}
catch(const std::bad_alloc &)
{
log << log1 << "Compress: can't allocate memory" << logend;
return false;
}
return true;
}
bool Compress::InitRawDeflate()
{
raw_deflate_inited = false;
strm_raw_deflate.next_in = 0;
strm_raw_deflate.zalloc = Z_NULL;
strm_raw_deflate.zfree = Z_NULL;
strm_raw_deflate.opaque = Z_NULL;
int ret = deflateInit2(&strm_raw_deflate, compress_level, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY);
if( ret != Z_OK )
log << log1 << "Compress: problem with deflateInit2() for raw deflate" << logend;
else
raw_deflate_inited = true;
return ret == Z_OK;
}
bool Compress::InitDeflate()
{
deflate_inited = false;
strm_deflate.next_in = 0;
strm_deflate.zalloc = Z_NULL;
strm_deflate.zfree = Z_NULL;
strm_deflate.opaque = Z_NULL;
int ret = deflateInit2(&strm_deflate, compress_level, Z_DEFLATED, 15, 8, Z_DEFAULT_STRATEGY);
if( ret != Z_OK )
log << log1 << "Compress: problem with deflateInit2() for deflate" << logend;
else
deflate_inited = true;
return ret == Z_OK;
}
bool Compress::InitGzip()
{
gzip_inited = false;
strm_gzip.next_in = 0;
strm_gzip.zalloc = Z_NULL;
strm_gzip.zfree = Z_NULL;
strm_gzip.opaque = Z_NULL;
int ret = deflateInit2(&strm_gzip, compress_level, Z_DEFLATED, 15 + 16, 8, Z_DEFAULT_STRATEGY);
if( ret != Z_OK )
log << log1 << "Compress: problem with deflateInit2() for gzip" << logend;
else
gzip_inited = true;
return ret == Z_OK;
}
/*
return:
0 - ok
1 - can't allocate memory
100 - unknown error
*/
int Compress::Init(int compress_level_)
{
compress_level = compress_level_;
if( !AllocateMemory() )
return 1;
if( InitRawDeflate() && InitDeflate() && InitGzip() )
ready_for_compress = true;
else
return 100;
return 0;
}
int Compress::MakeCompress(z_stream & strm, const char * source, size_t source_len, BinaryPage & out_stream, int encoding)
{
int ret, flush;
size_t have;
do
{
strm.avail_in = (source_len > buffer_max_len) ? buffer_max_len : source_len;
source_len -= strm.avail_in;
flush = (source_len == 0) ? Z_FINISH : Z_NO_FLUSH;
strm.next_in = (Bytef*)source;
source += strm.avail_in;
do
{
strm.avail_out = buffer_max_len;
strm.next_out = (Bytef*)buffer_out;
ret = deflate(&strm, flush);
if( ret == Z_STREAM_ERROR || ret == Z_BUF_ERROR )
{
log << log1 << "Compress: problem with deflate()" << logend;
return 2;
}
have = buffer_max_len - strm.avail_out;
last_out_size += have;
out_stream.write(buffer_out, have);
}
while( strm.avail_out == 0 );
if( strm.avail_in != 0 )
{
log << log1 << "Compress: problem with deflate() - not all input is used" << logend;
return 2;
}
}
while( flush != Z_FINISH );
if( ret != Z_STREAM_END )
{
log << log1 << "Compress: problem with deflate() - stream not complete" << logend;
return 2;
}
return 0;
}
void Compress::CopyToInputBuffer(BinaryPage::const_iterator & i, size_t len)
{
for(size_t a=0 ; a<len ; ++a, ++i)
buffer_in[a] = *i;
}
// new way
int Compress::MakeCompress(z_stream & strm, const BinaryPage & page, BinaryPage & out, int encoding)
{
int ret, flush;
size_t have;
BinaryPage::const_iterator i = page.begin();
size_t source_len = page.size();
do
{
strm.avail_in = (source_len > buffer_max_len) ? buffer_max_len : source_len;
source_len -= strm.avail_in;
flush = (source_len == 0) ? Z_FINISH : Z_NO_FLUSH;
strm.next_in = (Bytef*)buffer_in;
CopyToInputBuffer(i, strm.avail_in);
do
{
strm.avail_out = buffer_max_len;
strm.next_out = (Bytef*)buffer_out;
ret = deflate(&strm, flush);
if( ret == Z_STREAM_ERROR || ret == Z_BUF_ERROR )
{
log << log1 << "Compress: problem with deflate()" << logend;
return 2;
}
have = buffer_max_len - strm.avail_out;
last_out_size += have;
out.write(buffer_out, have);
}
while( strm.avail_out == 0 );
if( strm.avail_in != 0 )
{
log << log1 << "Compress: problem with deflate() - not all input is used" << logend;
return 2;
}
}
while( flush != Z_FINISH );
if( ret != Z_STREAM_END )
{
log << log1 << "Compress: problem with deflate() - stream not complete" << logend;
return 2;
}
return 0;
}
z_stream * Compress::SelectStream(int encoding)
{
z_stream * pstrm;
if( encoding == 0 )
pstrm = &strm_raw_deflate;
else
if( encoding == 1 )
pstrm = &strm_deflate;
else
pstrm = &strm_gzip;
return pstrm;
}
void Compress::ResetStream(z_stream * pstrm, int encoding)
{
if( deflateReset(pstrm) != Z_OK )
{
log << log1 << "Compress: problem with deflateReset()" << logend;
deflateEnd(pstrm);
if( encoding == 0 )
InitRawDeflate();
else
if( encoding == 1 )
InitDeflate();
else
InitGzip();
}
}
void Compress::PutLog(size_t source_len, int encoding)
{
double ratio = 100.0 - (double(last_out_size) / double(source_len) * 100.0);
char buffer[30];
sprintf(buffer, "%.1f", ratio);
log << log2 << "Compress: ";
if( encoding == 0 )
log << "raw deflate";
else
if( encoding == 1 )
log << "deflate";
else
log << "gzip";
log << ", original size: " << source_len << ", size after compressing: "
<< (int)last_out_size << ", ratio: " << buffer << "%" << logend;
}
/*
return:
0 - ok;
1 - can't allocate memory
2 - error during compressing
3 - not inited (use Init() first)
100 - unknown
*/
int Compress::Compressing(const char * source, size_t source_len, BinaryPage & out_stream, int encoding)
{
int ret;
z_stream * pstrm;
last_out_size = 0;
out_stream.clear();
if( !ready_for_compress )
{
log << log1 << "Compress: not ready yet" << logend;
return 3;
}
// !! CHECK ME
// it is correct to immediately return? what about headers in the compressed page?
if( source_len == 0 )
return 0;
pstrm = SelectStream(encoding);
ret = MakeCompress(*pstrm, source, source_len, out_stream, encoding);
ResetStream(pstrm, encoding);
PutLog(source_len, encoding);
return ret;
}
/*
return:
0 - ok;
1 - can't allocate memory
2 - error during compressing
3 - not inited (use Init() first)
100 - unknown
*/
int Compress::Compressing(const BinaryPage & in, BinaryPage & out, int encoding)
{
int ret;
z_stream * pstrm;
last_out_size = 0;
out.clear();
if( !ready_for_compress )
{
log << log1 << "Compress: not ready yet" << logend;
return 3;
}
// !! CHECK ME
// it is correct to immediately return? what about headers in the compressed page?
if( in.empty() )
return 0;
pstrm = SelectStream(encoding);
ret = MakeCompress(*pstrm, in, out, encoding);
ResetStream(pstrm, encoding);
PutLog(in.size(), encoding);
return ret;
}
} // namespace Winix

102
winixd/core/compress.h Normal file
View File

@@ -0,0 +1,102 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2008-2014, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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 headerfile_winix_core_compress
#define headerfile_winix_core_compress
#include <cstring>
#include <zlib.h>
#include "requesttypes.h"
#include "winixbase.h"
namespace Winix
{
class Compress : public WinixBase
{
public:
Compress();
~Compress();
int Init(int compress_level_ = 6);
/*
encoding:
0 - raw deflate data with no zlib header or trailer, and will not compute an adler32 check value
(for Internet Explorer)
1 - deflate
2 - gzip
*/
int Compressing(const char * source, size_t source_len, BinaryPage & out_stream, int encoding = 2);
int Compressing(const BinaryPage & in, BinaryPage & out, int encoding = 2);
private:
bool AllocateMemory();
bool InitRawDeflate();
bool InitDeflate();
bool InitGzip();
int MakeCompress(z_stream & strm, const char * source, size_t source_len, BinaryPage & out_stream, int encoding);
int MakeCompress(z_stream & strm, const BinaryPage & page, BinaryPage & out, int encoding);
z_stream * SelectStream(int encoding);
void ResetStream(z_stream * pstrm, int encoding);
void PutLog(size_t source_len, int encoding);
void CopyToInputBuffer(BinaryPage::const_iterator & i, size_t len);
int compress_level;
size_t buffer_max_len;
// size of the last compressed page
size_t last_out_size;
char * buffer_in;
char * buffer_out;
z_stream strm_raw_deflate, strm_deflate, strm_gzip;
bool raw_deflate_inited, deflate_inited, gzip_inited;
bool ready_for_compress;
};
} // namespace Winix
#endif

537
winixd/core/config.cpp Normal file
View File

@@ -0,0 +1,537 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2008-2018, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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.
*
*/
#include "config.h"
#include "log.h"
#include "misc.h"
#include "crypt.h"
namespace Winix
{
Config::Config()
{
errors_to_stdout = true;
}
void Config::SetFileLog(FileLog * file_log)
{
log.SetFileLog(file_log);
}
void Config::SetLogBuffer(PT::WTextStream * log_buffer)
{
log.SetLogBuffer(log_buffer);
}
void Config::ShowError()
{
switch( parser.status )
{
case PT::SpaceParser::no_space:
log << log2 << "Config: space not set" << logend;
break;
case PT::SpaceParser::ok:
log << log2 << "Config: syntax ok" << logend;
break;
case PT::SpaceParser::cant_open_file:
if( errors_to_stdout )
std::wcout << L"Config: I cannot open a config file: " << config_file << std::endl;
log << log1 << "Config: cant open a config file: " << config_file << logend;
break;
case PT::SpaceParser::syntax_error:
if( errors_to_stdout )
std::wcout << "Config: syntax error, line: " << parser.line << std::endl;
log << log1 << "Config: syntax error, line: " << parser.line << logend;
break;
}
}
bool Config::ReadConfig(bool errors_to_stdout_, bool stdout_is_closed)
{
errors_to_stdout = errors_to_stdout_;
if( config_file.empty() )
{
log << log2 << "Config: name of the config file is empty" << logend;
return false;
}
log << log2 << "Config: reading a config file" << logend;
parser.SetSpace(space);
PT::SpaceParser::Status status = parser.Parse(config_file);
if( status == PT::SpaceParser::ok )
{
AssignValues(stdout_is_closed);
SetAdditionalVariables();
return true;
}
else
{
ShowError();
return false;
}
}
void Config::AssignValues(bool stdout_is_closed)
{
server_mode = Text(L"server_mode");
demonize = Bool(L"demonize", true);
user = Text(L"user");
group = Text(L"group");
additional_groups = Bool(L"additional_groups", true);
log_file = Text(L"log_file");
log_delimiter = Text(L"log_delimiter", L"---------------------------------------------------------------------------------");
fcgi_socket = Text(L"fcgi_socket");
fcgi_socket_chmod = Int(L"fcgi_socket_chmod", 0770);
fcgi_socket_user = Text(L"fcgi_socket_user");
fcgi_socket_group = Text(L"fcgi_socket_group");
fcgi_socket_listen = Int(L"fcgi_socket_listen", 100);
log_level = Int(L"log_level", 1);
log_request = Int(L"log_request", 1);
log_save_each_line = Bool(L"log_save_each_line", false);
log_time_zone_id = Size(L"log_time_zone_id", 34);
log_server_answer = Bool(L"log_server_answer", false);
log_stdout = Bool(L"log_stdout", false);
log_db_query = Bool(L"log_db_query", false);
log_plugin_call = Bool(L"log_plugin_call", false);
log_post_value_size = Size(L"log_post_value_size", 80);
log_env_variables = Bool(L"log_env_variables", false);
log_env_http_variables = Bool(L"log_env_http_variables", false);
log_http_answer_headers = Bool(L"log_http_answer_headers", false);
post_file_max = Size(L"post_file_max", 8388608); // 8 MB
upload_dir = Text(L"upload_dir");
common_dir = Text(L"common_dir");
NoLastSlash(upload_dir);
NoLastSlash(common_dir);
upload_group = Text(L"upload_group");
upload_dirs_chmod = Int(L"upload_dirs_chmod", 0750);
upload_files_chmod = Int(L"upload_files_chmod", 0640);
ListText(L"static_dirs", static_dirs);
dont_use_static_dirs = Bool(L"dont_use_static_dirs", false);
create_thumb = Bool(L"create_thumb", true);
thumb_mode = Int(L"thumb_mode", 2);
thumb_cx = Size(L"thumb_cx", 150);
thumb_cy = Size(L"thumb_cy", 150);
thumb_quality = Int(L"thumb_quality", 92);
image_resize = Bool(L"image_resize", true);
image_mode = Int(L"image_mode", 6);
image_cx = Size(L"image_cx", 1000);
image_cy = Size(L"image_cy", 800);
image_quality = Int(L"image_quality", 92);
convert_cmd = Text(L"convert_cmd", L"/usr/local/bin/convert");
templates_dir = Text(L"templates_dir");
templates_dir_default = Text(L"templates_dir_default");
txt_templates_dir = Text(L"txt_templates_dir");
txt_templates_dir_default = Text(L"txt_templates_dir_default");
templates_fun_prefix = Text(L"templates_fun_prefix", L"fun_");
templates_fun_postfix = Text(L"templates_fun_postfix", L".html");
templates_index = Text(L"templates_index", L"index.html");
templates_index_raw = Text(L"templates_index_raw", L"index_raw.html");
template_only_root_use_template_fun = Bool(L"template_only_root_use_template_fun", false);
http_session_id_name = Text(L"http_session_id_name", L"session_id");
db_database = Text(L"db_database");
db_user = Text(L"db_user");
db_pass = Text(L"db_pass");
db_postgresql_smaller_than_10 = Bool(L"db_postgresql_smaller_than_10", false);
item_url_empty = Text(L"item_url_empty");
url_proto = Text(L"url_proto", L"http://");
url_ssl_proto = Text(L"url_ssl_proto", L"https://");
use_ssl = Bool(L"use_ssl", false);
use_ssl_static = Bool(L"use_ssl_static", false);
use_ssl_common = Bool(L"use_ssl_common", false);
use_ssl_only_for_logged_users = Bool(L"use_ssl_only_for_logged_users", false);
use_ssl_redirect_code = Int(L"use_ssl_redirect_code", 303);
assume_connection_is_through_ssl = Bool(L"assume_connection_is_through_ssl", false);
base_url = Text(L"base_url");
base_url_static = Text(L"base_url_static");
base_url_common = Text(L"base_url_common");
base_url_redirect = Bool(L"base_url_redirect", false);
base_url_redirect_code = Int(L"base_url_redirect_code", 301);
NoLastSlash(base_url);
NoLastSlash(base_url_static);
NoLastSlash(base_url_common);
priv_no_user = Text(L"priv_no_user", L"-- no user --");
priv_no_group = Text(L"priv_no_group", L"-- no group --");
session_max_idle = Int(L"session_max_idle", 10800); // 3h
session_remember_max_idle = Int(L"session_remember_max_idle", 16070400); // 3 months
session_file = Text(L"session_file");
session_max = Size(L"session_max", 1000000);
session_cookie_encode = Bool(L"session_cookie_encode", false);
session_keys_file = Text(L"session_keys_file");
session_allow_index_difference = Size(L"session_allow_index_difference", 8);
session_index_time_increment = Long(L"session_index_time_increment", 30);
session_key_renew_time = Size(L"session_key_renew_time", 172800); // 2 days
broken_encoded_cookie_treshold = Size(L"broken_encoded_cookie_treshold", 2);
session_hijacking_treshold = Size(L"session_hijacking_treshold", 128);
no_session_cookie_treshold = Size(L"no_session_cookie_treshold", 128);
no_session_cookie_ban_mode = Int(L"no_session_cookie_ban_mode", 0);
compression = Bool(L"compression", true);
compression_page_min_size = Size(L"compression_page_min_size", 512);
compression_encoding = Int(L"compression_encoding", 20);
html_filter = Bool(L"html_filter", true);
html_filter_trim_white = Bool(L"html_filter_trim_white", true);
html_filter_break_word = Int(L"html_filter_break_word", 60);
html_filter_wrap_line = Int(L"html_filter_wrap_line", 110);
html_filter_tabs = Size(L"html_filter_tabs", 2);
html_filter_orphans = Bool(L"html_filter_orphans", true);
html_filter_orphans_mode_str = Text(L"html_filter_orphans_mode_str", L"nbsp");
html_filter_nofilter_tag = Text(L"html_filter_nofilter_tag", L"nofilter");
locale_dir = Text(L"locale_dir");
locale_dir_default = Text(L"locale_dir_default");
locale_max_id = Size(L"locale_max_id", 100);
locale_default_id = Size(L"locale_default_id", 0);
ListText(L"locale_files", locale_files);
title_separator = Text(L"title_separator", L" / ");
http_header_send_file = Text(L"http_header_send_file", L"X-LIGHTTPD-send-file");
editors_html_safe_mode = Bool(L"editors_html_safe_mode", true);
editors_html_safe_mode_skip_root = Bool(L"editors_html_safe_mode_skip_root", true);
plugins_dir = Text(L"plugins_dir", L"/usr/local/winix/plugins");
NoLastSlash(plugins_dir);
ListText(L"plugins", plugin_file);
symlinks_follow_max = Size(L"symlinks_follow_max", 20);
ticket_form_prefix = Text(L"ticket_form_prefix", L"ticketparam");
pass_min_size = Size(L"pass_min_size", 5);
pass_type = Int(L"pass_type", 12);
pass_hash_use_salt = Bool(L"pass_hash_use_salt", false);
pass_hash_salt = Text(L"pass_hash_salt");
pass_use_rsa = Bool(L"pass_use_rsa", false);
pass_rsa_private_key = Text(L"pass_rsa_private_key");
opensll_path = Text(L"opensll_path", L"/usr/bin/openssl");
pattern_cacher_when_delete = Size(L"pattern_cacher_when_delete", 130);
pattern_cacher_how_many_delete = Size(L"pattern_cacher_how_many_delete", 30);
content_type_header = Int(L"content_type_header", 0);
umask = Int(L"umask", 0222);
ezc_max_elements = Size(L"ezc_max_elements", 50000);
ezc_max_loop_elements = Size(L"ezc_max_loop_elements", 5000);
ezc_out_streams_size = Size(L"ezc_out_streams_size", 128);
ezc_error_prefix = Text(L"ezc_error_prefix", L"<!-- ");
ezc_error_postfix = Text(L"ezc_error_postfix", L" -->");
account_need_email_verification = Bool(L"account_need_email_verification", true);
reset_password_code_expiration_time = Long(L"reset_password_code_expiration_time", 86400);
time_zone_default_id = Size(L"time_zone_default_id", 34);
time_zone_max_id = Size(L"time_zone_max_id", 130);
etc_dir = Text(L"etc_dir", L"");
time_zones_file = Text(L"time_zones_file", L"time_zones.conf");
use_ban_list = Bool(L"use_ban_list", true);
ban_list_soft_max_size = Size(L"ban_list_soft_max_size", 50000);
ban_list_max_size = Size(L"ban_list_max_size", 51000);
ban_level_1_delay = Size(L"ban_level_1_delay", 1800);
ban_level_2_delay = Size(L"ban_level_2_delay", 86400);
ban_level_3_delay = Size(L"ban_level_3_delay", 604800);
incorrect_login_min_time_between_get_post = Size(L"incorrect_login_min_time_between_get_post", 2);
incorrect_login_captcha_treshold = Size(L"incorrect_login_captcha_treshold", 3);
incorrect_login_cannot_login_mode = Int(L"incorrect_login_cannot_login_mode", 0);
incorrect_login_cannot_login_treshold = Size(L"incorrect_login_cannot_login_treshold", 20);
incorrect_login_cannot_login_delay = Size(L"incorrect_login_cannot_login_delay", 1800);
pid_file = Text(L"pid_file", L"");
allow_ezc_out_in_executable_items = Bool(L"allow_ezc_out_in_executable_items", false);
check_proxy_ip_header = Bool(L"check_proxy_ip_header", false);
proxy_ip_header = Text(L"proxy_ip_header", L"X_Real_IP");
antispam_list_max_size = Size(L"antispam_list_max_size", 10);
}
void Config::SetAdditionalVariables()
{
for(size_t i=0 ; i<static_dirs.size() ; ++i)
NoLastSlash(static_dirs[i]);
CheckPasswd();
if( content_type_header < 0 || content_type_header > 2 )
content_type_header = 0;
if( locale_default_id > locale_max_id )
locale_default_id = locale_max_id;
if( locale_files.empty() )
locale_files.push_back(L"en");
if( !upload_group.empty() )
upload_group_int = GetGroupId(upload_group);
else
upload_group_int = -1;
if( session_cookie_encode && session_keys_file.empty() )
session_cookie_encode = false;
if( session_index_time_increment < 0 )
session_index_time_increment = 0;
}
void Config::CheckPasswd()
{
switch(pass_type)
{
case WINIX_CRYPT_HASH_NONE:
case WINIX_CRYPT_HASH_MD4:
case WINIX_CRYPT_HASH_MD5:
case WINIX_CRYPT_HASH_SHA1:
case WINIX_CRYPT_HASH_SHA224:
case WINIX_CRYPT_HASH_SHA256:
case WINIX_CRYPT_HASH_SHA384:
case WINIX_CRYPT_HASH_SHA512:
break;
default:
pass_type = WINIX_CRYPT_HASH_SHA256;
}
}
std::wstring Config::Text(const wchar_t * name)
{
return space.Text(name);
}
std::wstring Config::Text(const wchar_t * name, const wchar_t * def)
{
return space.Text(name, def);
}
std::wstring Config::Text(const std::wstring & name, const wchar_t * def)
{
return space.Text(name, def);
}
std::wstring & Config::TextRef(const wchar_t * name)
{
return space.TextRef(name);
}
std::wstring & Config::TextRef(const wchar_t * name, const wchar_t * def)
{
return space.TextRef(name, def);
}
std::wstring & Config::TextRef(const std::wstring & name, const wchar_t * def)
{
return space.TextRef(name, def);
}
int Config::Int(const wchar_t * name)
{
return space.Int(name);
}
int Config::Int(const wchar_t * name, int def)
{
return space.Int(name, def);
}
int Config::Int(const std::wstring & name, int def)
{
return space.Int(name, def);
}
long Config::Long(const wchar_t * name)
{
return space.Long(name);
}
long Config::Long(const wchar_t * name, long def)
{
return space.Long(name, def);
}
long Config::Long(const std::wstring & name, long def)
{
return space.Long(name, def);
}
size_t Config::Size(const wchar_t * name)
{
return space.Size(name);
}
size_t Config::Size(const wchar_t * name, size_t def)
{
return space.Size(name, def);
}
size_t Config::Size(const std::wstring & name, size_t def)
{
return space.Size(name, def);
}
bool Config::Bool(const wchar_t * name)
{
return space.Bool(name);
}
bool Config::Bool(const wchar_t * name, bool def)
{
return space.Bool(name, def);
}
bool Config::Bool(const std::wstring & name, bool def)
{
return space.Bool(name, def);
}
bool Config::ListText(const wchar_t * name, std::vector<std::wstring> & list)
{
return space.ListText(name, list);
}
bool Config::ListText(const std::wstring & name, std::vector<std::wstring> & list)
{
return space.ListText(name, list);
}
bool Config::HasValue(const wchar_t * name, const wchar_t * value)
{
return space.HasValue(name, value);
}
bool Config::HasValue(const wchar_t * name, const std::wstring & value)
{
return space.HasValue(name, value);
}
bool Config::HasValue(const std::wstring & name, const wchar_t * value)
{
return space.HasValue(name, value);
}
bool Config::HasValue(const std::wstring & name, const std::wstring & value)
{
return space.HasValue(name, value);
}
void Config::Print(std::wostream & out)
{
space.Serialize(out);
}
} // namespace Winix

848
winixd/core/config.h Normal file
View File

@@ -0,0 +1,848 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2008-2018, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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 headerfile_winix_core_config
#define headerfile_winix_core_config
#include <string>
#include "space/spaceparser.h"
#include "log.h"
#include "filelog.h"
namespace Winix
{
class Config
{
public:
// name of the config file
// this is the parameter passed to winix programm
std::wstring config_file;
// server mode
// you can assign any string to it such as "production" "dev"
// this value is not used by winix itself
// you can refer to it from [server_mode] and [server_mode_is] ezc functions
std::wstring server_mode;
// start as a demon (in the background)
// default: true
bool demonize;
// system user's name to whom winix should drop privileges
// used only if winix is started as the root
std::wstring user;
// system group's name to which drop privileges
// used only if winix is started as the root
std::wstring group;
// setting additional effective groups from /etc/group
// by using initgroups()
// used only if winix is started as the root
// default: true
bool additional_groups;
// log file name
std::wstring log_file;
// the log level (how much info should be inserted to logs)
// 1 - minimum
// 2 - (default)
// 3 - maximum - all logs
int log_level;
// logging to stdout too
// this option is valid only if 'demonize' option is set to 'false'
// default: false
bool log_stdout;
// how many requests should be saved in the same time
// if you have a very busy server you can incrase this value
// default: 1
int log_request;
// whether to save each line of the config (used for debugging purposes)
// default: false
bool log_save_each_line;
// time zone identifier used in log messages
// this affects only the first line of logs (where there is IP address, request method etc)
// see time_zone_default_id below for more info
// default: 34 (Coordinated Universal Time UTC+00:00)
size_t log_time_zone_id;
// put to log what server is sending back to the client (html/json etc)
// default: false
bool log_server_answer;
// logging db queries
// warning: use it only on a developer's server as it logs the hashes of passwords too
// default: false
bool log_db_query;
// logging when a plugin function is called
// default: false
bool log_plugin_call;
// how many characters in values should be logged from POST parameters
// default: 80
// set to 0 to turn it off
size_t log_post_value_size;
// request delimiter in the log file, default "---------"
std::wstring log_delimiter;
// log environment variables (fastcgi environment)
bool log_env_variables;
// log environment http variables (only HTTP_* variables from fastcgi environment)
bool log_env_http_variables;
// log headers (+cookies) which are returned to the client
// this is what winix has generated -- the web server can change or add other headers
// default: false
bool log_http_answer_headers;
// fast cgi: socket (unix domain)
std::wstring fcgi_socket;
// fast cgi: socket permissions
// chmod and chown of the socket are set before winix drops privileges
int fcgi_socket_chmod;
// fast cgi: owner of the socket
// chmod and chown of the socket are set before winix drops privileges
std::wstring fcgi_socket_user;
// fast cgi: group of the socket
// chmod and chown of the socket are set before winix drops privileges
std::wstring fcgi_socket_group;
// fcgi_socket_listen is the listen queue depth used in the listen() call
// when creating a FastCGI socket for the web server
// default: 100
int fcgi_socket_listen;
std::wstring templates_dir;
std::wstring templates_dir_default; // html templates from winix
std::wstring txt_templates_dir;
std::wstring txt_templates_dir_default; // txt (notifications) templates from winix
// prefix and postfix for functions templates
// default:
// prefix: "fun_"
// postfix: ".html"
std::wstring templates_fun_prefix;
std::wstring templates_fun_postfix;
// main html template
// default: index.html
std::wstring templates_index;
// html template used to send raw content
// default: index_raw.html
std::wstring templates_index_raw;
// if true then only root can use 'template' winix function
// default: false
bool template_only_root_use_template_fun;
// the database name, user name and a password for the PostgreSQL database
std::wstring db_database;
std::wstring db_user;
std::wstring db_pass;
// is the PostgreSQL later than 10
// default false
// if true then we are not using ROW() statements in sql query
bool db_postgresql_smaller_than_10;
// the name of the cookie which has the session identifier
std::wstring http_session_id_name;
// string used in a place where is a user (or group) selected
// !! IMPROVE ME should be moved to locales
std::wstring priv_no_user;
std::wstring priv_no_group;
// time in seconds when a user will be automatically logged out (iddle time)
// default: 10800 = 3 hours
int session_max_idle;
// time in seconds when a user will be automatically logged out
// when he has selected the 'remember me' option when logging in
// this time is usually greater than session_max_idle
// default: 16070400 = 3 months
int session_remember_max_idle;
// a file to which winix stores sessions info
// it is used when winix starts (boots) and quits
std::wstring session_file;
// how many sessions can be (zero turn off this checking)
// default: 1000000 (one milion)
size_t session_max;
// whether or not we should encode the session cookie
// (we have a special algorithm)
// default: false
bool session_cookie_encode;
// if session_cookie_encode is true then you should provide
// a file where AES keys will be stored
std::wstring session_keys_file;
// each session has an index -- an unsigned int value
// this value is sent in the cookie string (is encoded)
// and is incremented when session_index_time_increment time is passed since the last incrementing
// if a client sent the cookie back the difference between
// current index and the index in the cookie should be less than or equal to session_allow_index_difference
// default: 8
size_t session_allow_index_difference;
// the time which should pass after the session index is incremented
// default: 30
// (session_allow_index_difference + 1) * session_index_time_increment should be less than a time
// load of a page and all elements on it such as images (of course it depends on client's download too)
time_t session_index_time_increment;
// time in seconds after a new AES key pair should be generated
// we have 256 pairs of keys so this time multiplied by 256 should not be less than
// the max time of a session (session_remember_max_idle),
// by default: 256 * 2 days = 512 days = 1.4 year > 3 months (session_remember_max_idle)
// default: 172800 = 2 days (max: 2678400 = 1 month, min: 10)
size_t session_key_renew_time;
// after how many broken encoded cookie we should ban the current IP
// default: 2 (value in the range <0 - 65535>)
size_t broken_encoded_cookie_treshold;
// after how many incorrect session identifiers (or session indices) we should ban the current IP
// do not set this value too low, as people connecting from the same IP address (from behind a NAT)
// would be banned if they have an old session cookie remembered in the browser
// default: 128 (value in the range <0 - 65535>)
size_t session_hijacking_treshold;
// after how many times a client will be banned (or given temporary session) if it did not send a session cookie
// this can be a bot such as a Google Bot or just people connecting from a NAT and all have the same IP
// default: 128 (value in the range <0 - 65535>)
size_t no_session_cookie_treshold;
// the way we behave when no_session_cookie_treshold limit is exceeded
// 0 - if a client doesn't send a session cookie again then use a temporary session
// (other sessions from this IP address are not affected)
// 1 - add this IP address to ban list and create a temporary session
// (this will block other sessions from this IP address too)
// default: 0
int no_session_cookie_ban_mode;
// allow the winix output to be compressed
// default: true
bool compression;
// compress only if the output is greater or equal to this value
// default: 512 bytes
size_t compression_page_min_size;
// 1 - use deflate if available (or raw deflate for Internet Explorer) or don't compress
// 2 - use gzip if available or don't compress
// 10 - prefer deflate -- use deflate (or raw deflate for IE) if both deflate and gzip are available
// 20 - prefer gzip -- use gzip if both deflate and gzip are available
// default: 20
int compression_encoding;
// plugins directory
// default: /usr/local/winix/plugins
std::wstring plugins_dir;
// plugins
// you can provide either a relative path (plugins_dir will be used)
// or a full path to a plugin
std::vector<std::wstring> plugin_file;
// should the html code be cleaned by the html filter
bool html_filter;
// should white characters be trimmed
bool html_filter_trim_white;
// when long words should be broken (a space will be inserted)
// default: after 60 non white characters there will be put a space
// set zero to turn off
size_t html_filter_break_word;
// when long lines should be broken (a new line character will be inserted)
// default: 110
// set zero to turn off
size_t html_filter_wrap_line;
// how many spaces will be put at one tree level
// default: 2
size_t html_filter_tabs;
// use checking for 'orphans' for a specicic language
// default: true
bool html_filter_orphans;
// orphans mode
// either: "nbsp" or "160"
// default: "nbsp"
std::wstring html_filter_orphans_mode_str;
// the html nofilter tag
// content betweeng these tags (opening and closing) will not be filtered
// and this tag will not be included in the html output
// default: nofilter
std::wstring html_filter_nofilter_tag;
// the url of a new empty item (if there is not the subject too)
// !! IMPROVE ME should be moved to locale
std::wstring item_url_empty;
// maximum length of a file send by post multipart form
// default: 8388608 - 8MB
// 0 - not used
size_t post_file_max;
// directory for static files
std::wstring upload_dir;
// additional static directories *not* managed by winix
// you can refer to this directories by using 'static' mount point
// e.g.
// let we say in the config you have:
// static_dirs = ("/home/a", "/home/b", "/home/c")
// and in /etc/fstab (in winix) you have such a line:
// "static /my/dir simplefs static(2)"
// above line in /etc/fstab means that when a user enters http://domain.com/my/dir/file.txt
// then "file.txt" will be taken from "/home/c/file.txt"
// this is useful for some javascript files which are protected from running from other domains
std::vector<std::wstring> static_dirs;
// sometimes you can have trouble when you have set an incorrect static path in /etc/fstab
// in such a case set dont_use_static_dirs to true
// and winix will behave as there are not any static directories
// so you can correct your mistake and then set this value to false
bool dont_use_static_dirs;
// static common directory
// this is a place where there are some common javascripts, images, css files
// winix is allowed to read some files from there
// for example ckeditor config, vim config and so on
// winix read it as a ezc template and put it into database
// default: empty
std::wstring common_dir;
// system group's name for new uploaded files (created directories in the file system)
// it can be empty (it is not used then)
std::wstring upload_group;
// this value will be set based on upload_group
// will be -1 if upload_group is empty or if it is invalid
int upload_group_int;
// chmod of newly created directories (under upload_dir)
// default: 0750
int upload_dirs_chmod;
// chmod of newly created files (under upload_dir)
// default: 0640
int upload_files_chmod;
// create a thumbnail from an image
// default: true
bool create_thumb;
// the mode of creating a thumbnail
// width means thumb_cx, height means thumb_cy
// 1: Width given, height automagically selected to preserve aspect ratio.
// 2: Height given, width automagically selected to preserve aspect ratio.
// 3: Maximum values of height and width given, aspect ratio preserved.
// 4: Minimum values of width and height given, aspect ratio preserved.
// 5: Width and height emphatically given, original aspect ratio ignored.
// 6: Change as per widthxheight (3) but only if an image dimension exceeds a specified dimension.
// 7: Change dimensions only if both image dimensions are less than specified dimensions.
// default: 2
int thumb_mode;
// width of thumbnails
// default: 150
size_t thumb_cx;
// height of thumbnails
// default: 150
size_t thumb_cy;
// quality of thumbnails
// from 0 (the worst) to 100 (the best)
// more info: http://www.imagemagick.org/script/command-line-options.php?ImageMagick=p4jtel7557hovd34ui3tgb54h6#quality
// default: 92
int thumb_quality;
// resizing images
// this not affects thumbnails
// default: true
bool image_resize;
// the mode of resizing an image
// the same as 'thumb_mode' above
// default: 6
int image_mode;
// width of images
// default: 1000
size_t image_cx;
// height of images
// default: 800
size_t image_cy;
// quality of an image (the same as in thumbnails)
// from 0 (the worst) to 100 (the best)
// default: 92
int image_quality;
// the convert program (ImageMagic) (for images and thumbnails)
// default: /usr/local/bin/convert
std::wstring convert_cmd;
// directory with locale files
std::wstring locale_dir;
// directory with default locale files (those from winix)
std::wstring locale_dir_default;
// locale files (e.g. "en", "pl")
// default: only one item: en
std::vector<std::wstring> locale_files;
// a maximum value of a locale identifier
// default: 100 (maximum: 1000)
// each locale files should have its own identifier (in "winix_locale_id" field)
// from zero to this value
size_t locale_max_id;
// locale for not logged users
// or for newly created accounts
// default: 0
size_t locale_default_id;
// url protocol
// default: http://
std::wstring url_proto;
// url protocol when using SSL
// default: https://
std::wstring url_ssl_proto;
// enables SSL
// it means this site should be accessed through SSL encrypted connection
// default: false
bool use_ssl;
// enables SSL for static content
// used mainly in templates, look at doc_base_url_static ezc function
// default: false
bool use_ssl_static;
// enables SSL for common content
// used mainly in templates, look at doc_base_url_common ezc function
// default: false
bool use_ssl_common;
// if SSL is enabled then if this is true the SSL will be used
// only for logged users
// default: false
bool use_ssl_only_for_logged_users;
// if current connection is without SSL and should be made through SSL
// or if is via SSL and should be done in plain text
// then we make a redirect
// default: 303
int use_ssl_redirect_code;
// winix is testing an environment variable "HTTPS" for the value "on"
// to think that the connection is made via SSL
// you can set assume_connection_is_through_ssl to true for the winix
// to not testing any environment variables but just think the connection
// was made by https (useful when using proxy)
// default: false
bool assume_connection_is_through_ssl;
// when the HOST_HTTP environment variable is not equal to 'base_url'
// (the part 'http://' and the last slash is removed)
// the server will redirect into base_url + 'REQUEST_URI'
// it's useful when you want to redirect from 'mydomain.tld' into 'www.mydomain.tld' etc.
// set this option to false if you have multiple subdomains
// default: false
bool base_url_redirect;
// the HTTP code used during the base redirect
// default: 301
int base_url_redirect_code;
// the main address of the site (e.g. www.someserver.com)
// (without http:// prefix)
std::wstring base_url;
// static content not authorized by winix
// (e.g. static.someserver.com)
std::wstring base_url_static;
// additional static server for common content (not authorized)
// (e.g. common.someserver.com)
std::wstring base_url_common;
// separator used in <title> html tag
std::wstring title_separator;
// http header recognized by www server as a file to send back
// default: X-LIGHTTPD-send-file
std::wstring http_header_send_file;
// in editors (emacs, ckeditor,...) the html will be filtered and unsafe tags
// will be dropped (script, frame, etc.)
// default: true;
bool editors_html_safe_mode;
// don't filter the html code for root
// default: true
// (if true the html code for root is not filtered)
bool editors_html_safe_mode_skip_root;
// how many maximum symlinks can be followed
// (symlinks on directories as well)
// default: 20
size_t symlinks_follow_max;
// the prefix of a name of html form controls used in the ticket plugin
// default: ticketparam
std::wstring ticket_form_prefix;
// the minimal size of a user's password
// default: 5
size_t pass_min_size;
// how passwords should be stored
// 0 - plain text
// 1 - md4 hash
// 2 - md5 hash
// 10 - sha1 hash
// 11 - sha224 hash
// 12 - sha256 hash (default)
// 13 - sha384 hash
// 14 - sha512 hash
int pass_type;
// whether the passwords' hashes should be salted or not
// this affects newly created accounts
// default: false
bool pass_hash_use_salt;
// salt to a password's hash
// default empty
// !! once you set this salt don't change it any more (people wouldn't be allowed to login)
std::wstring pass_hash_salt;
// whether the passwords' hashes should be encrypted
// this affects newly created accounts
// default: false
bool pass_use_rsa;
// path to a RSA private key
// this is actually private + public key in one file
// generated by "openssl genrsa"
// default empty which means encryption will not be used
// !! once you set these keys don't change it any more (people wouldn't be allowed to login)
std::wstring pass_rsa_private_key;
// path to 'openssl'
// default: /usr/bin/openssl
std::wstring opensll_path;
// setting when we should delete patterns (EZC patterns)
// we are deleting when we have more (or equal) patterns than 'when_delete'
// and then we are deleting 'how_many_del' patterns
// those patterns comes from items (pages) with executable bit set
size_t pattern_cacher_when_delete;
size_t pattern_cacher_how_many_delete;
// header "Content-Type" send to the client
// 0 - text/html - for HTML
// 1 - application/xhtml+xml - for XHTML 1.0
// 2 - application/xml - for XHTML 1.0 or for XHTML 1.1
// default: 0
// if utf8 is true then "; charset=UTF-8" will also be appended
int content_type_header;
// global umask
// it is used when an user doesn't have your own umask or for guests (not logged users)
// default: 0222
int umask;
// maximum number for elements through the whole template
// default: 50000
size_t ezc_max_elements;
// maximum number of each [for] loop
// default: 5000 (from ezc generator)
size_t ezc_max_loop_elements;
// how many output streams do we have in Request class
// those streams used in ajax responses
// you can use no more [ezc out] statements than this limit
// default: 128
size_t ezc_out_streams_size;
// prefix and postfix used when there is an error in Ezc patterns
// default:
// prefix: "<!-- "
// postfix: " -->"
std::wstring ezc_error_prefix;
std::wstring ezc_error_postfix;
// when true then when a user want to create a new account
// he has to provide his email and a message will be sent back to him
// with a link to activate the account
// default: true
bool account_need_email_verification;
// when a user forgot his password we are able to send an email to him
// with a link to the page where there is a html form for setting a new password
// this option tells how long (in seconds) the link is valid
// default: 86400 (24 hours)
long reset_password_code_expiration_time;
// time zone identifier for not logged users
// or for newly created accounts
// those identifiers you can see in etc/time_zones.conf file
// or by using timezone winix function with 'a' parameter (timezone/a) (!!IMPROVE ME NOT IMPLEMENTED YET)
// default: 34 (Coordinated Universal Time UTC+00:00)
size_t time_zone_default_id;
// a maximum value of a time zone identifier
// time zones with an id greater than this will be skipped
// default: 130 (maximum: 1000)
size_t time_zone_max_id;
// a directory in which there are some config files
// used mainly when winix starts
// default: empty (means not for using)
std::wstring etc_dir;
// a file in etc_dir with time zones info
// default: time_zones.conf
// this is a Space structure with all time zones
// with following format:
// "tz_-12:00" ( # the name of a space is also a key to the locale files
// tz_offset_str = "-12:00" # a string representing the offset from UTC in a format: [+|-]HH:MM
// tz_has_dst = "false" # whether the time zone has daylight saving time (bool)
// tz_dst_offset = "" # offset of the daylight saving time
// tz_dst_start = "" # when the daylight saving time starts, format: MM:DD HH:MM:SS
// tz_dst_end = "") # when the daylight saving time ends, format: MM:DD HH:MM:SS
// each time zone is in a seperate space
std::wstring time_zones_file;
// turn on the IP ban mechanizm
// we have got three levels of bans (level 1, level 2, and the highest level 3)
// default: true
bool use_ban_list;
// the so called 'soft' max size
// read below description for explanation
// this is introduced to avoid deleting only one record from the ban list
// default: 50000
size_t ban_list_soft_max_size;
// this is the 'hard' max size of an IP's ban list
// if there are more records than this value
// then some of them will be removed (until the size will be ban_list_soft_max_size equal)
// this value should be a little larger from ban_list_soft_max_size
// default: 51000
size_t ban_list_max_size;
// delay in seconds of the first level ban
// default: 1800 (30 minutes)
// it means withing the next 30 minutes you see only 'you are banned...' message on your webbrowser
size_t ban_level_1_delay;
// delay in seconds of the second level ban
// default: 86400 (24 hours)
size_t ban_level_2_delay;
// delay in seconds of the third level ban
// default: 604800 (7 days)
size_t ban_level_3_delay;
// the minimum time in seconds which has to pass between the first GET request
// (showing your the login form) and the second POST request (which sends the
// login and password to the server)
// if the time is shorter then the login attempt is treated as incorrect
// (the same as if you provide incorrect user/password)
// default: 2
size_t incorrect_login_min_time_between_get_post;
// how many incorrect logins there must have been passed to display a captcha
// next to the login form
// default: 3 (value in the range <0 - 65535>)
size_t incorrect_login_captcha_treshold;
// the way how we prevent to login if there are too many incorrect login attempts
// 0 - 'block logging' - do not show the login form in 'login' winix function
// (instead a warning message will be printed)
// 1 - add to ban list (warning: people from this IP will not be able to see your site and do anything)
// default: 0
int incorrect_login_cannot_login_mode;
// after how many incorrect login attempts we do the incorrect_login_cannot_login_mode action
// default: 20 (value in the range <0 - 65535>)
size_t incorrect_login_cannot_login_treshold;
// used when incorrect_login_cannot_login_mode is zero
// it is the time which should be passed to allow logging
// default: 1800 (30 minutes)
// if incorrect_login_cannot_login_mode is one then ban_level_X_delay times
// will be taken accordingly
size_t incorrect_login_cannot_login_delay;
// pid file (a full path to a pid file)
// default: empty which means there is not a pid file used
// pid file is saved after winix has dropped privileges
std::wstring pid_file;
// allow to use [ezc out] statement in executable items (used in 'run' winix function)
// default false
// warning: if you enable this options a user can override a different output stream when using ajax
bool allow_ezc_out_in_executable_items;
// check whether there is a 'log_proxy_ip_header' header
// and if so then log the IP address from it
// default: false
bool check_proxy_ip_header;
// proxy header representing the real IP address of a client
// default: X_Real_IP
std::wstring proxy_ip_header;
// antispam mechanizm
// size of an list for map: form_id to counter_id for anonymous users (each session has such an map)
// this value allowes you to open the same or different html form in the browser more than once
// and each form has its own form_id and counter_id
// default: 10 (max ten forms can be open in different tabs)
size_t antispam_list_max_size;
Config();
bool ReadConfig(bool errors_to_stdout_, bool stdout_is_closed = true);
/*
*
* CHECK ME
* there was a change in Pikotools
* before Text() returns a reference to the std::wstring
*
*/
std::wstring Text(const wchar_t * name);
std::wstring Text(const wchar_t * name, const wchar_t * def);
std::wstring Text(const std::wstring & name, const wchar_t * def);
std::wstring & TextRef(const wchar_t * name);
std::wstring & TextRef(const wchar_t * name, const wchar_t * def);
std::wstring & TextRef(const std::wstring & name, const wchar_t * def);
int Int(const wchar_t *);
int Int(const wchar_t * name, int def);
int Int(const std::wstring & name, int def);
long Long(const wchar_t *);
long Long(const wchar_t * name, long def);
long Long(const std::wstring & name, long def);
size_t Size(const wchar_t *);
size_t Size(const wchar_t * name, size_t def);
size_t Size(const std::wstring & name, size_t def);
bool Bool(const wchar_t *);
bool Bool(const wchar_t * name, bool def);
bool Bool(const std::wstring & name, bool def);
bool ListText(const wchar_t * name, std::vector<std::wstring> & list);
bool ListText(const std::wstring & name, std::vector<std::wstring> & list);
bool HasValue(const wchar_t * name, const wchar_t * value);
bool HasValue(const wchar_t * name, const std::wstring & value);
bool HasValue(const std::wstring & name, const wchar_t * value);
bool HasValue(const std::wstring & name, const std::wstring & value);
// for debug
void Print(std::wostream & out);
// raw access to the config
PT::Space space;
void SetFileLog(FileLog * file_log);
void SetLogBuffer(PT::WTextStream * log_buffer);
private:
PT::SpaceParser parser;
bool errors_to_stdout;
Log log;
void ShowError();
void AssignValues(bool stdout_is_closed);
void SetAdditionalVariables();
void CheckPasswd();
};
} // namespace Winix
#endif

121
winixd/core/cookieparser.h Normal file
View File

@@ -0,0 +1,121 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2008-2014, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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 headerfile_winix_core_cookieparser
#define headerfile_winix_core_cookieparser
#include "httpsimpleparser.h"
#include "requesttypes.h"
#include "log.h"
namespace Winix
{
class CookieParser : public HttpSimpleParser
{
const wchar_t * cookie_string;
CookieTab * cookie_tab;
protected:
virtual int GetChar()
{
if( !cookie_string || *cookie_string == 0 )
return -1;
return (int)*(cookie_string++);
}
virtual void Parameter(std::wstring & name, std::wstring & value)
{
// Cookie names are case insensitive according to section 3.1 of RFC 2965
// (we don't use locale here)
ToLower(name);
std::pair<CookieTab::iterator, bool> res = cookie_tab->insert( std::make_pair(name, value) );
log << log2 << "Cookie, name: \"" << name << "\", value: \"" << value << "\"";
if( res.second == false )
{
res.first->second = value;
log << " (overwritten)";
}
log << logend;
}
public:
CookieParser()
{
HttpSimpleParser::separator = ';';
HttpSimpleParser::value_can_be_quoted = true;
HttpSimpleParser::skip_white_chars = true;
HttpSimpleParser::recognize_special_chars = false;
HttpSimpleParser::getchar_returns_utf8_chars = false;
}
// cookie_string can be null
void Parse(const wchar_t * cookie_string_, CookieTab & cookie_tab_)
{
cookie_string = cookie_string_;
cookie_tab = &cookie_tab_;
HttpSimpleParser::Parse();
}
void Parse(const std::wstring & cookie_string_, CookieTab & cookie_tab_)
{
Parse(cookie_string_.c_str(), cookie_tab_);
}
};
} // namespace Winix
#endif

356
winixd/core/crypt.cpp Normal file
View File

@@ -0,0 +1,356 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2011-2018, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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.
*
*/
#include <cstring>
#include "crypt.h"
#include "utf8/utf8.h"
#include "log.h"
#include "misc.h"
namespace Winix
{
//void Crypt::SetConfig(Config * pconfig)
//{
// config = pconfig;
//}
void Crypt::set_dependency(WinixBase * winix_base)
{
WinixBase::set_dependency(winix_base);
run.set_dependency(winix_base);
}
char Crypt::ConvertToHexForm(int val)
{
if( val < 10 )
return val + '0';
return val - 10 + 'a';
}
bool Crypt::HashBin(int hash, const char * in, size_t inlen, std::string & out)
{
out.clear();
if( !config )
return false;
run.Clear();
run.set_dependency(this);
PT::WideToUTF8(config->opensll_path, command);
run.Cmd(command);
run.Par("dgst");
run.Par("-binary");
switch(hash)
{
case WINIX_CRYPT_HASH_MD4: run.Par("-md4"); break;
case WINIX_CRYPT_HASH_MD5: run.Par("-md5"); break;
case WINIX_CRYPT_HASH_SHA1: run.Par("-sha1"); break;
case WINIX_CRYPT_HASH_SHA224: run.Par("-sha224"); break;
case WINIX_CRYPT_HASH_SHA256: run.Par("-sha256"); break;
case WINIX_CRYPT_HASH_SHA384: run.Par("-sha384"); break;
case WINIX_CRYPT_HASH_SHA512: run.Par("-sha512"); break;
default:
return false;
}
return run.Go(in, inlen, out) == 0;
}
bool Crypt::HashBin(int hash, const char * in, std::string & out)
{
size_t len = strlen(in);
return HashBin(hash, in, len, out);
}
bool Crypt::HashBin(int hash, const std::string & in, std::string & out)
{
return HashBin(hash, in.c_str(), in.size(), out);
}
bool Crypt::HashBin(int hash, const wchar_t * in, size_t inlen, std::string & out)
{
PT::WideToUTF8(in, inlen, bufina);
int res = HashBin(hash, bufina.c_str(), bufina.size(), out);
bufina.clear();
return res;
}
bool Crypt::HashBin(int hash, const wchar_t * in, std::string & out)
{
size_t len = wcslen(in);
return HashBin(hash, in, len, out);
}
bool Crypt::HashBin(int hash, const std::wstring & in, std::string & out)
{
return HashBin(hash, in.c_str(), in.size(), out);
}
bool Crypt::HashHex(int hash, const char * in, size_t inlen, std::string & out)
{
int res = HashBin(hash, in, inlen, out_temp);
ConvertToHexForm(out_temp, out);
out_temp.clear();
return res;
}
bool Crypt::HashHex(int hash, const char * in, std::string & out)
{
size_t len = strlen(in);
return HashHex(hash, in, len, out);
}
bool Crypt::HashHex(int hash, const std::string & in, std::string & out)
{
return HashHex(hash, in.c_str(), in.size(), out);
}
bool Crypt::HashHex(int hash, const wchar_t * in, size_t inlen, std::wstring & out)
{
int res = HashBin(hash, in, inlen, out_temp);
ConvertToHexForm(out_temp, out);
out_temp.clear();
return res;
}
bool Crypt::HashHex(int hash, const wchar_t * in, std::wstring & out)
{
size_t len = wcslen(in);
return HashHex(hash, in, len, out);
}
bool Crypt::HashHex(int hash, const std::wstring & in, std::wstring & out)
{
return HashHex(hash, in.c_str(), in.size(), out);
}
bool IsAllWhite(const char * str)
{
for( ; *str ; ++str)
{
if( !(IsWhite(*str) || *str==10) )
return false;
}
return true;
}
bool Crypt::RSA(bool encrypt, const char * keypath, const char * in, size_t inlen, std::string & out)
{
out.clear();
if( !config || IsAllWhite(keypath) )
return false;
run.Clear();
PT::WideToUTF8(config->opensll_path, command);
run.Cmd(command);
run.Par("rsautl");
run.Par("-inkey");
run.Par(keypath);
if(encrypt)
run.Par("-encrypt");
else
run.Par("-decrypt");
return run.Go(in, inlen, out) == 0;
}
bool Crypt::RSA(bool encrypt, const char * keypath, const std::string & in, std::string & out)
{
return RSA(encrypt, keypath, in.c_str(), in.size(), out);
}
bool Crypt::RSA(bool encrypt, const std::string & keypath, const std::string & in, std::string & out)
{
return RSA(encrypt, keypath.c_str(), in.c_str(), in.size(), out);
}
bool Crypt::RSA(bool encrypt, const wchar_t * keypath, const char * in, size_t inlen, std::string & out)
{
PT::WideToUTF8(keypath, keypatha);
return RSA(encrypt, keypatha.c_str(), in, inlen, out);
}
bool Crypt::RSA(bool encrypt, const wchar_t * keypath, const std::string & in, std::string & out)
{
return RSA(encrypt, keypath, in.c_str(), in.size(), out);
}
bool Crypt::RSA(bool encrypt, const std::wstring & keypath, const std::string & in, std::string & out)
{
return RSA(encrypt, keypath.c_str(), in.c_str(), in.size(), out);
}
bool Crypt::PassHash(const std::wstring & salt, UserPass & up)
{
bool result = true;
up.pass_hash_salted = false;
if( up.pass_type != WINIX_CRYPT_HASH_NONE )
{
pass_org = up.pass;
pass_salted = up.pass;
pass_salted += salt;
if( HashHex(up.pass_type, pass_salted, up.pass) )
{
if( !salt.empty() )
up.pass_hash_salted = true;
}
else
{
log << log1 << "Crypt: problem with generating a hash, the password will not be hashed" << logend;
up.pass = pass_org;
up.pass_type = WINIX_CRYPT_HASH_NONE;
result = false;
}
ClearString(pass_salted);
ClearString(pass_org);
}
return result;
}
bool Crypt::PassCrypt(const std::wstring & path_to_rsa_private_key, UserPass & up)
{
bool result = false;
ClearString(up.pass_encrypted);
if( !path_to_rsa_private_key.empty() )
{
PT::WideToUTF8(up.pass, passa);
if( RSA(true, path_to_rsa_private_key, passa, up.pass_encrypted) )
{
result = true;
}
else
{
ClearString(up.pass_encrypted);
log << log1 << "AddUser: problem with encrypting, the password will not be encrypted!" << logend;
}
ClearString(passa);
}
return result;
}
void Crypt::PassHashCrypt(const std::wstring & salt, const std::wstring & path_to_rsa_private_key, UserPass & up)
{
PassHash(salt, up);
PassCrypt(path_to_rsa_private_key, up);
}
void Crypt::PassHashCrypt(UserPass & up)
{
up.pass_type = config->pass_type;
empty.clear();
if( config->pass_hash_use_salt && !config->pass_hash_salt.empty() )
PassHash(config->pass_hash_salt, up);
else
PassHash(empty, up);
if( config->pass_use_rsa && !config->pass_rsa_private_key.empty() )
PassCrypt(config->pass_rsa_private_key, up);
}
} // namespace Winix

299
winixd/core/crypt.h Normal file
View File

@@ -0,0 +1,299 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2011-2014, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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 headerfile_winix_core_crypt
#define headerfile_winix_core_crypt
#include <string>
#include "run.h"
#include "config.h"
#include "user.h"
#include "winixbase.h"
namespace Winix
{
/*
the kind of hashes we are able to obtain in winix
*/
#define WINIX_CRYPT_HASH_NONE 0
#define WINIX_CRYPT_HASH_MD4 1
#define WINIX_CRYPT_HASH_MD5 2
#define WINIX_CRYPT_HASH_SHA1 10
#define WINIX_CRYPT_HASH_SHA224 11
#define WINIX_CRYPT_HASH_SHA256 12
#define WINIX_CRYPT_HASH_SHA384 13
#define WINIX_CRYPT_HASH_SHA512 14
/*
calculating hashes, encrypting and decrypting with RSA
*/
class Crypt : public WinixBase
{
public:
void set_dependency(WinixBase * winix_base);
//void SetConfig(Config * pconfig);
/*
calculating a hash from a given input
input:
hash - the kind of the hash - WINIX_CRYPT_HASH_*
in - input buffer
inlen - the length of the buffer
output:
out - the hash in binary form
*/
bool HashBin(int hash, const char * in, size_t inlen, std::string & out);
bool HashBin(int hash, const char * in, std::string & out);
bool HashBin(int hash, const std::string & in, std::string & out);
/*
calculating a hash from a given input
the input string is first changed to UTF8 and then hash is calculated
input:
hash - the kind of the hash - WINIX_CRYPT_HASH_*
in - input buffer
inlen - the length of the buffer
output:
out - the hash in binary form
*/
bool HashBin(int hash, const wchar_t * in, size_t inlen, std::string & out);
bool HashBin(int hash, const wchar_t * in, std::string & out);
bool HashBin(int hash, const std::wstring & in, std::string & out);
/*
calculating a hash from a given input
input:
hash - the kind of the hash - WINIX_CRYPT_HASH_*
in - input buffer
inlen - the length of the buffer
output:
out - the hash in the hex form (one byte is saved as two hex digits)
*/
bool HashHex(int hash, const char * in, size_t inlen, std::string & out);
bool HashHex(int hash, const char * in, std::string & out);
bool HashHex(int hash, const std::string & in, std::string & out);
/*
calculating a hash from a given input
the input string is first changed to UTF8 and then hash is calculated
input:
hash - the kind of the hash - WINIX_CRYPT_HASH_*
in - input buffer
inlen - the length of the buffer
output:
out - the hash in the hex form (one byte is saved as two hex digits)
the 'out' here is std::wstring (not std::string like beforehand)
*/
bool HashHex(int hash, const wchar_t * in, size_t inlen, std::wstring & out);
bool HashHex(int hash, const wchar_t * in, std::wstring & out);
bool HashHex(int hash, const std::wstring & in, std::wstring & out);
/*
encrypt/decrypt by using RSA algorithm
input:
encrypt - true means encrypting, false means decrypting
keypath - path to a RSA private key (this is a private and public key in one file)
in - input buffer
inlen - the size of the buffer
output:
out - encrypted or decrypted buffer (always binary)
*/
bool RSA(bool encrypt, const char * keypath, const char * in, size_t inlen, std::string & out);
bool RSA(bool encrypt, const char * keypath, const std::string & in, std::string & out);
bool RSA(bool encrypt, const std::string & keypath, const std::string & in, std::string & out);
bool RSA(bool encrypt, const wchar_t * keypath, const char * in, size_t inlen, std::string & out);
bool RSA(bool encrypt, const wchar_t * keypath, const std::string & in, std::string & out);
bool RSA(bool encrypt, const std::wstring & keypath, const std::string & in, std::string & out);
/*
this method creates a hash from the given plain text password
input.
salt - salt for the hash
up.pass_type - what kind of hash do you want - look at WINIX_CRYPT_HASH_* macros (in crypt.h)
up.pass - plain text password
if salt is empty then the hash will not be salted
output:
up.pass_type - (can be changed to 0 when there is a problem with generating a hash)
up.pass - hash from the password (or plain text if up.pass_type was zero)
up.pass_hash_salted (true if the hash is salted - when salt was not empty)
if there is a problem with generating a hash the method stores a plain text password
and changes up.pass_type to zero (plain text passwords are not salted)
*/
bool PassHash(const std::wstring & salt, UserPass & up);
/*
this method encrypts the given password
input:
path_to_rsa_private_key - a path to rsa private key (this are a private and public keys both in one file)
up.pass - given password (can be a plain text or a hash)
if path_to_rsa_private_key is empty then the password will not be encrypted
output:
up.pass_encrypted
if there is a problem (or the path to the key is empty) then up.pass_encrypted will be empty
and the method returns false
*/
bool PassCrypt(const std::wstring & path_to_rsa_private_key, UserPass & up);
/*
this method creates a hash from the given plain text password and then encrypts it
input:
salt - salt for the hash
path_to_rsa_private_key - a path to rsa private key (this are a private and public keys both in one file)
up.pass_type - what kind of hash do you want - look at WINIX_CRYPT_HASH_* macros (in crypt.h)
up.pass - plain text password
if salt is empty then the hash will not be salted
if path_to_rsa_private_key is empty then the password will not be encrypted
output:
up.pass_type - (can be changed to 0 when there is a problem with generating a hash)
up.pass - hash from the password (or plain text if up.pass_type was zero)
up.pass_hash_salted (true if the hash is salted - when salt was not empty)
up.pass_encrypted - encrypted password (if not empty)
*/
void PassHashCrypt(const std::wstring & salt, const std::wstring & path_to_rsa_private_key, UserPass & up);
/*
this method creates a hash from the given plain text password and then encrypts it
input:
up.pass - plain text password
output:
up.pass_type - what kind of hash there is in up.pass
up.pass - hash from the password (or plain text if up.pass_type is zero)
up.pass_hash_salted - true if the hash is salted (plain text are never salted)
up.pass_encrypted - encrypted password (if not empty)
*/
void PassHashCrypt(UserPass & up);
/*
putting some characters into the string and then calling clear()
*/
template<class StringType>
void ClearString(StringType & str);
private:
//Config * config;
Run run;
std::string command, bufina, keypatha;
//std::wstring pass_salted;//, pass_hashed;
//std::string pass_hasheda, pass_encrypteda;
std::wstring pass_salted, pass_org;
std::string passa, out_temp;
std::wstring empty;
template<typename StringType>
void ConvertToHexForm(const std::string & in, StringType & out);
char ConvertToHexForm(int val);
};
template<typename StringType>
void Crypt::ClearString(StringType & str)
{
for(size_t i=0 ; i<str.size() ; ++i)
str[i] = 0x0c;
str.clear();
}
template<typename StringType>
void Crypt::ConvertToHexForm(const std::string & in, StringType & out)
{
out.clear();
if( in.size() * 2 > out.capacity() )
out.reserve(in.size() * 2);
for(size_t i=0 ; i<in.size() ; ++i)
{
out += ConvertToHexForm(((unsigned char)in[i]) >> 4);
out += ConvertToHexForm(((unsigned char)in[i]) & 0x0f);
}
}
} // namespace Winix
#endif

68
winixd/core/cur.h Normal file
View File

@@ -0,0 +1,68 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2010-2014, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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 headerfile_winix_core_cur
#define headerfile_winix_core_cur
#include "request.h"
#include "session.h"
#include "mount.h"
namespace Winix
{
/*
current request and session
*/
struct Cur
{
Request * request;
Session * session;
Mount * mount;
// those pointers are never null, if there is no a session for the user
// the 'session' pointer pointers at a special temporary session
};
} // namespace Winix
#endif

View File

@@ -0,0 +1,365 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2008-2014, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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.
*
*/
#include "dircontainer.h"
#include "log.h"
namespace Winix
{
std::wstring DirContainer::dir_etc = L"etc";
std::wstring DirContainer::dir_var = L"var";
DirContainer::DirContainer()
{
is_root = false;
is_etc = false;
is_var = false;
}
DirContainer::Iterator DirContainer::GetRoot()
{
if( !is_root )
return table.end();
return root_iter;
}
DirContainer::Iterator DirContainer::GetEtc()
{
if( !is_etc )
return table.end();
return etc_iter;
}
DirContainer::Iterator DirContainer::GetVar()
{
if( !is_var )
return table.end();
return var_iter;
}
DirContainer::Iterator DirContainer::Begin()
{
return table.begin();
}
DirContainer::Iterator DirContainer::End()
{
return table.end();
}
DirContainer::SizeType DirContainer::Size()
{
return table.size(); // !! warning: it has O(n)
}
bool DirContainer::Empty()
{
return table.empty();
}
bool DirContainer::IsNameOfSpecialFolder(const std::wstring & name)
{
return name == dir_etc || name == dir_var;
}
// looking for '/etc'
// 'root' is found beforehand
// CheckSpecialFolder() may not find everything (when the first is a special folder and then the root)
void DirContainer::FindSpecialFolders()
{
is_etc = false;
is_var = false;
if( !is_root )
return;
DirContainer::ParentIterator i = FindFirstChild(root_iter->id);
for( ; i!=ParentEnd() ; i = NextChild(i) )
{
if( i->second->url == dir_etc )
{
is_etc = true;
etc_iter = i->second;
}
else
if( i->second->url == dir_var )
{
is_var = true;
var_iter = i->second;
}
}
}
// this is used with PushBack() method
void DirContainer::CheckSpecialFolder(const Item & item, Iterator iter)
{
if( item.parent_id == -1 )
{
is_root = true;
root_iter = iter;
}
if( !is_root )
return;
if( item.parent_id==root_iter->id && item.url==dir_etc )
{
is_etc = true;
etc_iter = iter;
log << log2 << "DirCont: added special folder: /etc" << logend;
}
if( item.parent_id==root_iter->id && item.url==dir_var )
{
is_var = true;
var_iter = iter;
log << log2 << "DirCont: added special folder: /var" << logend;
}
}
DirContainer::Iterator DirContainer::PushBack(const Item & item)
{
if( item.parent_id == -1 && is_root )
{
log << log1 << "DirCont: more than one root dir - skipped, id: " << item.id << logend;
return root_iter;
}
Iterator last_iter = table.insert(table.end(), item);
CheckSpecialFolder(item, last_iter);
log << log2 << "DirCont: added dir, url: " << item.url << ", id: " << item.id << ", parent_id: " << item.parent_id << logend;
table_id.insert( std::make_pair(last_iter->id, last_iter) );
table_parent.insert( std::make_pair(last_iter->parent_id, last_iter) );
log << log3 << "DirCont: added indexes to dir, id: " << last_iter->id << ", parent_id: " << last_iter->parent_id << logend;
return last_iter;
}
bool DirContainer::ChangeParent(long dir_id, long new_parent_id)
{
Iterator i = FindId(dir_id);
if( i == table.end() )
return false;
if( i->parent_id == new_parent_id )
return true; // nothing to do
ParentIterator p = FindFirstChild(i->parent_id);
bool found = false;
for( ; p != table_parent.end() ; p = NextChild(p) )
{
if( p->second->id == dir_id )
{
table_parent.erase(p);
log << log3 << "DirCont: removed parent index to dir: " << i->id << logend;
i->parent_id = new_parent_id;
table_parent.insert( std::make_pair(new_parent_id, i) );
log << log3 << "DirCont: added parent index to dir, id: " << i->id << ", parent_id: " << i->parent_id << logend;
found = true;
if( IsNameOfSpecialFolder(i->url) )
FindSpecialFolders();
break; // that iterator (p) is only one
}
}
if( !found )
log << log1 << "DirCont: cannot find parent_id: " << i->parent_id << " in parent indexes" << logend;
return found;
}
void DirContainer::Clear()
{
table.clear();
table_id.clear();
table_parent.clear();
is_root = false;
}
DirContainer::Iterator DirContainer::FindId(long id)
{
TableId::iterator i = table_id.find(id);
if( i == table_id.end() )
return table.end();
return i->second;
}
DirContainer::ParentIterator DirContainer::ParentBegin()
{
return table_parent.begin();
}
DirContainer::ParentIterator DirContainer::ParentEnd()
{
return table_parent.end();
}
DirContainer::ParentSizeType DirContainer::ParentSize()
{
return table_parent.size();
}
bool DirContainer::ParentEmpty()
{
return table_parent.empty();
}
DirContainer::ParentIterator DirContainer::FindFirstChild(long parent)
{
ParentIterator i = table_parent.lower_bound(parent);
if( i == table_parent.end() || i->first != parent )
return table_parent.end();
return i;
}
DirContainer::ParentIterator DirContainer::NextChild(ParentIterator i)
{
if( i == table_parent.end() )
return table_parent.end();
long parent = i->first;
++i;
if( i == table_parent.end() || i->first != parent )
return table_parent.end();
return i;
}
bool DirContainer::DelById(long id)
{
TableId::iterator i = table_id.find(id);
if( i == table_id.end() )
{
log << log1 << "DirCont: delete: there is no directory with id: " << id << logend;
return false;
}
long parent_id = i->second->parent_id;
TableParent::iterator z = table_parent.lower_bound(parent_id);
bool found = false;
for( ; z != table_parent.end() && z->first == parent_id ; ++z )
{
if( z->second == i->second )
{
log << log2 << "DirCont: deleted directory id: " << id << ", url: " << i->second->url;
if( i->second->parent_id == -1 )
{
log << log2 << " (root directory)";
is_root = false;
}
log << log2 << logend;
table.erase(i->second);
log << log3 << "DirCont: deleted indexes into directory id: " << id << logend;
table_id.erase(i);
table_parent.erase(z);
found = true;
break;
}
}
if( !found )
{
log << log1 << "DirCont: can't find an index_parent into directory id: " << id << ", url: " << i->second->url << " (deleting skipped)" << logend;
return false;
}
return true;
}
} // namespace Winix

129
winixd/core/dircontainer.h Normal file
View File

@@ -0,0 +1,129 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2008-2014, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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 headerfile_winix_core_dircontainer
#define headerfile_winix_core_dircontainer
#include <list>
#include <map>
#include "item.h"
#include "winixbase.h"
namespace Winix
{
class DirContainer : public WinixBase
{
public:
typedef std::list<Item> Table;
typedef Table::iterator Iterator;
typedef Table::size_type SizeType;
typedef std::map<long, Iterator> TableId;
typedef std::multimap<long, Iterator> TableParent;
typedef TableParent::iterator ParentIterator;
typedef TableParent::size_type ParentSizeType;
DirContainer();
Iterator GetRoot();
Iterator GetEtc();
Iterator GetVar();
Iterator Begin();
Iterator End();
SizeType Size();
bool Empty();
Iterator PushBack(const Item & item);
bool ChangeParent(long dir_id, long new_parent_id);
void Clear();
Iterator FindId(long id);
bool DelById(long id);
ParentIterator ParentBegin(); // IMPROVE ME: may it should be renamed to ChildBegin() similarly as FindFirstChild() ?
ParentIterator ParentEnd();
ParentSizeType ParentSize();
bool ParentEmpty();
ParentIterator FindFirstChild(long parent);
ParentIterator NextChild(ParentIterator pi);
bool IsNameOfSpecialFolder(const std::wstring & name);
void FindSpecialFolders();
private:
void CheckSpecialFolder(const Item & item, Iterator iter);
// main table with dirs
Table table;
// true if there is a root dir in the table
bool is_root;
// root
Iterator root_iter;
// true if there is a etc dir in the table
bool is_etc;
// etc
Iterator etc_iter;
// true if there is a var dir in the table
bool is_var;
// var
Iterator var_iter;
// indexes
TableId table_id;
TableParent table_parent;
// names of folders
static std::wstring dir_etc, dir_var;
};
} // namespace Winix
#endif

796
winixd/core/dirs.cpp Normal file
View File

@@ -0,0 +1,796 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2008-2018, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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.
*
*/
#include "dirs.h"
#include "error.h"
#include "notify/notify.h"
namespace Winix
{
void Dirs::SetDb(Db * pdb)
{
db = pdb;
}
void Dirs::SetCur(Cur * pcur)
{
cur = pcur;
}
void Dirs::SetNotify(Notify * pnotify)
{
notify = pnotify;
}
void Dirs::set_dependency(WinixModel * winix_model)
{
WinixModel::set_dependency(winix_model);
dir_tab.set_dependency(winix_model);
}
void Dirs::Clear()
{
dir_tab.Clear();
}
bool Dirs::HasReadExecAccessForRoot(const Item & item)
{
// there must be at least one 'x' (for the root)
return (item.privileges & 01111) != 0;
}
void Dirs::CheckRootDir()
{
DirContainer::Iterator i = dir_tab.GetRoot();
if( i != dir_tab.End() )
{
if( !HasReadExecAccessForRoot(*i) )
{
i->privileges = 07555;
log << log1 << "Dirs: there is no access for a root (admin) to the root dir, setting 07555 for the root directory" << logend;
db->EditPrivById(*i, i->id);
}
return;
}
log << log1 << "Dirs: there is no a root directory in the database (creating one)" << logend;
Item root;
root.type = Item::dir;
root.parent_id = -1;
root.user_id = -1;
root.group_id = -1;
root.privileges = 07555;
// !! upewnic sie ze baza nie zmieni url (gdyby wczesniej juz byl w bazie pusty url)
// !! zrobic jakis wyjatek do wprowadzania roota?
if( db->AddItem(root) == WINIX_ERR_OK )
{
dir_tab.PushBack(root);
}
}
void Dirs::ReadDirs()
{
Clear();
db->GetDirs(dir_tab);
CheckRootDir();
dir_tab.FindSpecialFolders();
}
bool Dirs::ExtractName(const wchar_t * & s, std::wstring & name)
{
name.clear();
// skipping first slashes (can be more than one)
for( ; *s == '/' ; ++s);
for( ; *s != 0 && *s != '/' ; ++s)
name += *s;
return !name.empty();
}
bool Dirs::IsDir(long id)
{
DirContainer::Iterator i = dir_tab.FindId(id);
if( i == dir_tab.End() )
return false;
return true;
}
// !! dac clearowanie childs_tab
// !! ewentualnie mozna dodac trzeci domyslny parametr bool clear_tab = true
bool Dirs::GetDirChilds(long parent, std::vector<Item*> & childs_tab)
{
if( parent != -1 && !IsDir(parent) )
return false;
DirContainer::ParentIterator i = dir_tab.FindFirstChild(parent);
for( ; i != dir_tab.ParentEnd() ; i = dir_tab.NextChild(i) )
childs_tab.push_back( &(*i->second) );
return true;
}
DirContainer::ParentIterator Dirs::FindFirstChild(long parent_id)
{
DirContainer::ParentIterator i = dir_tab.FindFirstChild(parent_id);
return i;
}
DirContainer::ParentIterator Dirs::NextChild(DirContainer::ParentIterator i)
{
return dir_tab.NextChild(i);
}
DirContainer::ParentIterator Dirs::ParentEnd()
{
return dir_tab.ParentEnd();
}
// !! dodatkowo moze metoda AppendPath dodajaca sciezke do biezacego stringa?
// albo tutaj stringa nie czyscic?
// O(m * log n) (m- how many parts are in 'id')
// path with a slash at the end and at the beginning
bool Dirs::MakePath(long id, std::wstring & path, bool clear_path)
{
DirContainer::Iterator i;
if( clear_path )
path.clear();
temp_path = '/';
while( true )
{
i = dir_tab.FindId(id);
if( i == dir_tab.End() ||
i->parent_id == id ) // means a loop (something wrong in the db)
{
// we don't change path if there is no such a directory
return false;
}
if( i->parent_id == -1 )
{
path += temp_path;
return true;
}
id = i->parent_id;
temp_path.insert(0, i->url);
temp_path.insert(temp_path.begin(), '/');
}
}
void Dirs::MakePath(const std::vector<Item*> dir_tab, std::wstring & path, bool clear_path)
{
if( clear_path )
path.clear();
for(size_t i=0 ; i<dir_tab.size() ; ++i)
{
path += dir_tab[i]->url;
path += '/';
}
}
size_t Dirs::DirLevel(long id)
{
DirContainer::Iterator i;
size_t level = 0;
while( true )
{
i = dir_tab.FindId(id);
if( i == dir_tab.End() ||
i->parent_id == id ) // means a loop (something wrong in the db)
{
return level;
}
if( i->parent_id == -1 )
return level;
id = i->parent_id;
level += 1;
}
}
bool Dirs::IsChild(long parent_id, long child_id)
{
if( child_id == parent_id )
return false;
DirContainer::Iterator i;
while( child_id != -1 )
{
i = dir_tab.FindId(child_id);
if( i == dir_tab.End() )
return false;
if( i->parent_id == parent_id )
return true;
child_id = i->parent_id;
}
return false;
}
bool Dirs::ChangeParent(long dir_id, long new_parent_id)
{
return dir_tab.ChangeParent(dir_id, new_parent_id);
}
/*
checking whether dir_id has a parent parent_id (somewhere in the path)
*/
bool Dirs::HasParent(long dir_id, long parent_id)
{
DirContainer::Iterator i;
while( true )
{
i = dir_tab.FindId(dir_id);
if( i==dir_tab.End() || i->parent_id==-1 )
return false;
if( i->parent_id == parent_id )
return true;
dir_id = i->parent_id;
}
}
bool Dirs::CreateDirTab(long dir_id, std::vector<Item*> & out_dir_tab)
{
DirContainer::Iterator i;
out_dir_tab.clear();
do
{
i = dir_tab.FindId(dir_id);
if( i == dir_tab.End() )
return false;
if( out_dir_tab.empty() )
out_dir_tab.insert(out_dir_tab.end(), &(*i)); // !! I am not sure whether begin() can be used on an empty container
else
out_dir_tab.insert(out_dir_tab.begin(), &(*i));
dir_id = i->parent_id;
}
while( dir_id != -1 );
return true;
}
Item * Dirs::GetRootDir()
{
DirContainer::Iterator root = dir_tab.GetRoot();
if( root == dir_tab.End() )
return 0;
return &(*root);
}
Item * Dirs::GetEtcDir()
{
DirContainer::Iterator etc = dir_tab.GetEtc();
if( etc == dir_tab.End() )
return 0;
return &(*etc);
}
Item * Dirs::GetVarDir()
{
DirContainer::Iterator etc = dir_tab.GetVar();
if( etc == dir_tab.End() )
return 0;
return &(*etc);
}
Item * Dirs::GetDir(const wchar_t * name, long parent)
{
DirContainer::ParentIterator i = dir_tab.FindFirstChild(parent);
for( ; i!=dir_tab.ParentEnd() ; i = dir_tab.NextChild(i) )
if( i->second->url == name )
return &(*i->second);
return 0;
}
Item * Dirs::GetDir(const std::wstring & name, long parent)
{
return GetDir(name.c_str(), parent);
}
Item * Dirs::GetDir(const wchar_t * path)
{
if( *path == 0 )
return 0;
DirContainer::Iterator root = dir_tab.GetRoot();
if( root == dir_tab.End() )
// ops, we do not have a root dir
return 0;
Item * pitem = &(*root);
const wchar_t * s = path;
while( ExtractName(s, get_dir_temp) )
{
pitem = GetDir(get_dir_temp, pitem->id);
if( !pitem )
return 0;
}
return pitem;
}
Item * Dirs::GetDir(const std::wstring & path)
{
return GetDir(path.c_str());
}
Item * Dirs::GetDir(long id)
{
DirContainer::Iterator i = dir_tab.FindId(id);
if( i == dir_tab.End() )
return 0;
return &(*i);
}
Item * Dirs::AddDir(const Item & item)
{
return &(*dir_tab.PushBack(item));
}
size_t Dirs::AnalyzeDir(Item * pdir, const std::wstring & path, long & dir_id, std::wstring & dir)
{
size_t i = 0;
size_t old_i;
while( true )
{
dir_id = pdir->id;
// skipping slashes
for( ; i<path.size() && path[i] == '/' ; ++i );
if( i == path.size() )
return i; // end of the path
// creating a name
old_i = i;
analyze_temp.clear();
for( ; i<path.size() && path[i] != '/' ; ++i)
analyze_temp += path[i];
pdir = GetDir(analyze_temp, pdir->id);
if( !pdir )
return old_i; // analyze_temp is not a directory
dir += analyze_temp;
dir += '/';
}
}
/*
the path should begin with a slash
return values:
0 - directory exists
dir_id - id of the directory
dir - the path to the directory (with a slash at the end)
file - if not empty means a file name (we don't check if the file really exists)
1 - there is not a root dir
2 - the path is empty
3 - there is not such a directory
*/
int Dirs::AnalyzePath(const std::wstring & path, long & dir_id, std::wstring & dir, std::wstring & file)
{
Item * pdir = GetRootDir();
dir = '/';
file.clear();
if( !pdir )
return 1;
if( path.empty() )
return 2;
if( path[0] != '/' )
return 3;
size_t i = AnalyzeDir(pdir, path, dir_id, dir);
if( i < path.size() )
{
// checking if at least one slash has left
for(size_t a=i ; a < path.size() ; ++a)
if( path[a] == '/' )
return 3; // there is not such a directory
// the rest of the path is a file name
file = path.c_str() + i;
}
return 0;
}
// current_dir_tab can be the same container as out_dir_tab
void Dirs::CopyDirTab(const std::vector<Item*> & in, std::vector<Item*> & out)
{
if( &in != &out )
{
out.resize(in.size());
for(size_t i=0 ; i<in.size() ; ++i)
out[i] = in[i];
}
}
/*
!! IMPROVE ME
may dir_tab can be empty when link_to is not relative?
and now the algorith doesn't check if link_to is not relative (it only uses dir_tab)
*/
bool Dirs::AnalyzeDir(std::vector<Item*> & dir_tab, const std::wstring & link_to, size_t & i)
{
size_t old_i;
i = 0;
if( dir_tab.empty() )
return false;
while( true )
{
// skipping slashes
for( ; i<link_to.size() && link_to[i] == '/' ; ++i);
if( i == link_to.size() )
return true; // end of the path
// creating a name
old_i = i;
analyze_temp.clear();
for( ; i<link_to.size() && link_to[i] != '/' ; ++i)
analyze_temp += link_to[i];
if( analyze_temp == L".." )
{
if( dir_tab.size() <= 1 )
return false;
dir_tab.pop_back();
}
else
if( analyze_temp != L"." )
{
Item * pdir = GetDir(analyze_temp, dir_tab.back()->id);
if( !pdir )
{
i = old_i;
return true; // analyze_temp is not a directory
}
dir_tab.push_back(pdir);
}
}
}
int Dirs::FollowLink(std::vector<Item*> & dir_tab, const std::wstring & link_to, std::wstring & out_item)
{
size_t i;
if( !AnalyzeDir(dir_tab, link_to, i) )
return 2; // incorrect link_to
if( i < link_to.size() )
{
// checking if at least one slash has left
for(size_t a=i ; a < link_to.size() ; ++a)
if( link_to[a] == '/' )
return 2; // there is not such a directory
// the rest of the path is a file name
out_item = link_to.c_str() + i;
return 1;
}
return 0;
}
/*
return codes:
ok:
0 - the link_to is a path to a directory (out_item skipped, out_dir_tab will not be empty)
1 - the link_to is a path to a file (out_item is used, out_dir_tab will not be empty)
error:
2 - incorrect link_to
3 - there is not a root dir
4 - current_dir_tab was empty
current_dir_tab can be the same container as out_dir_tab
link_to can be a relative path (without the first slash) and can contain ".." or "."
*/
int Dirs::FollowLink(const std::vector<Item*> & current_dir_tab, const std::wstring & link_to,
std::vector<Item*> & out_dir_tab, std::wstring & out_item)
{
temp_link_to = link_to; // link_to can be from the out_item and would be cleared next
out_item.clear();
if( current_dir_tab.empty() )
return 4;
if( temp_link_to.empty() )
{
CopyDirTab(current_dir_tab, out_dir_tab);
return 0;
}
if( temp_link_to[0] == '/' )
{
// temp_link_to is an absolute path
Item * pdir = GetRootDir();
if( !pdir )
return 3;
out_dir_tab.clear();
out_dir_tab.push_back(pdir);
}
else
{
// temp_link_to is a relative path
CopyDirTab(current_dir_tab, out_dir_tab);
}
return FollowLink(out_dir_tab, temp_link_to, out_item);
}
void Dirs::SplitPath(const std::wstring & path, std::wstring & dir, std::wstring & file)
{
std::wstring::size_type i;
dir.clear();
file.clear();
if( path.empty() )
// !! moze dir ustawic na '/' ?
return;
for( i=path.size()-1 ; i>0 && path[i]!='/' ; --i);
if( path[i] != '/' )
{
// we do not have any slashes '/'
file = path;
return;
}
dir.assign(path, 0, i + 1); // +1 means with a slash at the end
if( i < path.size() - 1 )
file.assign(path, i+1, path.size() - i - 1);
}
// !! dodac kasowanie z bazy
bool Dirs::DelDir(long dir_id)
{
return dir_tab.DelById(dir_id);
}
Error Dirs::AddDirectory(Item & item, bool add_to_dir_tab, Item ** pdir, int notify_code)
{
if( pdir )
*pdir = 0;
if( item.type != Item::dir )
return WINIX_ERR_DIR_EXPECTED;
Error status = db->AddItem(item);
if( status == WINIX_ERR_OK )
{
Item * d = AddDir(item);
if( add_to_dir_tab && !cur->request->dir_tab.empty() && cur->request->dir_tab.back()->id == item.parent_id )
cur->request->dir_tab.push_back(d);
if( pdir )
*pdir = d;
if( notify_code )
notify->ItemChanged(notify_code, item);
}
return status;
}
Item * Dirs::CreateVarDir()
{
Item * var = GetVarDir();
if( var )
return var;
Item v;
Item * root = GetRootDir();
if( root )
{
v.parent_id = root->id;
v.user_id = root->user_id;
v.group_id = root->group_id;
v.privileges = root->privileges;
v.subject = L"var";
v.url = L"var";
v.type = Item::dir;
AddDirectory(v, false, &var);
}
return var;
}
// printing first and last slash
void Dirs::LogDir(const std::vector<Item*> & dir_tab)
{
log << '/';
// skipping the first (root) directory
for(size_t i=1 ; i<dir_tab.size() ; ++i)
log << dir_tab[i]->url << '/';
}
} // namespace Winix

156
winixd/core/dirs.h Normal file
View File

@@ -0,0 +1,156 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2008-2018, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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 headerfile_winix_core_dirs
#define headerfile_winix_core_dirs
#include <vector>
#include <map>
#include <string>
#include "item.h"
#include "dircontainer.h"
#include "db/db.h"
#include "request.h"
#include "winixmodel.h"
namespace Winix
{
class Notify;
// !! IMPROVE ME
// we do not support '..' in a path (for simplicity and security reasons)
// (we will support '..' in the future)
class Dirs : public WinixModel
{
public:
void Clear();
void ReadDirs();
void SetCur(Cur * pcur);
void SetDb(Db * pdb);
void SetNotify(Notify * pnotify);
void set_dependency(WinixModel * winix_model);
// these methods return false if there is no such a dir
bool IsDir(long dir_id);
bool GetDirChilds(long parent_id, std::vector<Item*> & childs_tab); // !! zamienic na GetChilds()
bool MakePath(long dir_id, std::wstring & path, bool clear_path = true);
void MakePath(const std::vector<Item*> dir_tab, std::wstring & path, bool clear_path = true);
bool ChangeParent(long dir_id, long new_parent_id);
bool HasParent(long dir_id, long parent_id);
bool DelDir(long dir_id);
// if returns true then out_dir_tab is not empty
bool CreateDirTab(long dir_id, std::vector<Item*> & out_dir_tab);
void LogDir(const std::vector<Item*> & dir_tab);
int AnalyzePath(const std::wstring & path, long & dir_id, std::wstring & dir, std::wstring & file);
int FollowLink(const std::vector<Item*> & current_dir_tab, const std::wstring & link_to,
std::vector<Item*> & out_dir_tab, std::wstring & out_item);
static void SplitPath(const std::wstring & path, std::wstring & dir, std::wstring & file);
DirContainer::ParentIterator FindFirstChild(long parent_id);
DirContainer::ParentIterator NextChild(DirContainer::ParentIterator i);
DirContainer::ParentIterator ParentEnd(); // !! pozostalo do zamiany na child
// these methods return null if there is no such a dir
// !! zmienic nazwy wskazujace ze operujemy tylko na lokalnej tablicy
Item * GetRootDir();
Item * GetEtcDir();
Item * GetVarDir();
Item * GetDir(const wchar_t * name, long parent);
Item * GetDir(const std::wstring & name, long parent);
Item * GetDir(const wchar_t * path);
Item * GetDir(const std::wstring & path);
Item * GetDir(long id);
Item * AddDir(const Item & item);
void CheckRootDir();
Item * CreateVarDir();
// !! jak juz wczesniejsze nazwy beda zmienione to tutaj damy AddDir() /AddDir() juz istnieje przeciez?/
Error AddDirectory(Item & item, bool add_to_dir_tab = false, Item ** pdir = 0, int notify_code = 0);
// returns how many levels of directories there are
// "/" -> 0 (root dir)
// "/abc" -> 1
// "/abc/def" -> 2
size_t DirLevel(long id);
// checking if child_id is really a child of parent_id
bool IsChild(long parent_id, long child_id);
private:
Cur * cur;
Db * db;
Notify * notify;
DirContainer dir_tab;
std::wstring temp_path;
std::wstring temp_link_to;
size_t AnalyzeDir(Item * pdir, const std::wstring & path, long & dir_id, std::wstring & dir);
bool AnalyzeDir(std::vector<Item*> & dir_tab, const std::wstring & link_to, size_t & i);
std::wstring analyze_temp;
std::wstring get_dir_temp;
void CopyDirTab(const std::vector<Item*> & in, std::vector<Item*> & out);
int FollowLink(std::vector<Item*> & dir_tab, const std::wstring & link_to, std::wstring & out_item);
bool ExtractName(const wchar_t * & s, std::wstring & name);
bool HasReadExecAccessForRoot(const Item & item);
};
} // namespace Winix
#endif

111
winixd/core/error.h Normal file
View File

@@ -0,0 +1,111 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2008-2014, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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 headerfile_winix_core_error
#define headerfile_winix_core_error
namespace Winix
{
#define WINIX_ERR_OK 0
//#define WINIX_ERR_INCORRECT_PATH 1
//#define WINIX_ERR_NO_POSTVAR 2
#define WINIX_ERR_INCORRECT_DIR 3
#define WINIX_ERR_CANT_CHANGE_USER 4
#define WINIX_ERR_CANT_CHANGE_GROUP 5
#define WINIX_ERR_CANT_CHANGE_PRIVILEGES 6
#define WINIX_ERR_PERMISSION_DENIED 7
#define WINIX_ERR_NO_ROOT_DIR 8
#define WINIX_ERR_NO_FUNCTION 9
#define WINIX_ERR_NO_ITEM 10
#define WINIX_ERR_UNKNOWN_PARAM 11
#define WINIX_ERR_MOUNT_UNKNOWN 12
#define WINIX_ERR_UNKNOWN_FILESYSTEM 13
#define WINIX_ERR_NO_MOUNTPOINT 14
//#define WINIX_ERR_MOUNT_NO_PARAM 15
#define WINIX_ERR_NO_THREAD 16
#define WINIX_ERR_EMPTY 17
#define WINIX_ERR_SPAM 18
#define WINIX_ERR_INCORRECT_REBUS 19
#define WINIX_ERR_NO_BOUNDARY 20
#define WINIX_ERR_BROKEN_INPUT 21
#define WINIX_ERR_INPUT_TOO_LARGE 22
#define WINIX_ERR_CANT_CREATE_FILE 23
#define WINIX_ERR_NO_TICKET 24
//#define WINIX_ERR_PASSWORDS_DIFFERENT 25
//#define WINIX_ERR_PASSWORD_TOO_SHORT 26
//#define WINIX_ERR_USER_EXISTS 27
//#define WINIX_ERR_LOGIN_EMPTY 28
#define WINIX_DIFFERENT_MOUNT_POINTS 29
#define WINIX_ERR_DB_FATAL_ERROR_DURING_CONNECTING 100
#define WINIX_ERR_DB_INCORRECT_QUERY 101
#define WINIX_ERR_DB_INCORRENT_RESULT_STATUS 102
#define WINIX_ERR_DB_NO_COLUMN 103
#define WINIX_ERR_DB_INCORRECT_LOGIN 104
#define WINIX_ERR_DB_MORE_THAN_ONE_LOGIN 105
#define WINIX_ERR_DB_ERR_CURRVAL 106
#define WINIX_ERR_FILE_EXPECTED 107
#define WINIX_ERR_DIR_EXPECTED 108
//#define WINIX_ERR_UNKNOWN 1000
#define WINIX_NOTHING_TO_DO 109
#define WINIX_ERR_INCORRECT_URI 110
#define WINIX_ERR_INTERNAL_ERROR 2000
typedef int Error;
} // namespace Winix
#endif

135
winixd/core/filelog.cpp Normal file
View File

@@ -0,0 +1,135 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2018-2019, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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.
*
*/
#include "filelog.h"
#include <ctime>
#include <string.h>
#include "utf8/utf8.h"
#include "timezones.h"
namespace Winix
{
FileLog::FileLog()
{
time_zones = nullptr;
synchro = nullptr;
log_time_zone_id = 0;
}
FileLog::~FileLog()
{
}
void FileLog::set_synchro(Synchro * synchro)
{
this->synchro = synchro;
}
void FileLog::init(const std::wstring & log_file, bool log_stdout, int log_level, bool save_each_line, size_t log_time_zone_id)
{
PT::FileLog::init(log_file, log_stdout, log_level, save_each_line);
this->log_time_zone_id = log_time_zone_id;
}
void FileLog::set_time_zones(TimeZones * time_zones)
{
this->time_zones = time_zones;
}
int FileLog::get_log_level()
{
return log_level;
}
bool FileLog::should_save_each_line()
{
return save_each_line;
}
PT::Date FileLog::get_local_date(const PT::Date & date)
{
if( time_zones )
{
Lock lock(synchro);
TimeZone * tz = time_zones->GetZone(log_time_zone_id);
if( tz )
{
PT::Date local_date = tz->ToLocal(date);
return local_date;
}
else
{
return date;
}
}
else
{
return date;
}
}
bool FileLog::synchro_lock()
{
return synchro->Lock();
}
void FileLog::synchro_unlock()
{
synchro->Unlock();
}
} // namespace Winix

92
winixd/core/filelog.h Normal file
View File

@@ -0,0 +1,92 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2018, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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 headerfile_winix_core_filelog
#define headerfile_winix_core_filelog
#include <sstream>
#include <fstream>
#include <iostream>
#include <string>
#include "core/synchro.h"
#include "log/log.h"
namespace Winix
{
class TimeZones;
class FileLog : public PT::FileLog
{
public:
FileLog();
virtual ~FileLog();
void set_synchro(Synchro * synchro);
void init(const std::wstring & log_file, bool log_stdout, int log_level, bool save_each_line, size_t log_time_zone_id);
void set_time_zones(TimeZones * time_zones);
PT::Date get_local_date(const PT::Date & date);
int get_log_level();
bool should_save_each_line();
protected:
size_t log_time_zone_id;
TimeZones * time_zones;
Synchro * synchro;
virtual bool synchro_lock();
virtual void synchro_unlock();
};
} // namespace Winix
#endif

74
winixd/core/group.h Normal file
View File

@@ -0,0 +1,74 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2008-2014, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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 headerfile_winix_core_group
#define headerfile_winix_core_group
#include <string>
#include <vector>
namespace Winix
{
struct Group
{
long id;
std::wstring name; // group name
std::vector<long> members; // users id
Group()
{
Clear();
}
void Clear()
{
id = -1;
name.clear();
members.clear();
}
};
} // namespace Winix
#endif

133
winixd/core/groups.cpp Normal file
View File

@@ -0,0 +1,133 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2008-2018, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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.
*
*/
#include "groups.h"
namespace Winix
{
Groups::Groups()
{
Clear();
}
void Groups::set_dependency(WinixModel * winix_model)
{
WinixModel::set_dependency(winix_model);
table.set_dependency(winix_model);
}
void Groups::Clear()
{
table.Clear();
}
void Groups::ReadGroups(Db * db)
{
Clear();
db->GetGroups(table);
}
Group * Groups::GetGroup(long group_id)
{
Table::Iterator i = table.FindId(group_id);
if( i == table.End() )
return 0;
return &(*i);
}
Group * Groups::GetGroup(const std::wstring & name)
{
Table::Iterator i = table.FindName(name);
if( i == table.End() )
return 0;
return &(*i);
}
long Groups::GetGroupId(const std::wstring & name)
{
Group * pgroup = GetGroup(name);
if( !pgroup )
return -1;
return pgroup->id;
}
Groups::Iterator Groups::Begin()
{
return table.Begin();
}
Groups::Iterator Groups::End()
{
return table.End();
}
Groups::SizeType Groups::Size()
{
return table.Size();
}
bool Groups::Remove(long group_id)
{
return table.Remove(group_id);
}
} // namespace Winix

85
winixd/core/groups.h Normal file
View File

@@ -0,0 +1,85 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2008-2018, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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 headerfile_winix_core_groups
#define headerfile_winix_core_groups
#include <map>
#include "group.h"
#include "ugcontainer.h"
#include "db/db.h"
#include "winixmodel.h"
namespace Winix
{
class Groups : public WinixModel
{
typedef UGContainer<Group> Table;
Table table;
public:
void set_dependency(WinixModel * winix_model);
typedef Table::Iterator Iterator;
typedef Table::SizeType SizeType;
Groups();
void Clear();
void ReadGroups(Db * db);
Group * GetGroup(long group_id);
Group * GetGroup(const std::wstring & name);
long GetGroupId(const std::wstring & name);
Iterator Begin();
Iterator End();
SizeType Size();
bool Remove(long group_id);
};
} // namespace Winix
#endif

1708
winixd/core/htmlfilter.cpp Normal file

File diff suppressed because it is too large Load Diff

373
winixd/core/htmlfilter.h Normal file
View File

@@ -0,0 +1,373 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2008-2018, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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 headerfile_winix_core_htmlfilter
#define headerfile_winix_core_htmlfilter
#include <string>
#include <map>
#include <vector>
#include <algorithm>
#include "core/winixbase.h"
namespace Winix
{
// max length of a name of a html tag (with terminating null)
#define WINIX_HTMLFILTER_ITEM_NAME_MAXLEN 30
// max length of a html lang attribute (e.g. "en", "pl")
#define WINIX_HTMLFILTER_ITEM_LANG_MAXLEN 10
#define WINIX_HTMLFILTER_ATTR_NAME_MAXLEN 40
#define WINIX_HTMLFILTER_ATTR_VALUE_MAXLEN 500
// depth of the html tree
#define WINIX_HTMLFILTER_STACK_MAXLEN 100
// length of a buffer used for printing
// it should be at least: WINIX_HTMLFILTER_ITEM_NAME_MAXLEN+3
#define WINIX_HTMLFILTER_BUFFER_MAXLEN 2048
/*!
very lightweight filter for html
(without using any dynamic memory - some memory is allocated only at the beginning - in ctors)
this filter has O(n) complexity over the whole html string
such tags as: <script> <pre> <textarea> are treated in a special way
all characters between the opening and closing tag (<script>....</script>) are untouched
if the filter finds that there are not closed tags it will close them,
if the filter finds a closing tag which doesn't have an opening tag - it will skip it
tags which don't need to be closed: meta, input, br, img, link
look at CheckExceptions() method
the filter recognizes xml simple tags (with / at the end) such as: <br />
*/
class HTMLFilter : public WinixBase
{
public:
enum OrphanMode
{
orphan_nbsp, // putting "&nbsp;" string
orphan_160space // putting 160 ascii code
};
HTMLFilter();
HTMLFilter(const HTMLFilter & f);
HTMLFilter & operator=(const HTMLFilter & f);
virtual ~HTMLFilter();
// main methods used for filtering
void Filter(const wchar_t * in, std::wstring & out);
void Filter(const std::wstring & in, std::wstring & out);
// insert a white space into long words
// (only between html tags)
// skipped in such tags: script, pre, textarea
// break_after - after how many characters insert a space (0 - off)
void BreakWord(size_t break_after_);
// insert a new line character into long lines
// (only between html tags)
// skipped in such tags: script, pre, textarea
// wrap_line - after how many characters wrap a line (0 - off)
// lines are wrapped only in 'body' tag (useful for text in 'title' tag which is in 'head' section)
void WrapLine(size_t wrap_line_);
// trimming white characters (with new lines)
// at the beginning, at the end and in the middle of a string
// only between html tags
// at the beginning and at the end only one space is left
// skipped in such tags: script, pre, textarea
// false by default
void TrimWhite(bool trim);
// first tabs in a tree
// default: 2 (spaces)
// set 0 to turn off
void InsertTabs(size_t tabsize);
// set a name of a html tag which will be used as 'nofilter' tag
// elements between such tags are not filtered (similarly as in <pre> and <textarea>)
// these tags (opening and closing) will no be placed in the html output
void SetNoFilterTag(const std::wstring & tag_name);
// orphans are checked only in 'body' tag
void AssignOrphans(const wchar_t * lang_code, const std::vector<std::wstring> & otab);
void AssignOrphans(const std::wstring & lang_code, const std::vector<std::wstring> & otab);
void ClearOrphans();
// check 'orphans' for the specicic language
// if an orphan is detected then the non-break space ("&nbsp;" or ascii 160 code) will be put
// default disable (lang_none)
void OrphansMode(const std::wstring & orphan_mode);
// skipping some unsafe tags
// (script, iframe, frame, frameset, applet, head, meta, html, link, body, ...)
void SafeMode(bool safe_mode_);
// skip all html tags
// gives only text without markup
// but there can be commentaries
void SkipTags(bool skip_tags);
// skip commentaries
void SkipCommentaries(bool skip_commentaries);
// if true then entities such as &nbsp; are skipped
// this automatically turns on AnalyzeEntities
// in such a case FoundEntity callbacks are sent
void SkipEntities(bool skip_entities);
// analyze html entities such as &nbsp;
// virtual method: FoundEntity is called
// entities are analyzed in normal text and in attribute values such as <p class="a&nbsp;">
void AnalyzeEntities(bool analyze_entities);
protected:
// orphans for one language
struct Orphans
{
std::vector<std::wstring> tab;
size_t max_len;
};
// orphans for all languages
// map<language_code, Orphans>
typedef std::map<std::wstring, Orphans> OrphansTab;
OrphansTab orphans_tab;
// html <nofilter> tag name
std::wstring no_filter_tag;
struct Item
{
std::wstring name; // max size: WINIX_HTMLFILTER_ITEM_NAME_MAXLEN
enum Type
{
opening, /* sample: <h1> */
closing, /* sample: </h1> */
simple, /* sample: <br/> */
special, /* sample: <!doctype> */
none
} type;
// is there a new line after this tag
bool new_line;
// current orphans table
// (will be propagated)
Orphans * porphans;
// this item or one from its parents is a 'body' html tag
// (will be propagated)
bool has_body_tag;
void Clear();
Item();
};
/*
virtual methods
*/
virtual void Init();
virtual void Uninit();
virtual bool IsOpeningTagMark(wchar_t c);
virtual bool IsClosingTagMark(wchar_t c);
virtual bool IsClosingXmlSimpleTagMark(wchar_t c);
virtual bool IsStartingEntityMark(wchar_t c);
virtual bool IsEndingEntityMark(wchar_t c);
virtual bool IsOpeningCommentaryTagMark(const wchar_t * str);
virtual size_t OpeningCommentaryTagMarkSize();
virtual bool IsValidCharForName(int c);
virtual bool IsValidCharForAttrName(int c);
virtual bool IsValidCharForEntityName(int c);
virtual void CheckExceptions();
virtual bool SkipCommentaryTagIfExists();
virtual void Put(wchar_t c);
virtual void Put(const wchar_t * str);
virtual void Put(const wchar_t * str, const wchar_t * end);
virtual void Put(const std::wstring & str);
virtual void AnalyzeEntitiesAndPut(const wchar_t * str, const wchar_t * end, std::wstring * out);
virtual void PutOpeningTagMark();
virtual void PutClosingTagMark();
virtual bool PutOpeningTag();
virtual void PutClosingTag(const wchar_t * tag);
virtual void PutNormalText(const wchar_t * str, const wchar_t * end);
virtual void ReadNormalTextSkipWhite(const wchar_t * & start, const wchar_t * & last_non_white);
virtual void ItemFound();
virtual void EntityFound(const wchar_t * str, const wchar_t * end);
/*
others
*/
void SetSomeDefaults();
Item & GetItem(size_t i);
Item & LastItem();
wchar_t ToLower(wchar_t c);
void ToLower(std::wstring & str);
bool IsNameEqual(const wchar_t * name1, const wchar_t * name2);
bool IsNameEqual(const wchar_t * name1, const std::wstring & name2);
bool IsNameEqual(const std::wstring & name1, const wchar_t * name2);
bool IsNameEqual(const std::wstring & name1, const std::wstring & name2);
bool IsNameEqual(const wchar_t * name1, const wchar_t * name2, size_t len);
bool IsNameEqual(const wchar_t * name1, const std::wstring & name2, size_t len);
bool IsNameEqual(const std::wstring & name1, const wchar_t * name2, size_t len);
bool IsNameEqual(const std::wstring & name1, const std::wstring & name2, size_t len);
bool IsLastTag(const wchar_t * name);
bool IsLastTag(const std::wstring & name);
bool IsTagSafe(const wchar_t * tag);
bool IsTagSafe(const std::wstring & tag);
int CheckOrphan(const wchar_t * str, const wchar_t * end, const std::wstring & orphan_str);
bool CheckOrphan(const wchar_t * str, const wchar_t * end, const std::vector<std::wstring> & orphans);
bool CheckOrphan(const wchar_t * str, const wchar_t * end);
bool IsWhite(int c);
void SkipWhite();
void SkipWhiteLines();
void SkipWhiteWithFirstNewLine();
void SkipWhiteLines(const wchar_t * & str, const wchar_t * end);
bool IsClosingTagForLastItem();
void SkipAndCheckClosingTag();
void PopStack();
bool PushStack();
void CheckNewLine();
void CheckStackPrintRest();
void AddForgottenTags();
void CheckClosingTags();
void ReadNormalText();
bool PrintRest();
bool PrintOpeningItem();
void ReadItemName();
void ReadItemAttrName();
void ReadItemAttrValueAdd(const wchar_t * value_start, const wchar_t * value_end);
void ReadItemAttrValue(bool has_quote, wchar_t quote_char);
bool ReadItemAttr();
bool CheckItemAttr();
void PrintItemAttr();
void ReadItemClosing();
void ReadItemSpecial();
void ReadItemOpening();
bool ReadItem();
void ReadLoop();
void Read();
void CheckChar(wchar_t c);
void CheckLineWrap();
bool HasEntityEndAround(const wchar_t * str, const wchar_t * end);
void PutNormalNonWhite(const wchar_t * & str, const wchar_t * end);
void PutNormalWhite(const wchar_t * & str, const wchar_t * end);
void PutEverythingUntilClosingTag(bool put_closing_tag_as_well);
void PutTabs(size_t len);
void PutNonBreakingSpace();
void PutNewLine();
void CalcOrphansMaxLen(Orphans & orphans);
const wchar_t * pchar;
Item empty;
Item * pstack; // stack pointer
size_t stack_len; // length of the stack
wchar_t * buffer; // buffer used when printing
std::wstring * out_string;
bool last_new_line;
size_t break_after; // insert a space into long words after 'break_after' characters
size_t wrap_line; // insert a new line character into long lines
bool trim_white; // trimming white characters
size_t tab_size;
OrphanMode orphan_mode;
std::wstring attr_name;
std::vector<std::wstring> attr_value;
std::wstring attr_value_temp;
std::wstring attr_value_lower;
bool attr_has_value;
std::wstring lang_code_lower;
size_t line_len; //length of the current line (without first spaces which create the html tree)
bool safe_mode; // skipping some unsafe tags
Orphans orphans_temp;
bool skip_tags;
bool skip_commentaries;
bool skip_entities;
bool analyze_entities;
};
} // namespace Winix
#endif

View File

@@ -0,0 +1,273 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2008-2014, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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.
*
*/
#include "httpsimpleparser.h"
#include "misc.h"
#include "utf8/utf8.h"
namespace Winix
{
void HttpSimpleParser::ToLower(std::wstring & s)
{
for(wchar_t & c : s)
{
if( c>='A' && c<='Z' )
c = c - 'A' + 'a';
}
}
bool HttpSimpleParser::IsWhite(int c)
{
if( c==' ' || c=='\t' )
return true;
return false;
}
void HttpSimpleParser::SkipWhiteChars()
{
while( IsWhite(last_c) )
last_c = GetChar();
}
int HttpSimpleParser::ParseHalfHex(int c)
{
if( c>='a' && c<='z' )
c += 'A' - 'a'; // to upper case
if( c >= 'A' )
c = c - 'A' + 10;
else
c = c - '0';
c &= 0xf;
return c;
}
void HttpSimpleParser::CheckSpecialChar()
{
if( last_c == '%' )
{
int c1 = GetChar();
int c2 = GetChar();
if( c1==-1 || c2==-1 )
{
last_c = -1;
}
else
{
c1 = ParseHalfHex(c1);
c2 = ParseHalfHex(c2);
last_c = (c1 << 4) + c2;
}
}
else
if( last_c == '+' )
{
last_c = ' ';
}
}
void HttpSimpleParser::ReadName()
{
// we're checking 'separator' and '=' because the string is allowed not having '=' (the value is optional)
utf8_token.clear();
last_name.clear();
for( ; last_c!=-1 && last_c!=separator && last_c!='=' ; last_c = GetChar() )
{
if( recognize_special_chars )
CheckSpecialChar();
if( last_c != -1 )
{
if( getchar_returns_utf8_chars )
utf8_token += last_c;
else
last_name += last_c;
}
}
if( getchar_returns_utf8_chars )
PT::UTF8ToWide(utf8_token, last_name);
if( last_c == '=' )
last_c = GetChar();
}
void HttpSimpleParser::ReadQuotedValue()
{
// skipping '"'
last_c = GetChar();
utf8_token.clear();
last_value.clear();
for( ; last_c!=-1 && last_c!='"' ; last_c = GetChar() )
{
if( recognize_special_chars )
CheckSpecialChar();
if( last_c != -1 )
{
if( getchar_returns_utf8_chars )
utf8_token += last_c;
else
last_value += last_c;
}
}
if( getchar_returns_utf8_chars )
PT::UTF8ToWide(utf8_token, last_value);
if( last_c == '"' )
last_c = GetChar();
// looking for a separator (skipping)
for( ; last_c!=-1 && last_c!=separator ; last_c = GetChar() );
}
void HttpSimpleParser::ReadNormalValue()
{
utf8_token.clear();
last_value.clear();
for( ; last_c!=-1 && last_c!=separator ; last_c = GetChar() )
{
if( recognize_special_chars )
CheckSpecialChar();
if( last_c != -1 )
{
if( getchar_returns_utf8_chars )
utf8_token += last_c;
else
last_value += last_c;
}
}
if( getchar_returns_utf8_chars )
PT::UTF8ToWide(utf8_token, last_value);
}
void HttpSimpleParser::ReadValue()
{
if( skip_white_chars )
SkipWhiteChars();
if( value_can_be_quoted && last_c == '"' )
ReadQuotedValue();
else
ReadNormalValue();
if( last_c == separator )
last_c = GetChar();
}
/*
* there can be some important values like passwords so its better
* to clear them now
*/
void HttpSimpleParser::Clear()
{
Overwrite(last_name);
Overwrite(last_value);
Overwrite(utf8_token);
last_name.clear();
last_value.clear();
utf8_token.clear();
}
void HttpSimpleParser::Parse()
{
for( last_c = GetChar() ; last_c != -1 ; )
{
last_name.clear();
last_value.clear();
if( read_name )
ReadName();
ReadValue();
if( skip_white_chars )
{
TrimWhite(last_name);
TrimWhite(last_value);
}
Parameter(last_name, last_value); // user definied function
}
Clear();
}
} // namespace Winix

View File

@@ -0,0 +1,108 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2008-2018, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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 headerfile_winix_core_httpsimpleparser
#define headerfile_winix_core_httpsimpleparser
#include <string>
#include "winixmodel.h"
namespace Winix
{
class HttpSimpleParser : public WinixModel
{
protected:
bool read_name;
bool value_can_be_quoted;
bool skip_white_chars;
bool recognize_special_chars;
// if false then GetChar() returns wide characters (converted to int)
// if true then GetChar() returns utf8 characters (we have to convert them from utf8 to wide chars)
bool getchar_returns_utf8_chars;
int ParseHalfHex(int c);
void ReadName();
void ReadQuotedValue();
void ReadNormalValue();
void ReadValue();
void Clear();
std::wstring last_name;
std::wstring last_value;
std::string utf8_token;
int last_c;
int separator;
// '-1' means end (eof)
// when there is an eof this method can be called more than once (it should always return -1 in such a case)
virtual int GetChar() = 0;
virtual void Parameter(std::wstring & last_name, std::wstring & last_value) = 0;
void ToLower(std::wstring & s);
bool IsWhite(int c);
void SkipWhiteChars();
void CheckSpecialChar();
void Parse();
public:
HttpSimpleParser()
{
separator = '&';
read_name = true;
value_can_be_quoted = false;
skip_white_chars = false;
recognize_special_chars = true;
getchar_returns_utf8_chars = false;
}
};
} // namespace Winix
#endif

629
winixd/core/image.cpp Normal file
View File

@@ -0,0 +1,629 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2010-2014, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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.
*
*/
#include <ctime>
#include "image.h"
#include "utf8/utf8.h"
#include "system.h"
#include "lock.h"
namespace Winix
{
void Image::SetDb(Db * pdb)
{
db = pdb;
}
void Image::SetConfig(Config * pconfig)
{
config = pconfig;
}
void Image::SetSystem(System * psystem)
{
system = psystem;
}
// first thread (objects locked)
Image::Scale Image::GetImageScale(long dir_id)
{
Scale scale;
Mount * m = system->mounts.CalcMount(dir_id);
scale.cx = config->image_cx;
scale.cy = config->image_cy;
scale.aspect_mode = config->image_mode;
scale.quality = config->image_quality;
// reading width and height from the mount point (if exists)
int index = system->mounts.MountParImageSize();
if( m && m->param[index].defined && m->param[index].arg.size() == 2 )
{
scale.cx = Tol(m->param[index].arg[0]);
scale.cy = Tol(m->param[index].arg[1]);
}
// reading image mode from the mount point (if exists)
index = system->mounts.MountParImageMode();
if( m && m->param[index].defined && m->param[index].arg.size() == 1 )
scale.aspect_mode = Toi(m->param[index].arg[0]);
// reading image quality from the mount point (if exists)
index = system->mounts.MountParImageQuality();
if( m && m->param[index].defined && m->param[index].arg.size() == 1 )
scale.quality = Toi(m->param[index].arg[0]);
return scale;
}
// first thread (objects locked)
Image::Scale Image::GetThumbScale(long dir_id)
{
Scale scale;
Mount * m = system->mounts.CalcMount(dir_id);
scale.cx = config->thumb_cx;
scale.cy = config->thumb_cy;
scale.aspect_mode = config->thumb_mode;
scale.quality = config->thumb_quality;
// reading width and height from the mount point (if exists)
int index = system->mounts.MountParThumbSize();
if( m && m->param[index].defined && m->param[index].arg.size() == 2 )
{
scale.cx = Tol(m->param[index].arg[0]);
scale.cy = Tol(m->param[index].arg[1]);
}
// reading thumb mode from the mount point (if exists)
index = system->mounts.MountParThumbMode();
if( m && m->param[index].defined && m->param[index].arg.size() == 1 )
scale.aspect_mode = Toi(m->param[index].arg[0]);
// reading image quality from the mount point (if exists)
index = system->mounts.MountParThumbQuality();
if( m && m->param[index].defined && m->param[index].arg.size() == 1 )
scale.quality = Toi(m->param[index].arg[0]);
return scale;
}
// first thread (objects locked)
void Image::Resize(long file_id, size_t cx, size_t cy, int aspect_mode, int quality)
{
item_temp.type = WINIX_IMAGE_TYPE_RESIZE;
item_temp.file_id = file_id;
item_temp.cx = cx;
item_temp.cy = cy;
item_temp.aspect_mode = aspect_mode;
item_temp.quality = quality;
CheckParam(item_temp);
image_tab.insert(image_tab.end(), item_temp);
WakeUpThread();
}
// first thread (objects locked)
void Image::CreateThumb(long file_id, size_t thumb_cx, size_t thumb_cy, int aspect_mode, int quality)
{
item_temp.type = WINIX_IMAGE_TYPE_CREATE_THUMB;
item_temp.file_id = file_id;
item_temp.thumb_cx = thumb_cx;
item_temp.thumb_cy = thumb_cy;
item_temp.aspect_mode = aspect_mode;
item_temp.quality = quality;
CheckParam(item_temp);
image_tab.insert(image_tab.end(), item_temp);
WakeUpThread();
}
// first thread (objects locked)
void Image::Crop(long file_id, size_t xoffset, size_t yoffset, size_t cx, size_t cy, int quality)
{
item_temp.type = WINIX_IMAGE_TYPE_CROP;
item_temp.file_id = file_id;
item_temp.xoffset = xoffset;
item_temp.yoffset = yoffset;
item_temp.cx = cx;
item_temp.cy = cy;
item_temp.quality = quality;
CheckParam(item_temp);
image_tab.insert(image_tab.end(), item_temp);
WakeUpThread();
}
// first thread (objects locked)
void Image::CropThumb(long file_id, size_t xoffset, size_t yoffset, size_t cx, size_t cy, int quality)
{
item_temp.type = WINIX_IMAGE_TYPE_CROP_THUMB;
item_temp.file_id = file_id;
item_temp.xoffset = xoffset;
item_temp.yoffset = yoffset;
item_temp.cx = cx;
item_temp.cy = cy;
item_temp.quality = quality;
CheckParam(item_temp);
image_tab.insert(image_tab.end(), item_temp);
WakeUpThread();
}
// first thread (objects locked)
void Image::CropNewThumb(long file_id, size_t xoffset, size_t yoffset, size_t cx, size_t cy,
size_t thumb_cx, size_t thumb_cy, int aspect_mode, int quality)
{
item_temp.type = WINIX_IMAGE_TYPE_CREATE_CROP_NEW_THUMB;
item_temp.file_id = file_id;
item_temp.xoffset = xoffset;
item_temp.yoffset = yoffset;
item_temp.cx = cx;
item_temp.cy = cy;
item_temp.thumb_cx = thumb_cx;
item_temp.thumb_cy = thumb_cy;
item_temp.aspect_mode = aspect_mode;
item_temp.quality = quality;
CheckParam(item_temp);
image_tab.insert(image_tab.end(), item_temp);
WakeUpThread();
}
void Image::CheckParam(ImageItem & item)
{
SetMinMax(item.aspect_mode, 1, 7);
SetMinMax(item.quality, 0, 100);
SetMinMax(item.cx, 1, 30000);
SetMinMax(item.cy, 1, 30000);
SetMinMax(item.thumb_cx, 1, 30000);
SetMinMax(item.thumb_cy, 1, 30000);
SetMinMax(item.xoffset, 0, 30000);
SetMinMax(item.yoffset, 0, 30000);
}
// second thread (objects locked)
bool Image::SignalReceived()
{
return !image_tab.empty();
}
// second thread (objects not locked)
void Image::Do()
{
ImageTab::iterator i;
bool end;
Lock();
i = image_tab.begin();
Unlock();
do
{
class Lock lock_object(synchro);
if( i != image_tab.end() )
{
item_work = *i;
image_tab.erase(i++);
end = false;
}
else
{
end = true;
}
lock_object.Unlock();
if( !end )
CreateImage();
}
while( !end && !IsExitSignal() );
}
void Image::Add(const std::wstring & in, TextStream<std::string> & out)
{
PT::WideToUTF8(in, add_tempa);
out << add_tempa;
}
void Image::EscapePath(const std::string & path, TextStream<std::string> & out, bool clear_stream)
{
if( clear_stream )
out.Clear();
out << '"';
for(size_t i=0 ; i<path.size() ; ++i)
{
if( path[i] == '"' )
out << '\\';
if( path[i] != 0 )
out << path[i];
}
out << '\"';
}
/*
from: http://www.imagemagick.org/script/command-line-processing.php#geometry
scale% Height and width both scaled by specified percentage.
scale-x%xscale-y% Height and width individually scaled by specified percentages. (Only one % symbol needed.)
width Width given, height automagically selected to preserve aspect ratio.
xheight Height given, width automagically selected to preserve aspect ratio.
widthxheight Maximum values of height and width given, aspect ratio preserved.
widthxheight^ Minimum values of width and height given, aspect ratio preserved.
widthxheight! Width and height emphatically given, original aspect ratio ignored.
widthxheight> Change as per widthxheight but only if an image dimension exceeds a specified dimension.
widthxheight< Change dimensions only if both image dimensions exceed specified dimensions.
*/
void Image::SelectAspect(size_t cx, size_t cy)
{
switch( item_work.aspect_mode )
{
case WINIX_IMAGE_MODE_1:
command << cx;
break;
case WINIX_IMAGE_MODE_3:
command << cx << "x" << cy;
break;
case WINIX_IMAGE_MODE_4:
command << '"' << cx << "x" << cy << "^\"";
break;
case WINIX_IMAGE_MODE_5:
command << '"' << cx << "x" << cy << "!\"";
break;
case WINIX_IMAGE_MODE_6:
command << '"' << cx << "x" << cy << ">\"";
break;
case WINIX_IMAGE_MODE_7:
command << '"' << cx << "x" << cy << "<\"";
break;
case WINIX_IMAGE_MODE_2:
default:
command << "x" << cy;
break;
}
}
// second thread (objects locked)
bool Image::CreateInputFileName()
{
bool thumb = (item_work.type == WINIX_IMAGE_TYPE_CROP_THUMB);
if( thumb && !file_work.has_thumb )
{
log << log1 << "Image: file id: " << file_work.id << ", url: " << file_work.url
<< " doesn't have a thumbnail yet (skipping)" << logend;
return false;
}
if( system->MakeFilePath(file_work, src_path, thumb) )
{
PT::WideToUTF8(src_path, input_file_name);
return true;
}
else
{
log << log1 << "Image: cannot create a source path" << logend;
return false;
}
}
// second thread (objects locked)
void Image::CreateTmpFileName()
{
stream_tmp_path.Clear();
stream_tmp_path << config->upload_dir << L"/tmp/image_" << std::time(0);
PT::WideToUTF8(stream_tmp_path.Str(), tmp_file_name);
}
// second thread (objects are not locked)
bool Image::CreateCommand()
{
class Lock lock_object(synchro);
iq.SetAll(true, false);
iq.WhereId(item_work.file_id);
// the file could have been changed especially when there is a long queue of files
if( db->GetItem(file_work, iq) != WINIX_ERR_OK )
return false;
if( !CreateInputFileName() )
return false;
command.Clear();
Add(config->convert_cmd, command);
command << " ";
EscapePath(input_file_name, command, false);
command << " -quiet -quality " << item_work.quality;
if( item_work.type == WINIX_IMAGE_TYPE_RESIZE )
{
command << " -resize ";
SelectAspect(item_work.cx, item_work.cy);
}
else
if( item_work.type == WINIX_IMAGE_TYPE_CREATE_THUMB )
{
command << " -strip -thumbnail ";
SelectAspect(item_work.thumb_cx, item_work.thumb_cy);
}
else
if( item_work.type == WINIX_IMAGE_TYPE_CROP )
{
command << " -crop " << item_work.cx << "x" << item_work.cy
<< "+" << item_work.xoffset << "+" << item_work.yoffset << " +repage ";
}
else
if( item_work.type == WINIX_IMAGE_TYPE_CROP_THUMB )
{
command << " -strip -crop " << item_work.cx << "x" << item_work.cy
<< "+" << item_work.xoffset << "+" << item_work.yoffset
<< " +repage ";
}
else
if( item_work.type == WINIX_IMAGE_TYPE_CREATE_CROP_NEW_THUMB )
{
command << " -strip -crop " << item_work.cx << "x" << item_work.cy
<< "+" << item_work.xoffset << "+" << item_work.yoffset
<< " +repage -thumbnail ";
SelectAspect(item_work.thumb_cx, item_work.thumb_cy);
}
CreateTmpFileName();
command << " ";
EscapePath(tmp_file_name, command, false);
log << log4 << "Image: running: " << command.Str() << logend;
return true;
}
// second thread (objects are locked)
void Image::ImageSavedCorrectly()
{
if( item_work.type == WINIX_IMAGE_TYPE_CREATE_THUMB )
{
if( !file_work.has_thumb )
{
file_work.has_thumb = true;
db->EditHasThumbById(true, file_work.id);
}
log << log3 << "Image: generated a thumbnail: " << dst_path << logend;
plugin->Call((Session*)0, WINIX_CREATED_THUMB, &file_work);
}
else
if( item_work.type == WINIX_IMAGE_TYPE_RESIZE )
{
log << log3 << "Image: image resized: " << dst_path << logend;
plugin->Call((Session*)0, WINIX_IMAGE_RESIZED, &file_work);
}
else
if( item_work.type == WINIX_IMAGE_TYPE_CROP )
{
log << log3 << "Image: image cropped: " << dst_path << logend;
// !! IMPROVE ME add a correct message
//plugin->Call((Session*)0, WINIX_IMAGE_RESIZED, &file_work);
}
else
if( item_work.type == WINIX_IMAGE_TYPE_CROP_THUMB )
{
log << log3 << "Image: image thumbnail cropped: " << dst_path << logend;
// !! IMPROVE ME add a correct message
//plugin->Call((Session*)0, WINIX_IMAGE_RESIZED, &file_work);
}
else
if( item_work.type == WINIX_IMAGE_TYPE_CREATE_CROP_NEW_THUMB )
{
log << log3 << "Image: a new thumbnail from an original image was cropped: " << dst_path << logend;
// !! IMPROVE ME add a correct message
//plugin->Call((Session*)0, WINIX_IMAGE_RESIZED, &file_work);
}
}
// second thread (objects are not locked)
void Image::SaveImage()
{
class Lock lock_object(synchro);
// the file could have been changed especially when creating the image lasted too long
iq.SetAll(true, false);
iq.WhereId(item_work.file_id);
if( db->GetItem(file_work, iq) == WINIX_ERR_OK )
{
bool thumb = (item_work.type == WINIX_IMAGE_TYPE_CREATE_THUMB ||
item_work.type == WINIX_IMAGE_TYPE_CROP_THUMB ||
item_work.type == WINIX_IMAGE_TYPE_CREATE_CROP_NEW_THUMB );
if( system->MakeFilePath(file_work, dst_path, thumb, true, config->upload_dirs_chmod, config->upload_group_int) )
{
if( RenameFile(stream_tmp_path.Str(), dst_path) )
{
// it doesn't matter for us if there is an error when chmod/chown on a file
// the admin (root) will correct it
SetPriv(dst_path, config->upload_files_chmod, config->upload_group_int);
ImageSavedCorrectly();
}
else
{
log << log1 << "Image: cannot move a temporary file: " << stream_tmp_path.Str()
<< ", to: " << dst_path << logend;
Winix::RemoveFile(stream_tmp_path.Str());
}
}
else
{
log << log1 << "Image: cannot create a destination path" << logend;
}
}
}
// second thread (objects are not locked)
void Image::CreateImage()
{
if( CreateCommand() )
{
int res = std::system(command.CStr());
if( res == 0 )
{
SaveImage();
}
else
{
class Lock lock_object(synchro);
log << log3 << "Image: some problems with creating an image"
<< ", 'convert' process returned: " << res << logend;
}
}
}
// second thread (objects are not locked)
// !! there is a problem with GIF files
// Bus error (core dumped)
/*
#include "wand/MagickWand.h"
// compiler options:
// include: -I/usr/local/include/ImageMagick
// link with: `MagickWand-config --ldflags --libs`
void Image::CreateThumbnail()
{
PT::WideToUTF8(item_work.source, sourcea);
PT::WideToUTF8(item_work.dst, dsta);
MagickWandGenesis();
MagickWand * wand = NewMagickWand();
if( MagickReadImage(wand, sourcea.c_str()) )
{
MagickThumbnailImage(wand, item_work.cx, item_work.cy);
if( MagickWriteImage(wand, dsta.c_str()) )
{
Lock();
log << log3 << "Image: created a thumbnail: " << dsta << logend;
Unlock();
}
}
DestroyMagickWand(wand);
MagickWandTerminus();
}
*/
} // namespace Winix

215
winixd/core/image.h Normal file
View File

@@ -0,0 +1,215 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2010-2014, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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 headerfile_winix_core_image
#define headerfile_winix_core_image
#include <string>
#include <list>
#include "basethread.h"
#include "textstream.h"
#include "db/db.h"
#include "core/item.h"
#include "core/config.h"
namespace Winix
{
class System;
// aspect modes:
// Width given, height automagically selected to preserve aspect ratio.
#define WINIX_IMAGE_MODE_1 1
// Height given, width automagically selected to preserve aspect ratio.
#define WINIX_IMAGE_MODE_2 2
// Maximum values of height and width given, aspect ratio preserved.
#define WINIX_IMAGE_MODE_3 3
// Minimum values of width and height given, aspect ratio preserved.
#define WINIX_IMAGE_MODE_4 4
// Width and height emphatically given, original aspect ratio ignored.
#define WINIX_IMAGE_MODE_5 5
// Change as per widthxheight but only if an image dimension exceeds a specified dimension.
#define WINIX_IMAGE_MODE_6 6
// Change dimensions only if both image dimensions are less than specified dimensions.
#define WINIX_IMAGE_MODE_7 7
// resizing
#define WINIX_IMAGE_TYPE_RESIZE 1
// generating a thumbnail
#define WINIX_IMAGE_TYPE_CREATE_THUMB 2
// cropping an image
#define WINIX_IMAGE_TYPE_CROP 3
// cropping an thumbnail
#define WINIX_IMAGE_TYPE_CROP_THUMB 4
// creating by cropping a new thumbnail (from an original image)
#define WINIX_IMAGE_TYPE_CREATE_CROP_NEW_THUMB 5
/*
*/
class Image : public BaseThread
{
public:
struct Scale
{
size_t cx;
size_t cy;
int aspect_mode;
int quality;
Scale()
{
cx = cy = 1;
aspect_mode = 2;
quality = 100;
};
};
void SetDb(Db * pdb);
void SetConfig(Config * pconfig);
void SetSystem(System * psystem);
// returning scale info for a directory
Scale GetImageScale(long dir_id);
// returning scale info (for thumbnails) for a directory
Scale GetThumbScale(long dir_id);
void Resize(long file_id, size_t cx, size_t cy, int aspect_mode, int quality);
// creating a new thumbnail from an original image
void CreateThumb(long file_id, size_t thumb_cx, size_t thumb_cy, int aspect_mode, int quality);
// cropping an image (the thumbnail is not changed)
void Crop(long file_id, size_t xoffset, size_t yoffset, size_t cx, size_t cy, int quality);
// cropping an existing thumbnail
void CropThumb(long file_id, size_t xoffset, size_t yoffset, size_t cx, size_t cy, int quality);
// creating and cropping a new thumbnail (from an original image)
void CropNewThumb(long file_id, size_t xoffset, size_t yoffset, size_t cx, size_t cy,
size_t thumb_cx, size_t thumb_cy, int aspect_mode, int quality);
private:
Db * db;
Config * config;
System * system;
struct ImageItem
{
int type; // WINIX_IMAGE_TYPE_*
long file_id;
size_t cx;
size_t cy;
size_t xoffset; // xoffset and yoffset are used when cropping
size_t yoffset;
size_t thumb_cx;
size_t thumb_cy;
int aspect_mode;
int quality;
};
template<typename int_type>
void SetMinMax(int_type & var, int var_min, int var_max)
{
if( static_cast<int>(var) < var_min )
var = var_min;
if( static_cast<int>(var) > var_max )
var = var_max;
}
// queue of thumbnails to create
typedef std::list<ImageItem> ImageTab;
ImageTab image_tab;
ImageItem item_temp;
// only for second thread
ImageItem item_work;
std::wstring src_path, dst_path;
TextStream<std::string> command;
TextStream<std::wstring> stream_tmp_path;
DbItemQuery iq;
std::string add_tempa;
std::string input_file_name;
std::string tmp_file_name;
Item file_work;
virtual bool SignalReceived();
virtual void Do();
bool CreateCommand();
bool CreateInputFileName();
void CreateTmpFileName();
void SaveImage();
void CreateImage();
void SelectAspect(size_t cx, size_t cy);
void EscapePath(const std::string & path, TextStream<std::string> & out, bool clear_stream = true);
void CheckParam(ImageItem & item);
void Add(const std::wstring & in, TextStream<std::string> & out);
void ImageSavedCorrectly();
};
} // namespace Winix
#endif

201
winixd/core/ipban.h Normal file
View File

@@ -0,0 +1,201 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2012-2014, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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 headerfile_winix_core_ipban
#define headerfile_winix_core_ipban
#include <ctime>
namespace Winix
{
// telling if the IPBan record is active
// we have two records: active and non active
// non active records is something like a history
// it is used to remember the last ban level
// so based on this in the future a next greater ban can be calculated
#define WINIX_IPBAN_FLAG_ACTIVE 1
// current ban level
// (if one of these flag is set and the record is active then it means the IP is banned at the moment)
// level 1: banned for short time
// level 2: can be set after level 1 has expired and the attacker still have not given up
// banned for some longer time in level 1
// level 3: can be set after level 2
// banned for much more time
#define WINIX_IPBAN_FLAG_BAN_LEVEL1 2
#define WINIX_IPBAN_FLAG_BAN_LEVEL2 4
#define WINIX_IPBAN_FLAG_BAN_LEVEL3 8
/*
struct defining some restrictions to an IP address
*/
struct IPBan
{
// at the moment only IPv4 are supported
int ip;
// one or more flags from WINIX_IPBAN_FLAG_*
int flags;
// when this record was last used
time_t last_used;
// when the restrictions (ban) should be removed
// valid only if some of WINIX_IPBAN_FLAG_BAN_LEVELX flags are set
// actually we do not remove the record but unsets WINIX_IPBAN_FLAG_ACTIVE flag
// so in the future we can check whether we need to change
// the ban level to a greater value
time_t expires;
// how many incorrect login attempts there are
unsigned short int incorrect_login_events;
// how many incorrect encoded cookie were sent
// only used if config.session_cookie_encode is true and session_keys_file is defined
unsigned short int broken_encoded_cookie_events;
// how many incorrect session identifiers were sent
unsigned short int session_hijacking_events;
// client didn't send a session cookie
// it can be a bot or just someone wants to DOS the server
// (a new session will be create)
unsigned short int no_session_cookie_events;
bool HasFlag(int flag) const
{
return (flags & flag) != 0;
}
void SetFlag(int flag)
{
flags = flags | flag;
}
void ClearFlag(int flag)
{
flags = flags & (~flag);
}
bool IsIPBanned() const
{
if( !HasFlag(WINIX_IPBAN_FLAG_ACTIVE) )
return false;
return HasFlag(WINIX_IPBAN_FLAG_BAN_LEVEL1) ||
HasFlag(WINIX_IPBAN_FLAG_BAN_LEVEL2) ||
HasFlag(WINIX_IPBAN_FLAG_BAN_LEVEL3);
}
void IncrementBanLevel(time_t level1_expires, time_t level2_expires, time_t level3_expires)
{
if( HasFlag(WINIX_IPBAN_FLAG_BAN_LEVEL3) )
{
expires = level3_expires;
return;
}
else
if( HasFlag(WINIX_IPBAN_FLAG_BAN_LEVEL2) )
{
SetFlag(WINIX_IPBAN_FLAG_BAN_LEVEL3);
expires = level3_expires;
return;
}
else
if( HasFlag(WINIX_IPBAN_FLAG_BAN_LEVEL1) )
{
SetFlag(WINIX_IPBAN_FLAG_BAN_LEVEL2);
expires = level2_expires;
return;
}
else
{
SetFlag(WINIX_IPBAN_FLAG_BAN_LEVEL1);
expires = level1_expires;
}
}
IPBan()
{
Clear();
}
void Clear()
{
ip = 0;
flags = 0;
last_used = 0;
expires = 0;
incorrect_login_events = 0;
broken_encoded_cookie_events = 0;
session_hijacking_events = 0;
no_session_cookie_events = 0;
}
void ResetEventsCounters()
{
ClearFlag(WINIX_IPBAN_FLAG_ACTIVE);
incorrect_login_events = 0;
broken_encoded_cookie_events = 0;
session_hijacking_events = 0;
no_session_cookie_events = 0;
expires = 0;
}
};
} // namespace Winix
#endif

View File

@@ -0,0 +1,253 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2012-2014, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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.
*
*/
#include <algorithm>
#include "ipbancontainer.h"
#include "log.h"
#include "date/date.h"
namespace Winix
{
IPBanContainer::IPBanContainer()
{
is_ipban_tab_sorted = true; // an empty list is sorted
soft_max_size = 100;
max_size = 110;
}
void IPBanContainer::SetMaxSize(size_t soft_size, size_t size)
{
soft_max_size = soft_size;
max_size = size;
if( max_size < soft_max_size )
max_size = soft_max_size + 1;
ipban_tab.reserve(max_size);
sort_helper_tab.reserve(max_size);
}
// returning a reference to the added (or existed) record
IPBan & IPBanContainer::AddIP(int ip)
{
IPBan * old_ip_ban = FindIP(ip);
if( !old_ip_ban )
{
IPBan ip_ban;
ip_ban.ip = ip;
if( ipban_tab.size() >= max_size )
RemoveOldRecords();
ipban_tab.push_back(ip_ban);
is_ipban_tab_sorted = false;
return ipban_tab.back();
}
else
{
return *old_ip_ban;
}
}
void IPBanContainer::RemoveIP(int ip)
{
IPBan * ipban = FindIP(ip);
if( ipban )
{
size_t index = ipban - &ipban_tab[0];
ipban_tab.erase(ipban_tab.begin() + index);
}
}
bool IPBanContainer::IsSorted()
{
return is_ipban_tab_sorted;
}
void IPBanContainer::Clear()
{
ipban_tab.clear();
is_ipban_tab_sorted = true;
}
// we need to remove some old records for the size of the container
// to be less or equal to soft_max_size
void IPBanContainer::RemoveOldRecords()
{
size_t to_remove = 0;
if( ipban_tab.size() >= soft_max_size )
to_remove = ipban_tab.size() - soft_max_size;
if( to_remove > 0 )
{
sort_helper_tab.resize(ipban_tab.size());
for(size_t i=0 ; i<ipban_tab.size() ; ++i)
sort_helper_tab[i] = i;
std::sort(sort_helper_tab.begin(), sort_helper_tab.end(), SortByLastUsedHelper(this));
sort_helper_tab.resize(to_remove);
std::sort(sort_helper_tab.begin(), sort_helper_tab.end());
while( to_remove-- > 0 )
ipban_tab.erase(ipban_tab.begin() + sort_helper_tab[to_remove]);
}
}
// for debug purposes
void IPBanContainer::PrintTab()
{
log << log4 << "ipban_tab (size: " << ipban_tab.size() << ")" << logend;
for(size_t i=0 ; i<ipban_tab.size() ; ++i)
{
log << log4 << i << ": ip: " << ipban_tab[i].ip << ", flags: " << ipban_tab[i].flags << ", last_used: ";
PT::Date date(ipban_tab[i].last_used);
log << date << ", expires: ";
date = ipban_tab[i].expires;
log << date << logend;
}
}
// for debug purposes
void IPBanContainer::PrintTab2()
{
log << log4 << "sort_helper_tab (size: " << sort_helper_tab.size() << ")" << logend;
for(size_t i=0 ; i<sort_helper_tab.size() ; ++i)
{
IPBan & ipban = ipban_tab[sort_helper_tab[i]];
log << log4 << i << ": ip: " << ipban.ip << ", flags: " << ipban.flags << ", last_used: ";
PT::Date date(ipban.last_used);
log << date << ", expires: ";
date = ipban.expires;
log << date << logend;
}
}
bool IPBanContainer::SortByLastUsedHelper::operator()(size_t index1, size_t index2)
{
if( index1 < container->ipban_tab.size() &&
index2 < container->ipban_tab.size() )
{
IPBan & ip1 = container->ipban_tab[index1];
IPBan & ip2 = container->ipban_tab[index2];
// prefer to select records which do not have WINIX_IPBAN_FLAG_ACTIVE
if( ip1.HasFlag(WINIX_IPBAN_FLAG_ACTIVE) !=
ip2.HasFlag(WINIX_IPBAN_FLAG_ACTIVE) )
{
return ip2.HasFlag(WINIX_IPBAN_FLAG_ACTIVE);
}
return ip1.last_used < ip2.last_used;
}
return false;
}
IPBan * IPBanContainer::FindIP(int ip)
{
// !! IMPROVE ME add binary search if is_ipban_tab_sorted is true
for(size_t i=0 ; i<ipban_tab.size() ; ++i)
{
if( ipban_tab[i].ip == ip )
{
return &ipban_tab[i];
}
}
return 0;
}
IPBan & IPBanContainer::GetIPBan(size_t index)
{
return ipban_tab[index];
}
void IPBanContainer::Sort()
{
std::sort(ipban_tab.begin(), ipban_tab.end(), SortIPBansFunction);
is_ipban_tab_sorted = true;
}
size_t IPBanContainer::Size()
{
return ipban_tab.size();
}
bool IPBanContainer::SortIPBansFunction(const IPBan & ip1, const IPBan & ip2)
{
return ip1.ip < ip2.ip;
}
} // namespace Winix

View File

@@ -0,0 +1,92 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2012-2018, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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 headerfile_winix_core_ipbancontainer
#define headerfile_winix_core_ipbancontainer
#include <vector>
#include "ipban.h"
#include "winixmodel.h"
namespace Winix
{
class IPBanContainer : public WinixModel
{
public:
IPBanContainer();
IPBan & AddIP(int ip);
IPBan * FindIP(int ip);
void Sort();
size_t Size();
IPBan & GetIPBan(size_t index);
void SetMaxSize(size_t soft_size, size_t size);
void RemoveIP(int ip);
void Clear();
bool IsSorted();
private:
std::vector<IPBan> ipban_tab;
bool is_ipban_tab_sorted;
size_t soft_max_size, max_size;
std::vector<size_t> sort_helper_tab;
static bool SortIPBansFunction(const IPBan & ip1, const IPBan & ip2);
void RemoveOldRecords();
void PrintTab();
void PrintTab2();
struct SortByLastUsedHelper
{
IPBanContainer * container;
SortByLastUsedHelper(IPBanContainer * c) : container(c) {}
bool operator()(size_t index1, size_t index2);
};
};
} // namespace Winix
#endif

129
winixd/core/item.cpp Normal file
View File

@@ -0,0 +1,129 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2010-2014, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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.
*
*/
#include "item.h"
#include "misc.h"
#include "crypt.h"
namespace Winix
{
Item::Item()
{
Clear();
}
// !! IMPROVE ME
// now we have Request::start_time and Request::start_date
// we can somehow get the current time from the request
// may setting the date should be completetly removed from here?
void Item::SetDateToNow()
{
date_creation = std::time(0);
date_modification = date_creation;
}
void Item::SetDateModifyToNow()
{
date_modification = std::time(0);
}
void Item::Clear()
{
id = -1;
user_id = -1;
group_id = -1;
privileges = 0;
modification_user_id = -1;
guest_name.clear();
subject.clear();
content.clear();
modify_index = 0;
url.clear();
content_type = ct_formatted_text;
type = none;
parent_id = -1;
link_to.clear();
link_redirect = false;
content_id = -1;
ref = 1;
file_path.clear();
file_fs = -1;
file_type = WINIX_ITEM_FILETYPE_NONE;
hash.clear();
hash_type = WINIX_CRYPT_HASH_NONE;
file_size = 0;
has_thumb = false;
html_template.clear();
sort_index = 0;
meta.Clear();
ameta.Clear();
SetDateToNow();
}
/*
* we're using the HtmlFilter only for those contents
*
*/
bool Item::CanContentBeHtmlFiltered(Item::ContentType ct)
{
return ct == ct_text || ct == ct_formatted_text || ct == ct_html || ct == ct_bbcode;
}
bool Item::CanContentBeHtmlFiltered()
{
return CanContentBeHtmlFiltered(content_type);
}
} // namespace Winix

156
winixd/core/item.h Normal file
View File

@@ -0,0 +1,156 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2008-2016, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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 headerfile_winix_core_item
#define headerfile_winix_core_item
#include <string>
#include "space/space.h"
#include "date/date.h"
namespace Winix
{
#define WINIX_ITEM_FILETYPE_NONE 0
#define WINIX_ITEM_FILETYPE_IMAGE 1
#define WINIX_ITEM_FILETYPE_DOCUMENT 2
#define WINIX_ITEM_FILETYPE_VIDEO 3
#define WINIX_ITEM_FILETYPE_UNKNOWN 10
struct Item
{
long id;
long parent_id;
long user_id;
long group_id;
std::wstring guest_name; // used as a user name when user_id is equal -1
long modification_user_id; // who has modified the item last (not taken into account when checking permissions)
int privileges;
PT::Date date_creation;
PT::Date date_modification;
std::wstring subject;
std::wstring content;
std::wstring url;
int modify_index;
enum ContentType
{
ct_text = 0,
ct_formatted_text,
ct_html,
ct_bbcode,
ct_other, // no auto-formatting is applied
};
ContentType content_type;
enum Type
{
dir = 0,
file = 1,
symlink = 2,
none = 1000
};
Type type;
// used when type is symlink or to a directory too (function 'default')
std::wstring link_to;
int link_redirect; // !! IMPROVE ME should it be 'bool'?
// static file (if exists)
std::wstring file_path; // relative file path
int file_fs; // file system type where the file was saved
int file_type; // file type (none, image, doc, etc)
bool has_thumb; // whether or not we have a thumbnail
std::wstring hash; // file hash (md4, md5, ...)
int hash_type; // hash type WINIX_CRYPT_HASH_* (see crypt.h)
size_t file_size; // size of the file
std::wstring html_template;
// sort index used when displaying a group of items
int sort_index;
// meta information
PT::Space meta;
PT::Space ameta;
// methods
Item();
void SetDateToNow();
void SetDateModifyToNow();
void Clear();
static bool CanContentBeHtmlFiltered(Item::ContentType ct);
bool CanContentBeHtmlFiltered();
private:
// used by the database
long content_id; // content id in 'content' table
int ref; // content references
friend class Db;
friend struct DbItemColumns;
};
} // namespace Winix
#endif

196
winixd/core/job.cpp Normal file
View File

@@ -0,0 +1,196 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2012-2019, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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.
*
*/
#include "job.h"
#include "plugin.h"
#include "log.h"
namespace Winix
{
Job::Job()
{
jobs_queue_tab.resize(WINIX_JOBS_HOW_MANY_PRIORITIES);
}
void Job::CheckPriority(int & priority) const
{
if( priority < 0 )
priority = 0;
if( priority >= WINIX_JOBS_HOW_MANY_PRIORITIES )
priority = WINIX_JOBS_HOW_MANY_PRIORITIES - 1;
}
// first thread (objects locked)
void Job::Add(PT::Space & job, int priority)
{
CheckPriority(priority);
jobs_queue_tab[priority].push(job);
WakeUpThread();
}
size_t Job::Size(int priority) const
{
CheckPriority(priority);
return jobs_queue_tab[priority].size();
}
size_t Job::Size() const
{
size_t sum = 0;
for(size_t i=0 ; i<WINIX_JOBS_HOW_MANY_PRIORITIES ; ++i)
sum += Size(i);
return sum;
}
bool Job::Empty(int priority) const
{
CheckPriority(priority);
return jobs_queue_tab[priority].empty();
}
bool Job::Empty() const
{
for(size_t i=0 ; i<WINIX_JOBS_HOW_MANY_PRIORITIES ; ++i)
if( !Empty(i) )
return false;
return true;
}
/*
second thread
*/
// second thread (objects locked)
bool Job::SignalReceived()
{
return !Empty();
}
// second thread (objects not locked)
void Job::Do()
{
size_t i = WINIX_JOBS_HOW_MANY_PRIORITIES;
bool is_empty;
while( i-- > 0 && !IsExitSignal() )
{
do
{
Lock();
is_empty = Empty(i);
Unlock();
if( !is_empty )
DoQueue(jobs_queue_tab[i]);
}
while( !is_empty && !IsExitSignal() );
}
}
// second thread (objects not locked, jobs_queue is not empty)
void Job::DoQueue(JobsQueue & jobs_queue)
{
bool is_empty;
do
{
Lock();
// references will not be invalidated after insertion to jobs_queue
// (jobs_queue is std::queue and it uses std::deque by default)
PT::Space & job = jobs_queue.front();
Unlock();
DoJob(job);
Lock();
jobs_queue.pop();
is_empty = jobs_queue.empty();
Unlock();
}
while( !is_empty && !IsExitSignal() );
}
// second thread (objects not locked)
void Job::DoJob(PT::Space & job)
{
try
{
PluginRes res = plugin->Call((Session*)0, WINIX_JOB, &job);
if( res.res_true == 0 )
DoWinixJob(job);
}
catch(...)
{
}
}
// second thread (objects not locked)
void Job::DoWinixJob(PT::Space & job)
{
//log << log1 << "standard winix job: " << job.Text(L"type") << logend;
}
} // namespace Winix

115
winixd/core/job.h Normal file
View File

@@ -0,0 +1,115 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2012-2014, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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 headerfile_winix_core_jobs
#define headerfile_winix_core_jobs
#include <vector>
#include <queue>
#include "basethread.h"
#include "space/space.h"
namespace Winix
{
#define WINIX_JOBS_HOW_MANY_PRIORITIES 32
class Job : public BaseThread
{
public:
Job();
/*
add a new job to the queue
priority: 0-31 (0 - the lowest priority, 31 - the highest priority)
*/
void Add(PT::Space & job, int priority = 0);
/*
queue size, and size of all jobs in any priority
*/
size_t Size(int priority) const;
size_t Size() const;
/*
true if specified queue is empty
or if all queues are empty
*/
bool Empty(int priority) const;
bool Empty() const;
private:
typedef std::queue<PT::Space> JobsQueue;
typedef std::vector<JobsQueue> JobsQueueTab;
JobsQueueTab jobs_queue_tab;
void CheckPriority(int & priority) const;
void SaveToFile();
void ReadFromFile();
/*
second thread
*/
// standard winix jobs
// Image image;
// sending emails
// etc.
bool SignalReceived();
void Do();
void DoQueue(JobsQueue & jobs_queue);
void DoJob(PT::Space & job);
void DoWinixJob(PT::Space & job);
};
} // namespace Winix
#endif

View File

@@ -0,0 +1,144 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2009-2014, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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.
*
*/
#include "lastcontainer.h"
#include "log.h"
#include "misc.h"
namespace Winix
{
LastItem::LastItem()
{
user_id = 0;
ip = 0;
session_id = 0;
}
bool LastItem::IsLoggedOut()
{
return end.year > 1970;
}
LastContainer::Iterator LastContainer::Begin()
{
return last_tab.begin();
}
LastContainer::Iterator LastContainer::End()
{
return last_tab.end();
}
LastContainer::Iterator LastContainer::FindNotLoggedOut(long user_id, long session_id)
{
LastTab::iterator i;
for(i=last_tab.begin() ; i!=last_tab.end() ; ++i)
{
if( i->user_id == user_id && i->session_id == session_id && !i->IsLoggedOut() )
return i;
}
return last_tab.end();
}
void LastContainer::UserLogin(long user_id, const std::wstring & name, unsigned int ip, long session_id)
{
LastTab::iterator i = FindNotLoggedOut(user_id, session_id);
if( i != last_tab.end() )
{
log << log1 << "LC: such a user and session_id exist, not added as a new one" << logend;
return;
}
if( last_tab.size() >= WINIX_LASTCONTAINER_TABLE_SIZE ) // last_tab has O(n) complexity
last_tab.erase(last_tab.begin());
LastItem li;
li.user_id = user_id;
li.name = name;
li.ip = ip;
li.session_id = session_id;
li.start = std::time(0);
last_tab.insert(last_tab.end(), li);
log << log2 << "LC: added user: " << name << " into the last table" << logend;
}
void LastContainer::UserLogout(long user_id, long session_id)
{
LastTab::iterator i = FindNotLoggedOut(user_id, session_id);
if( i != last_tab.end() )
{
i->end = std::time(0);
}
else
{
/*
!! IMPROVE ME
users read from the session file (at boot time)
are not added to LastContainer
*/
log << log4 << "LC: there is no such a user to log out: user_id: "
<< user_id << " ses_id: " << session_id << logend;
}
}
} // namespace Winix

113
winixd/core/lastcontainer.h Normal file
View File

@@ -0,0 +1,113 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2009-2014, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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 headerfile_winix_core_lastcontainer
#define headerfile_winix_core_lastcontainer
#include <string>
#include <list>
#include <cstring>
#include <ctime>
#include "date/date.h"
#include "winixbase.h"
namespace Winix
{
// how many items we store in the 'last' function
#define WINIX_LASTCONTAINER_TABLE_SIZE 100
struct LastItem
{
long user_id;
// additional we store the whole string-name
// (you can delete a user from the database but we can still print the name)
std::wstring name;
// ip address
unsigned int ip;
// session id (used when logging out)
long session_id;
// start logging and end logging
PT::Date start;
PT::Date end;
LastItem();
bool IsLoggedOut();
};
class LastContainer : public WinixBase
{
public:
typedef std::list<LastItem> LastTab;
typedef LastTab::iterator Iterator;
public:
Iterator Begin();
Iterator End();
void UserLogin(long user_id, const std::wstring & name, unsigned int ip, long session_id);
void UserLogout(long user_id, long session_id);
private:
LastTab last_tab;
Iterator FindNotLoggedOut(long user_id, long session_id);
};
} // namespace Winix
#endif

413
winixd/core/loadavg.cpp Normal file
View File

@@ -0,0 +1,413 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2008-2018, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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.
*
*/
#include "loadavg.h"
#include "misc.h"
namespace Winix
{
LoadAvg::LoadAvg()
{
current1.Clear();
current5.Clear();
current15.Clear();
cache_load1 = 0.0;
cache_load5 = 0.0;
cache_load15 = 0.0;
cache_req_per_sec1 = 0.0;
cache_req_per_sec5 = 0.0;
cache_req_per_sec15 = 0.0;
was_stop_request = false;
CreateTable();
}
LoadAvg & LoadAvg::operator=(const LoadAvg & l)
{
current1 = l.current1;
current5 = l.current5;
current15 = l.current15;
cache_load1 = l.cache_load1;
cache_load5 = l.cache_load5;
cache_load15 = l.cache_load15;
cache_req_per_sec1 = l.cache_req_per_sec1;
cache_req_per_sec5 = l.cache_req_per_sec5;
cache_req_per_sec15 = l.cache_req_per_sec15;
was_stop_request = l.was_stop_request;
CreateTable();
return *this;
}
LoadAvg::LoadAvg(const LoadAvg & l)
{
operator=(l);
}
LoadAvg::~LoadAvg()
{
delete [] tab1;
delete [] tab5;
delete [] tab15;
}
void LoadAvg::CreateTable(size_t seconds, size_t granularity, Times* & tab, size_t & len)
{
len = (seconds / granularity) + 1; // rounding up (len mininum is 1)
tab = new Times[len];
for(size_t i=0 ; i<len ; ++i)
{
tab[i].Clear();
tab[i].dp = granularity; // at the beginning we assume the pause for all items
}
}
void LoadAvg::CreateTable()
{
CreateTable(60, WINIX_LOADAVG_GRANULARITY1, tab1, len1);
CreateTable(60 * 5, WINIX_LOADAVG_GRANULARITY5, tab5, len5);
CreateTable(60 * 15, WINIX_LOADAVG_GRANULARITY15, tab15, len15);
}
void LoadAvg::MoveTab(Times * tab, size_t len)
{
if( len > 1 )
{
for(size_t i=0 ; i<len-1 ; ++i)
tab[i] = tab[i+1];
}
tab[len-1].Clear();
}
void LoadAvg::UpdateTimer1()
{
MoveTab(tab1, len1);
tab1[len1-1] = current1;
current1.Clear();
cache_load1 = 0.0;
cache_req_per_sec1 = 0.0;
}
void LoadAvg::UpdateTimer5()
{
MoveTab(tab5, len5);
tab5[len5-1] = current5;
current5.Clear();
cache_load5 = 0.0;
cache_req_per_sec5 = 0.0;
}
void LoadAvg::UpdateTimer15()
{
MoveTab(tab15, len15);
tab15[len15-1] = current15;
current15.Clear();
cache_load15 = 0.0;
cache_req_per_sec15 = 0.0;
}
void LoadAvg::CheckTimers()
{
if( current1.dr + current1.dp > (double)WINIX_LOADAVG_GRANULARITY1 )
UpdateTimer1();
if( current5.dr + current5.dp > (double)WINIX_LOADAVG_GRANULARITY5 )
UpdateTimer5();
if( current15.dr + current15.dp > (double)WINIX_LOADAVG_GRANULARITY15 )
UpdateTimer15();
}
void LoadAvg::StartRequest()
{
clock_gettime(CLOCK_REALTIME, &start_req);
if( was_stop_request )
{
double dp = (start_req.tv_sec - stop_req.tv_sec);
dp += double(start_req.tv_nsec - stop_req.tv_nsec) / 1000000000.0; // make sure that tv_nsec has signed type
current1.dp += dp;
current5.dp += dp;
current15.dp += dp;
CheckTimers();
}
}
void LoadAvg::StopRequest()
{
char buf[50];
clock_gettime(CLOCK_REALTIME, &stop_req);
double dr = (stop_req.tv_sec - start_req.tv_sec);
dr += double(stop_req.tv_nsec - start_req.tv_nsec) / 1000000000.0; // make sure that tv_nsec has signed type
current1.dr += dr;
current5.dr += dr;
current15.dr += dr;
current1.req += 1;
current5.req += 1;
current15.req += 1;
sprintf(buf, "%f", dr);
SetNonZeroDigitsAfterComma(buf, 2);
log << log2 << "LA: request took: " << buf << "s" << logend;
was_stop_request = true;
}
void LoadAvg::SumTab(Times * tab, size_t len, double expected, Times & t)
{
size_t i = len;
while( i-- > 0 && t.dr+t.dp < expected )
{
t.dr += tab[i].dr;
t.dp += tab[i].dp;
t.req += tab[i].req;
}
}
void LoadAvg::Calculate1()
{
Times t = current1;
SumTab(tab1, len1, 60.0, t);
if( t.dr+t.dp == 0.0 )
{
cache_load1 = 0.0;
cache_req_per_sec1 = 0.0;
}
else
{
cache_load1 = t.dr / (t.dr+t.dp);
cache_req_per_sec1 = t.req / (t.dr+t.dp);
}
}
void LoadAvg::Calculate5()
{
Times t = current5;
SumTab(tab5, len5, 60.0 * 5, t);
if( t.dr+t.dp == 0.0 )
{
cache_load5 = 0.0;
cache_req_per_sec5 = 0.0;
}
else
{
cache_load5 = t.dr / (t.dr+t.dp);
cache_req_per_sec5 = t.req / (t.dr+t.dp);
}
}
void LoadAvg::Calculate15()
{
Times t = current15;
SumTab(tab15, len15, 60.0 * 15, t);
if( t.dr+t.dp == 0.0 )
{
cache_load15 = 0.0;
cache_req_per_sec15 = 0.0;
}
else
{
cache_load15 = t.dr / (t.dr+t.dp);
cache_req_per_sec15 = t.req / (t.dr+t.dp);
}
}
double LoadAvg::LoadAvgNow()
{
double load = 0.0;
double dr = current1.dr;
double dp = current1.dp;
if( tab1[len1-1].dr + tab1[len1-1].dp < WINIX_LOADAVG_GRANULARITY1 * 2 )
{
dr += tab1[len1-1].dr;
dp += tab1[len1-1].dp;
}
if( dr + dp != 0.0 )
load = dr / (dr + dp);
return load;
}
double LoadAvg::LoadAvg1()
{
if( cache_load1 != 0.0 )
return cache_load1;
Calculate1();
return cache_load1;
}
double LoadAvg::LoadAvg5()
{
if( cache_load5 != 0.0 )
return cache_load5;
Calculate5();
return cache_load5;
}
double LoadAvg::LoadAvg15()
{
if( cache_load15 != 0.0 )
return cache_load15;
Calculate15();
return cache_load15;
}
double LoadAvg::ReqPerSecNow()
{
double req_per_sec = 0.0;
double dr = current1.dr;
double dp = current1.dp;
double req = current1.req;
if( tab1[len1-1].dr + tab1[len1-1].dp < WINIX_LOADAVG_GRANULARITY1 * 2 )
{
dr += tab1[len1-1].dr;
dp += tab1[len1-1].dp;
req += tab1[len1-1].req;
}
if( dr + dp != 0.0 )
req_per_sec = req / (dr + dp);
return req_per_sec;
}
double LoadAvg::ReqPerSec1()
{
if( cache_req_per_sec1 != 0.0 )
return cache_req_per_sec1;
Calculate1();
return cache_req_per_sec1;
}
double LoadAvg::ReqPerSec5()
{
if( cache_req_per_sec5 != 0.0 )
return cache_req_per_sec5;
Calculate5();
return cache_req_per_sec5;
}
double LoadAvg::ReqPerSec15()
{
if( cache_req_per_sec15 != 0.0 )
return cache_req_per_sec15;
Calculate15();
return cache_req_per_sec15;
}
} // namespace Winix

147
winixd/core/loadavg.h Normal file
View File

@@ -0,0 +1,147 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2008-2018, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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 headerfile_winix_core_loadavg
#define headerfile_winix_core_loadavg
#include <ctime>
#include "winixbase.h"
namespace Winix
{
// in seconds
#define WINIX_LOADAVG_GRANULARITY1 2
#define WINIX_LOADAVG_GRANULARITY5 15
#define WINIX_LOADAVG_GRANULARITY15 45
class LoadAvg : public WinixBase
{
public:
LoadAvg();
~LoadAvg();
LoadAvg & operator=(const LoadAvg & l);
LoadAvg(const LoadAvg & l);
void StartRequest();
void StopRequest();
double LoadAvgNow(); // load average withing last WINIX_LOADAVG_GRANULARITY1 seconds
double LoadAvg1();
double LoadAvg5();
double LoadAvg15();
double ReqPerSecNow();
double ReqPerSec1();
double ReqPerSec5();
double ReqPerSec15();
private:
struct Times
{
double dr; // time for the request (in seconds)
double dp; // time for the pause between requestes (in seconds)
long req; // how many requests
void Clear()
{
dr = 0.0;
dp = 0.0;
req = 0;
}
Times & operator=(const Times & t)
{
dr = t.dr;
dp = t.dp;
req = t.req;
return *this;
}
};
void CheckTimers();
void UpdateTimer1();
void UpdateTimer5();
void UpdateTimer15();
Times current1;
Times current5;
Times current15;
void CreateTable(size_t seconds, size_t granulatiry, Times* & tab, size_t & len);
void CreateTable();
void MoveTab(Times * tab, size_t len);
void SumTab(Times * tab, size_t len, double expected, Times & t);
void Calculate1();
void Calculate5();
void Calculate15();
bool was_stop_request;
timespec start_req, stop_req;
Times * tab1;
size_t len1;
Times * tab5;
size_t len5;
Times * tab15;
size_t len15;
double cache_load1;
double cache_load5;
double cache_load15;
double cache_req_per_sec1;
double cache_req_per_sec5;
double cache_req_per_sec15;
};
} // namespace Winix
#endif

82
winixd/core/lock.cpp Normal file
View File

@@ -0,0 +1,82 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2012-2014, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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.
*
*/
#include "lock.h"
namespace Winix
{
Lock::Lock()
{
synchro = 0;
}
Lock::Lock(Synchro * synchro_)
{
synchro = synchro_;
synchro->Lock();
}
Lock::Lock(Synchro & synchro_)
{
synchro = &synchro_;
synchro->Lock();
}
Lock::~Lock()
{
Unlock();
}
void Lock::Unlock()
{
if( synchro )
{
synchro->Unlock();
synchro = 0;
}
}
} // namespace Winix

71
winixd/core/lock.h Normal file
View File

@@ -0,0 +1,71 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2012-2014, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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 headerfile_winix_core_lock
#define headerfile_winix_core_lock
#include "synchro.h"
namespace Winix
{
class Lock
{
public:
Lock(Synchro * synchro_);
Lock(Synchro & synchro_);
~Lock();
void Unlock();
private:
Synchro * synchro;
Lock();
};
} // namespace Winix
#endif

300
winixd/core/log.cpp Normal file
View File

@@ -0,0 +1,300 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2008-2019, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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.
*
*/
#include "log.h"
#include <ctime>
#include <string.h>
#include "utf8/utf8.h"
namespace Winix
{
Log::Log()
{
request = 0;
max_requests = 1;
}
Log::~Log()
{
}
void Log::SetDependency(Log * log)
{
buffer = log->buffer;
file_log = log->file_log;
}
void Log::SetMaxRequests(int max_requests)
{
this->max_requests = max_requests;
}
void Log::PrintDate(const PT::Date & date)
{
FileLog * winix_file_log = dynamic_cast<FileLog*>(file_log);
if( winix_file_log )
(*this) << winix_file_log->get_local_date(date); // synchronization is made in get_local_date
else
(*this) << date;
}
Log & Log::operator<<(const void * s)
{
PT::Log::operator<<(s);
return *this;
}
Log & Log::operator<<(const char * s)
{
PT::Log::operator<<(s);
return *this;
}
Log & Log::operator<<(const std::string & s)
{
PT::Log::operator<<(s);
return *this;
}
Log & Log::operator<<(const std::string * s)
{
PT::Log::operator<<(s);
return *this;
}
Log & Log::operator<<(const wchar_t * s)
{
PT::Log::operator<<(s);
return *this;
}
Log & Log::operator<<(const std::wstring & s)
{
PT::Log::operator<<(s);
return *this;
}
Log & Log::operator<<(const std::wstring * s)
{
PT::Log::operator<<(s);
return *this;
}
Log & Log::operator<<(int s)
{
PT::Log::operator<<(s);
return *this;
}
Log & Log::operator<<(long s)
{
PT::Log::operator<<(s);
return *this;
}
Log & Log::operator<<(char s)
{
PT::Log::operator<<(s);
return *this;
}
Log & Log::operator<<(wchar_t s)
{
PT::Log::operator<<(s);
return *this;
}
Log & Log::operator<<(size_t s)
{
PT::Log::operator<<(s);
return *this;
}
Log & Log::operator<<(double s)
{
PT::Log::operator<<(s);
return *this;
}
Log & Log::operator<<(const PT::Space & s)
{
PT::Log::operator<<(s);
return *this;
}
Log & Log::operator<<(const PT::Date & date)
{
PT::Log::operator<<(date);
return *this;
}
Log & Log::operator<<(LogManipulators m)
{
switch(m)
{
case LogManipulators::log1:
PT::Log::operator<<(PT::Log::log1);
break;
case LogManipulators::log2:
PT::Log::operator<<(PT::Log::log2);
break;
case LogManipulators::log3:
PT::Log::operator<<(PT::Log::log3);
break;
case LogManipulators::log4:
PT::Log::operator<<(PT::Log::log4);
break;
case LogManipulators::logend:
PT::Log::operator<<(PT::Log::logend);
break;
case LogManipulators::logsave:
PT::Log::operator<<(PT::Log::logsave);
break;
case LogManipulators::logendrequest:
if( ++request >= max_requests )
{
save_log_and_clear();
request = 0;
}
break;
default:
break;
}
return *this;
}
//Log & Log::SystemErr(int err)
//{
// (*this) << "errno: " << err;
//
// // strerror is not thread safe and we now use Log in each thread
// const char * err_msg = strerror(err);
//
// if( err_msg )
// (*this) << " (" << err_msg << ")";
//
// return *this;
//}
Log & Log::LogString(const std::string & value, size_t max_size)
{
PT::Log::LogString(value, max_size);
return *this;
}
Log & Log::LogString(const std::wstring & value, size_t max_size)
{
PT::Log::LogString(value, max_size);
return *this;
}
Log & Log::LogBinary(const char * blob, size_t blob_len)
{
PT::Log::LogBinary(blob, blob_len);
return *this;
}
Log & Log::LogBinary(const std::string & blob)
{
PT::Log::LogBinary(blob);
return *this;
}
} // namespace Winix

127
winixd/core/log.h Normal file
View File

@@ -0,0 +1,127 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2008-2019, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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 headerfile_winix_core_log
#define headerfile_winix_core_log
#include <sstream>
#include <fstream>
#include <iostream>
#include <string>
#include "logmanipulators.h"
#include "filelog.h"
#include "log/log.h"
namespace Winix
{
class Log : public PT::Log
{
public:
Log();
virtual ~Log();
virtual void SetDependency(Log * log);
virtual void SetMaxRequests(int max_requests);
virtual Log & operator<<(const void * s);
virtual Log & operator<<(const char * s);
virtual Log & operator<<(const std::string * s);
virtual Log & operator<<(const std::string & s);
virtual Log & operator<<(const wchar_t * s);
virtual Log & operator<<(const std::wstring * s);
virtual Log & operator<<(const std::wstring & s);
virtual Log & operator<<(int s);
virtual Log & operator<<(long s);
virtual Log & operator<<(char s);
virtual Log & operator<<(wchar_t s);
virtual Log & operator<<(size_t s);
virtual Log & operator<<(double s);
virtual Log & operator<<(const PT::Space & space);
virtual Log & operator<<(LogManipulators m);
virtual Log & operator<<(const PT::Date & date);
virtual void PrintDate(const PT::Date & date);
template<typename char_type, size_t stack_size, size_t heap_block_size>
Log & operator<<(const PT::TextStreamBase<char_type, stack_size, heap_block_size> & buf);
virtual Log & LogString(const std::string & value, size_t max_size);
virtual Log & LogString(const std::wstring & value, size_t max_size);
virtual Log & LogBinary(const char * blob, size_t blob_len);
virtual Log & LogBinary(const std::string & blob);
//virtual Log & SystemErr(int err);
private:
// current request for logging
// starts from zero and incremented after logendrequest modifier
int request;
// how many request to save at once
int max_requests;
};
template<typename char_type, size_t stack_size, size_t heap_block_size>
Log & Log::operator<<(const PT::TextStreamBase<char_type, stack_size, heap_block_size> & buf)
{
PT::Log::operator<<(buf);
return *this;
}
} // namespace Winix
#endif

View File

@@ -0,0 +1,85 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2011-2018, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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 headerfile_winix_core_logmanipulators
#define headerfile_winix_core_logmanipulators
#include "log/log.h"
namespace Winix
{
/*
log1 - the first level
log2
log3
log4 - the last level (debug level)
logend - the end of a line
logendrequest - end of a current request
logsave - current log buffer is saved and cleared
manipulators used by the session logger (SLog)
loginfo - normal info to a user
logerror - we are reporting an error
logwarning - we are reporting a warning
make sure that loginfo, logerror and logwarning have values less than 32 (space)
their are used as control codes in a string
*/
enum LogManipulators
{
log1,
log2,
log3,
log4,
logend,
logsave,
logendrequest,
loginfo,
logerror,
logwarning
};
} // namespace Winix
#endif

1418
winixd/core/misc.cpp Normal file

File diff suppressed because it is too large Load Diff

992
winixd/core/misc.h Normal file
View File

@@ -0,0 +1,992 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2008-2018, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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 headerfile_winix_core_misc
#define headerfile_winix_core_misc
#include <string>
#include <sstream>
#include <ctime>
#include <cstdio>
#include "item.h"
#include "requesttypes.h"
#include "date/date.h"
#include "textstream/textstream.h"
#include "utf8/utf8.h"
#include "winix_const.h"
#include "convert/convert.h"
namespace Winix
{
/*
conversions between text and numbers
*/
int Toi(const std::string & str, int base = 10);
int Toi(const std::wstring & str, int base = 10);
int Toi(const char * str, int base = 10);
int Toi(const wchar_t * str, int base = 10);
long Tol(const std::string & str, int base = 10);
long Tol(const std::wstring & str, int base = 10);
long Tol(const char * str, int base = 10);
long Tol(const wchar_t * str, int base = 10);
double Tod(const std::string & str);
double Tod(const std::wstring & str);
double Tod(const char * str);
double Tod(const wchar_t * str);
// if the buffer is too small it will be terminated at the beginning (empty string)
// and the function returns false
template<class CharType>
bool Toa(unsigned long value, CharType * buffer, size_t buf_len, int base = 10)
{
size_t i1, i2;
long rest;
if( buf_len == 0 )
return false;
i1 = i2 = 0;
if( base < 2 ) base = 2;
if( base > 16 ) base = 16;
do
{
rest = value % base;
value = value / base;
buffer[i2++] = (rest < 10) ? char(rest) + '0' : char(rest) - 10 + 'A';
}
while(value != 0 && i2 < buf_len);
if( i2 >= buf_len )
{
buffer[0] = 0; // ops, the buffer was too small
return false;
}
buffer[i2--] = 0;
for( ; i1 < i2 ; ++i1, --i2)
{
CharType temp = buffer[i1];
buffer[i1] = buffer[i2];
buffer[i2] = temp;
}
return true;
}
// if the buffer is too small it will be terminated at the beginning (empty string)
// and the function returns false
template<class CharType>
bool Toa(long value, CharType * buffer, size_t buf_len, int base = 10)
{
if( buf_len == 0 )
return false;
CharType * buf = buffer;
if( value < 0 )
{
buffer[0] = '-';
buf += 1;
buf_len -= 1;
value = -value;
}
bool res = Toa(static_cast<unsigned long>(value), buf, buf_len, base);
if( !res )
buffer[0] = 0;
return res;
}
template<class CharType>
bool Toa(unsigned int value, CharType * buffer, size_t buf_len, int base = 10)
{
return Toa(static_cast<unsigned long>(value), buffer, buf_len, base);
}
template<class CharType>
bool Toa(int value, CharType * buffer, size_t buf_len, int base = 10)
{
return Toa(static_cast<long>(value), buffer, buf_len, base);
}
/*
these methos don't take the buffer size
make sure the buffer size is sufficient big
2^64 - 1 = 18446744073709551615 = 20 characters (plus minus sign and plus terminating zero)
so the buffer should have at least 22 characters
!! CHECK ME check the size whether is correct
*/
template<class CharType>
bool Toa(unsigned long value, CharType * buffer)
{
size_t sufficient_space = 25;
return Toa(value, buffer, sufficient_space);
}
template<class CharType>
bool Toa(long value, CharType * buffer)
{
size_t sufficient_space = 25;
return Toa(value, buffer, sufficient_space);
}
template<class CharType>
bool Toa(unsigned int value, CharType * buffer)
{
size_t sufficient_space = 25;
return Toa(value, buffer, sufficient_space);
}
template<class CharType>
bool Toa(int value, CharType * buffer)
{
size_t sufficient_space = 25;
return Toa(value, buffer, sufficient_space);
}
// warning: it uses its own static buffer
// one buffer for both these functions
// !! REMOVE ME they are deprecated (don't use it)
const wchar_t * Toa(unsigned int value, int base = 10);
const wchar_t * Toa(unsigned long value, int base = 10);
const wchar_t * Toa(int value, int base = 10);
const wchar_t * Toa(long value, int base = 10);
void Toa(int value, std::string & res, int base = 10, bool clear = true);
void Toa(long value, std::string & res, int base = 10, bool clear = true);
void Toa(int value, std::wstring & res, int base = 10, bool clear = true);
void Toa(long value, std::wstring & res, int base = 10, bool clear = true);
/*
* this method make sure that there is no more than 'digits' non zero digits
* in the given string
*
*
* samples (if parameter 'digits' is equal to two):
* "0.0001234" -> "0.00012"
* "10" -> "10"
* "123.345" -> "123.34"
* "55.1003" -> "55.10"
*
*/
void SetNonZeroDigitsAfterComma(char * str, size_t digits);
bool CorrectUrlChar(wchar_t c);
void CorrectUrlDots(std::wstring & url);
void CorrectUrlChars(std::wstring & url);
void CorrectUrlOnlyAllowedChar(std::wstring & url);
const wchar_t * DateToStr(int year, int month, int day);
const wchar_t * DateToStr(int year, int month, int day, int hour, int min, int sec);
const wchar_t * DateToStr(const PT::Date & d);
const wchar_t * DateToStr(time_t t);
const wchar_t * DateToStrWithoutHours(const PT::Date & d);
const wchar_t * DateToStrWithoutHours(time_t t);
const char * DateToStrCookie(int year, int month, int day, int hour, int min, int sec);
const char * DateToStrCookie(const PT::Date & d);
const char * DateToStrCookie(time_t t);
// depracated
// not thread safe
const wchar_t * IpToStr(unsigned int ip_);
// in a new code we can use WTextStream in such a way
// DateToStr() etc can use it too
PT::WTextStream IPToStr(unsigned int ip);
PT::WTextStream IPToStr(int ip);
bool IsWhite(wchar_t s, bool treat_new_line_as_white = false);
bool IsWhite(const wchar_t * str, bool treat_new_line_as_white = false);
bool IsWhite(const std::wstring & str, bool treat_new_line_as_white = false);
void TrimWhite(std::wstring & s, bool trim_new_line_too = false);
const wchar_t * SkipWhite(const wchar_t * s, bool treat_new_line_as_white = false);
void TrimFirst(std::wstring & s, wchar_t c);
void TrimLast(std::wstring & s, wchar_t c);
void Trim(std::wstring & s, wchar_t c);
bool IsLastSlash(const std::wstring & path);
/*
* returns true if str is an integer number
* white strings at the beginning and at the end are ignored
* e.g. returns true for:
* " 10 "
* " -20 "
* e.g. returns false for:
* ""
* "- 20"
* "z"
*/
bool IsInt(const wchar_t * str, bool treat_new_line_as_white = false);
bool IsInt(const std::wstring & str, bool treat_new_line_as_white = false);
/*
* returns true if str is a non-negative integer number
* white strings at the beginning and at the end are ignored
* e.g. returns true for:
* " 0 "
* " 10 "
* " 20 "
* e.g. returns false for:
* ""
* " -20 "
* "z"
*/
bool IsSize(const wchar_t * str, bool treat_new_line_as_white = false);
bool IsSize(const std::wstring & str, bool treat_new_line_as_white = false);
/*
* returns true if str is a floating point number
* white strings at the beginning and at the end are ignored
* as a decimal comma can be a dot or a comma
* e.g. returns true for:
* " 10 "
* " -20.3 "
* " 30,5 "
* e.g. returns false for:
* ""
* "- 20.1"
* "20.1.2"
* "z"
*/
bool IsFloat(const wchar_t * str, bool treat_new_line_as_white = false);
bool IsFloat(const std::wstring & str, bool treat_new_line_as_white = false);
void Overwrite(std::string & str);
void Overwrite(std::wstring & str);
template<class StringType>
void MaxSize(StringType & str, size_t max_size)
{
if( str.size() > max_size )
str.erase(max_size);
}
/*
this method removing all characters from given string
only digits are allowed and if allow_comma then one comma (or dot)
character is allowed
if change_to_dot is true then if a comma exists then it is changed to a dot
*/
template<class StringType>
void OnlyDigit(StringType & s, bool allow_comma = true, bool change_to_dot = true)
{
typename StringType::size_type i;
bool was_comma = false;
if( s.empty() )
{
s = '0';
return;
}
for(i=0 ; i<s.size() ; )
{
if( (s[i]>='0' && s[i]<='9') ||
(allow_comma && !was_comma && (s[i]=='.' || s[i]==',')) )
{
if( change_to_dot && s[i] == ',' )
s[i] = '.';
if( s[i]=='.' || s[i]==',' )
was_comma = true;
i += 1;
}
else
{
s.erase(i, 1);
}
}
}
template<class StringType1, class StringType2>
bool Equal(const StringType1 * str1, const StringType2 * str2)
{
while( *str1 && *str2 && wchar_t(*str1) == wchar_t(*str2) )
{
++str1;
++str2;
}
if( *str1 == 0 && *str2 == 0 )
return true;
return false;
}
template<class StringType1, class StringType2>
bool Equal(const StringType1 & str1, const StringType2 & str2)
{
return Equal(str1.c_str(), str2.c_str());
}
/*
looking for 'look_for' string in 'buf' and replacing it with 'replace'
'replace' can be empty (so only 'look_for' will be deleted)
*/
template<class StringType>
void ReplaceString(StringType & buf, const StringType & look_for, const StringType & replace)
{
size_t i = 0;
if( look_for.empty() )
return;
while( i < buf.size() )
{
if( PT::IsSubString(look_for.c_str(), buf.c_str() + i) )
{
buf.erase(i, look_for.size());
buf.insert(i, replace);
i += replace.size();
}
else
{
i += 1;
}
}
}
template<class StringType>
void NoLastSlash(StringType & s)
{
if( s.empty() )
return;
size_t i = s.size();
for( ; i>0 && s[i-1]=='/' ; --i);
if( i < s.size() )
s.erase(i);
}
template<class StringType>
void NoFirstHttp(StringType & s)
{
if( s.empty() )
return;
const char http[] = "http://";
const char https[] = "https://";
if( IsSubStringNoCase(http, s.c_str()) )
{
s.erase(0, sizeof(http)/sizeof(char));
}
else
if( IsSubStringNoCase(https, s.c_str()) )
{
s.erase(0, sizeof(https)/sizeof(char));
}
}
/*
this method returns true if there are two dots meaning 'go up' somewhere in the path
for example such paths return true:
".."
"test/../path"
"test/where/../"
"test/where/.."
"../abc"
*/
template<class StringType>
bool PathHasUpDir(const StringType * str)
{
size_t i = 0;
while( str[i] )
{
if( str[i]=='.' && str[i+1]=='.' )
{
i += 2;
if( str[i]=='/' || str[i]==0 )
return true;
}
// skipping until to next slash
while( str[i] && str[i]!='/' )
i += 1;
// skipping the slash (or slashes)
while( str[i]=='/' )
i += 1;
}
return false;
}
template<class StringType>
bool PathHasUpDir(const StringType & str)
{
return PathHasUpDir(str.c_str());
}
/*
this method calculates how many directories there are in the given path
input:
str - path
last_is_dir - true if the last part of the path should be treated as a directory too
samples:
HowManyDirs("", false) -> 0
HowManyDirs("", true) -> 0
HowManyDirs("abc", false) -> 0
HowManyDirs("abc", true) -> 1
HowManyDirs("/abc/", true) -> 1
HowManyDirs("////", false) -> 0
HowManyDirs("////", true) -> 0
HowManyDirs("////abc", false) -> 0
HowManyDirs("////abc", true) -> 1
HowManyDirs("/var/static", false) -> 1
HowManyDirs("/var/static", true) -> 2
HowManyDirs("/var/static/", false) -> 2
HowManyDirs("/var/static/", true) -> 2
*/
template<class StringType>
size_t HowManyDirs(const StringType * str, bool is_last_dir = false)
{
size_t res = 0;
size_t i = 0;
// first slash (root dir) is not calculated
while( str[i]=='/' )
i += 1;
while( str[i] )
{
if( str[i]=='/' )
{
res += 1;
while( str[i]=='/' )
i += 1;
}
else
{
i += 1;
}
}
if( is_last_dir && i>0 && str[i-1]!='/' )
res += 1;
return res;
}
template<class StringType>
size_t HowManyDirs(const StringType & str, bool is_last_dir = false)
{
return HowManyDirs(str.c_str(), is_last_dir);
}
/*
this method skips some first directories from given path
samples:
SkipDirs("/var/test", 1) -> "test"
SkipDirs("/var/test/somewhere", 1) -> "test/somewhere"
SkipDirs("/var/test/somewhere", 2) -> "somewhere"
SkipDirs("/var/test/somewhere", 10) -> ""
*/
template<class StringType>
const StringType * SkipDirs(const StringType * str, size_t how_many_skip)
{
size_t i = 0;
size_t skipped = 0;
if( how_many_skip == 0 )
return str;
// first slash (root dir) is not calculated
while( str[i]=='/' )
i += 1;
while( str[i] )
{
if( str[i]=='/' )
{
skipped += 1;
while( str[i]=='/' )
i += 1;
if( skipped == how_many_skip )
return str+i;
}
else
{
i += 1;
}
}
return str + i;
}
bool IsEmailCorrectChar(wchar_t c);
bool ValidateEmail(const wchar_t * email);
bool ValidateEmail(const std::wstring & email);
bool IsFile(const wchar_t * file);
bool IsFile(const std::wstring & file);
bool CreateDir(const wchar_t * dir, int priv, int group = -1);
bool CreateDir(const std::wstring & dir, int priv, int group = -1);
// creating directories (dirs) under base_dir (base_dir must exist)
// if skip_last == true then last part from dir is treated as a file (the last directory is not created)
bool CreateDirs(const wchar_t * base_dir, const wchar_t * dirs, int priv = 0755, int group = -1, bool skip_last = false);
bool CreateDirs(const std::wstring & base_dir, const std::wstring & dirs, int priv = 0755, int group = -1, bool skip_last = false);
int GetGroupId(const wchar_t * name);
int GetGroupId(const std::wstring & name);
bool SetPriv(const wchar_t * name, int priv, int group = -1);
bool SetPriv(const std::wstring & name, int priv, int group = -1);
bool CopyFile(FILE * in, FILE * out);
bool CopyFile(const wchar_t * src, const wchar_t * dst);
bool CopyFile(const std::wstring & src, const std::wstring & dst);
bool RemoveFile(const wchar_t * file);
bool RemoveFile(const std::wstring & file);
bool RenameFile(const wchar_t * from, const wchar_t * to);
bool RenameFile(const std::wstring & from, const std::wstring & to);
bool GetUTF8File(const wchar_t * file_path, std::wstring & content, bool clear_content = true);
bool GetUTF8File(const std::wstring & file_path, std::wstring & content, bool clear_content = true);
const wchar_t * GetFileExt(const wchar_t * name);
int SelectFileType(const wchar_t * file_name);
int SelectFileType(const std::wstring & file_name);
// thread safe
template<typename char_type, size_t stack_size, size_t heap_block_size>
void UrlEncode(char c,
PT::TextStreamBase<char_type, stack_size, heap_block_size> & out,
bool clear_out = true)
{
char buffer[10];
size_t buflen = sizeof(buffer)/sizeof(char);
if( clear_out )
out.clear();
if( (c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') ||
c == '.' || c == ',' || c == '-' || c == '_' || c == '(' || c == ')' )
{
out << c;
}
else
{
Toa(static_cast<unsigned char>(c), buffer, buflen, 16);
out << '%';
if( buffer[1] == 0 )
out << '0'; // there is only one character in the buffer
out << buffer;
}
}
// thread safe
template<typename char_type, size_t stack_size, size_t heap_block_size>
void UrlEncode(const char * in,
PT::TextStreamBase<char_type, stack_size, heap_block_size> & out,
bool clear_out = true)
{
if( clear_out )
out.clear();
for(size_t i=0 ; in[i] != 0 ; ++i)
UrlEncode(in[i], out, false);
}
// thread safe
template<typename char_type, size_t stack_size, size_t heap_block_size>
void UrlEncode(const std::string & in,
PT::TextStreamBase<char_type, stack_size, heap_block_size> & out,
bool clear_out = true)
{
UrlEncode(in.c_str(), out, clear_out);
}
// not thread safe
template<typename char_type, size_t stack_size, size_t heap_block_size>
void UrlEncode(const wchar_t * in,
PT::TextStreamBase<char_type, stack_size, heap_block_size> & out,
bool clear_out = true)
{
static std::string ain;
PT::WideToUTF8(in, ain);
if( clear_out )
out.clear();
for(size_t i=0 ; i < ain.size() ; ++i)
UrlEncode(ain[i], out, false);
}
// not thread safe
template<typename char_type, size_t stack_size, size_t heap_block_size>
void UrlEncode(const std::wstring & in,
PT::TextStreamBase<char_type, stack_size, heap_block_size> & out,
bool clear_out = true)
{
UrlEncode(in.c_str(), out, clear_out);
}
// no thread safe
template<class StringType>
void UrlEncode(char c, StringType & out, bool clear_out = true)
{
static PT::TextStream tmp;
UrlEncode(c, tmp);
tmp.to_string(out, clear_out);
}
// !! IMROVE ME we need some UrlEncode methods with PT::TextBuffer instead of std::string
void UrlEncode(const char * in, std::string & out, bool clear_out = true);
void UrlEncode(const std::string & in, std::string & out, bool clear_out = true);
void UrlEncode(const wchar_t * in, std::string & out, bool clear_out = true);
void UrlEncode(const std::wstring & in, std::string & out, bool clear_out = true);
void UrlEncode(const wchar_t * in, std::wstring & out, bool clear_out = true);
void UrlEncode(const std::wstring & in, std::wstring & out, bool clear_out = true);
/*
* decoding a URL
*
* return false is the url is too long (longer than WINIX_URL_MAX_SIZE)
* or it cannot be correctly converted from UTF8 to wide characters
*
*/
bool UrlDecode(const char * url, std::wstring & out, bool clear_out = true);
bool UrlDecode(const std::string & url, std::wstring & out, bool clear_out = true);
template<typename char_type, size_t stack_size, size_t heap_block_size>
void QEncodeAddChar(char_type c, PT::TextStreamBase<char_type, stack_size, heap_block_size> & out)
{
if( (c>='A' && c<='Z') ||
(c>='a' && c<='z') ||
(c>='0' && c<='9') )
{
out << c;
}
else
{
char buf1[10];
char buf2[10];
size_t len1 = sizeof(buf1) / sizeof(char);
size_t len2 = sizeof(buf2) / sizeof(char);
size_t len = PT::IntToUTF8(int(c), buf1, len1);
for(size_t i=0 ; i<len ; ++i)
{
// make sure that it produces *capital* letters (ABC...)
Toa((unsigned long)(unsigned char)buf1[i], buf2, len2, 16);
out << '=';
if( buf2[1] == 0 )
out << '0';
out << buf2;
}
}
}
/*
this encoding is used in mails headers
encoded-word = "=?" charset "?" encoding "?" encoded-text "?="
http://www.faqs.org/rfcs/rfc1522.html
we have:
charset = UTF-8
encoding = Q
current limitation:
we do not support checking the maximum length:
"An encoded-word may not be more than 75 characters long, including
charset, encoding, encoded-text, and delimiters."
*/
template<typename char_type, size_t stack_size, size_t heap_block_size>
void QEncode(const wchar_t * in, PT::TextStreamBase<char_type, stack_size, heap_block_size> & out,
bool clear = true)
{
if( clear )
out.clear();
out << "=?UTF-8?Q?";
for( ; *in ; ++in)
QEncodeAddChar(*in, out);
out << "?=";
}
template<typename char_type, size_t stack_size, size_t heap_block_size>
void QEncode(const std::wstring & in, PT::TextStreamBase<char_type, stack_size, heap_block_size> & out,
bool clear = true)
{
if( clear )
out.clear();
out << "=?UTF-8?Q?";
// do not use QEncode(in.c_str()) as 'in' can have a zero byte
for(size_t i=0 ; i<in.size() ; ++i)
QEncodeAddChar(in[i], out);
out << "?=";
}
void QEncode(const std::wstring & in, std::string & out, bool clear = true);
void RemovePostFileTmp(PostFileTab & post_file_tab);
/*
short_str is removed from long_str (and a last dots are removed too)
and the result is stored in out
sample:
short_str: "mydomain.tld"
long_str: "www.subdomain.mydomain.tld"
out: "www.subdomain"
short_str: "mydomain.tld"
long_str: "otherdifferentstring"
out: ""
*/
template<class StringType1, class StringType2, class StringType3>
void CreateSubdomain(const StringType1 * short_str, const StringType2 * long_str, StringType3 & out)
{
size_t i1, i2;
out.clear();
for(i1=0 ; short_str[i1] != 0 ; ++i1);
for(i2=0 ; long_str[i2] != 0 ; ++i2);
if( i1 >= i2 )
return;
// i1 is < i2
while( i1-- > 0 )
{
i2 -= 1;
if( short_str[i1] != long_str[i2] )
return; // short_str is not a last substring of long_str
}
while( i2>0 && long_str[i2-1] == '.' )
i2 -= 1;
for(i1=0 ; i1 < i2 ; ++i1)
out += long_str[i1];
}
template<typename IntType>
void SetMinMax(IntType & val, IntType min_val, IntType max_val)
{
if( val < min_val )
val = min_val;
if( val > max_val )
val = max_val;
}
template<class Stream, class StringType>
void JSONescape(Stream & out, const StringType & str)
{
// !! IMPROVE ME (optimizing)
// it is better to not write one by one character
// but use write method insted
for(size_t i=0 ; i<str.size() ; ++i)
{
switch(str[i])
{
case 0: out << '\\'; out << '0'; break;
case '\r': out << '\\'; out << 'r'; break;
case '\n': out << '\\'; out << 'n'; break;
case '\t': out << '\\'; out << 't'; break;
case 0x08: out << '\\'; out << 'b'; break;
case 0x0c: out << '\\'; out << 'f'; break;
case '\\': out << '\\'; out << '\\'; break;
//case '/': out << '\\'; out << '/'; break; // slash doesn't have to be escaped
case '"': out << '\\'; out << '\"'; break;
default:
out << str[i];
}
}
}
/*
* converting from a wide string to an UTF-8 string
* and puts a log if the conversion fails
*
* it uses PT::WideToUTF8()
*/
bool WideToUTF8(const wchar_t * wide_string, char * utf8, size_t utf8_size);
bool WideToUTF8(const std::wstring & wide_string, char * utf8, size_t utf8_size);
} // namespace Winix
#endif

145
winixd/core/mount.cpp Normal file
View File

@@ -0,0 +1,145 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2009-2014, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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.
*
*/
#include "mount.h"
#include "misc.h"
namespace Winix
{
Mount::Mount()
{
dir_id = -1;
type = -1;
fs = -1;
}
void Mount::ClearParams()
{
size_t i;
for(i=0 ; i<param.size() ; ++i)
param[i].Clear();
}
bool Mount::IsPar(int code)
{
if( code < 0 || code >= (int)param.size() )
return false;
if( !param[code].defined )
return false;
return true;
}
bool Mount::IsArg(int code, const wchar_t * arg)
{
ParamRow::ParamArg::iterator i;
if( code < 0 || code >= (int)param.size() )
return false;
if( !param[code].defined )
return false;
for(i=param[code].arg.begin() ; i!=param[code].arg.end() ; ++i)
{
if( *i == arg )
return true;
}
return false;
}
bool Mount::IsArg(int code, const std::wstring & arg)
{
return IsArg(code, arg.c_str());
}
bool Mount::IsArg(int code, int arg)
{
ParamRow::ParamArg::iterator i;
if( code < 0 || code >= (int)param.size() )
return false;
if( !param[code].defined )
return false;
for(i=param[code].arg.begin() ; i!=param[code].arg.end() ; ++i)
{
if( Toi(*i) == arg )
return true;
}
return false;
}
const std::wstring & Mount::Arg(int code, int arg) const
{
if( code < 0 || code >= (int)param.size() )
return empty_str;
if( !param[code].defined )
return empty_str;
if( arg >= (int)param[code].arg.size() )
return empty_str;
return param[code].arg[arg];
}
const std::wstring & Mount::FirstArg(int code) const
{
return Arg(code, 0);
}
} // namespace Winix

103
winixd/core/mount.h Normal file
View File

@@ -0,0 +1,103 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2009-2014, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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 headerfile_winix_core_mount
#define headerfile_winix_core_mount
#include <map>
#include <string>
#include <vector>
namespace Winix
{
class Mount
{
public:
struct ParamRow
{
typedef std::vector<std::wstring> ParamArg;
bool defined;
ParamArg arg;
ParamRow() { defined = false; }
void Clear() { defined = false; arg.clear(); }
};
typedef std::vector<ParamRow> Param;
long dir_id;
int type;
int fs;
Param param;
Mount();
void ClearParams();
bool IsPar(int code);
bool IsArg(int code, const wchar_t * arg);
bool IsArg(int code, const std::wstring & arg);
bool IsArg(int code, int arg);
// returning the arg argument if defined (or an empty string)
const std::wstring & Arg(int code, int arg) const;
// returning the first argument (arg=0) if defined (or an empty string)
const std::wstring & FirstArg(int code) const;
private:
// for Arg() methods when the argument is not defined
const std::wstring empty_str;
};
} // namespace Winix
#endif

540
winixd/core/mountparser.cpp Normal file
View File

@@ -0,0 +1,540 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2010-2014, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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.
*
*/
#include "mountparser.h"
#include "log.h"
#include "misc.h"
namespace Winix
{
MountParser::MountParser()
{
dirs = 0;
skip_static = false;
mount_type_tab = 0;
mount_fs_tab = 0;
mount_par_tab = 0;
static_mount_id = -1;
}
void MountParser::SkipStaticDirs(bool skip)
{
skip_static = skip;
}
void MountParser::SetStaticMountId(int id)
{
static_mount_id = id;
}
void MountParser::SetDirs(Dirs * pdirs)
{
dirs = pdirs;
}
void MountParser::SetMountTypeTab(const std::vector<std::wstring> & tab)
{
mount_type_tab = &tab;
}
void MountParser::SetMountFsTab(const std::vector<std::wstring> & tab)
{
mount_fs_tab = &tab;
}
void MountParser::SetMountParTab(const std::vector<std::wstring> & tab)
{
mount_par_tab = &tab;
}
bool MountParser::IsWhite(int c)
{
if( c==' ' || c=='\t' || c==13 || c==160 )
return true;
return false;
}
void MountParser::SkipWhite()
{
while( IsWhite(*pinput) )
++pinput;
}
void MountParser::SkipLine()
{
while( *pinput && *pinput != 10 )
++pinput;
if( *pinput == 10 )
++pinput;
}
void MountParser::ReadWordQuote(std::wstring & res)
{
++pinput;
while( *pinput && *pinput!=10 && *pinput!='\"' )
{
if( pinput[0]=='\\' && pinput[1]=='\"' )
{
res += '\"';
pinput += 2;
}
else
if( pinput[0]=='\\' && pinput[1]=='\\' )
{
res += '\\';
pinput += 2;
}
else
{
res += *pinput;
pinput += 1;
}
}
if( *pinput == '"' )
++pinput;
}
// a white character is the separator
void MountParser::ReadWordWhite(std::wstring & res)
{
while( *pinput && *pinput!=10 && !IsWhite(*pinput) )
{
res += *pinput;
++pinput;
}
}
// the comma or the second bracket ')' are the separators
void MountParser::ReadWordComma(std::wstring & res)
{
while( *pinput && *pinput!=10 && *pinput!=',' && *pinput!=')' )
{
res += *pinput;
++pinput;
}
// trimming last white characters
// (white characters can be in the middle of the string)
TrimWhite(res);
}
void MountParser::ReadWord(std::wstring & res, bool comma_bracket_separator)
{
res.clear();
SkipWhite();
if( *pinput == '"' )
{
ReadWordQuote(res);
}
else
if( comma_bracket_separator )
{
ReadWordComma(res);
}
else
{
ReadWordWhite(res);
}
}
void MountParser::ReadParamArgsLoop(Mount::ParamRow::ParamArg & args)
{
SkipWhite();
while( *pinput && *pinput!=10 && *pinput!=')' )
{
ReadWord(temp_arg, true);
if( !temp_arg.empty() )
args.push_back(temp_arg);
if( *pinput == ',' )
++pinput;
}
}
void MountParser::ReadParamArgs(Mount::ParamRow::ParamArg & args)
{
SkipWhite();
args.clear();
if( *pinput == '(' )
{
++pinput;
ReadParamArgsLoop(args);
if( *pinput != ')' )
{
// there should be ')' at the end
// temporarily we do nothing
}
else
{
++pinput;
}
}
}
void MountParser::ReadParamName(std::wstring & res)
{
SkipWhite();
res.clear();
while( *pinput && *pinput!=10 && *pinput!=',' && *pinput!='(' && !IsWhite(*pinput) )
{
res += *pinput;
++pinput;
}
}
void MountParser::ReadParam(std::wstring & res, Mount::ParamRow::ParamArg & args)
{
ReadParamName(res);
if( res.empty() )
return;
ReadParamArgs(args);
SkipWhite();
if( *pinput == ',' )
++pinput;
}
int MountParser::FindIndex(const std::vector<std::wstring> * tab, const std::wstring & value)
{
for(size_t i=0 ; i < tab->size() ; ++i)
{
if( (*tab)[i] == value )
return static_cast<int>(i);
}
return -1;
}
bool MountParser::ReadMountType()
{
ReadWord(temp);
if( temp.empty() )
{
// an empty line (some white characters only)
return false;
}
mount.type = FindIndex(mount_type_tab, temp);
if( mount.type != -1 )
{
log << log3 << "MP: mount type: " << (*mount_type_tab)[mount.type] << logend;
}
else
{
log << log1 << "MP: unknown mount type: " << temp << logend;
// IMPROVE ME there is no slog now
//slog << logerror << T("unknown_mount_type") << ": " << temp << logend;
}
return mount.type != -1;
}
bool MountParser::ReadMountPoint()
{
ReadWord(last_dir);
pdir = dirs->GetDir(last_dir);
if( pdir )
{
mount.dir_id = pdir->id;
log << log3 << "MP: mount point (directory): " << last_dir << logend;
}
else
{
log << log1 << "MP: there is no such a mount point (directory): " << last_dir << logend;
// IMPROVE ME there is no slog now
//slog << logerror << T("no_such_dir") << ": " << last_dir << logend;
}
return pdir != 0;
}
bool MountParser::ReadFs()
{
ReadWord(temp);
mount.fs = FindIndex(mount_fs_tab, temp);
if( mount.fs != -1 )
{
log << log2 << "MP: file system: " << (*mount_fs_tab)[mount.fs] << logend;
}
else
{
log << log1 << "MP: unknown filesystem: " << temp << logend;
// IMPROVE ME there is no slog now
//slog << logerror << T("unknown_filesystem") << ": " << temp << " (" << last_dir << ")" << logend;
}
return mount.fs != -1;
}
void MountParser::LogMountParams()
{
size_t i;
log << log3 << "MP: mount param: " << temp << "(";
for(i=0 ; i<param_args.size() ; ++i)
{
log << param_args[i];
if( i != param_args.size()-1 )
log << ",";
}
log << ")" << logend;
}
void MountParser::ReadMountParams()
{
mount.ClearParams();
for( ReadParam(temp, param_args) ; !temp.empty() ; ReadParam(temp, param_args) )
{
int code = FindIndex(mount_par_tab, temp);
if( code != -1 )
{
mount.param[code].defined = true;
mount.param[code].arg = param_args;
LogMountParams();
}
else
{
log << log1 << "MP: unknown mount param: " << temp << logend;
// IMPROVE ME there is no slog now
//slog << logwarning << T("unknown_mount_param") << ": " << temp << " (" << T("skipped") << ")" << logend;
}
}
}
void MountParser::AddParams(Mount::Param & src, Mount::Param & dst)
{
if( src.size() != dst.size() )
{
log << log1 << "MP: addparams: incorrect sizes" << logend;
return;
}
for(size_t p=0 ; p < src.size() ; ++p)
{
if( src[p].defined && !dst[p].defined )
dst[p] = src[p];
}
}
bool MountParser::AddParamsBefore(long dir_id)
{
std::map<long, Mount>::iterator i = poutput->find(dir_id);
if( i == poutput->end() )
return false;
AddParams(i->second.param, mount_inserted.first->second.param);
return true;
}
/*
adding all non-existing parameters to this mount point from parents
*/
void MountParser::AddParamsBefore()
{
if( !pdir )
return;
Item * dir;
long dir_id = pdir->parent_id;
while( dir_id != -1 )
{
if( AddParamsBefore(dir_id) )
{
// we don't have to check others parents
// the parameters are already copied
break;
}
dir = dirs->GetDir(dir_id);
if( !dir )
break;
dir_id = dir->parent_id;
}
}
/*
adding all non-existing parameters to childs (childs to this mount point)
*/
void MountParser::AddParamsAfter()
{
std::map<long, Mount>::iterator i = poutput->begin();
for( ; i != poutput->end() ; ++i)
{
if( dirs->IsChild(mount_inserted.first->second.dir_id, i->first) )
AddParams(mount_inserted.first->second.param, i->second.param);
}
}
void MountParser::ReadRow()
{
if( ReadMountType() && ReadMountPoint() && ReadFs() )
{
ReadMountParams();
if( skip_static && mount.type==static_mount_id )
{
log << log1 << "MP: static mount points are skipped (dont_use_static_dirs in config is true)" << logend;
// IMPROVE ME there is no slog now
//slog << logwarning << T("skipped_static_mount") << ": " << last_dir << logend;
}
else
{
mount_inserted = poutput->insert( std::make_pair(mount.dir_id, mount) );
if( mount_inserted.second )
{
AddParamsBefore();
AddParamsAfter();
}
else
{
log << log1 << "MP: this mount point exists (skipped)" << logend;
// IMPROVE ME there is no slog now
//slog << logwarning << T("mount_exists") << ": " << last_dir << " (" << T("skipped") << ")" << logend;
}
}
}
SkipLine();
}
void MountParser::Parse(const std::wstring & input, std::map<long, Mount> & output)
{
if( !dirs || !mount_type_tab || !mount_fs_tab || !mount_par_tab )
{
log << log1 << "MP: input tables not set" << logend;
return;
}
pinput = input.c_str();
poutput = &output;
mount.param.resize(mount_par_tab->size());
mount.ClearParams();
poutput->clear();
while( *pinput )
ReadRow();
}
} // namespace Winix

120
winixd/core/mountparser.h Normal file
View File

@@ -0,0 +1,120 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2010-2014, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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 headerfile_winix_core_mountparser
#define headerfile_winix_core_mountparser
#include <map>
#include <string>
#include <vector>
#include <stdlib.h>
#include <limits.h>
#include "mount.h"
#include "item.h"
#include "dirs.h"
#include "winixmodel.h"
namespace Winix
{
class MountParser : public WinixModel
{
public:
MountParser();
void SkipStaticDirs(bool skip);
void SetStaticMountId(int id);
void Parse(const std::wstring & input, std::map<long, Mount> & output);
void SetDirs(Dirs * pdirs);
void SetMountTypeTab(const std::vector<std::wstring> & tab);
void SetMountFsTab(const std::vector<std::wstring> & tab);
void SetMountParTab(const std::vector<std::wstring> & tab);
private:
Dirs * dirs;
bool skip_static;
int static_mount_id;
const std::vector<std::wstring> * mount_type_tab;
const std::vector<std::wstring> * mount_fs_tab;
const std::vector<std::wstring> * mount_par_tab;
bool IsWhite(int c);
void SkipWhite();
void SkipLine();
void ReadWordQuote(std::wstring & res);
void ReadWordWhite(std::wstring & res);
void ReadWordComma(std::wstring & res);
void ReadWord(std::wstring & res, bool comma_bracket_separator = false);
void ReadParamArgsLoop(Mount::ParamRow::ParamArg & args);
void ReadParamArgs(Mount::ParamRow::ParamArg & args);
void ReadParamName(std::wstring & res);
void ReadParam(std::wstring & res, Mount::ParamRow::ParamArg & args);
int FindIndex(const std::vector<std::wstring> * tab, const std::wstring & value);
bool ReadMountType();
bool ReadMountPoint();
bool ReadFs();
void LogMountParams();
void ReadMountParams();
void ReadRow();
void AddParams(Mount::Param & src, Mount::Param & dst);
bool AddParamsBefore(long dir_id);
void AddParamsBefore();
void AddParamsAfter();
const wchar_t * pinput;
std::wstring temp;
std::wstring last_dir;
std::wstring temp_arg;
Mount::ParamRow::ParamArg param_args;
Mount mount;
Item * pdir;
std::map<long, Mount> * poutput;
std::pair<std::map<long, Mount>::iterator, bool> mount_inserted;
};
} // namespace Winix
#endif

359
winixd/core/mounts.cpp Normal file
View File

@@ -0,0 +1,359 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2009-2018, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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.
*
*/
#include "mounts.h"
#include "request.h"
#include "log.h"
#include "db/db.h"
#include "cur.h"
namespace Winix
{
Mounts::Mounts()
{
pmount = &empty_mount;
skip_static = false;
}
void Mounts::SkipStaticDirs(bool skip)
{
skip_static = skip;
}
void Mounts::CreateMountType()
{
mount_type_cms = AddMountType(L"cms");
mount_type_static = AddMountType(L"static");
}
void Mounts::CreateMountFs()
{
mount_fs_simplefs = AddMountFs(L"simplefs");
mount_fs_hashfs = AddMountFs(L"hashfs");
}
void Mounts::CreateMountPar()
{
mount_par_page = AddMountPar(L"page");
mount_par_thumb_size = AddMountPar(L"thumb_size");
mount_par_thumb_mode = AddMountPar(L"thumb_mode");
mount_par_thumb_quality = AddMountPar(L"thumb_quality");
mount_par_image_size = AddMountPar(L"image_size");
mount_par_image_mode = AddMountPar(L"image_mode");
mount_par_image_quality = AddMountPar(L"image_quality");
mount_par_emacs_on = AddMountPar(L"emacs_on");
mount_par_mkdir_on = AddMountPar(L"mkdir_on");
mount_par_app = AddMountPar(L"app");
mount_par_html_template = AddMountPar(L"html_template");
mount_par_change_template = AddMountPar(L"change_template");
mount_par_static = AddMountPar(L"static");
mount_par_css = AddMountPar(L"css");
mount_par_lang = AddMountPar(L"lang");
}
void Mounts::CreateMounts()
{
CreateMountType();
CreateMountFs();
CreateMountPar();
plugin->Call((Session*)0, WINIX_ADD_MOUNTS);
empty_mount.param.resize(mount_par_tab.size());
empty_mount.ClearParams();
}
void Mounts::SetDirs(Dirs * pdirs)
{
dirs = pdirs;
}
void Mounts::SetDb(Db * pdb)
{
db = pdb;
}
void Mounts::SetCur(Cur * pcur)
{
cur = pcur;
}
int Mounts::AddMountType(const wchar_t * type)
{
mount_type_tab.push_back(type);
return static_cast<int>(mount_type_tab.size()) - 1;
}
int Mounts::AddMountType(const std::wstring & type)
{
return AddMountType(type.c_str());
}
int Mounts::AddMountFs(const wchar_t * fs)
{
mount_fs_tab.push_back(fs);
return static_cast<int>(mount_fs_tab.size()) - 1;
}
const std::wstring & Mounts::GetMountType(int id)
{
if( id < 0 || id >= (int)mount_type_tab.size() )
return empty_str;
return mount_type_tab[id];
}
int Mounts::FindMountType(const std::wstring & type)
{
for(size_t i=0 ; i<mount_type_tab.size() ; ++i)
if( mount_type_tab[i] == type )
return (int)i;
return -1;
}
int Mounts::AddMountFs(const std::wstring & fs)
{
return AddMountFs(fs.c_str());
}
const std::wstring & Mounts::GetMountFs(int id)
{
if( id < 0 || id >= (int)mount_fs_tab.size() )
return empty_str;
return mount_fs_tab[id];
}
int Mounts::AddMountPar(const wchar_t * par)
{
mount_par_tab.push_back(par);
return static_cast<int>(mount_par_tab.size()) - 1;
}
int Mounts::AddMountPar(const std::wstring & par)
{
return AddMountPar(par.c_str());
}
const std::wstring & Mounts::GetMountPar(int id)
{
if( id < 0 || id >= (int)mount_par_tab.size() )
return empty_str;
return mount_par_tab[id];
}
// reading from 'mounts'
void Mounts::ReadMounts(const std::wstring & mounts)
{
mount_parser.set_dependency(this);
mount_parser.SkipStaticDirs(skip_static);
mount_parser.SetStaticMountId(mount_type_static);
mount_parser.SetDirs(dirs);
mount_parser.SetMountTypeTab(mount_type_tab);
mount_parser.SetMountFsTab(mount_fs_tab);
mount_parser.SetMountParTab(mount_par_tab);
mount_parser.Parse(mounts, mount_tab);
CalcCurMount();
plugin->Call((Session*)0, WINIX_FSTAB_CHANGED);
}
// reading from /etc/fstab
Error Mounts::ReadMounts()
{
static std::wstring file = L"fstab";
Item * etc = dirs->GetEtcDir();
if( !etc )
{
log << log1 << "M: there is no /etc directory" << logend;
return WINIX_ERR_NO_ITEM;
}
Item fstab;
Error err = db->GetItem(etc->id, file, fstab);
if( err == WINIX_ERR_NO_ITEM )
{
log << log1 << "M: there is no /etc/fstab file" << logend;
return err;
}
if( err != WINIX_ERR_OK )
{
log << log1 << "M: cannot read /etc/fstab" << logend;
return err;
}
ReadMounts(fstab.content);
return WINIX_ERR_OK;
}
void Mounts::MountCmsForRoot()
{
Mount mount;
mount.type = MountTypeCms();
mount.fs = MountFsSimplefs();
Item * proot = dirs->GetRootDir();
if( proot )
mount.dir_id = proot->id;
else
{
mount.dir_id = -1;
log << log1 << "M: there is no a root dir" << logend;
}
mount.param.resize(mount_par_tab.size());
mount.ClearParams();
std::pair<MountTab::iterator, bool> res = mount_tab.insert( std::make_pair(mount.dir_id, mount) );
pmount = &(res.first->second);
}
Mount * Mounts::CalcCurMount()
{
std::vector<Item*>::reverse_iterator i;
pmount = &empty_mount;
// when the program starts (when the dir_tab is empty()
// we don't want to call MountCmsForRoot()
if( cur->request->dir_tab.empty() )
return pmount;
for(i = cur->request->dir_tab.rbegin() ; i!=cur->request->dir_tab.rend() ; ++i)
{
std::map<long, Mount>::iterator m = mount_tab.find( (*i)->id );
if( m != mount_tab.end() )
{
pmount = &(m->second);
log << log2 << "M: current mount point is: " << GetMountType(pmount->type)
<< ", fs: " << GetMountFs(pmount->fs) << logend;
return pmount;
}
}
// if nothing was found
// we assume that 'cms' mount point is used
MountCmsForRoot();
log << log2 << "M: current mount point is: " << GetMountType(pmount->type) << " (default)"
<< ", fs: " << GetMountFs(pmount->fs) << logend;
return pmount;
}
// can return null pointer
// and we don't assume cms as a default mount point if nothing is found
Mount * Mounts::CalcMount(long dir_id)
{
while( true )
{
Item * pdir = dirs->GetDir(dir_id);
if( !pdir )
return 0;
std::map<long, Mount>::iterator m = mount_tab.find( pdir->id );
if( m != mount_tab.end() )
return &(m->second);
dir_id = pdir->parent_id;
}
}
const Mounts::MountTab * Mounts::GetMountTab()
{
return &mount_tab;
}
Mount * Mounts::GetEmptyMount()
{
return &empty_mount;
}
} // namespace Winix

203
winixd/core/mounts.h Normal file
View File

@@ -0,0 +1,203 @@
/*
* This file is a part of Winix
* and is distributed under the 2-Clause BSD licence.
* Author: Tomasz Sowa <t.sowa@ttmath.org>
*/
/*
* Copyright (c) 2009-2018, Tomasz Sowa
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT HOLDER OR 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 headerfile_winix_core_mounts
#define headerfile_winix_core_mounts
#include <map>
#include <string>
#include <vector>
#include "mount.h"
#include "error.h"
#include "dirs.h"
#include "db/db.h"
#include "request.h"
#include "mountparser.h"
#include "winixmodel.h"
namespace Winix
{
class Mounts : public WinixModel
{
public:
void SkipStaticDirs(bool skip);
/*
mount point's types
*/
int AddMountType(const wchar_t * type);
int AddMountType(const std::wstring & type);
const std::wstring & GetMountType(int id);
// id of a specific mount type (the id is always valid)
int MountTypeCms() { return mount_type_cms; }
int MountTypeStatic() { return mount_type_static; }
// return -1 if there is no such a mount type
// or index otherwhise
int FindMountType(const std::wstring & type);
/*
file systems
*/
int AddMountFs(const wchar_t * fs);
int AddMountFs(const std::wstring & fs);
const std::wstring & GetMountFs(int id);
// id of a specific file system (the id is always valid)
int MountFsSimplefs() { return mount_fs_simplefs; }
int MountFsHashfs() { return mount_fs_hashfs; }
/*
mount point's parameters
*/
int AddMountPar(const wchar_t * par);
int AddMountPar(const std::wstring & par);
const std::wstring & GetMountPar(int id);
int MountParPage() { return mount_par_page; }
int MountParThumbSize() { return mount_par_thumb_size; }
int MountParThumbMode() { return mount_par_thumb_mode; }
int MountParThumbQuality() { return mount_par_thumb_quality; }
int MountParImageSize() { return mount_par_image_size; }
int MountParImageMode() { return mount_par_image_mode; }
int MountParImageQuality() { return mount_par_image_quality; }
int MountParEmacsOn() { return mount_par_emacs_on; }
int MountParMkdirOn() { return mount_par_mkdir_on; }
int MountParApp() { return mount_par_app; }
int MountParHtmlTemplate() { return mount_par_html_template; }
int MountParChangeTemplate() { return mount_par_change_template; }
int MountParStatic() { return mount_par_static; }
int MountParCss() { return mount_par_css; }
int MountParLang() { return mount_par_lang; }
void SetDirs(Dirs * pdirs);
void SetDb(Db * pdb);
void SetCur(Cur * pcur);
// dir_id, mount_point
typedef std::map<long, Mount> MountTab;
Mounts();
void CreateMounts();
void ReadMounts(const std::wstring & mounts);
Error ReadMounts();
Mount * CalcCurMount();
Mount * CalcMount(long dir_id);
// current mount point
// will not be null after calling CalcCurMount() or ReadMounts([...])
// !! nie korzystac obecnie z niego
// korzystac z cur->mount
// a tez zostanie wycofany
Mount * pmount;
const MountTab * GetMountTab();
// at the beginning used to initialize cur->mount
Mount * GetEmptyMount();
private:
Db * db;
Dirs * dirs;
Cur * cur;
bool skip_static;
Mount empty_mount;
const std::wstring empty_str;
MountParser mount_parser;
std::vector<std::wstring> mount_type_tab;
int mount_type_cms;
int mount_type_static;
// simplefs
// hashfs
std::vector<std::wstring> mount_fs_tab;
int mount_fs_simplefs;
int mount_fs_hashfs;
std::vector<std::wstring> mount_par_tab;
int mount_par_page;
int mount_par_thumb_size;
int mount_par_thumb_mode;
int mount_par_thumb_quality;
int mount_par_image_size;
int mount_par_image_mode;
int mount_par_image_quality;
int mount_par_emacs_on;
int mount_par_mkdir_on;
int mount_par_app;
int mount_par_html_template;
int mount_par_change_template;
int mount_par_static;
int mount_par_css;
int mount_par_lang;
MountTab mount_tab;
void CreateMountType();
void CreateMountFs();
void CreateMountPar();
void MountCmsForRoot();
};
} // namespace Winix
#endif

Some files were not shown because too many files have changed in this diff Show More