Debian Codegraph @

src/bnetd/userlog.cpp

raw symbols SCIP
1 /*
2 * Copyright (C) 2014 HarpyWar ([email protected])
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version 2
7 * of the License, or (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17 */
18 #include "common/setup_before.h"
19
20 #include <algorithm>
21 #include <cctype>
22 #include <cerrno>
23 #include <cmath>
24 #include <cstdlib>
25 #include <cstring>
26 #include <stdexcept>
27 #include <string>
28
29 #include "compat/strcasecmp.h"
30 #include "compat/pdir.h"
31 #include "compat/mkdir.h"
32 #include "common/util.h"
33 #include "common/eventlog.h"
34 #include "common/xstring.h"
35
36 #include "connection.h"
37 #include "message.h"
38 #include "account.h"
39 #include "account_wrap.h"
40 #include "command_groups.h"
41 #include "command.h"
42 #include "prefs.h"
43 #include "helpfile.h"
44 #include "i18n.h"
45 #include "userlog.h"
46
47 #include "common/setup_after.h"
48
49
50 namespace pvpgn
51 {
52
53 namespace bnetd
54 {
55 // max output lines to send user from /log command result
56 static const int userlog_max_output_lines = 50;
57
58 static std::vector<std::string> userlog_commands;
59
60 extern void userlog_init()
61 {
62 char * temp;
63 char const * tok;
64
65 userlog_commands.clear();
66
67 // fill command list that must be logged
68 if (const char * cmdlist = prefs_get_log_command_list())
69 {
70 temp = xstrdup(cmdlist);
71 tok = std::strtok(temp, ","); /* std::strtok modifies the string it is passed */
72 while (tok) {
73 userlog_commands.push_back(tok);
74 tok = std::strtok(NULL, ",");
75 }
76 xfree(temp);
77 }
78 }
79
80 // add new line at the end of log file
81 extern void userlog_append(t_account * account, const char * text)
82 {
83 // is logging enabled?
84 if (!prefs_get_log_commands())
85 return;
86
87 unsigned int groups = 0;
88 const char * cglist = prefs_get_log_command_groups();
89 size_t cglistlen = std::strlen(cglist);
90
91 // convert string groups from config to integer
92 for (std::size_t i = 0; i < cglistlen; i++)
93 {
94 if (cglist[i] == '1') groups |= 1;
95 else if (cglist[i] == '2') groups |= 2;
96 else if (cglist[i] == '3') groups |= 4;
97 else if (cglist[i] == '4') groups |= 8;
98 else if (cglist[i] == '5') groups |= 16;
99 else if (cglist[i] == '6') groups |= 32;
100 else if (cglist[i] == '7') groups |= 64;
101 else if (cglist[i] == '8') groups |= 128;
102 }
103
104 // log only commands for admins/operators and users in "groups" defined in config
105 if (!account_is_operator_or_admin(account, NULL) && !(account_get_command_groups(account) & groups))
106 return;
107
108 bool is_cmd_found = false;
109
110 // if command list empty then log all commands
111 if (userlog_commands.size() == 0)
112 is_cmd_found = true;
113 else
114 {
115 // get command name
116 std::vector<std::string> args = split_command(text, 0);
117 std::string cmd = args[0];
118
119 // find command in defined command list
120 for (std::vector<std::string>::iterator it = userlog_commands.begin(); it != userlog_commands.end(); ++it) {
121 if (*it == cmd)
122 {
123 is_cmd_found = true;
124 break;
125 }
126 }
127 }
128 if (!is_cmd_found)
129 return;
130
131 // get time string
132 char time_string[USEREVENT_TIME_MAXLEN];
133 struct std::tm * tmnow;
134 std::time_t now;
135
136 std::time(&now);
137 if (!(tmnow = std::localtime(&now)))
138 std::strcpy(time_string, "?");
139 else
140 std::strftime(time_string, USEREVENT_TIME_MAXLEN, USEREVENT_TIME_FORMAT, tmnow);
141
142
143 std::string filename = userlog_filename(account_get_name(account), true);
144
145 if (FILE *fp = fopen(filename.c_str(), "a"))
146 {
147 // append date and text
148 std::fprintf(fp, "[%s] %s\n", time_string, text);
149 std::fclose(fp);
150 }
151 else
152 {
153 ERROR1("could not write into user log file \"{}\"", filename);
154 }
155 }
156
157 // read "count" lines from the end starting from "startline"
158 extern std::map<long, char*> userlog_read(const char* username, long startline, const char* search_substr)
159 {
160 if (!username)
161 throw std::runtime_error("username is a nullptr");
162
163 FILE* fp = std::fopen(userlog_filename(username).c_str(), "r");
164 if (!fp)
165 throw std::runtime_error("Could not open userlog");
166
167 // set position to the end of file
168 std::fseek(fp, 0, SEEK_END);
169
170 long pos = std::ftell(fp);
171 int c = {}, prev_c = {};
172 std::map<long, char*> lines;
173 long linecount = 0;
174 char line[MAX_MESSAGE_LEN + 1] = {};
175 int linepos = 0;
176
177 // read file in reverse, byte by byte
178 do
179 {
180 pos--;
181 std::fseek(fp, pos, SEEK_SET);
182 c = std::fgetc(fp);
183
184 // add char into line array
185 if (c != '\n')
186 line[linepos] = c;
187
188 // end of line (or start of file)
189 if ((c == '\n' && c != prev_c) || pos == -1)
190 {
191 // hack for large lines (instead we will receive cut line without start symbols)
192 if (linepos == MAX_MESSAGE_LEN)
193 {
194 // return carriage to read whole line to(from) start
195 pos = pos + MAX_MESSAGE_LEN;
196 linepos = 0;
197 }
198
199 if (linepos > 0)
200 {
201 line[linepos] = '\0'; // set end of string
202 strreverse(line);
203
204 linepos = 0; // reset position inside line
205
206 linecount++;
207 if (linecount >= startline)
208 {
209 if (search_substr && std::strlen(search_substr) > 0)
210 {
211 if (find_substr(line, search_substr))
212 lines[linecount] = xstrdup(line);
213 }
214 else
215 {
216 lines[linecount] = xstrdup(line);
217 }
218 }
219
220 // limitation of results
221 if (lines.size() >= userlog_max_output_lines)
222 break;
223 }
224 }
225 prev_c = c;
226 if (c != '\n' && linepos < MAX_MESSAGE_LEN)
227 linepos++;
228
229 } while (c != EOF);
230
231 std::fclose(fp);
232
233 return lines;
234 }
235
236 // search "substring" in user log file from the end starting from "startline" and return "count" results
237 extern std::map<long, char*> userlog_find_text(const char * username, const char * search_substr, long startline)
238 {
239 return userlog_read(username, startline, search_substr);
240 }
241
242 // return full path for user log filename
243 // if (force_create_path == true) then create dirs in path if not exist
244 extern std::string userlog_filename(const char * username, bool force_create_path)
245 {
246 // lowercase username
247 std::string lusername = std::string(username);
248 std::transform(lusername.begin(), lusername.end(), lusername.begin(), ::tolower);
249 // get first 3 symbols of account and use it in path
250 // it will improve performance with large count of files
251 std::string dir_prefix = lusername.substr(0, 3);
252
253 std::string filepath = fmt::format("{}/{}", prefs_get_userlogdir(), dir_prefix);
254 // create directories in path
255 if (force_create_path)
256 {
257 struct stat statbuf;
258 // create inside user dir
259 if (stat(filepath.c_str(), &statbuf) == -1)
260 {
261 p_mkdir(filepath.c_str(), S_IRWXU | S_IRWXG | S_IRWXO);
262 eventlog(eventlog_level_info, __FUNCTION__, "created user directory: {}", filepath);
263 }
264 }
265
266 filepath += fmt::format("/{}.log", lusername.c_str());
267
268 return filepath;
269 }
270
271 // handle command
272 // /log read user startline
273 // /log find user substr startline
274 extern int handle_log_command(t_connection * c, char const *text)
275 {
276 const char *subcommand, *username;
277 long startline = 0;
278 std::map<long, char*> lines;
279
280 // split command args
281 std::vector<std::string> args = split_command(text, 4);
282 if (args[1].empty() || args[2].empty()
283 || (args[1].at(0) != 'r' && args[1].at(0) != 'f')) // check start symbols for subcommand
284 {
285 describe_command(c, args[0].c_str());
286 return -1;
287 }
288 subcommand = args[1].c_str(); // sub command
289 username = args[2].c_str(); // username
290
291 if (!accountlist_find_account(username))
292 {
293 message_send_text(c, message_type_error, c, localize(c, "Invalid user."));
294 return -1;
295 }
296
297 std::string title = localize(c, "{}'s log output", username);
298 // read
299 if (subcommand[0] == 'r')
300 {
301 if (!args[3].empty())
302 startline = atoi(args[3].c_str());
303
304 try
305 {
306 lines = userlog_read(username, startline);
307 }
308 catch (...)
309 {
310 message_send_text(c, message_type_error, c, "Could not read user log");
311 return 0;
312 }
313 }
314 // find
315 else if (subcommand[0] == 'f')
316 {
317 if (args[3].empty())
318 {
319 describe_command(c, args[0].c_str());
320 return -1;
321 }
322 const char * search = args[3].c_str();
323 title += localize(c, " by occurrence \"{}\"", search);
324
325 if (!args[4].empty())
326 startline = atoi(args[4].c_str());
327
328 lines = userlog_find_text(username, search, startline);
329 }
330
331 title += ":";
332 message_send_text(c, message_type_info, c, title);
333
334 int linelen = 0;
335 int paddedlen = 0;
336 std::string linenum;
337
338 // send each log line to user
339 for (std::map<long, char*>::reverse_iterator it = lines.rbegin(); it != lines.rend(); ++it)
340 {
341 int linelen = floor(log10(static_cast<double>(abs(it->first)))) + 1; // get length of integer (line number)
342 if (linelen > paddedlen)
343 paddedlen = linelen;
344
345 linenum = std_to_string(it->first);
346 // pad left to max line length
347 linenum.insert(linenum.begin(), paddedlen - linenum.size(), '0');
348
349 message_send_text(c, message_type_info, c, linenum + ": " + std::string(it->second));
350 }
351
352 return 0;
353 }
354
355
356 }
357 }