]> jfr.im git - irc/quakenet/newserv.git/blob - trojanscan/trojanscan.c
Merge.
[irc/quakenet/newserv.git] / trojanscan / trojanscan.c
1 /*
2 * Trojanscan version 2
3 *
4 * Trojanscan copyright (C) Chris Porter 2002-2007
5 * Newserv bits copyright (C) David Mansell 2002-2003
6 *
7 * TODO: CHECK::
8 * - Poke splidge about +r'ing bots, potential problems:
9 * - users might whine about T clone stealing account
10 * - would have to steal one already in use, so if trojans start using /msg q whois they'll see
11 * (though they have to be authed for this, they could use a clone of their own however)
12 */
13
14 #include "trojanscan.h"
15 #include "../lib/strlfunc.h"
16 #include "../lib/version.h"
17 #include "../core/nsmalloc.h"
18
19 #define tmalloc(x) nsmalloc(POOL_TROJANSCAN, x)
20 #define tfree(x) nsfree(POOL_TROJANSCAN, x)
21
22 MODULE_VERSION(TROJANSCAN_VERSION);
23
24 void trojanscan_phrasematch(channel *chp, nick *sender, trojanscan_phrases *phrase, char messagetype, char *matchbuf);
25 char *trojanscan_sanitise(char *input);
26 void trojanscan_refresh_settings(void);
27 static void trojanscan_part_watch(int hook, void *arg);
28 static void trojanscan_connect_nick(void *);
29
30 #define TROJANSCAN_SETTING_SIZE 256
31 #define TROJANSCAN_MAX_SETTINGS 50
32
33 static struct {
34 char setting[TROJANSCAN_SETTING_SIZE];
35 char value[TROJANSCAN_SETTING_SIZE];
36 } trojanscan_settings[TROJANSCAN_MAX_SETTINGS];
37
38 static int settingcount = 0;
39 static char *versionreply;
40 static int hooksregistered = 0;
41 static void *trojanscan_connect_nick_schedule;
42
43 void _init() {
44 trojanscan_cmds = newcommandtree();
45
46 addcommandtotree(trojanscan_cmds, "showcommands", TROJANSCAN_ACL_UNAUTHED, 0, &trojanscan_showcommands);
47 addcommandtotree(trojanscan_cmds, "help", TROJANSCAN_ACL_UNAUTHED, 1, &trojanscan_help);
48 addcommandtotree(trojanscan_cmds, "hello", TROJANSCAN_ACL_UNAUTHED | TROJANSCAN_ACL_OPER, 1, &trojanscan_hello);
49
50 addcommandtotree(trojanscan_cmds, "join", TROJANSCAN_ACL_STAFF, 1, &trojanscan_userjoin);
51 addcommandtotree(trojanscan_cmds, "chanlist", TROJANSCAN_ACL_STAFF, 0, &trojanscan_chanlist);
52 addcommandtotree(trojanscan_cmds, "whois", TROJANSCAN_ACL_STAFF, 1, &trojanscan_whois);
53
54 addcommandtotree(trojanscan_cmds, "changelev", TROJANSCAN_ACL_STAFF | TROJANSCAN_ACL_OPER, 2, &trojanscan_changelev);
55 addcommandtotree(trojanscan_cmds, "deluser", TROJANSCAN_ACL_TEAMLEADER | TROJANSCAN_ACL_OPER, 2, &trojanscan_deluser);
56 addcommandtotree(trojanscan_cmds, "mew", TROJANSCAN_ACL_STAFF, 2, &trojanscan_mew);
57 addcommandtotree(trojanscan_cmds, "status", TROJANSCAN_ACL_STAFF | TROJANSCAN_ACL_OPER, 0, &trojanscan_status);
58 addcommandtotree(trojanscan_cmds, "listusers", TROJANSCAN_ACL_TEAMLEADER, 0, &trojanscan_listusers);
59
60 addcommandtotree(trojanscan_cmds, "rehash", TROJANSCAN_ACL_WEBSITE, 0, &trojanscan_rehash);
61
62 addcommandtotree(trojanscan_cmds, "cat", TROJANSCAN_ACL_OPER, 1, &trojanscan_cat);
63
64 addcommandtotree(trojanscan_cmds, "reschedule", TROJANSCAN_ACL_DEVELOPER | TROJANSCAN_ACL_OPER, 0, &trojanscan_reschedule);
65
66 srand((int)time(NULL));
67
68 trojanscan_connect_schedule = scheduleoneshot(time(NULL) + 1, &trojanscan_connect, NULL);
69 }
70
71 void _fini(void) {
72 int i;
73 struct trojanscan_realchannels *rp = trojanscan_realchanlist, *oldrp;
74 struct trojanscan_rejoinlist *rj = trojanscan_schedulerejoins, *oldrj;
75
76 if (trojanscan_nick)
77 deregisterlocaluser(trojanscan_nick, NULL);
78
79 if (trojanscan_connect_schedule)
80 deleteschedule(trojanscan_connect_schedule, &trojanscan_connect, NULL);
81
82 if (trojanscan_connect_nick_schedule)
83 deleteschedule(trojanscan_connect_nick_schedule, &trojanscan_connect_nick, NULL);
84
85 if(trojanscan_schedule)
86 deleteschedule(trojanscan_schedule, &trojanscan_dojoin, NULL);
87
88 if(trojanscan_poolschedule)
89 deleteschedule(trojanscan_poolschedule, &trojanscan_repool, NULL);
90
91 if(trojanscan_cloneschedule)
92 deleteschedule(trojanscan_poolschedule, &trojanscan_registerclones, NULL);
93
94 if(hooksregistered)
95 deregisterhook(HOOK_CHANNEL_PART, trojanscan_part_watch);
96
97 while(rp) {
98 deleteschedule(rp->schedule, &trojanscan_dopart, (void *)rp);
99 oldrp = rp;
100 rp = rp->next;
101 tfree(oldrp);
102 }
103
104 while(rj) {
105 deleteschedule(rj->schedule, &trojanscan_rejoin_channel, (void *)rj);
106 freesstring(rj->channel);
107 oldrj = rj;
108 rj = rj->next;
109 tfree(oldrj);
110 }
111
112 if(trojanscan_initialschedule)
113 deleteschedule(trojanscan_initialschedule, &trojanscan_fill_channels, NULL);
114
115 deleteschedule(trojanscan_rehashschedule, &trojanscan_rehash_schedule, NULL);
116
117 for (i=0;i<TROJANSCAN_CLONE_TOTAL;i++)
118 if(trojanscan_swarm[i].clone) {
119 deregisterlocaluser(trojanscan_swarm[i].clone, NULL);
120 derefnode(iptree, trojanscan_swarm[i].fakeipnode);
121 trojanscan_swarm[i].clone = NULL;
122 }
123 trojanscan_free_database();
124 trojanscan_free_channels();
125
126 for (i=0;i<trojanscan_hostpoolsize;i++)
127 freesstring(trojanscan_hostpool[i]);
128
129 for (i=0;i<trojanscan_tailpoolsize;i++)
130 freesstring(trojanscan_tailpool[i]);
131 trojanscan_database_close();
132
133 deletecommandfromtree(trojanscan_cmds, "showcommands", &trojanscan_showcommands);
134 deletecommandfromtree(trojanscan_cmds, "help", &trojanscan_help);
135 deletecommandfromtree(trojanscan_cmds, "hello", &trojanscan_hello);
136 deletecommandfromtree(trojanscan_cmds, "join", &trojanscan_userjoin);
137 deletecommandfromtree(trojanscan_cmds, "chanlist", &trojanscan_chanlist);
138 deletecommandfromtree(trojanscan_cmds, "whois", &trojanscan_whois);
139 deletecommandfromtree(trojanscan_cmds, "changelev", &trojanscan_changelev);
140 deletecommandfromtree(trojanscan_cmds, "deluser", &trojanscan_deluser);
141 deletecommandfromtree(trojanscan_cmds, "mew", &trojanscan_mew);
142 deletecommandfromtree(trojanscan_cmds, "status", &trojanscan_status);
143 deletecommandfromtree(trojanscan_cmds, "listusers", &trojanscan_listusers);
144 deletecommandfromtree(trojanscan_cmds, "rehash", &trojanscan_rehash);
145 deletecommandfromtree(trojanscan_cmds, "cat", &trojanscan_cat);
146 deletecommandfromtree(trojanscan_cmds, "reschedule", &trojanscan_reschedule);
147
148 destroycommandtree(trojanscan_cmds);
149 nscheckfreeall(POOL_TROJANSCAN);
150 }
151
152 static void trojanscan_connect_nick(void *arg) {
153 sstring *mnick, *myident, *myhost, *myrealname, *myauthname;
154 channel *cp;
155
156 mnick = getcopyconfigitem("trojanscan", "nick", "T", NICKLEN);
157 myident = getcopyconfigitem("trojanscan", "ident", "trojanscan", NICKLEN);
158 myhost = getcopyconfigitem("trojanscan", "hostname", "trojanscan.slug.netsplit.net", HOSTLEN);
159 myrealname = getcopyconfigitem("trojanscan", "realname", "Trojanscan v" TROJANSCAN_VERSION, REALLEN);
160 myauthname = getcopyconfigitem("trojanscan", "authname", "T", ACCOUNTLEN);
161
162 trojanscan_nick = registerlocaluser(mnick->content, myident->content, myhost->content, myrealname->content, myauthname->content, UMODE_SERVICE | UMODE_DEAF |
163 UMODE_OPER | UMODE_INV |
164 UMODE_ACCOUNT,
165 &trojanscan_handlemessages);
166 freesstring(mnick);
167 freesstring(myident);
168 freesstring(myhost);
169 freesstring(myrealname);
170 freesstring(myauthname);
171
172 cp = findchannel(TROJANSCAN_OPERCHANNEL);
173 if (!cp) {
174 localcreatechannel(trojanscan_nick, TROJANSCAN_OPERCHANNEL);
175 } else {
176 if(!localjoinchannel(trojanscan_nick, cp))
177 localgetops(trojanscan_nick, cp);
178 }
179
180 cp = findchannel(TROJANSCAN_CHANNEL);
181 if (!cp) {
182 localcreatechannel(trojanscan_nick, TROJANSCAN_CHANNEL);
183 } else {
184 if(!localjoinchannel(trojanscan_nick, cp))
185 localgetops(trojanscan_nick, cp);
186 }
187
188 #ifdef TROJANSCAN_PEONCHANNEL
189 cp = findchannel(TROJANSCAN_PEONCHANNEL);
190 if (!cp) {
191 localcreatechannel(trojanscan_nick, TROJANSCAN_PEONCHANNEL);
192 } else {
193 if(!localjoinchannel(trojanscan_nick, cp))
194 localgetops(trojanscan_nick, cp);
195 }
196 #endif
197 }
198
199 void trojanscan_connect(void *arg) {
200 sstring *dbhost, *dbuser, *dbpass, *db, *dbport, *temp;
201 int length, i;
202 char buf[10];
203
204 trojanscan_connect_schedule = NULL;
205
206 for(i=0;i<TROJANSCAN_CLONE_TOTAL;i++)
207 trojanscan_swarm[i].index = i; /* sure this could be done with pointer arithmetic... */
208
209 trojanscan_hostpoolsize = 0;
210 trojanscan_tailpoolsize = 0;
211 trojanscan_hostmode = 0;
212 trojanscan_poolschedule = NULL;
213 trojanscan_cloneschedule = NULL;
214 trojanscan_realchanlist = NULL;
215 trojanscan_database.glines = 0;
216 trojanscan_database.detections = 0;
217
218 dbhost = getcopyconfigitem("trojanscan", "dbhost", "localhost", HOSTLEN);
219 dbuser = getcopyconfigitem("trojanscan", "dbuser", "", NICKLEN);
220 dbpass = getcopyconfigitem("trojanscan", "dbpass", "", REALLEN);
221 db = getcopyconfigitem("trojanscan", "db", "", NICKLEN);
222
223 dbport = getcopyconfigitem("trojanscan", "dbport", "3306", ACCOUNTLEN);
224
225 length = snprintf(buf, sizeof(buf) - 1, "%d", TROJANSCAN_DEFAULT_MAXCHANS);
226 temp = getcopyconfigitem("trojanscan", "maxchans", buf, length);
227
228 trojanscan_maxchans = atoi(temp->content);
229 freesstring(temp);
230
231 length = snprintf(buf, sizeof(buf) - 1, "%d", TROJANSCAN_DEFAULT_CYCLETIME);
232 temp = getcopyconfigitem("trojanscan", "cycletime", buf, length);
233
234 trojanscan_cycletime = atoi(temp->content);
235 freesstring(temp);
236
237 length = snprintf(buf, sizeof(buf) - 1, "%d", TROJANSCAN_DEFAULT_PARTTIME);
238 temp = getcopyconfigitem("trojanscan", "parttime", buf, length);
239 trojanscan_part_time = atoi(temp->content);
240 freesstring(temp);
241
242 length = snprintf(buf, sizeof(buf) - 1, "%d", TROJANSCAN_DEFAULT_MAXUSERS);
243 temp = getcopyconfigitem("trojanscan", "maxusers", buf, length);
244 trojanscan_maxusers = atoi(temp->content);
245 freesstring(temp);
246
247 length = snprintf(buf, sizeof(buf) - 1, "%d", TROJANSCAN_MINIMUM_HOSTS_BEFORE_POOL);
248 temp = getcopyconfigitem("trojanscan", "minpoolhosts", buf, length);
249 trojanscan_min_hosts = atoi(temp->content);
250 freesstring(temp);
251
252 if ((trojanscan_cycletime / trojanscan_maxchans) < 1) {
253 Error("trojanscan", ERR_FATAL, "Cycletime / maxchans < 1, increase cycletime or decrease maxchans else cycling breaks.");
254 return; /* PPA: module failed to load */
255 }
256
257 length = snprintf(buf, sizeof(buf) - 1, "%d", TROJANSCAN_DEFAULT_MINIMUM_CHANNEL_SIZE);
258 temp = getcopyconfigitem("trojanscan", "minchansize", buf, length);
259 trojanscan_minchansize = atoi(temp->content);
260 freesstring(temp);
261
262 trojanscan_connect_nick(NULL);
263
264 if (trojanscan_database_connect(dbhost->content, dbuser->content, dbpass->content, db->content, atoi(dbport->content)) < 0) {
265 Error("trojanscan", ERR_FATAL, "Cannot connect to database host!");
266 return; /* PPA: module failed to load */
267 }
268
269 trojanscan_database_query("CREATE TABLE phrases (id INT(10) PRIMARY KEY AUTO_INCREMENT, wormid INT(10) NOT NULL, phrase TEXT NOT NULL, priority INT(10) DEFAULT 0 NOT NULL, dateadded int(10), disabled BOOL DEFAULT 0 NOT NULL)");
270 trojanscan_database_query("CREATE TABLE worms (id INT(10) PRIMARY KEY AUTO_INCREMENT, wormname TEXT NOT NULL, glinetype INT DEFAULT 0, data text, hitmsgs BOOL DEFAULT 1, hitchans BOOL DEFAULT 0, epidemic BOOL DEFAULT 0, privinfo text)");
271 trojanscan_database_query("CREATE TABLE logs (id INT(10) PRIMARY KEY AUTO_INCREMENT, userid INT(10) NOT NULL, act TEXT NOT NULL, description TEXT NOT NULL, ts TIMESTAMP)");
272 trojanscan_database_query("CREATE TABLE channels (id INT(10) PRIMARY KEY AUTO_INCREMENT, channel VARCHAR(%d) NOT NULL, exempt BOOL DEFAULT 0)", CHANNELLEN);
273 trojanscan_database_query("CREATE TABLE users (id INT(10) PRIMARY KEY AUTO_INCREMENT, authname VARCHAR(%d) NOT NULL, authlevel TINYINT(4) NOT NULL)", ACCOUNTLEN);
274 trojanscan_database_query("CREATE TABLE hits (id INT(10) PRIMARY KEY AUTO_INCREMENT, nickname VARCHAR(%d) NOT NULL, ident VARCHAR(%d) NOT NULL, host VARCHAR(%d) NOT NULL, phrase INT(10) NOT NULL, ts TIMESTAMP, messagetype VARCHAR(1) NOT NULL DEFAULT 'm', glined BOOL DEFAULT 1)", NICKLEN, USERLEN, HOSTLEN);
275 trojanscan_database_query("CREATE TABLE settings (id INT(10) PRIMARY KEY AUTO_INCREMENT, setting VARCHAR(255) NOT NULL UNIQUE, value VARCHAR(255) NOT NULL)");
276 trojanscan_database_query("CREATE TABLE wwwlogs (id INT(10) PRIMARY KEY AUTO_INCREMENT, authid INT(10) NOT NULL, ip VARCHAR(15), action TEXT, ts TIMESTAMP)");
277 trojanscan_database_query("CREATE TABLE unknownlog (id INT(10) PRIMARY KEY AUTO_INCREMENT, data TEXT, user VARCHAR(%d) NOT NULL, ts TIMESTAMP)", NICKLEN+USERLEN+HOSTLEN+3);
278
279 trojanscan_database_query("DELETE FROM settings WHERE setting = 'rehash' OR setting = 'changed'");
280 trojanscan_database_query("INSERT INTO settings (setting, value) VALUES ('rehash','0')");
281 trojanscan_database_query("INSERT INTO settings (setting, value) VALUES ('changed','0')");
282
283 /* assumption: constants aren't supplied by someone evil */
284 trojanscan_database_query("INSERT INTO settings (setting, value) VALUES ('versionreply','" TROJANSCAN_DEFAULT_VERSION_REPLY "')");
285
286 trojanscan_refresh_settings();
287 trojanscan_read_database(1);
288
289 freesstring(dbhost);
290 freesstring(dbuser);
291 freesstring(dbpass);
292 freesstring(db);
293 freesstring(dbport);
294 trojanscan_registerclones(NULL);
295
296 trojanscan_rehashschedule = scheduleoneshot(time(NULL) + 60, &trojanscan_rehash_schedule, NULL);
297
298 registerhook(HOOK_CHANNEL_PART, trojanscan_part_watch);
299 hooksregistered = 1;
300 }
301
302 char *trojanscan_get_setting(char *setting) {
303 int i;
304
305 for(i=0;i<settingcount;i++)
306 if(!strcmp(trojanscan_settings[i].setting, setting))
307 return trojanscan_settings[i].value;
308
309 return NULL;
310 }
311
312 void trojanscan_refresh_settings(void) {
313 trojanscan_database_res *res;
314 trojanscan_database_row sqlrow;
315 int i = 0;
316
317 if(trojanscan_database_query("SELECT setting, value FROM settings"))
318 return;
319
320 if(!(res = trojanscan_database_store_result(&trojanscan_sql)))
321 return;
322
323 if (trojanscan_database_num_rows(res) <= 0)
324 return;
325
326 while((sqlrow = trojanscan_database_fetch_row(res))) {
327 strlcpy(trojanscan_settings[i].setting, sqlrow[0], TROJANSCAN_SETTING_SIZE);
328 strlcpy(trojanscan_settings[i].value, sqlrow[1], TROJANSCAN_SETTING_SIZE);
329
330 trojanscan_sanitise(trojanscan_settings[i].value);
331
332 if(++i == TROJANSCAN_MAX_SETTINGS)
333 break;
334 }
335
336 settingcount = i;
337
338 trojanscan_database_free_result(res);
339
340 /* optimisation hack */
341 versionreply = trojanscan_get_setting("versionreply");
342 }
343
344 void trojanscan_rehash_schedule(void *arg) {
345 char *v;
346 trojanscan_rehashschedule = scheduleoneshot(time(NULL) + 60, &trojanscan_rehash_schedule, NULL);
347
348 trojanscan_refresh_settings();
349
350 v = trojanscan_get_setting("rehash");
351 if(v && v[0] == '1') {
352 trojanscan_mainchanmsg("n: rehash initiated by website. . .");
353 trojanscan_read_database(0);
354 }
355 }
356
357 void trojanscan_free_database(void) {
358 int i;
359 for(i=0;i<trojanscan_database.total_channels;i++)
360 freesstring(trojanscan_database.channels[i].name);
361 tfree(trojanscan_database.channels);
362 for(i=0;i<trojanscan_database.total_phrases;i++) {
363 if (trojanscan_database.phrases[i].phrase)
364 pcre_free(trojanscan_database.phrases[i].phrase);
365 if (trojanscan_database.phrases[i].hint)
366 pcre_free(trojanscan_database.phrases[i].hint);
367 }
368 tfree(trojanscan_database.phrases);
369 for(i=0;i<trojanscan_database.total_worms;i++)
370 freesstring(trojanscan_database.worms[i].name);
371 tfree(trojanscan_database.worms);
372 trojanscan_database.total_channels = 0;
373 trojanscan_database.total_phrases = 0;
374 trojanscan_database.total_worms = 0;
375
376 }
377
378 char *trojanscan_sanitise(char *input) {
379 char *p;
380
381 for(p=input;*p;p++)
382 if(*p == '\r' || *p == '\n')
383 *p = '!';
384
385 return input;
386 }
387
388 sstring *trojanscan_getsstring(char *string, int length) {
389 int i;
390
391 for(i=0;i<length;i++) {
392 if ((string[i] == '\r') || (string[i] == '\n')) {
393 Error("trojanscan", ERR_WARNING, "Error reading %s at position %d, set to ERROR!", string, i+1);
394 return getsstring("ERROR", sizeof("ERROR"));
395 }
396 }
397
398 return getsstring(string, length);
399 }
400
401 int trojanscan_strip_codes(char *buf, size_t max, char *original) {
402 int i, j, length = TROJANSCAN_MMIN(strlen(original), max-1);
403 char *p2 = original, *p3, flag = 0;
404 p3 = buf;
405 for(i=0;i<length+1;i++) {
406 switch (*p2) {
407 case '\002':
408 case '\017':
409 case '\026':
410 case '\037':
411 break;
412 case '\003':
413 for(j=0;j<6;j++) {
414 if ((i + 1) > length)
415 break;
416 if ((j == 4) && flag)
417 break;
418 p2++;
419 i++;
420 if ((j == 0) && (!((*p2 >= '0') && (*p2 <= '9'))))
421 break;
422 if (j == 1) {
423
424 if (*p2 == ',') {
425 if ((i + 1) > length)
426 break;
427 if (!((*(p2 + 1) >= '0') && (*(p2 + 1) <= '9')))
428 break;
429 flag = 1;
430 } else if ((*p2 >= '0') && (*p2 <= '9')) {
431 flag = 0;
432 } else {
433 break;
434 }
435 }
436 if (j == 2) {
437 if (flag) {
438 if (!((*p2 >= '0') && (*p2 <= '9')))
439 break;
440 } else {
441 if (*p2 != ',') {
442 break;
443 } else {
444 if ((i + 1) > length)
445 break;
446 if (!((*(p2 + 1) >= '0') && (*(p2 + 1) <= '9')))
447 break;
448 }
449 }
450 }
451 if ((j == 3) && (!((*p2 >= '0') && (*p2 <= '9'))))
452 break;
453 if ((j == 4) && (!((*p2 >= '0') && (*p2 <= '9'))))
454 break;
455 }
456 p2--;
457 i--;
458 break;
459
460 default:
461 *p3 = *p2;
462 p3++;
463 break;
464 }
465 p2++;
466 }
467 return p3 - buf;
468 }
469
470 struct trojanscan_worms *trojanscan_find_worm_by_id(int id) {
471 int i;
472 for(i=0;i<trojanscan_database.total_worms;i++)
473 if ((trojanscan_database.worms[i].id == id))
474 return &trojanscan_database.worms[i];
475 return NULL;
476 }
477
478 void trojanscan_read_database(int first_time) {
479 const char *error;
480 int erroroffset, i, tempresult;
481
482 trojanscan_database_res *res;
483 trojanscan_database_row sqlrow;
484
485 if (!first_time) {
486 trojanscan_free_database();
487 } else {
488 trojanscan_database.total_channels = 0;
489 trojanscan_database.total_phrases = 0;
490 trojanscan_database.total_worms = 0;
491 }
492
493 if (!(trojanscan_database_query("SELECT channel, exempt FROM channels"))) {
494 if ((res = trojanscan_database_store_result(&trojanscan_sql))) {
495 trojanscan_database.total_channels = trojanscan_database_num_rows(res);
496 if (trojanscan_database.total_channels > 0) {
497 if ((trojanscan_database.channels = (trojanscan_channels *)tmalloc(sizeof(trojanscan_channels) * trojanscan_database.total_channels))) {
498 if ((trojanscan_database.total_channels>0) && trojanscan_database.channels) {
499 i = 0;
500 while((sqlrow = trojanscan_database_fetch_row(res))) {
501 trojanscan_database.channels[i].name = trojanscan_getsstring(trojanscan_sanitise(sqlrow[0]), strlen(sqlrow[0]));
502 trojanscan_database.channels[i].exempt = (sqlrow[1][0] == '1');
503 i++;
504 }
505 }
506 }
507 }
508 trojanscan_database_free_result(res);
509 }
510 }
511
512 if (!(trojanscan_database_query("SELECT id, wormname, glinetype, length(data), hitmsgs, hitchans, epidemic FROM worms"))) {
513 if ((res = trojanscan_database_store_result(&trojanscan_sql))) {
514 trojanscan_database.total_worms = trojanscan_database_num_rows(res);
515 if (trojanscan_database.total_worms > 0) {
516 if ((trojanscan_database.worms = (trojanscan_worms *)tmalloc(sizeof(trojanscan_worms) * trojanscan_database.total_worms))) {
517 i = 0;
518 while((sqlrow = trojanscan_database_fetch_row(res))) {
519 trojanscan_database.worms[i].id = atoi(sqlrow[0]);
520 trojanscan_database.worms[i].name = trojanscan_getsstring(trojanscan_sanitise(sqlrow[1]), strlen(sqlrow[1]));
521 tempresult = atoi(sqlrow[2]);
522 trojanscan_database.worms[i].glineuser = (tempresult == 0);
523 trojanscan_database.worms[i].glinehost = (tempresult == 1);
524 trojanscan_database.worms[i].monitor = (tempresult == 2);
525 if(sqlrow[3]) {
526 trojanscan_database.worms[i].datalen = ((atoi(sqlrow[3]) == 0) ? 0 : 1);
527 } else {
528 trojanscan_database.worms[i].datalen = 0;
529 }
530
531 trojanscan_database.worms[i].hitpriv = (atoi(sqlrow[4]) == 1);
532 trojanscan_database.worms[i].hitchans = (atoi(sqlrow[5]) == 1);
533 trojanscan_database.worms[i].epidemic = (atoi(sqlrow[6]) == 1);
534
535 i++;
536 }
537 }
538 }
539 trojanscan_database_free_result(res);
540 }
541 }
542
543 if (!(trojanscan_database_query("SELECT id, phrase, wormid FROM phrases WHERE disabled = 0 ORDER BY priority DESC"))) {
544 if ((res = trojanscan_database_store_result(&trojanscan_sql))) {
545 trojanscan_database.total_phrases = trojanscan_database_num_rows(res);
546 if (trojanscan_database.total_phrases > 0) {
547 if ((trojanscan_database.phrases = (trojanscan_phrases *)tmalloc(sizeof(trojanscan_phrases) * trojanscan_database.total_phrases))) {
548 i = 0;
549 while((sqlrow = trojanscan_database_fetch_row(res))) {
550 trojanscan_database.phrases[i].id = atoi(sqlrow[0]);
551 trojanscan_database.phrases[i].worm = trojanscan_find_worm_by_id(atoi(sqlrow[2]));
552 if (!(trojanscan_database.phrases[i].phrase = pcre_compile(sqlrow[1], PCRE_CASELESS, &error, &erroroffset, NULL))) {
553 Error("trojanscan", ERR_WARNING, "Error compiling expression %s at offset %d: %s", sqlrow[1], erroroffset, error);
554 } else {
555 trojanscan_database.phrases[i].hint = pcre_study(trojanscan_database.phrases[i].phrase, 0, &error);
556 if (error) {
557 Error("trojanscan", ERR_WARNING, "Error studying expression %s: %s", sqlrow[1], error);
558 pcre_free(trojanscan_database.phrases[i].phrase);
559 trojanscan_database.phrases[i].phrase = NULL;
560 }
561 }
562 i++;
563 }
564 }
565 }
566 trojanscan_database_free_result(res);
567 }
568 }
569
570 trojanscan_database_query("UPDATE settings SET value = '0' where setting = 'rehash'");
571 }
572
573 void trojanscan_log(nick *np, char *event, char *details, ...) {
574 int nickid = 0;
575 char eevent[TROJANSCAN_QUERY_TEMP_BUF_SIZE], edetails[TROJANSCAN_QUERY_TEMP_BUF_SIZE], buf[513];
576 va_list va;
577
578 va_start(va, details);
579 vsnprintf(buf, sizeof(buf) - 1, details, va);
580 va_end(va);
581
582 if (np)
583 if (IsAccount(np))
584 nickid = trojanscan_user_id_by_authname(np->authname);
585
586 trojanscan_database_escape_string(eevent, event, strlen(event));
587 trojanscan_database_escape_string(edetails, buf, strlen(buf));
588 trojanscan_database_query("INSERT INTO logs (userid, act, description) VALUES ('%d', '%s', '%s')", nickid, eevent, edetails);
589 }
590
591 void trojanscan_generateclone(void *arg) {
592 int i, loops = 0, modes = UMODE_XOPER | UMODE_INV;
593 char c_nick[NICKLEN+1], c_ident[USERLEN+1], c_host[HOSTLEN+1], c_real[REALLEN+1];
594 patricia_node_t *fakeip;
595
596 i = (int)((long)arg);
597
598 /* PPA: unlikely to be infinite */
599 do {
600 c_nick[0] = '\0';
601 if (!loops && trojanscan_hostmode) /* only have one go at this */
602 trojanscan_generatenick(c_nick, NICKLEN);
603 if(!c_nick[0])
604 trojanscan_gennick(c_nick, trojanscan_minmaxrand(7, TROJANSCAN_MMIN(13, NICKLEN)));
605 loops++;
606 } while ((getnickbynick(c_nick) != NULL));
607
608 trojanscan_generateident(c_ident, USERLEN);
609 if(!c_ident[0])
610 trojanscan_genident(c_ident, trojanscan_minmaxrand(4, TROJANSCAN_MMIN(8, USERLEN)));
611
612 if(trojanscan_hostmode) {
613 trojanscan_generatehost(c_host, HOSTLEN, &fakeip);
614 if(!c_host[0])
615 trojanscan_genhost(c_host, HOSTLEN, &fakeip);
616 } else {
617 trojanscan_genhost(c_host, HOSTLEN, &fakeip);
618 }
619
620 trojanscan_generaterealname(c_real, REALLEN);
621 if(!c_real[0])
622 trojanscan_genreal(c_real, trojanscan_minmaxrand(15, TROJANSCAN_MMIN(50, REALLEN)));
623
624 trojanscan_swarm[i].clone = registerlocaluser(c_nick, c_ident, c_host, c_real, NULL, modes, &trojanscan_clonehandlemessages);
625 trojanscan_swarm[i].fakeipnode = fakeip;
626
627 if(trojanscan_swarm[i].clone && !trojanscan_swarm_created) {
628 nick *np = trojanscan_selectuser();
629 if(np) /* select a 'random' sign on time for whois generation */
630 trojanscan_swarm[i].clone->timestamp = np->timestamp;
631 }
632 trojanscan_swarm[i].remaining = trojanscan_minmaxrand(5, 100);
633
634 trojanscan_swarm[i].sitting = 0;
635
636 }
637
638 void trojanscan_free_channels(void) {
639 int i;
640 if(trojanscan_chans) {
641 for(i=0;i<trojanscan_activechans;i++)
642 freesstring(trojanscan_chans[i].channel);
643 tfree(trojanscan_chans);
644 trojanscan_chans = NULL;
645 trojanscan_activechans = 0;
646 }
647 }
648
649 void trojanscan_repool(void *arg) {
650 if (trojanscan_generatepool() < TROJANSCAN_MINPOOLSIZE) {
651 trojanscan_hostmode = 0;
652 return;
653 } else {
654 trojanscan_hostmode = 1;
655 trojanscan_poolschedule = scheduleoneshot(time(NULL) + TROJANSCAN_POOL_REGENERATION, &trojanscan_repool, NULL);
656 }
657 }
658
659 void trojanscan_registerclones(void *arg) {
660 unsigned int i;
661
662 if (trojanscan_generatepool() < TROJANSCAN_MINPOOLSIZE) {
663 trojanscan_hostmode = 0;
664 trojanscan_cloneschedule = scheduleoneshot(time(NULL) + 10, &trojanscan_registerclones, NULL);
665 return;
666 } else {
667 trojanscan_hostmode = 1;
668 trojanscan_poolschedule = scheduleoneshot(time(NULL) + TROJANSCAN_POOL_REGENERATION, &trojanscan_repool, NULL);
669 trojanscan_cloneschedule = NULL;
670 }
671
672 for (i=0;i<TROJANSCAN_CLONE_TOTAL;i++)
673 trojanscan_generateclone((void *)((long)i));
674 trojanscan_mainchanmsg("n: swarm (%d clones) created.", TROJANSCAN_CLONE_TOTAL);
675 trojanscan_swarm_created = 1;
676
677 trojanscan_initialschedule = scheduleoneshot(time(NULL) + 60, &trojanscan_fill_channels, NULL);
678 }
679
680 int trojanscan_status(void *sender, int cargc, char **cargv) {
681 nick *np = (nick *)sender;
682 trojanscan_log(np, "status", "");
683 trojanscan_reply(np, "Channels in schedule: %d", trojanscan_activechans);
684 trojanscan_reply(np, "Channels in database: %d", trojanscan_database.total_channels);
685 trojanscan_reply(np, "Phrases: %d", trojanscan_database.total_phrases);
686 trojanscan_reply(np, "Worms: %d", trojanscan_database.total_worms);
687 trojanscan_reply(np, "Detections: %d", trojanscan_database.detections);
688 trojanscan_reply(np, "Glines: %d", trojanscan_database.glines);
689 trojanscan_reply(np, "Host/tail pool size: %d", TROJANSCAN_POOLSIZE);
690 trojanscan_reply(np, "Cycletime: %d", trojanscan_cycletime);
691 trojanscan_reply(np, "Clones: %d", TROJANSCAN_CLONE_TOTAL);
692 return CMD_OK;
693 }
694
695 int trojanscan_chanlist(void *sender, int cargc, char **cargv) {
696 int i;
697 nick *np = (nick *)sender;
698 char buf[CHANNELLEN * 2 + 20];
699 trojanscan_reply(np, "Channel list (%d total):", trojanscan_activechans);
700 buf[0] = '\0';
701
702 for(i=0;i<trojanscan_activechans;i++) {
703 if(trojanscan_chans[i].channel->length + 3 > sizeof(buf) - strlen(buf)) {
704 trojanscan_reply(np, "%s", buf);
705 buf[0] = '\0';
706 }
707
708 /* if splidge sees this I'm going to die */
709 strlcat(buf, trojanscan_chans[i].channel->content, sizeof(buf));
710 strlcat(buf, " ", sizeof(buf));
711 }
712 if(buf[0])
713 trojanscan_reply(np, "%s", buf);
714
715 trojanscan_reply(np, "Done.");
716 return CMD_OK;
717 }
718
719 int trojanscan_whois(void *sender, int cargc, char **cargv) {
720 char *tochange;
721 nick *np = (nick *)sender, *np2;
722 int templevel;
723
724 if (cargc < 1) {
725 trojanscan_reply(np, "Not enough parameters.");
726 return CMD_ERROR;
727 }
728
729 if (cargv[0][0] == '#') {
730 tochange = cargv[0] + 1;
731 } else {
732 int i;
733 np2 = getnickbynick(cargv[0]);
734 if (!np2) {
735 trojanscan_reply(np, "That nickname is not on the network.");
736 return CMD_ERROR;
737 }
738 for(i=0;i<TROJANSCAN_CLONE_TOTAL;i++) {
739 if(trojanscan_swarm[i].clone->nick && !ircd_strcmp(trojanscan_swarm[i].clone->nick, np2->nick)) {
740 trojanscan_reply(np, "Nickname : %s", np2->nick);
741 trojanscan_reply(np, "Swarm : yes", trojanscan_swarm[i].clone->nick);
742 return CMD_OK;
743 }
744 }
745 if (!IsAccount(np2)) {
746 trojanscan_reply(np, "User is not authed.");
747 return CMD_OK;
748 }
749 tochange = np2->authname;
750 }
751
752 templevel = trojanscan_user_level_by_authname(tochange);
753 if (templevel == -1) {
754 trojanscan_reply(np, "User does not exist.");
755 } else {
756 union trojanscan_userlevel flags;
757 flags.number = templevel;
758 trojanscan_reply(np, "Authname : %s", tochange);
759 trojanscan_reply(np, "Flags : +" TROJANSCAN_FLAG_MASK, TrojanscanFlagsInfo(flags));
760 }
761
762 return CMD_OK;
763 }
764
765 void trojanscan_privmsg_chan_or_nick(channel *cp, nick *np, char *message, ...) {
766 char buf[513];
767 va_list va;
768
769 if (!trojanscan_nick)
770 return;
771
772 va_start(va, message);
773 vsnprintf(buf, sizeof(buf) - 1, message, va);
774 va_end(va);
775
776 if (cp) {
777 sendmessagetochannel(trojanscan_nick, cp, buf);
778 } else {
779 sendmessagetouser(trojanscan_nick, np, buf);
780 }
781
782 }
783
784 int trojanscan_mew(void *sender, int cargc, char **cargv) {
785 nick *np = (nick *)sender, *np2 = NULL;
786 channel *cp = NULL;
787
788 if (cargc < 2) {
789 trojanscan_reply(np, "Not enough paramaters.");
790 return CMD_ERROR;
791 }
792
793 if(cargv[0][0] == '#') {
794 if (!(cp = findchannel(cargv[0]))) {
795 trojanscan_reply(np, "Channel not found.");
796 return CMD_ERROR;
797 }
798 trojanscan_log(np, "mew", "%s %s", cp->index->name->content, cargv[1]);
799 } else {
800 if (!(np2 = getnickbynick(cargv[0]))) {
801 trojanscan_reply(np, "Nickname is not present on the network.");
802 return CMD_ERROR;
803 }
804 trojanscan_log(np, "mew", "%s %s", np2->nick, cargv[1]);
805 }
806
807 trojanscan_privmsg_chan_or_nick(cp, np2, "\001ACTION mews hopefully at %s\001", cargv[1]);
808
809 if (cp) {
810 trojanscan_reply(np, "Mewed at %s in %s.", cargv[1], cp->index->name->content);
811 } else {
812 trojanscan_reply(np, "Mewed at %s at %s.", cargv[1], np2->nick);
813 }
814
815 if(!IsOper(np))
816 trojanscan_mainchanmsg("n: mew: %s %s (%s/%s)", cargv[1], cp?cp->index->name->content:np2->nick, np->nick, np->authname);
817
818 return CMD_OK;
819 }
820
821 int trojanscan_cat(void *sender, int cargc, char **cargv) {
822 nick *np = (nick *)sender, *np2 = NULL;
823 channel *cp = NULL;
824 FILE *cat;
825 char buf[513], *p;
826
827 if (cargc < 1) {
828 trojanscan_reply(np, "Not enough paramaters.");
829 return CMD_ERROR;
830 }
831
832 if(cargv[0][0] == '#') {
833 if (!(cp = findchannel(cargv[0]))) {
834 trojanscan_reply(np, "Channel not found.");
835 return CMD_ERROR;
836 }
837 trojanscan_log(np, "cat", cp->index->name->content);
838 } else {
839 if (!(np2 = getnickbynick(cargv[0]))) {
840 trojanscan_reply(np, "Nickname is not present on the network.");
841 return CMD_ERROR;
842 }
843 trojanscan_log(np, "cat", np2->nick);
844 }
845
846 if ((!(cat = fopen(TROJANSCAN_CAT, "r")))) {
847 trojanscan_reply(np, "Unable to open cat!");
848 return CMD_ERROR;
849 }
850
851 while (fgets(buf, sizeof(buf) - 1, cat)) {
852 if ((p = strchr(buf, '\n'))) {
853 *p = '\0';
854 trojanscan_privmsg_chan_or_nick(cp, np2, "%s", buf);
855 } else if (feof(cat)) {
856 trojanscan_privmsg_chan_or_nick(cp, np2, "%s", buf);
857 }
858 }
859
860 fclose(cat);
861
862 if (cp) {
863 trojanscan_reply(np, "Spammed cat in %s.", cp->index->name->content);
864 } else {
865 trojanscan_reply(np, "Spammed cat at %s.", np2->nick);
866 }
867
868 return CMD_OK;
869 }
870
871 int trojanscan_reschedule(void *sender, int cargc, char **cargv) {
872 nick *np = (nick *)sender;
873 trojanscan_log(np, "reschedule", "");
874 trojanscan_fill_channels(NULL);
875
876 trojanscan_reply(np, "Rescheduled.");
877 return CMD_OK;
878 }
879
880 int trojanscan_listusers(void *sender, int cargc, char **cargv) {
881 nick *np = (nick *)sender;
882
883 trojanscan_log(np, "listusers", "");
884
885 trojanscan_reply(np, "User list:");
886
887 if (!(trojanscan_database_query("SELECT authname, authlevel FROM users ORDER BY authlevel DESC, authname"))) {
888 trojanscan_database_res *res;
889 if ((res = trojanscan_database_store_result(&trojanscan_sql))) {
890 if (trojanscan_database_num_rows(res)) {
891 trojanscan_database_row sqlrow;
892 union trojanscan_userlevel flags;
893 while((sqlrow = trojanscan_database_fetch_row(res))) {
894 flags.number = atoi(sqlrow[1]);
895 trojanscan_reply(np, "%s +" TROJANSCAN_FLAG_MASK, sqlrow[0], TrojanscanIsDeveloper(flags) ? "d" : "", TrojanscanIsTeamLeader(flags) ? "t" : "", TrojanscanIsStaff(flags) ? "s" : "", TrojanscanIsWebsite(flags) ? "w" : "", TrojanscanIsCat(flags) ? "c" : "");
896 }
897 }
898 trojanscan_database_free_result(res);
899 }
900 }
901
902 trojanscan_reply(np, "Done.");
903 return CMD_OK;
904 }
905
906 int trojanscan_help(void *sender, int cargc, char **cargv) {
907 nick *np = (nick *)sender;
908
909 if (cargc == 0) {
910 trojanscan_reply(np, "Not enough parameters.");
911 return CMD_ERROR;
912 }
913
914 if (!strcasecmp("help", cargv[0])) {
915 trojanscan_reply(np, "Syntax: help <command name>");
916 trojanscan_reply(np, "Gives help on commands.");
917 } else if (!strcasecmp("status", cargv[0])) {
918 trojanscan_reply(np, "Syntax: status");
919 trojanscan_reply(np, "Gives statistical information about the bot.");
920 } else if (!strcasecmp("join", cargv[0])) {
921 trojanscan_reply(np, "Syntax: join <#channel>");
922 trojanscan_reply(np, "Orders a clone to join supplied channel.");
923 } else if (!strcasecmp("showcommands", cargv[0])) {
924 trojanscan_reply(np, "Syntax: showcommands");
925 trojanscan_reply(np, "Pretty obvious.");
926 } else if (!strcasecmp("hello", cargv[0])) {
927 trojanscan_reply(np, "Syntax: hello ?nickname?");
928 trojanscan_reply(np, "Creates a new user.");
929 } else if (!strcasecmp("rehash", cargv[0])) {
930 trojanscan_reply(np, "Syntax: rehash");
931 trojanscan_reply(np, "Reloads bot database.");
932 } else if (!strcasecmp("changelev", cargv[0])) {
933 trojanscan_reply(np, "Syntax: changelev <nickname or #authname> <flags>");
934 trojanscan_reply(np, "Changes access flags of selected user to supplied input.");
935 trojanscan_reply(np, "+d -> developer");
936 trojanscan_reply(np, "+t -> team leader");
937 trojanscan_reply(np, "+s -> staff");
938 trojanscan_reply(np, "+w -> web management");
939 trojanscan_reply(np, "+c -> cat access");
940 } else if (!strcasecmp("deluser", cargv[0])) {
941 trojanscan_reply(np, "Syntax: deluser <nickname or #authname>");
942 trojanscan_reply(np, "Deletes selected user from my database.");
943 } else if (!strcasecmp("mew", cargv[0])) {
944 trojanscan_reply(np, "Syntax: mew <#channel or nickname> <nickname>");
945 trojanscan_reply(np, "Gracefully mews at target in selected channel or query.");
946 } else if (!strcasecmp("cat", cargv[0])) {
947 trojanscan_reply(np, "Syntax: cat <#channel or nickname>");
948 trojanscan_reply(np, "Shows the almightly cat.");
949 } else if (!strcasecmp("reschedule", cargv[0])) {
950 trojanscan_reply(np, "Syntax: reschedule");
951 trojanscan_reply(np, "Recalculates bots schedule.");
952 } else if (!strcasecmp("chanlist", cargv[0])) {
953 trojanscan_reply(np, "Syntax: chanlist");
954 trojanscan_reply(np, "Displays bots current channel list.");
955 } else if (!strcasecmp("whois", cargv[0])) {
956 trojanscan_reply(np, "Syntax: whois <nickname or #authname>");
957 trojanscan_reply(np, "Displays information on given user.");
958 } else if (!strcasecmp("whois", cargv[0])) {
959 trojanscan_reply(np, "Syntax: listusers <flags>");
960 trojanscan_reply(np, "Displays users with listusersing flags.");
961 } else {
962 trojanscan_reply(np, "Command not found.");
963 return CMD_ERROR;
964 }
965
966 return CMD_OK;
967 }
968
969 int trojanscan_hello(void *sender, int cargc, char **cargv) {
970 nick *np = (nick *)sender, *toadd;
971 char eaccount[TROJANSCAN_QUERY_TEMP_BUF_SIZE];
972 int level = 0;
973
974 if (cargc > 0) {
975 toadd = getnickbynick(cargv[0]);
976 if (!toadd) {
977 trojanscan_reply(np, "That nickname is not on the network.");
978 return CMD_ERROR;
979 }
980 if (!IsAccount(toadd)) {
981 trojanscan_reply(np, "That user is not authed with the network.");
982 return CMD_ERROR;
983 }
984 } else {
985 if (!IsAccount(np)) {
986 trojanscan_reply(np, "You are not authed with the network, auth before creating your user.");
987 return CMD_ERROR;
988 }
989 toadd = np;
990 }
991
992 if (trojanscan_user_level_by_authname(toadd->authname)!=-1) {
993 trojanscan_reply(np, "Authname (%s) is already on file.", toadd->authname);
994 return CMD_ERROR;
995 }
996
997 trojanscan_log(np, "hello", toadd->authname);
998
999 if (!(trojanscan_database_query("SELECT id FROM users LIMIT 1"))) {
1000 trojanscan_database_res *res;
1001 if ((res = trojanscan_database_store_result(&trojanscan_sql))) {
1002 if (trojanscan_database_num_rows(res) == 0)
1003 level = TROJANSCAN_ACL_DEVELOPER | TROJANSCAN_ACL_STAFF | TROJANSCAN_ACL_WEBSITE | TROJANSCAN_ACL_CAT;
1004 trojanscan_database_free_result(res);
1005 }
1006 }
1007
1008 trojanscan_database_escape_string(eaccount, toadd->authname, strlen(toadd->authname));
1009 trojanscan_database_query("INSERT INTO users (authname, authlevel) VALUES ('%s', %d)", eaccount, level);
1010 trojanscan_reply(np, "Account added to database, account %s%s.", toadd->authname, level>0?" (first user so developer access)":"");
1011
1012 return CMD_OK;
1013 }
1014
1015 int trojanscan_user_level_by_authname(char *authname) {
1016 int result = -1, sl = strlen(authname);
1017 char eaccount[TROJANSCAN_QUERY_TEMP_BUF_SIZE];
1018
1019 trojanscan_database_escape_string(eaccount, authname, sl);
1020 if (!(trojanscan_database_query("SELECT authlevel, authname FROM users WHERE authname = '%s'", eaccount))) {
1021 trojanscan_database_res *res;
1022 if ((res = trojanscan_database_store_result(&trojanscan_sql))) {
1023 if (trojanscan_database_num_rows(res) > 0) {
1024 trojanscan_database_row sqlrow = trojanscan_database_fetch_row(res);
1025 result = atoi(sqlrow[0]);
1026 strlcpy(authname, sqlrow[1], sl + 1);
1027 }
1028 trojanscan_database_free_result(res);
1029 }
1030 }
1031 return result;
1032 }
1033
1034 int trojanscan_user_id_by_authname(char *authname) {
1035 int result = 0;
1036 char eaccount[TROJANSCAN_QUERY_TEMP_BUF_SIZE];
1037
1038 trojanscan_database_escape_string(eaccount, authname, strlen(authname));
1039 if (!(trojanscan_database_query("SELECT id FROM users WHERE authname = '%s'", eaccount))) {
1040 trojanscan_database_res *res;
1041 if ((res = trojanscan_database_store_result(&trojanscan_sql))) {
1042 if (trojanscan_database_num_rows(res) > 0) {
1043 trojanscan_database_row sqlrow = trojanscan_database_fetch_row(res);
1044 result = atoi(sqlrow[0]);
1045 }
1046 trojanscan_database_free_result(res);
1047 }
1048 }
1049 return result;
1050 }
1051
1052 struct trojanscan_clones *trojanscan_selectclone(char type) {
1053 struct trojanscan_clones *rc;
1054 int randomclone, hits = 0, minlimit, maxlimit;
1055
1056 if(type == TROJANSCAN_WATCH_CLONES) {
1057 minlimit = TROJANSCAN_CLONE_MAX;
1058 maxlimit = minlimit + TROJANSCAN_WATCHCLONE_MAX - 1;
1059 } else {
1060 minlimit = 0;
1061 maxlimit = TROJANSCAN_CLONE_MAX - 1;
1062 }
1063
1064 do {
1065 randomclone = trojanscan_minmaxrand(minlimit, maxlimit);
1066 if (hits++ > 200)
1067 return NULL;
1068 rc = &trojanscan_swarm[randomclone];
1069 if ((type == TROJANSCAN_NORMAL_CLONES) && (rc->sitting == 0) && (rc->remaining == 0))
1070 break;
1071
1072 } while (rc->remaining == 0);
1073
1074 if(type == TROJANSCAN_NORMAL_CLONES) {
1075 if ((rc->sitting == 0) && (rc->remaining == 0)) {
1076 if ((!rc->remaining) && (!rc->sitting)) {
1077 if (rc->clone) {
1078 deregisterlocaluser(rc->clone, NULL);
1079 derefnode(iptree, rc->fakeipnode);
1080 rc->clone = NULL;
1081 }
1082 trojanscan_generateclone((void *)((long)rc->index));
1083 }
1084 }
1085 }
1086
1087 return rc;
1088
1089 }
1090
1091 /* hack hack hack */
1092 int trojanscan_nickbanned(trojanscan_clones *np, channel *cp) {
1093 int ret;
1094 patricia_node_t *realipnode = np->clone->ipnode;
1095
1096 np->clone->ipnode = np->fakeipnode;
1097
1098 ret = nickbanned(np->clone, cp);
1099
1100 np->clone->ipnode = realipnode;
1101
1102 return ret;
1103 }
1104
1105 struct trojanscan_realchannels *trojanscan_allocaterc(char *chan) {
1106 struct trojanscan_realchannels *rc;
1107 struct trojanscan_clones *clonep;
1108 channel *cp;
1109 int attempts_left = 10;
1110
1111 if (!chan) {
1112 trojanscan_errorcode = 1; /* sorry splidge ;( */
1113 return NULL;
1114 }
1115
1116 if(chan[0] != '#') {
1117 trojanscan_errorcode = 2;
1118 return NULL;
1119 }
1120
1121 if (strlen(chan) > 1) {
1122 if(strrchr(chan, ',')) {
1123 trojanscan_errorcode = 3;
1124 return NULL;
1125 }
1126
1127 if(strrchr(chan, ' ')) {
1128 trojanscan_errorcode = 4;
1129 return NULL;
1130 }
1131 }
1132
1133 cp = findchannel(chan);
1134 if (!cp) {
1135 trojanscan_errorcode = 5;
1136 return NULL;
1137 }
1138
1139 do {
1140 clonep = trojanscan_selectclone(TROJANSCAN_NORMAL_CLONES);
1141 if (!clonep) {
1142 trojanscan_errorcode = 6;
1143 return NULL;
1144 }
1145 if(!trojanscan_nickbanned(clonep, cp))
1146 break;
1147 } while (--attempts_left > 0);
1148
1149 if (!attempts_left) {
1150 trojanscan_errorcode = 7;
1151 return NULL;
1152 }
1153
1154 rc = (struct trojanscan_realchannels *)tmalloc(sizeof(struct trojanscan_realchannels));
1155
1156 rc->next = NULL;
1157 rc->clone = clonep;
1158 rc->chan = cp;
1159 rc->donotpart = 0;
1160 rc->kickedout = 0;
1161 return rc;
1162 }
1163
1164 void trojanscan_join(struct trojanscan_realchannels *rc) {
1165 struct trojanscan_realchannels *rp = trojanscan_realchanlist;
1166
1167 if (rc->clone && rc->clone->clone) {
1168 if (!localjoinchannel(rc->clone->clone, rc->chan)) {
1169 rc->clone->remaining--;
1170 rc->clone->sitting++;
1171 if (trojanscan_minmaxrand(1, TROJANSCAN_NICKCHANGE_ODDS)%TROJANSCAN_NICKCHANGE_ODDS == 0)
1172 trojanscan_donickchange((void *)rc->clone);
1173
1174 rc->schedule = scheduleoneshot(time(NULL)+trojanscan_part_time, &trojanscan_dopart, (void *)rc);
1175
1176 if (rp) {
1177 for(;rp->next;rp=rp->next);
1178 rp->next = rc;
1179 } else {
1180 trojanscan_realchanlist = rc;
1181 }
1182 }
1183 }
1184
1185 }
1186
1187 int trojanscan_userjoin(void *sender, int cargc, char **cargv) {
1188 nick *np = (nick *)sender;
1189 struct trojanscan_realchannels *rc;
1190
1191 if (cargc < 1) {
1192 trojanscan_reply(np, "Not enough paramaters");
1193 return CMD_ERROR;
1194 }
1195
1196 if (!trojanscan_swarm_created) {
1197 trojanscan_reply(np, "My swarm is currently empty.");
1198 return CMD_OK;
1199 }
1200
1201 if((rc = trojanscan_allocaterc(cargv[0]))) {
1202 trojanscan_log(np, "join", cargv[0]);
1203 trojanscan_join(rc);
1204 trojanscan_reply(np, "Clone has joined channel.");
1205 if(!IsOper(np))
1206 trojanscan_mainchanmsg("n: join: %s (%s/%s)", cargv[0], np->nick, np->authname);
1207 } else {
1208 if (trojanscan_errorcode == 5) {
1209 trojanscan_reply(np, "Not joining empty channel, check you entered the correct channel name.");
1210 } else {
1211 trojanscan_reply(np, "Clone could not join channel (error code %d)!", trojanscan_errorcode);
1212 }
1213 }
1214 return CMD_OK;
1215 }
1216
1217 int trojanscan_rehash(void *sender, int cargc, char **cargv) {
1218 nick *np = (void *)sender;
1219 trojanscan_refresh_settings();
1220 trojanscan_read_database(0);
1221 trojanscan_log(np, "rehash", "");
1222 trojanscan_reply(np, "Done.");
1223 return CMD_OK;
1224 }
1225
1226 int trojanscan_changelev(void *sender, int cargc, char **cargv) {
1227 nick *np = (nick *)sender, *np2;
1228 int templevel;
1229 char eaccount[TROJANSCAN_QUERY_TEMP_BUF_SIZE], *tochange, *p, mode = 1, error = 0, clast = 0, specialcase;
1230 union trojanscan_userlevel flags1, flags2;
1231
1232 if (cargc < 2) {
1233 trojanscan_reply(np, "Not enough parameters.");
1234 return CMD_ERROR;
1235 }
1236
1237 templevel = trojanscan_user_level_by_authname(np->authname);
1238
1239 if (templevel == -1) {
1240 trojanscan_reply(np, "You do not have an account.");
1241 return CMD_ERROR;
1242 }
1243
1244 flags1.number = templevel;
1245
1246 if (cargv[0][0] == '#') {
1247 tochange = cargv[0] + 1;
1248 } else {
1249 np2 = getnickbynick(cargv[0]);
1250 if (!np2) {
1251 trojanscan_reply(np, "That nickname is not on the network.");
1252 return CMD_ERROR;
1253 }
1254 if (!IsAccount(np2)) {
1255 trojanscan_reply(np, "That user is not authed with the network.");
1256 return CMD_ERROR;
1257 }
1258 tochange = np2->authname;
1259 }
1260
1261 templevel = trojanscan_user_level_by_authname(tochange);
1262
1263 if (templevel == -1) {
1264 trojanscan_reply(np, "User does not exist.");
1265 return CMD_ERROR;
1266 }
1267
1268 flags2.number = templevel;
1269
1270 if (!ircd_strcmp(np->authname, tochange)) {
1271 specialcase = 1;
1272 } else {
1273 specialcase = 0;
1274 }
1275
1276 for (p=cargv[1];*p;p++) {
1277 switch (*p) {
1278 case '+':
1279 case '-':
1280 mode = (*p == '+');
1281 break;
1282 case 'd':
1283 if (!TrojanscanIsDeveloper(flags1))
1284 clast = 1;
1285 flags2.values.developer = mode;
1286 break;
1287 case 't':
1288 if (!TrojanscanIsDeveloper(flags1))
1289 clast = 1;
1290 flags2.values.teamleader = mode;
1291 break;
1292 case 's':
1293 if (!TrojanscanIsLeastTeamLeader(flags1))
1294 clast = 1;
1295 flags2.values.staff = mode;
1296 break;
1297 case 'w':
1298 if (!TrojanscanIsDeveloper(flags1))
1299 clast = 1;
1300 flags2.values.website = mode;
1301 break;
1302 case 'c':
1303 if (!TrojanscanIsDeveloper(flags1))
1304 clast = 1;
1305 flags2.values.cat = mode;
1306 break;
1307 default:
1308 error = 1;
1309 goto last;
1310 break;
1311 }
1312 if (clast == 1) {
1313 if (specialcase && !mode) { /* allow user to remove their own flags */
1314 clast = 0;
1315 } else {
1316 goto last;
1317 }
1318 }
1319 }
1320
1321 last:
1322 if (*p) {
1323 if (error) {
1324 trojanscan_reply(np, "Unknown mode: %c%c.", mode?'+':'-', *p);
1325 } else {
1326 trojanscan_reply(np, "You have insufficient privilidges to add/remove one or more flags specified.");
1327 }
1328 return CMD_ERROR;
1329 }
1330
1331 trojanscan_log(np, "changelev", "%s %s", tochange, cargv[1]);
1332 trojanscan_database_escape_string(eaccount, tochange, strlen(tochange));
1333 trojanscan_database_query("UPDATE users SET authlevel = %d WHERE authname = '%s'", flags2.number, eaccount);
1334
1335 trojanscan_reply(np, "Flags changed.");
1336
1337 return CMD_OK;
1338 }
1339
1340 int trojanscan_deluser(void *sender, int cargc, char **cargv) {
1341 nick *np = (nick *)sender, *to;
1342 int templevel;
1343 char eaccount[TROJANSCAN_QUERY_TEMP_BUF_SIZE], *account;
1344 union trojanscan_userlevel flags1, flags2;
1345
1346 if (cargc < 1) {
1347 trojanscan_reply(np, "Not enough parameters.");
1348 return CMD_ERROR;
1349 }
1350
1351 if (cargv[0][0] == '#') {
1352 account = cargv[0] + 1;
1353 } else {
1354 to = getnickbynick(cargv[0]);
1355 if (!to) {
1356 trojanscan_reply(np, "That nickname is not on the network.");
1357 return CMD_ERROR;
1358 }
1359 if (!IsAccount(to)) {
1360 trojanscan_reply(np, "That user is not authed with the network.");
1361 return CMD_ERROR;
1362 }
1363 account = to->authname;
1364 }
1365
1366 flags1.number = trojanscan_user_level_by_authname(np->authname);
1367 templevel = trojanscan_user_level_by_authname(account);
1368
1369 if (templevel == -1) {
1370 trojanscan_reply(np, "Auth %s does not exist.", account);
1371 return CMD_ERROR;
1372 }
1373
1374 flags2.number = templevel;
1375
1376 if (!TrojanscanIsDeveloper(flags1) && TrojanscanIsLeastTeamLeader(flags2)) {
1377 trojanscan_reply(np, "Your cannot delete %s as his/her flags equal or surpass your own.", account);
1378 return CMD_ERROR;
1379 }
1380
1381 trojanscan_log(np, "deluser", account);
1382 trojanscan_database_escape_string(eaccount, account, strlen(account));
1383 trojanscan_database_query("DELETE FROM users WHERE authname = '%s'", eaccount);
1384 trojanscan_reply(np, "User deleted.");
1385
1386 return CMD_OK;
1387 }
1388
1389 int trojanscan_add_ll(struct trojanscan_prechannels **head, struct trojanscan_prechannels *newitem) {
1390 struct trojanscan_prechannels *position, *lastitem = NULL, *location = NULL;
1391 if (!*head) {
1392 *head = newitem;
1393 newitem->next = NULL;
1394 if (newitem->exempt) {
1395 return 0;
1396 } else {
1397 return 1;
1398 }
1399 }
1400 /* if its exempt, we don't give a monkeys where it is... */
1401 if (newitem->exempt) {
1402 newitem->next = *head;
1403 *head = newitem;
1404 return 0;
1405 }
1406
1407 for(position=*head;position;lastitem=position,position=position->next) {
1408 if (!ircd_strcmp(position->name->content, newitem->name->content)) {
1409 tfree(newitem);
1410 return 0;
1411 }
1412 if (!location && (position->size < newitem->size)) {
1413 if (!lastitem) {
1414 location = *head;
1415 } else {
1416 location = lastitem;
1417 }
1418 }
1419 }
1420 if (!location) {
1421 newitem->next = NULL;
1422 lastitem->next = newitem;
1423 } else {
1424 newitem->next = location->next;
1425 location->next = newitem;
1426 }
1427 if(newitem->exempt) {
1428 return 0;
1429 } else {
1430 return 1;
1431 }
1432 }
1433
1434 void trojanscan_watch_clone_update(struct trojanscan_prechannels *hp, int count) {
1435 int i, j, marked;
1436 struct trojanscan_prechannels *lp;
1437 struct trojanscan_templist *markedlist = NULL;
1438
1439 if(count > 0) {
1440 markedlist = (struct trojanscan_templist *)tmalloc(count * sizeof(struct trojanscan_templist));
1441 if (!markedlist)
1442 return;
1443 memset(markedlist, 0, sizeof(struct trojanscan_templist) * count);
1444 }
1445
1446 for(i=0;i<trojanscan_activechans;i++) {
1447 marked = 0;
1448 if(markedlist) {
1449 for(lp=hp,j=0;j<count&&lp;j++,lp=lp->next) {
1450 if(!markedlist[j].active && !lp->exempt && !ircd_strcmp(lp->name->content, trojanscan_chans[i].channel->content)) { /* we're already on the channel */
1451 if(trojanscan_chans[i].watch_clone) {
1452 markedlist[j].active = 1;
1453 markedlist[j].watch_clone = trojanscan_chans[i].watch_clone;
1454 lp->watch_clone = trojanscan_chans[i].watch_clone;
1455 }
1456 marked = 1;
1457 break;
1458 }
1459 }
1460 }
1461 if(!marked && trojanscan_chans[i].watch_clone) {
1462 channel *cp = findchannel(trojanscan_chans[i].channel->content);
1463 if(cp)
1464 localpartchannel(trojanscan_chans[i].watch_clone->clone, cp, NULL);
1465 }
1466 }
1467
1468 if(!markedlist)
1469 return;
1470
1471 for(j=0,lp=hp;j<count&&lp;j++,lp=lp->next) {
1472 if((!markedlist[j].active || !markedlist[j].watch_clone) && !lp->exempt) {
1473 channel *cp = findchannel(lp->name->content);
1474 if(cp) {
1475 int attempts = 10;
1476 do {
1477 lp->watch_clone = trojanscan_selectclone(TROJANSCAN_WATCH_CLONES);
1478 if(!lp->watch_clone)
1479 break;
1480 if(!trojanscan_nickbanned(lp->watch_clone, cp)) {
1481 if(localjoinchannel(lp->watch_clone->clone, cp))
1482 lp->watch_clone = NULL;
1483 break;
1484 }
1485 } while(--attempts > 0);
1486 if(!attempts)
1487 lp->watch_clone = NULL;
1488
1489 }
1490 }
1491 }
1492
1493 tfree(markedlist);
1494 }
1495
1496 void trojanscan_fill_channels(void *arg) {
1497 struct trojanscan_prechannels *head = NULL, *lp, *last = NULL;
1498 int i, count, tempctime = 0;
1499
1500 chanindex *chn;
1501
1502 for (count=i=0;i<trojanscan_database.total_channels;i++) {
1503 lp = (trojanscan_prechannels *)tmalloc(sizeof(trojanscan_prechannels));
1504 lp->name = trojanscan_database.channels[i].name;
1505 lp->size = 65535;
1506 lp->exempt = trojanscan_database.channels[i].exempt;
1507 lp->watch_clone = NULL;
1508 if (trojanscan_add_ll(&head, lp))
1509 count++;
1510 }
1511
1512 for (i=0;i<CHANNELHASHSIZE;i++) {
1513 for(chn=chantable[i];chn;chn=chn->next) {
1514 if (chn->channel && !IsKey(chn->channel) && !IsInviteOnly(chn->channel) && !IsRegOnly(chn->channel) && (chn->channel->users->totalusers >= trojanscan_minchansize)) {
1515 lp = (trojanscan_prechannels *)tmalloc(sizeof(trojanscan_prechannels));
1516 lp->name = chn->name;
1517 lp->size = chn->channel->users->totalusers;
1518 lp->exempt = 0;
1519 lp->watch_clone = NULL;
1520 if (trojanscan_add_ll(&head, lp))
1521 count++;
1522 }
1523 }
1524 }
1525
1526 count = TROJANSCAN_MMIN(count, trojanscan_maxchans);
1527
1528 trojanscan_watch_clone_update(head, count);
1529
1530 trojanscan_free_channels();
1531 trojanscan_chans = (struct trojanscan_inchannel *)tmalloc(count * sizeof(struct trojanscan_inchannel));
1532 memset(trojanscan_chans, 0, count * sizeof(struct trojanscan_inchannel));
1533 trojanscan_activechans = count;
1534 i = 0;
1535
1536 for(lp=head;lp;last=lp,lp=lp->next) {
1537 if (!(lp->exempt) && (i < count)) {
1538 trojanscan_chans[i].channel = getsstring(lp->name->content, lp->name->length);
1539 trojanscan_chans[i++].watch_clone = lp->watch_clone;
1540 }
1541 if (last)
1542 tfree(last);
1543 }
1544
1545 if (last)
1546 tfree(last);
1547
1548 if (trojanscan_activechans > 0) {
1549 tempctime = trojanscan_cycletime / trojanscan_activechans;
1550 } else {
1551 tempctime = 60;
1552 trojanscan_mainchanmsg("d: just escaped a divide by zero error (no activechans!), rescheduling in 60 seconds");
1553 }
1554
1555 if(trojanscan_schedule)
1556 deleteschedule(trojanscan_schedule, &trojanscan_dojoin, NULL);
1557
1558 trojanscan_channumber = 0;
1559
1560 trojanscan_schedule = schedulerecurring(time(NULL) + tempctime, trojanscan_activechans + 1, tempctime, trojanscan_dojoin, NULL);
1561
1562 }
1563
1564 void trojanscan_dojoin(void *arg) {
1565 struct trojanscan_realchannels *rc;
1566 if (trojanscan_channumber >= trojanscan_activechans) {
1567 trojanscan_schedule = NULL;
1568 trojanscan_fill_channels(NULL);
1569 } else {
1570 if ((rc = trojanscan_allocaterc(trojanscan_chans[trojanscan_channumber++].channel->content)))
1571 trojanscan_join(rc);
1572 }
1573 }
1574
1575
1576 void trojanscan_dopart(void *arg) {
1577 struct trojanscan_realchannels *rc = (struct trojanscan_realchannels *)arg, *rp, *past = NULL;
1578
1579 if (rc->kickedout) { /* there's a join scheduled, wait for it (reschedule) */
1580 rc->schedule = scheduleoneshot(time(NULL)+5, &trojanscan_dopart, (void *)rc);
1581 return;
1582 }
1583
1584 if (rc->clone->clone && (!(rc->donotpart)))
1585 localpartchannel(rc->clone->clone, rc->chan, NULL);
1586
1587 rc->clone->sitting--;
1588
1589 for(rp=trojanscan_realchanlist;rp;rp=rp->next) {
1590 if (rp == rc) {
1591 if (!past) {
1592 trojanscan_realchanlist = rp->next;
1593 } else {
1594 past->next = rp->next;
1595 }
1596 tfree(rp);
1597 break;
1598 }
1599 past = rp;
1600 }
1601
1602 }
1603
1604 void trojanscan_donickchange(void *arg) { /* just incase I choose to make this schedule at some point */
1605 struct trojanscan_clones *clone = (trojanscan_clones *)arg;
1606 if (clone && clone->clone) {
1607 char c_nick[NICKLEN+1];
1608 int loops = 0;
1609 /* PPA: unlikely to be infinite */
1610 do {
1611 if ((loops++ < 10) && trojanscan_hostmode) {
1612 trojanscan_generatenick(c_nick, NICKLEN);
1613 } else {
1614 trojanscan_gennick(c_nick, trojanscan_minmaxrand(7, TROJANSCAN_MMIN(13, NICKLEN)));
1615 }
1616 } while (c_nick[0] && (getnickbynick(c_nick) != NULL));
1617
1618 renamelocaluser(clone->clone, c_nick);
1619 }
1620
1621 }
1622
1623 int trojanscan_keysort(const void *v1, const void *v2) {
1624 return ((*(trojanscan_prechannels **)v2)->size - (*(trojanscan_prechannels **)v1)->size);
1625 }
1626
1627 int trojanscan_showcommands(void *sender, int cargc, char **cargv) {
1628 nick *np = (nick *)sender;
1629 Command *cmdlist[100];
1630 int i, n;
1631 char level = 0;
1632
1633 n = getcommandlist(trojanscan_cmds, cmdlist, 100);
1634
1635 trojanscan_reply(np, "The following commands are registered at present:");
1636
1637 for(i=0;i<n;i++) {
1638 if (cmdlist[i]->level & TROJANSCAN_ACL_STAFF) {
1639 level = 's';
1640 } else if (cmdlist[i]->level & TROJANSCAN_ACL_DEVELOPER) {
1641 level = 'd';
1642 } else if (cmdlist[i]->level & TROJANSCAN_ACL_TEAMLEADER) {
1643 level = 't';
1644 } else if (cmdlist[i]->level & TROJANSCAN_ACL_CAT) {
1645 level = 'c';
1646 } else if (cmdlist[i]->level & TROJANSCAN_ACL_WEBSITE) {
1647 level = 'w';
1648 } else if (cmdlist[i]->level & TROJANSCAN_ACL_UNAUTHED) {
1649 level = 0;
1650 }
1651 if (level) {
1652 trojanscan_reply(np, "%s (+%c)", cmdlist[i]->command->content, level);
1653 } else {
1654 trojanscan_reply(np, "%s", cmdlist[i]->command->content);
1655 }
1656 }
1657 trojanscan_reply(np, "End of list.");
1658 return CMD_OK;
1659 }
1660
1661 void trojanscan_handlemessages(nick *target, int messagetype, void **args) {
1662 Command *cmd;
1663 char *cargv[50];
1664 int cargc, templevel;
1665 nick *sender;
1666 union trojanscan_userlevel level;
1667
1668 switch(messagetype) {
1669 case LU_PRIVMSG:
1670 case LU_SECUREMSG:
1671 /* If it's a message, first arg is nick and second is message */
1672 sender = (nick *)args[0];
1673
1674 if(strncmp(TROJANSCAN_VERSION_DETECT, args[1], sizeof(TROJANSCAN_VERSION_DETECT)-1)==0) {
1675 char p = ((char *)args[1])[sizeof(TROJANSCAN_VERSION_DETECT)-1];
1676 if((p == ' ') || (p == '\0') || (p == 1)) {
1677 trojanscan_reply(sender, "\001VERSION Trojanscan (or Tigger) Newserv module version %s by Chris Porter (slug), Newserv by David Mansell (splidge). Compiled " __DATE__ " " __TIME__ ".\001", TROJANSCAN_VERSION);
1678 return;
1679 }
1680 }
1681
1682 /* Split the line into params */
1683 cargc = splitline((char *)args[1], cargv, 50, 0);
1684 if(cargc == 0 || !cargv[0])
1685 return;
1686
1687 cmd=findcommandintree(trojanscan_cmds, cargv[0], 1);
1688 if (!cmd) {
1689 trojanscan_reply(sender, "Unknown command.");
1690 return;
1691 }
1692
1693 if ((cmd->level & TROJANSCAN_ACL_OPER) && !IsOper(sender)) {
1694 trojanscan_reply(sender, "You need to be opered to use this command.");
1695 return;
1696 }
1697
1698 /* bit grim code... */
1699
1700 if (!(cmd->level & TROJANSCAN_ACL_UNAUTHED)) {
1701 if (!IsAccount(sender)) {
1702 trojanscan_reply(sender, "You must be authed with the network to access this command!");
1703 return;
1704 }
1705 templevel = trojanscan_user_level_by_authname(sender->authname);
1706
1707 if (templevel == -1) {
1708 trojanscan_reply(sender, "You do not have an account.");
1709 return;
1710 }
1711
1712 level.number = templevel;
1713
1714 if ((cmd->level & TROJANSCAN_ACL_DEVELOPER) && !TrojanscanIsDeveloper(level)) {
1715 trojanscan_reply(sender, "Access denied.");
1716 return;
1717 }
1718 if ((cmd->level & TROJANSCAN_ACL_TEAMLEADER) && !TrojanscanIsLeastTeamLeader(level)) {
1719 trojanscan_reply(sender, "Access denied.");
1720 return;
1721 }
1722 if ((cmd->level & TROJANSCAN_ACL_STAFF) && !TrojanscanIsLeastStaff(level)) {
1723 trojanscan_reply(sender, "Access denied.");
1724 return;
1725 }
1726 if ((cmd->level & TROJANSCAN_ACL_CAT) && !TrojanscanIsCat(level)) {
1727 trojanscan_reply(sender, "Access denied.");
1728 return;
1729 }
1730 if ((cmd->level & TROJANSCAN_ACL_WEBSITE) && !TrojanscanIsLeastWebsite(level)) {
1731 trojanscan_reply(sender, "Access denied.");
1732 return;
1733 }
1734 }
1735
1736 /* Check the maxargs */
1737 if (cmd->maxparams<(cargc-1)) {
1738 /* We need to do some rejoining */
1739 rejoinline(cargv[cmd->maxparams], cargc-(cmd->maxparams));
1740 cargc = (cmd->maxparams) + 1;
1741 }
1742
1743 (cmd->handler)((void *)sender, cargc - 1, &(cargv[1]));
1744 break;
1745
1746 case LU_KILLED:
1747 /* someone killed me? Bastards */
1748 trojanscan_connect_nick_schedule = scheduleoneshot(time(NULL) + 1, &trojanscan_connect_nick, NULL);
1749 trojanscan_nick = NULL;
1750 break;
1751
1752 default:
1753 break;
1754 }
1755 }
1756
1757 static char trojanscan_getmtfromhooktype(int input) {
1758 switch(input) {
1759 case HOOK_CHANNEL_PART: return 'P';
1760 default: return '?';
1761 }
1762 }
1763
1764 char trojanscan_getmtfrommessagetype(int input) {
1765 switch(input) {
1766 case LU_PRIVMSG: return 'm';
1767 case LU_PRIVNOTICE: return 'n';
1768 case LU_SECUREMSG: return 's';
1769 case LU_CHANMSG: return 'M';
1770 case LU_CHANNOTICE: return 'N';
1771 default: return '?';
1772 }
1773 }
1774
1775 static void trojanscan_process(nick *sender, channel *cp, char mt, char *pretext) {
1776 char text[513];
1777 unsigned int len;
1778 unsigned int i;
1779 struct trojanscan_worms *worm;
1780 int vector[30], detected = 0;
1781
1782 trojanscan_strip_codes(text, sizeof(text) - 1, pretext);
1783
1784 len = strlen(text);
1785
1786 for(i=0;i<trojanscan_database.total_phrases;i++) {
1787 if (
1788 (
1789 (worm = trojanscan_database.phrases[i].worm)
1790 ) &&
1791 (
1792 (
1793 (
1794 (mt == 'm') || (mt == 's') || (mt == 'n')
1795 ) &&
1796 (
1797 (trojanscan_database.phrases[i].worm->hitpriv)
1798 )
1799 ) ||
1800 (
1801 (
1802 (mt == 'M') || (mt == 'N') || (mt == 'P')
1803 ) &&
1804 (
1805 (trojanscan_database.phrases[i].worm->hitchans)
1806 )
1807 )
1808 ) &&
1809 (trojanscan_database.phrases[i].phrase)
1810 ) {
1811 int pre = pcre_exec(trojanscan_database.phrases[i].phrase, trojanscan_database.phrases[i].hint, text, len, 0, 0, vector, 30);
1812 if(pre >= 0) {
1813 char matchbuf[513];
1814 matchbuf[0] = 0;
1815 matchbuf[512] = 0; /* hmm */
1816
1817 if(pre > 1)
1818 if(pcre_copy_substring(text, vector, pre, 1, matchbuf, sizeof(matchbuf) - 1) <= 0)
1819 matchbuf[0] = 0;
1820
1821 trojanscan_phrasematch(cp, sender, &trojanscan_database.phrases[i], mt, matchbuf);
1822
1823 detected = 1;
1824 break;
1825 }
1826 }
1827 }
1828 if (!detected && (mt != 'N') && (mt != 'M')) {
1829 char etext[TROJANSCAN_QUERY_TEMP_BUF_SIZE], enick[TROJANSCAN_QUERY_TEMP_BUF_SIZE], eident[TROJANSCAN_QUERY_TEMP_BUF_SIZE], ehost[TROJANSCAN_QUERY_TEMP_BUF_SIZE];
1830 trojanscan_database_escape_string(etext, text, len);
1831 trojanscan_database_escape_string(enick, sender->nick, strlen(sender->nick));
1832 trojanscan_database_escape_string(eident, sender->ident, strlen(sender->ident));
1833 trojanscan_database_escape_string(ehost, sender->host->name->content, sender->host->name->length);
1834 trojanscan_database_query("INSERT INTO unknownlog (data, user) VALUES ('%s','%s!%s@%s')", etext, enick, eident, ehost);
1835 }
1836 }
1837
1838 void trojanscan_clonehandlemessages(nick *target, int messagetype, void **args) {
1839 char *pretext = NULL;
1840 nick *sender;
1841 struct trojanscan_realchannels *rp;
1842 struct trojanscan_rejoinlist *rj;
1843 char mt = trojanscan_getmtfrommessagetype(messagetype);
1844 char *channel_name;
1845 channel *cp = NULL;
1846 int i;
1847
1848 switch(messagetype) {
1849 case LU_PRIVMSG:
1850 case LU_SECUREMSG:
1851 case LU_PRIVNOTICE:
1852
1853 pretext = (char *)args[1];
1854
1855 case LU_CHANMSG:
1856 case LU_CHANNOTICE:
1857 sender = (nick *)args[0];
1858
1859 if (strlen(sender->nick) < 2)
1860 break;
1861
1862 if (!pretext) {
1863 pretext = (char *)args[2];
1864 cp = args[1];
1865 }
1866
1867 if(strncmp(TROJANSCAN_VERSION_DETECT, pretext, sizeof(TROJANSCAN_VERSION_DETECT)-1)==0) {
1868 char p = pretext[sizeof(TROJANSCAN_VERSION_DETECT)-1];
1869 if((p == ' ') || (p == '\0') || (p == 1)) {
1870 int staff = 0;
1871 if (IsOper(sender)) {
1872 staff = 1;
1873 } else {
1874 if (IsAccount(sender)) {
1875 int templevel = trojanscan_user_level_by_authname(sender->authname);
1876 if (templevel != -1) {
1877 union trojanscan_userlevel level;
1878 level.number = templevel;
1879 if (TrojanscanIsLeastStaff(level))
1880 staff = 1;
1881 }
1882 }
1883 }
1884 if (staff) {
1885 if(trojanscan_nick) {
1886 sendnoticetouser(target, sender, "\001VERSION T clone, check T for confirmation.\001");
1887 sendnoticetouser(trojanscan_nick, sender, "\001VERSION %s is part of my swarm.\001", target->nick);
1888 } else {
1889 sendnoticetouser(target, sender, "\001VERSION T clone, though since T is currently gone you'll have to version me again in a minute for confirmation.\001");
1890 }
1891 } else {
1892 sendnoticetouser(target, sender, "\001VERSION %s\001", versionreply);
1893 }
1894
1895 return;
1896 }
1897 }
1898
1899 trojanscan_process(sender, cp, mt, pretext);
1900 break;
1901 case LU_KILLED:
1902 /* someone killed me? Bastards */
1903
1904 /* PPA: we do NOT rejoin channels at this moment in time, it is possible to do this though */
1905 for (i=0;i<TROJANSCAN_CLONE_TOTAL;i++) {
1906 if (trojanscan_swarm[i].clone == target) {
1907
1908 scheduleoneshot(time(NULL)+1, &trojanscan_generateclone, (void *)((long)i));
1909 if(i >= TROJANSCAN_CLONE_MAX) {
1910 int j;
1911 for(j=0;j<trojanscan_activechans;j++)
1912 if(trojanscan_chans[j].watch_clone == &trojanscan_swarm[i])
1913 trojanscan_chans[j].watch_clone = NULL;
1914 } else {
1915 for(rp=trojanscan_realchanlist;rp;rp=rp->next)
1916 if ((rp->clone == &(trojanscan_swarm[i])))
1917 rp->donotpart = 1;
1918 }
1919 derefnode(iptree, trojanscan_swarm[i].fakeipnode);
1920 trojanscan_swarm[i].clone = NULL;
1921 trojanscan_swarm[i].remaining = 0; /* bah */
1922 break;
1923 }
1924 }
1925 break;
1926
1927 case LU_KICKED:
1928 channel_name = ((channel *)args[1])->index->name->content;
1929 for (i=0;i<trojanscan_activechans;i++) {
1930 if (!trojanscan_chans[i].watch_clone)
1931 continue;
1932 if ((trojanscan_chans[i].watch_clone->clone == target) && (!strcmp(trojanscan_chans[i].channel->content, channel_name)))
1933 break;
1934 }
1935 if(i != trojanscan_activechans) {
1936 int j;
1937 for(j=0;j<TROJANSCAN_CLONE_TOTAL;j++) {
1938 if(&trojanscan_swarm[j] == trojanscan_chans[i].watch_clone) {
1939 trojanscan_chans[i].watch_clone = NULL;
1940 break;
1941 }
1942 }
1943 } else {
1944 /*
1945 trojanscan_mainchanmsg("k: %s on %s by %s", target->nick, ((channel *)args[1])->index->name->content, (((nick *)args[0])->nick)?(((nick *)args[0])->nick):"(server)");
1946 */
1947 rj = (struct trojanscan_rejoinlist *)tmalloc(sizeof(struct trojanscan_rejoinlist));
1948 if (rj) {
1949 rj->rp = NULL;
1950 for(rp=trojanscan_realchanlist;rp;rp=rp->next)
1951 if ((rp->clone->clone == target) && (rp->chan == args[1])) {
1952 rp->kickedout++;
1953 rj->rp = rp;
1954 break;
1955 }
1956 if(!rj->rp) {
1957 tfree(rj);
1958 return;
1959 }
1960
1961 rj->channel = getsstring(((channel *)args[1])->index->name->content, ((channel *)args[1])->index->name->length);
1962 if(!rj->channel) {
1963 trojanscan_mainchanmsg("d: unable to allocate memory for channel: %s upon rejoin", ((channel *)args[1])->index->name->content);
1964 tfree(rj);
1965 return;
1966 }
1967
1968 rj->clone = rp->clone;
1969 rj->next = trojanscan_schedulerejoins;
1970 trojanscan_schedulerejoins = rj;
1971
1972 rj->schedule = scheduleoneshot(time(NULL)+1, &trojanscan_rejoin_channel, (void *)rj);
1973 }
1974 }
1975 break;
1976 default:
1977 break;
1978 }
1979 }
1980
1981 static void trojanscan_part_watch(int hook, void *arg) {
1982 void **arglist = (void **)arg;
1983 channel *cp = (channel *)arglist[0];
1984 nick *np = arglist[1];
1985 char *reason = arglist[2];
1986
1987 if(!cp || !np || !reason || (*reason == '\0'))
1988 return;
1989
1990 trojanscan_process(np, cp, trojanscan_getmtfromhooktype(hook), reason);
1991 }
1992
1993 static int trojanscan_hostcount(nick *sender, int hostmode, char *mask, int masklen) {
1994 int usercount = 0, j;
1995 nick *np = NULL; /* sigh at warnings */
1996
1997 if(hostmode)
1998 for (j=0;j<NICKHASHSIZE;j++)
1999 for (np=nicktable[j];np;np=np->next)
2000 if (np->ipnode==sender->ipnode)
2001 usercount++;
2002
2003 if(usercount > TROJANSCAN_MAX_HOST_GLINE) {
2004 hostmode = 0;
2005 usercount = 0;
2006 }
2007
2008 if(!hostmode)
2009 for (j=0;j<NICKHASHSIZE;j++)
2010 for (np=nicktable[j];np;np=np->next)
2011 if (np->ipnode==sender->ipnode && !ircd_strcmp(np->ident, sender->ident))
2012 usercount++;
2013
2014 if(mask)
2015 snprintf(mask, masklen, "%s@%s", hostmode?"*":sender->ident, IPtostr(sender->p_ipaddr));
2016
2017 return usercount;
2018 }
2019
2020 void trojanscan_phrasematch(channel *chp, nick *sender, trojanscan_phrases *phrase, char messagetype, char *matchbuf) {
2021 char glinemask[HOSTLEN + USERLEN + NICKLEN + 4], enick[TROJANSCAN_QUERY_TEMP_BUF_SIZE], eident[TROJANSCAN_QUERY_TEMP_BUF_SIZE], ehost[TROJANSCAN_QUERY_TEMP_BUF_SIZE];
2022 unsigned int frequency;
2023 int glining = 0, usercount;
2024 struct trojanscan_worms *worm = phrase->worm;
2025
2026 trojanscan_database.detections++;
2027
2028 usercount = 0;
2029 if (worm->monitor) {
2030 usercount = -1;
2031 } else if(worm->glinehost || worm->glineuser) {
2032 glining = 1;
2033
2034 usercount = trojanscan_hostcount(sender, worm->glinehost, glinemask, sizeof(glinemask));
2035 }
2036
2037 if (!usercount) {
2038 trojanscan_mainchanmsg("w: user %s!%s@%s triggered infection monitor, yet no hosts found at stage 2 -- worm: %s", sender->nick, sender->ident, sender->host->name->content, worm->name->content);
2039 return;
2040 }
2041
2042 if (glining && (usercount > trojanscan_maxusers)) {
2043 trojanscan_mainchanmsg("w: not glining %s!%s@%s due to too many users (%d) with mask: *!%s -- worm: %s)", sender->nick, sender->ident, sender->host->name->content, usercount, glinemask, worm->name->content);
2044 return;
2045 }
2046
2047 if (glining && !worm->datalen) {
2048 trojanscan_mainchanmsg("w: not glining %s!%s@%s due to too lack of removal data with mask: *!%s (%d users) -- worm: %s)", sender->nick, sender->ident, sender->host->name->content, glinemask, usercount, worm->name->content);
2049 return;
2050 }
2051
2052 trojanscan_database_escape_string(enick, sender->nick, strlen(sender->nick));
2053 trojanscan_database_escape_string(eident, sender->ident, strlen(sender->ident));
2054 trojanscan_database_escape_string(ehost, sender->host->name->content, sender->host->name->length);
2055
2056 frequency = 1;
2057
2058 if (!(trojanscan_database_query("SELECT COUNT(*) FROM hits WHERE glined = %d AND host = '%s'", glining, ehost))) {
2059 trojanscan_database_res *res;
2060 if ((res = trojanscan_database_store_result(&trojanscan_sql))) {
2061 trojanscan_database_row sqlrow;
2062 if ((trojanscan_database_num_rows(res) > 0) && (sqlrow = trojanscan_database_fetch_row(res)))
2063 frequency = atoi(sqlrow[0]) + 1;
2064 trojanscan_database_free_result(res);
2065 }
2066 }
2067
2068 if (!glining) {
2069 trojanscan_mainchanmsg("m: t: %c u: %s!%s@%s%s%s w: %s p: %d %s%s", messagetype, sender->nick, sender->ident, sender->host->name->content, messagetype=='N'||messagetype=='M'||messagetype=='P'?" #: ":"", messagetype=='N'||messagetype=='M'||messagetype=='P'?chp->index->name->content:"", worm->name->content, phrase->id, matchbuf[0]?" --: ":"", matchbuf[0]?matchbuf:"");
2070 #ifdef TROJANSCAN_PEONCHANNEL
2071 trojanscan_peonchanmsg("m: t: %c u: %s!%s@%s%s%s%s w: %s %s%s", messagetype, sender->nick, sender->ident, (IsHideHost(sender)&&IsAccount(sender))?sender->authname:sender->host->name->content, (IsHideHost(sender)&&IsAccount(sender))?"."HIS_HIDDENHOST:"", messagetype=='N'||messagetype=='M'||messagetype=='P'?" #: ":"", messagetype=='N'||messagetype=='M'||messagetype=='P'?chp->index->name->content:"", worm->name->content, matchbuf[0]?" --: ":"", matchbuf[0]?matchbuf:"");
2072 #endif
2073 } else {
2074 int glinetime = TROJANSCAN_FIRST_OFFENSE * frequency * (worm->epidemic?TROJANSCAN_EPIDEMIC_MULTIPLIER:1);
2075 if(glinetime > 7 * 24)
2076 glinetime = 7 * 24; /* can't set glines over 7 days with normal non U:lined glines */
2077
2078 trojanscan_database_query("INSERT INTO hits (nickname, ident, host, phrase, messagetype, glined) VALUES ('%s', '%s', '%s', %d, '%c', %d)", enick, eident, ehost, phrase->id, messagetype, glining);
2079 trojanscan_database.glines++;
2080
2081 irc_send("%s GL * +%s %d :You (%s!%s@%s) are infected with a trojan (%s/%d), see %s%d for details - banned for %d hours\r\n", mynumeric->content, glinemask, glinetime * 3600, sender->nick, sender->ident, sender->host->name->content, worm->name->content, phrase->id, TROJANSCAN_URL_PREFIX, worm->id, glinetime);
2082
2083 trojanscan_mainchanmsg("g: *!%s t: %c u: %s!%s@%s%s%s c: %d w: %s%s p: %d f: %d%s%s", glinemask, messagetype, sender->nick, sender->ident, sender->host->name->content, messagetype=='N'||messagetype=='M'||messagetype=='P'?" #: ":"", messagetype=='N'||messagetype=='M'||messagetype=='P'?chp->index->name->content:"", usercount, worm->name->content, worm->epidemic?"(E)":"", phrase->id, frequency, matchbuf[0]?" --: ":"", matchbuf[0]?matchbuf:"");
2084 }
2085 }
2086
2087 void trojanscan_rejoin_channel(void *arg) {
2088 struct trojanscan_rejoinlist *rj2, *lrj, *rj = (struct trojanscan_rejoinlist *)arg;
2089
2090 channel *cp = findchannel(rj->channel->content);
2091 freesstring(rj->channel);
2092
2093 if (rj->rp) {
2094 rj->rp->kickedout--;
2095 if (!cp) {
2096 rj->rp->donotpart = 1; /* we were the last user on the channel, so we need to be VERY careful freeing it */
2097 } else {
2098 if(!rj->rp->donotpart && !rj->rp->kickedout) { /* check we're allowed to join channels (not killed), and we're the last one to join */
2099 if (trojanscan_nickbanned(rj->clone, cp)) {
2100 rj->rp->donotpart = 1;
2101 } else {
2102 localjoinchannel(rj->clone->clone, cp);
2103 }
2104 }
2105 }
2106 }
2107
2108 rj2 = trojanscan_schedulerejoins;
2109 lrj = NULL;
2110
2111 if (rj2 == rj) {
2112 trojanscan_schedulerejoins = rj->next;
2113 tfree(rj);
2114 } else {
2115 for(rj2=trojanscan_schedulerejoins;rj2;lrj=rj2,rj2=rj2->next) {
2116 if (rj2 == rj) {
2117 lrj->next = rj2->next;
2118 tfree(rj);
2119 break;
2120 }
2121 }
2122 }
2123
2124 }
2125
2126 void trojanscan_reply(nick *target, char *message, ... ) {
2127 char buf[513];
2128 va_list va;
2129
2130 if (!trojanscan_nick)
2131 return;
2132
2133 va_start(va, message);
2134 vsnprintf(buf, sizeof(buf) - 1, message, va);
2135 va_end(va);
2136
2137 sendnoticetouser(trojanscan_nick, target, "%s", buf);
2138 }
2139
2140
2141 void trojanscan_mainchanmsg(char *message, ...) {
2142 char buf[513];
2143 va_list va;
2144 channel *cp;
2145
2146 if (!trojanscan_nick)
2147 return;
2148 if (!(cp = findchannel(TROJANSCAN_CHANNEL)))
2149 return;
2150
2151 va_start(va, message);
2152 vsnprintf(buf, sizeof(buf) - 1, message, va);
2153 va_end(va);
2154
2155 sendmessagetochannel(trojanscan_nick, cp, "%s", buf);
2156 }
2157
2158 #ifdef TROJANSCAN_PEONCHANNEL
2159 void trojanscan_peonchanmsg(char *message, ...) {
2160 char buf[513];
2161 va_list va;
2162 channel *cp;
2163
2164 if (!trojanscan_nick)
2165 return;
2166 if (!(cp = findchannel(TROJANSCAN_PEONCHANNEL)))
2167 return;
2168
2169 va_start(va, message);
2170 vsnprintf(buf, sizeof(buf) - 1, message, va);
2171 va_end(va);
2172
2173 sendmessagetochannel(trojanscan_nick, cp, "%s", buf);
2174 }
2175 #endif
2176
2177 int trojanscan_minmaxrand(float min, float max) {
2178 return (int)((max-min+1)*rand()/(RAND_MAX+min))+min;
2179 }
2180
2181 char *trojanscan_iptostr(char *buf, int buflen, unsigned int ip) {
2182 snprintf(buf, buflen, "%d.%d.%d.%d", ip >> 24, (ip >> 16) & 255, (ip >> 8) & 255, ip & 255);
2183 return buf;
2184 }
2185
2186 char trojanscan_genchar(int ty) {
2187 /* hostname and realname characters*/
2188 if (!ty) {
2189 if (!(trojanscan_minmaxrand(0, 40) % 10)) {
2190 return trojanscan_minmaxrand(48, 57);
2191 } else {
2192 return trojanscan_minmaxrand(97, 122);
2193 }
2194 /* ident characters - without numbers*/
2195 } else if (ty == 1) {
2196 return trojanscan_minmaxrand(97, 122);
2197 /* ident characters - with numbers*/
2198 } else if (ty == 2) {
2199 ty = trojanscan_minmaxrand(97, 125);
2200 if (ty > 122) return trojanscan_minmaxrand(48, 57);
2201 return ty;
2202 /* nick characters - with and without numbers*/
2203 } else if (ty == 3 || ty == 4) {
2204 if (!(trojanscan_minmaxrand(0, 59) % 16)) {
2205 char weirdos[6] = { '\\', '|', '[', '{', ']', '}' };
2206 return weirdos[trojanscan_minmaxrand(0, 5)];
2207 }
2208 if (ty == 4) {
2209 ty = trojanscan_minmaxrand(65, 93);
2210 if (ty > 90) return trojanscan_minmaxrand(48, 57);
2211 } else {
2212 ty = trojanscan_minmaxrand(65, 90);
2213 }
2214 if (!(trojanscan_minmaxrand(0, 40) % 8)) return ty;
2215 return ty + 32;
2216 /* moron check */
2217 } else {
2218 return ' ';
2219 }
2220 }
2221
2222 void trojanscan_gennick(char *ptc, char size) {
2223 int i;
2224 for (i=0;i<size;i++) {
2225 if (i == 0) {
2226 ptc[i] = trojanscan_genchar(3);
2227 } else {
2228 ptc[i] = trojanscan_genchar(4);
2229 }
2230 }
2231 ptc[i] = '\0';
2232 }
2233
2234 void trojanscan_genident(char *ptc, char size) {
2235 int i;
2236 for (i=0;i<size;i++) {
2237 if (i == 0) {
2238 ptc[i] = trojanscan_genchar(1);
2239 } else {
2240 ptc[i] = trojanscan_genchar(2);
2241 }
2242 }
2243 ptc[i] = '\0';
2244 }
2245
2246 void trojanscan_genhost(char *ptc, char size, patricia_node_t **fakeipnode) {
2247 int dots = trojanscan_minmaxrand(2, 5), i, dotexist = 0, cur;
2248 struct irc_in_addr ipaddress;
2249
2250 while (!dotexist) {
2251 for (i=0;i<size;i++) {
2252 ptc[i] = trojanscan_genchar(0);
2253 if ((i > 5) && (i < (size-4))) {
2254 if ((ptc[i-1] != '.') && (ptc[i-1] != '-')) {
2255 cur = trojanscan_minmaxrand(1,size / dots);
2256 if (cur < 3) {
2257 if (cur == 1) {
2258 ptc[i] = '.';
2259 dotexist = 1;
2260 } else {
2261 ptc[i] = '-';
2262 }
2263 }
2264 }
2265 }
2266 }
2267 }
2268 ptc[i] = '\0';
2269
2270 memset(&ipaddress, 0, sizeof(ipaddress));
2271 ((unsigned short *)(ipaddress.in6_16))[5] = 65535;
2272 ((unsigned short *)(ipaddress.in6_16))[6] = trojanscan_minmaxrand(0, 65535);
2273 ((unsigned short *)(ipaddress.in6_16))[7] = trojanscan_minmaxrand(0, 65535);
2274
2275 *fakeipnode = refnode(iptree, &ipaddress, PATRICIA_MAXBITS);
2276 }
2277
2278 void trojanscan_genreal(char *ptc, char size) {
2279 int spaces = trojanscan_minmaxrand(2, 4), i;
2280 for (i=0;i<size;i++) {
2281 ptc[i] = trojanscan_genchar(0);
2282 if ((i > 5) && (i < (size-4))) {
2283 if (ptc[i-1] != ' ') {
2284 if (trojanscan_minmaxrand(1,size / spaces) == 1) ptc[i] = ' ';
2285 }
2286 }
2287 }
2288 ptc[i] = '\0';
2289 }
2290
2291 int trojanscan_is_not_octet(char *begin, int length) {
2292 int i;
2293 if(length > 3)
2294 return 0;
2295 for(i=0;i<length;i++) {
2296 if (!((*begin >= '0') && (*begin <= '9')))
2297 return 0;
2298 begin++;
2299 }
2300 return 1;
2301 }
2302
2303 int trojanscan_generatepool(void) {
2304 int i, k = 0, j = 0, loops = 0;
2305 char *p, *pp;
2306 nick *np;
2307
2308 for (i=0;i<NICKHASHSIZE;i++)
2309 for (np=nicktable[i];np;np=np->next)
2310 j++;
2311
2312 if(j < trojanscan_min_hosts)
2313 return 0;
2314
2315 if(TROJANSCAN_HOST_MODE == TROJANSCAN_STEAL_HOST)
2316 return TROJANSCAN_MINPOOLSIZE;
2317
2318 i = 0;
2319 do {
2320 for (j=trojanscan_minmaxrand(0, NICKHASHSIZE-1);j<NICKHASHSIZE;j++) {
2321 if (nicktable[j]) {
2322 for(p=nicktable[j]->host->name->content, pp=p;*p;) {
2323 if (*++p == '.') {
2324 if (!trojanscan_is_not_octet(pp, p-pp)) {
2325 if (i < TROJANSCAN_POOLSIZE) {
2326 if (i < trojanscan_hostpoolsize)
2327 freesstring(trojanscan_hostpool[i]);
2328 trojanscan_hostpool[i] = getsstring(pp, p-pp);
2329 i++;
2330 } else {
2331 if (k >= TROJANSCAN_POOLSIZE)
2332 break;
2333 }
2334 }
2335 pp=++p;
2336 }
2337 }
2338 if (!trojanscan_is_not_octet(pp, p-pp)) {
2339 if (k < TROJANSCAN_POOLSIZE) {
2340 if (k < trojanscan_tailpoolsize)
2341 freesstring(trojanscan_tailpool[k]);
2342 trojanscan_tailpool[k] = getsstring(pp, p-pp);
2343 k++;
2344 } else {
2345 if (i >= TROJANSCAN_POOLSIZE)
2346 break;
2347 }
2348 }
2349 }
2350 }
2351 loops++;
2352 } while ((loops < 5) && ((i < TROJANSCAN_POOLSIZE) || (k < TROJANSCAN_POOLSIZE)));
2353
2354 trojanscan_hostpoolsize = i;
2355 trojanscan_tailpoolsize = k;
2356 return i;
2357 }
2358
2359 nick *trojanscan_selectuser(void) {
2360 int target = trojanscan_minmaxrand(0, 500), loops = 150, j;
2361 nick *np;
2362 do {
2363 for (j=trojanscan_minmaxrand(0, NICKHASHSIZE-1);j<NICKHASHSIZE;j++)
2364 for(np=nicktable[j];np;np=np->next)
2365 if (!--target)
2366 return np;
2367 } while(--loops > 0);
2368 return NULL;
2369 }
2370
2371 host *trojanscan_selecthost(void) {
2372 int target = trojanscan_minmaxrand(0, 500), loops = 150, j;
2373 host *hp;
2374 do {
2375 for (j=trojanscan_minmaxrand(0, HOSTHASHSIZE-1);j<HOSTHASHSIZE;j++)
2376 for(hp=hosttable[j];hp;hp=hp->next)
2377 if (!--target)
2378 return hp;
2379 } while(--loops > 0);
2380
2381 return NULL;
2382 }
2383
2384 void trojanscan_generatehost(char *buf, int maxsize, patricia_node_t **fakeip) {
2385 struct irc_in_addr ipaddress;
2386
2387 if(TROJANSCAN_HOST_MODE == TROJANSCAN_STEAL_HOST) {
2388 host *hp;
2389 int loops = 20;
2390
2391 buf[0] = '\0';
2392
2393 do {
2394 hp = trojanscan_selecthost();
2395 if(hp && (hp->clonecount <= TROJANSCAN_MAX_CLONE_COUNT) && !trojanscan_isip(hp->name->content)) {
2396 strlcpy(buf, hp->name->content, maxsize + 1);
2397 if(hp->nicks) {
2398 *fakeip = hp->nicks->ipnode;
2399 patricia_ref_prefix(hp->nicks->ipnode->prefix);
2400 } else {
2401 memset(&ipaddress, 0, sizeof(ipaddress));
2402 ((unsigned short *)(ipaddress.in6_16))[5] = 65535;
2403 ((unsigned short *)(ipaddress.in6_16))[6] = trojanscan_minmaxrand(0, 65535);
2404 ((unsigned short *)(ipaddress.in6_16))[7] = trojanscan_minmaxrand(0, 65535);
2405
2406 *fakeip = refnode(iptree, &ipaddress, PATRICIA_MAXBITS);
2407 }
2408 break;
2409 }
2410 } while(--loops > 0);
2411 } else {
2412 char *cpos;
2413 int pieces = trojanscan_minmaxrand(2, 4), totallen = 0, a = 0, i;
2414 int *choices = tmalloc(sizeof(int) * (pieces + 1));
2415 int *lengths = tmalloc(sizeof(int) * (pieces + 1));
2416
2417 choices[pieces] = trojanscan_minmaxrand(0, trojanscan_tailpoolsize-1);
2418 lengths[pieces] = strlen(trojanscan_tailpool[choices[pieces]]->content) + 1;
2419 totallen += lengths[pieces];
2420
2421 for (i=0;i<pieces;i++) {
2422 choices[i] = trojanscan_minmaxrand(0, trojanscan_hostpoolsize-1);
2423 lengths[i] = strlen(trojanscan_hostpool[choices[i]]->content) + 1;
2424 if (totallen+lengths[i] > maxsize) {
2425 choices[i] = choices[pieces];
2426 lengths[i] = lengths[pieces];
2427 pieces-=(pieces-i);
2428 break;
2429 }
2430 totallen += lengths[i];
2431 }
2432
2433 for (i=0;i<pieces;i++) {
2434 for (cpos=trojanscan_hostpool[choices[i]]->content; *cpos;)
2435 buf[a++] = *cpos++;
2436 buf[a++] = '.';
2437 }
2438
2439 for (cpos=trojanscan_tailpool[choices[i]]->content; *cpos;) {
2440 buf[a++] = *cpos++;
2441 }
2442
2443 buf[a] = '\0';
2444 tfree(choices);
2445 tfree(lengths);
2446
2447 memset(&ipaddress, 0, sizeof(ipaddress));
2448 ((unsigned short *)(ipaddress.in6_16))[5] = 65535;
2449 ((unsigned short *)(ipaddress.in6_16))[6] = trojanscan_minmaxrand(0, 65535);
2450 ((unsigned short *)(ipaddress.in6_16))[7] = trojanscan_minmaxrand(0, 65535);
2451
2452 *fakeip = refnode(iptree, &ipaddress, PATRICIA_MAXBITS);
2453 }
2454 }
2455
2456 void trojanscan_generatenick(char *buf, int maxsize) {
2457 int bits = trojanscan_minmaxrand(2, 3), loops = 0, wanttocopy, len = 0, i, d = 0, newmaxsize = maxsize - trojanscan_minmaxrand(0, 7);
2458 nick *np;
2459
2460 if(newmaxsize > 2)
2461 maxsize = newmaxsize;
2462
2463 do {
2464 np = trojanscan_selectuser();
2465 if(np) {
2466 wanttocopy = trojanscan_minmaxrand(1, (strlen(np->nick) / 2) + 3);
2467 for(i=0;((i<wanttocopy) && (len<maxsize));i++)
2468 buf[len++] = np->nick[i];
2469 if(++d > bits) {
2470 buf[len] = '\0';
2471 return;
2472 }
2473 }
2474 } while (++loops < 10);
2475 buf[0] = '\0';
2476 }
2477
2478 void trojanscan_generateident(char *buf, int maxsize) {
2479 nick *np = trojanscan_selectuser();
2480 buf[0] = '\0';
2481 if(np)
2482 strlcpy(buf, np->ident, maxsize + 1);
2483 }
2484
2485 void trojanscan_generaterealname(char *buf, int maxsize) {
2486 nick *np = trojanscan_selectuser();
2487 buf[0] = '\0';
2488 if(np)
2489 strlcpy(buf, np->realname->name->content, maxsize + 1);
2490 }
2491
2492 void trojanscan_database_close(void) {
2493 mysql_close(&trojanscan_sql);
2494 }
2495
2496 int trojanscan_database_connect(char *dbhost, char *dbuser, char *dbpass, char *db, unsigned int port) {
2497 mysql_init(&trojanscan_sql);
2498 if (!mysql_real_connect(&trojanscan_sql, dbhost, dbuser, dbpass, db, port, NULL, 0))
2499 return -1;
2500 return 0;
2501 }
2502
2503 void trojanscan_database_escape_string(char *dest, char *source, size_t length) {
2504 mysql_escape_string(dest, source, length);
2505 }
2506
2507 int trojanscan_database_query(char *format, ...) {
2508 char trojanscan_sqlquery[TROJANSCAN_QUERY_BUF_SIZE];
2509 va_list va;
2510
2511 va_start(va, format);
2512 vsnprintf(trojanscan_sqlquery, sizeof(trojanscan_sqlquery) - 1, format, va);
2513 va_end(va);
2514 return mysql_query(&trojanscan_sql, trojanscan_sqlquery);
2515 }
2516
2517 int trojanscan_database_num_rows(trojanscan_database_res *res) {
2518 return mysql_num_rows(res);
2519 }
2520
2521 trojanscan_database_res *trojanscan_database_store_result() {
2522 return mysql_store_result(&trojanscan_sql);
2523 }
2524
2525 trojanscan_database_row trojanscan_database_fetch_row(trojanscan_database_res *res) {
2526 return mysql_fetch_row(res);
2527 }
2528
2529 void trojanscan_database_free_result(trojanscan_database_res *res) {
2530 mysql_free_result(res);
2531 }
2532
2533 int trojanscan_isip(char *host) {
2534 char *p = host, components = 0, length = 0;
2535
2536 for(;*p;p++) {
2537 if(*p == '.') {
2538 if(((!length) || (length = 0)) || (++components > 3))
2539 return 0;
2540 } else {
2541 if ((++length > 3) || !isdigit(*p))
2542 return 0;
2543 }
2544 }
2545 return components == 3;
2546 }
2547