server.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188
  1. /*
  2. * Copyright (C) 1997 Robey Pointer
  3. * Copyright (C) 1999 - 2002 Eggheads Development Team
  4. * Copyright (C) 2002 - 2008 Bryan Drewery
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU General Public License
  8. * as published by the Free Software Foundation; either version 2
  9. * of the License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program; if not, write to the Free Software
  18. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  19. */
  20. /*
  21. * server.c -- part of server.mod
  22. * basic irc server support
  23. *
  24. */
  25. #include "src/common.h"
  26. #include "src/set.h"
  27. #include "src/botmsg.h"
  28. #include "src/rfc1459.h"
  29. #include "src/settings.h"
  30. #include "src/match.h"
  31. #include "src/binds.h"
  32. #include "src/users.h"
  33. #include "src/userrec.h"
  34. #include "src/main.h"
  35. #include "src/response.h"
  36. #include "src/misc.h"
  37. #include "src/chanprog.h"
  38. #include "src/net.h"
  39. #include "src/auth.h"
  40. #include "src/adns.h"
  41. #include "src/socket.h"
  42. #include "src/egg_timer.h"
  43. #include "src/mod/channels.mod/channels.h"
  44. #include "src/mod/ctcp.mod/ctcp.h"
  45. #include "src/mod/irc.mod/irc.h"
  46. #include <bdlib/src/Stream.h>
  47. #include <bdlib/src/String.h>
  48. #include <bdlib/src/Array.h>
  49. #include "server.h"
  50. #include <stdarg.h>
  51. int default_alines = 5; /* How many mode lines are assumed will work before throttling */
  52. bool floodless = 0; /* floodless iline? */
  53. int ctcp_mode;
  54. int serv = -1; /* sock # of server currently */
  55. int servidx = -1; /* idx of server */
  56. char newserver[121] = ""; /* new server? */
  57. port_t newserverport = 0; /* new server port? */
  58. char newserverpass[121] = ""; /* new server password? */
  59. static char serverpass[121] = "";
  60. static time_t trying_server; /* trying to connect to a server right now? */
  61. int curserv = 999; /* current position in server list: */
  62. port_t curservport = 0;
  63. rate_t flood_msg = { 5, 60 };
  64. rate_t flood_ctcp = { 3, 60 };
  65. char botuserhost[UHOSTLEN] = ""; /* bot's user@host (refreshed whenever the bot joins a channel) */
  66. /* may not be correct user@host BUT it's how the server sees it */
  67. char botuserip[UHOSTLEN] = ""; /* bot's user@host with the ip. */
  68. time_t release_time = 0;
  69. bool keepnick = 1; /* keep trying to regain my intended
  70. nickname? */
  71. static int nick_juped = 0; /* True if origbotname is juped(RPL437) (dw) (1 = RESV, 2 = NETSPLIT) */
  72. static int jnick_juped = 0; /* True if jupenick is juped (1 = RESV, 2 = NETSPLIT) */
  73. time_t tried_jupenick = 0;
  74. time_t tried_nick = 0;
  75. bool use_monitor = 0;
  76. static bool waiting_for_awake; /* set when i unidle myself, cleared when I get the response */
  77. time_t server_online = 0; /* server connection time */
  78. char botrealname[121] = "A deranged product of evil coders."; /* realname of bot */
  79. static interval_t server_timeout = 15; /* server timeout for connecting */
  80. static const interval_t stoned_timeout = 500;
  81. struct server_list *serverlist = NULL; /* old-style queue, still used by
  82. server list */
  83. interval_t cycle_time; /* cycle time till next server connect */
  84. port_t default_port = 6667; /* default IRC port */
  85. bool trigger_on_ignore; /* trigger bindings if user is ignored ? */
  86. int answer_ctcp = 1; /* answer how many stacked ctcp's ? */
  87. static bool resolvserv; /* in the process of resolving a server host */
  88. static time_t lastpingtime; /* IRCNet LAGmeter support -- drummer */
  89. static char stackablecmds[511] = "";
  90. static char stackable2cmds[511] = "";
  91. static egg_timeval_t last_time;
  92. static time_t connect_bursting = 0;
  93. static int real_msgburst = 0;
  94. static int real_msgrate = 0;
  95. static int flood_count = 0;
  96. static bool use_flood_count = 0;
  97. static egg_timeval_t flood_time = {0, 0};
  98. static bool use_penalties;
  99. static int use_fastdeq;
  100. size_t nick_len = 9; /* Maximal nick length allowed on the network. */
  101. char deaf_char = 0;
  102. bool in_deaf = 0;
  103. char callerid_char = 0;
  104. bool in_callerid = 0;
  105. bool have_cprivmsg = 0;
  106. bool have_cnotice = 0;
  107. static bool double_warned = 0;
  108. static void empty_msgq(void);
  109. static void disconnect_server(int, int);
  110. static void calc_penalty(char *, size_t);
  111. static bool fast_deq(int);
  112. static char *splitnicks(char **);
  113. static void msgq_clear(struct msgq_head *qh);
  114. static int stack_limit = 4;
  115. static bool replaying_cache = 0;
  116. /* New bind tables. */
  117. static bind_table_t *BT_raw = NULL, *BT_msg = NULL;
  118. bind_table_t *BT_ctcr = NULL, *BT_ctcp = NULL;
  119. // Ratbox is (5*8):30, ircd-seven is (5*8):20, try to not push th elimits.
  120. #define SERVER_CONNECT_BURST_TIME 18
  121. #define SERVER_CONNECT_BURST_RATE 5 * 7
  122. #include "servmsg.c"
  123. #define MAXPENALTY 10
  124. // If use_flood_count, don't bother with msgrate, otherwise use the user specified msgrate
  125. #define MSGRATE (use_flood_count ? DEQ_RATE : msgrate)
  126. /* Maximum messages to store in each queue. */
  127. static struct msgq_head mq, hq, modeq, aq, cacheq;
  128. static const struct {
  129. struct msgq_head* const q;
  130. const int idx;
  131. const char* name;
  132. const char pfx;
  133. const bool double_msg;
  134. const bool burst;
  135. const bool connect_burst;
  136. const size_t maxqmsg;
  137. } qdsc[5] = {
  138. { &modeq, DP_MODE, "MODE", 'm', 0, 1, 1, 300 },
  139. { &mq, DP_SERVER, "SERVER", 's', 0, 1, 1, 300 },
  140. { &hq, DP_HELP, "HELP", 'h', 0, 0, 0, 300 },
  141. { &aq, DP_PLAY, "PLAY", 'p', 1, 1, 0, 10000 },
  142. { &cacheq, DP_CACHE, "CACHE", 'c', 0, 0, 0, 1000 },
  143. };
  144. #define Q_MODE 0
  145. #define Q_SERVER 1
  146. #define Q_HELP 2
  147. #define Q_PLAY 3
  148. #define Q_CACHE 4
  149. static int burst;
  150. #include "cmdsserv.c"
  151. /*
  152. * Bot server queues
  153. */
  154. static bool burst_mode_ok(const char *msg, size_t len) {
  155. bd::String mode(msg, len);
  156. bd::Array<bd::String> list(mode.split(' '));
  157. if (list.length() == 2) return 1;
  158. if (list.length() == 3) {
  159. if (!strchr(CHANMETA, bd::String(list[1]).at(0))) return 1;
  160. else if (bd::String(list[2]).at(0) == 'b') return 1;
  161. }
  162. return 0;
  163. }
  164. // Hybrid/ratbox allows bursting 5*8 lines on connect until certain commands are sent, for up to 30 seconds
  165. /*
  166. BAD:
  167. JOIN 0
  168. MODE #chan b
  169. NICK
  170. PART
  171. KICK
  172. CPRIVMSG
  173. CNOTICE
  174. WHO 0/mask
  175. TIME
  176. TOPIC
  177. INVITE
  178. AWAY
  179. OPER
  180. OK:
  181. WHO *
  182. WHO !
  183. WHO #Chan
  184. WHO NICK
  185. */
  186. static bool burst_ok(const char* msg, size_t len) {
  187. if (strstr(msg, "JOIN 0") ||
  188. (strstr(msg, "MODE") && !burst_mode_ok(msg, len)) ||
  189. strstr(msg, "NICK") ||
  190. strstr(msg, "PRIVMSG") ||
  191. strstr(msg, "NOTICE") ||
  192. strstr(msg, "PART") ||
  193. strstr(msg, "KICK") ||
  194. strstr(msg, "INVITE") ||
  195. strstr(msg, "AWAY")) {
  196. sdprintf("BURST MODE VIOLATION!!!: %s\n", msg);
  197. return 0;
  198. }
  199. return 1;
  200. }
  201. /* Called periodically to shove out another queued item.
  202. *
  203. * 'mode' queue gets priority now.
  204. *
  205. * Most servers will allow 'busts' of upto 5 msgs, so let's put something
  206. * in to support flushing modeq a little faster if possible.
  207. * Will send upto 4 msgs from modeq, and then send 1 msg every time
  208. * it will *not* send anything from hq until the 'burst' value drops
  209. * down to 0 again (allowing a sudden mq flood to sneak through).
  210. *
  211. * ratbox:
  212. * Every msg sent is added to a count, every second this count decreases by 2.
  213. * Typical max count is 20, then excess flood is triggered.
  214. * So after 1 bursts:
  215. * Count = 5
  216. * Decaying by 1 every second
  217. */
  218. void deq_msg()
  219. {
  220. if (serv < 0)
  221. return;
  222. if (timeval_diff(&egg_timeval_now, &flood_time) >= 1000) {
  223. // Increase flood_count by 1 every msg, but decrease by 2 every second, use this to determine an acceptable burst rate
  224. if (flood_count > 1)
  225. flood_count -= 2;
  226. else if (flood_count == 1)
  227. flood_count = 0;
  228. flood_time.sec = egg_timeval_now.sec;
  229. flood_time.usec = egg_timeval_now.usec;
  230. }
  231. /* now < last_time tested 'cause clock adjustments could mess it up */
  232. if (timeval_diff(&egg_timeval_now, &last_time) >= MSGRATE || now < (last_time.sec - 90)) {
  233. last_time.sec = egg_timeval_now.sec;
  234. last_time.usec = egg_timeval_now.usec;
  235. if (burst > 0) {
  236. if (use_flood_count) {
  237. if (flood_count < 5)
  238. burst = 0;
  239. else if (flood_count < 10)
  240. burst -= 4;
  241. else if (flood_count < 13)
  242. burst -= 3;
  243. else if (flood_count < 15)
  244. burst -= 2;
  245. else
  246. --burst;
  247. if (burst < 0)
  248. burst = 0;
  249. } else
  250. --burst;
  251. }
  252. } else
  253. return;
  254. struct msgq *q = NULL;
  255. /* Send upto 'set msgburst' msgs to server if the *critical queue* has anything in it;
  256. * otherwise, dequeue and burst up to 'set msgburst' messages from the `normal' message
  257. * queue.
  258. */
  259. egg_timeval_t last_time_save = { last_time.sec, last_time.usec };
  260. bool bursted = 0;
  261. // -1 here to avoid DP_CACHE
  262. for(size_t nq = 0; nq < (sizeof(qdsc) / sizeof(qdsc[0])) - 1; ++nq) {
  263. while (qdsc[nq].q->head &&
  264. // If burstable queue and can burst, or not a burstable queue and not connect bursting
  265. ((qdsc[nq].burst && (burst < msgburst)) || (!qdsc[nq].burst && !connect_bursting)) &&
  266. ((last_time.sec - now) < MAXPENALTY)) {
  267. #ifdef not_implemented
  268. if (deq_kick(qdsc[nq].idx)) {
  269. ++burst;++flood_count;
  270. continue;
  271. }
  272. #endif
  273. if (fast_deq(nq))
  274. continue;
  275. write_to_server(qdsc[nq].q->head->msg, qdsc[nq].q->head->len);
  276. ++burst;++flood_count;
  277. if (debug_output)
  278. putlog(LOG_SRVOUT, "*", "[%c->] %s", qdsc[nq].pfx, qdsc[nq].q->head->msg);
  279. --(qdsc[nq].q->tot);
  280. calc_penalty(qdsc[nq].q->head->msg, qdsc[nq].q->head->len);
  281. q = qdsc[nq].q->head->next;
  282. free(qdsc[nq].q->head->msg);
  283. free(qdsc[nq].q->head);
  284. qdsc[nq].q->head = q;
  285. if (qdsc[nq].burst)
  286. bursted = 1;
  287. else // Help Queue does not burst, push out 1 line then go to next queue.
  288. break;
  289. }
  290. if (!qdsc[nq].q->head)
  291. qdsc[nq].q->last = NULL;
  292. }
  293. // Do this penalty calc here as it's dependant on burst/flood_count
  294. if (use_flood_count && !connect_bursting) {
  295. // The penalty includes a length-based penalty from calc_penalty
  296. last_time.sec -= (MSGRATE / 1000); // Remove normal msgrate
  297. // Add 150ms for each current burst
  298. last_time.usec += (150*burst) * 1000;
  299. // Add some penalty for each flood_count
  300. last_time.usec += (40*flood_count) * 1000;
  301. // Cap the penalty at 1800 and depent more on flood_count
  302. if (timeval_diff(&last_time, &last_time_save) > 1800) {
  303. last_time.sec = last_time_save.sec;
  304. last_time.usec = 1800 * 1000;
  305. }
  306. // If lagging, raise the penalty up to avoid TCP burst/excess flood
  307. if (server_lag > 5)
  308. last_time.sec += 2;
  309. #ifdef DEBUG
  310. if (timeval_diff(&last_time, &last_time_save))
  311. sdprintf("PENALTY (%d): %lims", flood_count, timeval_diff(&last_time, &last_time_save));
  312. #endif
  313. }
  314. #ifdef DEBUG
  315. else if (connect_bursting && bursted)
  316. sdprintf("BURSTING!!!!!\n");
  317. #endif
  318. }
  319. static void calc_penalty(char * msg, size_t len)
  320. {
  321. if (connect_bursting)
  322. return;
  323. char *cmd = NULL, *par1 = NULL, *par2 = NULL, *par3 = NULL;
  324. register int penalty, i, ii;
  325. cmd = newsplit(&msg);
  326. if (msg)
  327. i = strlen(msg);
  328. else
  329. i = strlen(cmd);
  330. if (!use_penalties) {
  331. // Add some penalty for large messages
  332. if (use_flood_count)
  333. last_time.usec += long(((double)i / 300.0) * (1000*1000));
  334. else
  335. last_time.usec += long(((double)i / 120.0) * (1000*1000));
  336. return;
  337. }
  338. last_time.sec -= (MSGRATE / 1000); // Remove normal msgrate
  339. penalty = (1 + i / 100);
  340. if (!strcasecmp(cmd, "KICK")) {
  341. par1 = newsplit(&msg); /* channel */
  342. par2 = newsplit(&msg); /* victim(s) */
  343. par3 = splitnicks(&par2);
  344. penalty++;
  345. while (strlen(par3) > 0) {
  346. par3 = splitnicks(&par2);
  347. penalty++;
  348. }
  349. ii = penalty;
  350. par3 = splitnicks(&par1);
  351. while (strlen(par1) > 0) {
  352. par3 = splitnicks(&par1);
  353. penalty += ii;
  354. }
  355. } else if (!strcasecmp(cmd, "MODE")) {
  356. i = 0;
  357. par1 = newsplit(&msg); /* channel */
  358. par2 = newsplit(&msg); /* mode(s) */
  359. if (!strlen(par2))
  360. i++;
  361. while (strlen(par2) > 0) {
  362. if (strchr("ntimps", par2[0]))
  363. i += 3;
  364. else if (!strchr("+-", par2[0]))
  365. i += 1;
  366. par2++;
  367. }
  368. while (strlen(msg) > 0) {
  369. newsplit(&msg);
  370. i += 2;
  371. }
  372. ii = 0;
  373. while (strlen(par1) > 0) {
  374. splitnicks(&par1);
  375. ii++;
  376. }
  377. penalty += (ii * i);
  378. } else if (!strcasecmp(cmd, "TOPIC")) {
  379. penalty++;
  380. par1 = newsplit(&msg); /* channel */
  381. par2 = newsplit(&msg); /* topic */
  382. if (strlen(par2) > 0) { /* topic manipulation => 2 penalty points */
  383. penalty += 2;
  384. par3 = splitnicks(&par1);
  385. while (strlen(par1) > 0) {
  386. par3 = splitnicks(&par1);
  387. penalty += 2;
  388. }
  389. }
  390. } else if (!strcasecmp(cmd, "PRIVMSG") ||
  391. !strcasecmp(cmd, "NOTICE")) {
  392. par1 = newsplit(&msg); /* channel(s)/nick(s) */
  393. /* Add one sec penalty for each recipient */
  394. while (strlen(par1) > 0) {
  395. splitnicks(&par1);
  396. penalty++;
  397. }
  398. } else if (!strcasecmp(cmd, "WHO")) {
  399. par1 = newsplit(&msg); /* masks */
  400. par2 = par1;
  401. while (strlen(par1) > 0) {
  402. par2 = splitnicks(&par1);
  403. if (strlen(par2) > 4) /* long WHO-masks receive less penalty */
  404. penalty += 3;
  405. else
  406. penalty += 5;
  407. }
  408. } else if (!strcasecmp(cmd, "AWAY")) {
  409. if (strlen(msg) > 0)
  410. penalty += 2;
  411. else
  412. penalty += 1;
  413. } else if (!strcasecmp(cmd, "INVITE")) {
  414. /* Successful invite receives 2 or 3 penalty points. Let's go
  415. * with the maximum.
  416. */
  417. penalty += 3;
  418. } else if (!strcasecmp(cmd, "JOIN")) {
  419. penalty += 2;
  420. } else if (!strcasecmp(cmd, "PART")) {
  421. penalty += 4;
  422. } else if (!strcasecmp(cmd, "VERSION")) {
  423. penalty += 2;
  424. } else if (!strcasecmp(cmd, "TIME")) {
  425. penalty += 2;
  426. } else if (!strcasecmp(cmd, "TRACE")) {
  427. penalty += 2;
  428. } else if (!strcasecmp(cmd, "NICK")) {
  429. penalty += 3;
  430. } else if (!strcasecmp(cmd, "ISON")) {
  431. penalty += 1;
  432. } else if (!strcasecmp(cmd, "WHOIS")) {
  433. penalty += 2;
  434. } else if (!strcasecmp(cmd, "DNS")) {
  435. penalty += 2;
  436. } else
  437. penalty++; /* just add standard-penalty */
  438. /* Shouldn't happen, but you never know... */
  439. if (penalty > 99)
  440. penalty = 99;
  441. if (penalty < 2) {
  442. putlog(LOG_SRVOUT, "*", "Penalty < 2sec, that's impossible!");
  443. penalty = 2;
  444. }
  445. if (debug_output && penalty != 0)
  446. putlog(LOG_SRVOUT, "*", "Adding penalty: %i", penalty);
  447. last_time.sec += penalty;
  448. }
  449. char *splitnicks(char **rest)
  450. {
  451. if (!rest)
  452. return *rest = "";
  453. register char *o = *rest, *r = NULL;
  454. while (*o == ' ')
  455. o++;
  456. r = o;
  457. while (*o && *o != ',')
  458. o++;
  459. if (*o)
  460. *o++ = 0;
  461. *rest = o;
  462. return r;
  463. }
  464. void replay_cache(int idx, bd::Stream* stream) {
  465. if (!cacheq.head) return;
  466. struct msgq *r = NULL;
  467. char *p_ptr = NULL, *p = NULL;
  468. replaying_cache = 1;
  469. for (r = cacheq.head; r; r = r->next) {
  470. if (stream) {
  471. bd::String buf;
  472. *stream << buf.printf(STR("+serv_cache %s\n"), r->msg);
  473. } else {
  474. //Create temporary buffer since server_activity may squash the buffer
  475. p_ptr = p = strdup(r->msg);
  476. server_activity(idx, p, r->len);
  477. free(p_ptr);
  478. }
  479. }
  480. replaying_cache = 0;
  481. }
  482. static bool fast_deq(int which)
  483. {
  484. if (!use_fastdeq)
  485. return 0;
  486. struct msgq_head *h = qdsc[which].q;
  487. struct msgq *m = NULL, *nm = NULL;
  488. char msgstr[511] = "", nextmsgstr[511] = "", tosend[511] = "", stackable[511] = "",
  489. *msg = NULL, *nextmsg = NULL, *cmd = NULL, *nextcmd = NULL, *to = NULL, *nextto = NULL, *stckbl = NULL;
  490. int cmd_count = 0;
  491. char stack_delim = ',';
  492. size_t len;
  493. bool found = 0, doit = 0;
  494. bd::String victims;
  495. m = h->head;
  496. strlcpy(msgstr, m->msg, sizeof msgstr);
  497. msg = msgstr;
  498. cmd = newsplit(&msg);
  499. if (use_fastdeq > 1) {
  500. strlcpy(stackable, stackablecmds, sizeof stackable);
  501. stckbl = stackable;
  502. while (strlen(stckbl) > 0)
  503. if (!strcasecmp(newsplit(&stckbl), cmd)) {
  504. found = 1;
  505. break;
  506. }
  507. /* If use_fastdeq is 2, only commands in the list should be stacked. */
  508. if (use_fastdeq == 2 && !found)
  509. return 0;
  510. /* If use_fastdeq is 3, only commands that are _not_ in the list
  511. * should be stacked.
  512. */
  513. if (use_fastdeq == 3 && found)
  514. return 0;
  515. /* we check for the stacking method (default=1) */
  516. strlcpy(stackable, stackable2cmds, sizeof stackable);
  517. stckbl = stackable;
  518. while (strlen(stckbl) > 0)
  519. if (!strcasecmp(newsplit(&stckbl), cmd)) {
  520. stack_delim = ' ';
  521. break;
  522. }
  523. }
  524. to = newsplit(&msg);
  525. len = strlen(to);
  526. victims = to;
  527. while (m) {
  528. nm = m->next;
  529. if (!nm)
  530. break;
  531. strlcpy(nextmsgstr, nm->msg, sizeof nextmsgstr);
  532. nextmsg = nextmsgstr;
  533. nextcmd = newsplit(&nextmsg);
  534. nextto = newsplit(&nextmsg);
  535. len = strlen(nextto);
  536. if ( strcmp(to, nextto) /* we don't stack to the same recipients */
  537. && !strcmp(cmd, nextcmd) && !strcmp(msg, nextmsg)
  538. && ((strlen(cmd) + victims.length() + strlen(nextto)
  539. + strlen(msg) + 2) < 510)
  540. && (!stack_limit || cmd_count < stack_limit - 1)) {
  541. ++cmd_count;
  542. victims += stack_delim + nextto;
  543. doit = 1;
  544. m->next = nm->next;
  545. if (!nm->next)
  546. h->last = m;
  547. free(nm->msg);
  548. free(nm);
  549. --(h->tot);
  550. } else
  551. m = m->next;
  552. }
  553. if (doit) {
  554. len = simple_snprintf(tosend, sizeof(tosend), "%s %s %s", cmd, victims.c_str(), msg);
  555. write_to_server(tosend, len);
  556. ++burst;++flood_count;
  557. m = h->head->next;
  558. free(h->head->msg);
  559. free(h->head);
  560. h->head = m;
  561. if (!h->head)
  562. h->last = 0;
  563. --(h->tot);
  564. if (debug_output)
  565. putlog(LOG_SRVOUT, "*", "[%c=>] %s", qdsc[which].pfx, tosend);
  566. calc_penalty(tosend, len);
  567. return 1;
  568. }
  569. return 0;
  570. }
  571. /* Clean out the msg queues (like when changing servers).
  572. */
  573. static void empty_msgq()
  574. {
  575. for (size_t i = 0; i < (sizeof(qdsc) / sizeof(qdsc[0])); ++i)
  576. msgq_clear(qdsc[i].q);
  577. burst = 0;
  578. flood_count = 0;
  579. flood_time.sec = flood_time.usec = 0;
  580. }
  581. /* Use when sending msgs... will spread them out so there's no flooding.
  582. */
  583. void queue_server(int which, char *buf, int len)
  584. {
  585. /* Don't even BOTHER if there's no server online. */
  586. if (serv < 0)
  587. return;
  588. // If connect bursting, hold off any commands which would end the gracetime (flood_endgrace)
  589. if (connect_bursting && (which == DP_MODE || which == DP_MODE_NEXT || which == DP_SERVER || which == DP_SERVER_NEXT)) {
  590. if (!burst_ok(buf, len))
  591. which = DP_HELP;
  592. }
  593. int qnext = 0;
  594. int which_q = 0;
  595. switch (which) {
  596. case DP_MODE_NEXT:
  597. qnext = 1;
  598. case DP_MODE:
  599. which_q = Q_MODE;
  600. break;
  601. case DP_SERVER_NEXT:
  602. qnext = 1;
  603. case DP_SERVER:
  604. which_q = Q_SERVER;
  605. break;
  606. case DP_HELP_NEXT:
  607. qnext = 1;
  608. case DP_HELP:
  609. which_q = Q_HELP;
  610. break;
  611. case DP_PLAY:
  612. which_q = Q_PLAY;
  613. break;
  614. case DP_CACHE:
  615. which_q = Q_CACHE;
  616. break;
  617. default:
  618. putlog(LOG_MISC, "*", "!!! queuing unknown type to server!!");
  619. return;
  620. }
  621. struct msgq_head *h = qdsc[which_q].q;
  622. if (h->tot < qdsc[which_q].maxqmsg) {
  623. /* Don't queue msg if it's already queued? */
  624. if (!qdsc[which_q].double_msg) {
  625. for (struct msgq* tq = qdsc[which_q].q->head; tq; tq = tq->next) {
  626. if (!strcasecmp(tq->msg, buf)) {
  627. if (!double_warned) {
  628. if (buf[len - 1] == '\n')
  629. buf[len - 1] = 0;
  630. putlog(LOG_DEBUG, "*", "msg already queued. skipping: %s", buf);
  631. double_warned = 1;
  632. }
  633. return;
  634. }
  635. }
  636. }
  637. struct msgq *q = (struct msgq *) my_calloc(1, sizeof(struct msgq));
  638. if (qnext)
  639. q->next = h->head;
  640. else
  641. q->next = NULL;
  642. if (h->head) {
  643. if (!qnext)
  644. h->last->next = q;
  645. } else
  646. h->head = q;
  647. if (qnext)
  648. h->head = q;
  649. h->last = q;
  650. q->len = len;
  651. q->msg = (char *) my_calloc(1, len + 1);
  652. strlcpy(q->msg, buf, len + 1);
  653. h->tot++;
  654. h->warned = 0;
  655. double_warned = 0;
  656. } else {
  657. if (!h->warned)
  658. putlog(LOG_MISC, "*", "!!! OVER MAXIMUM %s QUEUE", qdsc[which_q].name);
  659. h->warned = 1;
  660. }
  661. if (debug_output && !h->warned)
  662. putlog(LOG_SRVOUT, "@", "[%s%c] %s", qnext ? "!!" : "!", qdsc[which_q].pfx, buf);
  663. /* Try flushing immediately */
  664. deq_msg();
  665. }
  666. /* Add a new server to the server_list.
  667. */
  668. void add_server(char *ss)
  669. {
  670. struct server_list *x = NULL, *z = NULL;
  671. char *p = NULL, *q = NULL;
  672. for (z = serverlist; z && z->next; z = z->next)
  673. ;
  674. while (ss) {
  675. p = strchr(ss, ',');
  676. if (p)
  677. *p++ = 0;
  678. x = (struct server_list *) my_calloc(1, sizeof(struct server_list));
  679. x->next = 0;
  680. x->port = 0;
  681. if (z)
  682. z->next = x;
  683. else
  684. serverlist = x;
  685. z = x;
  686. q = strchr(ss, ':');
  687. if (!q) {
  688. x->pass = 0;
  689. x->name = strdup(ss);
  690. } else {
  691. #ifdef USE_IPV6
  692. if (ss[0] == '[') {
  693. ++ss;
  694. q = strchr(ss, ']');
  695. *q++ = 0; /* intentional */
  696. }
  697. #endif /* USE_IPV6 */
  698. *q++ = 0;
  699. x->name = (char *) my_calloc(1, q - ss);
  700. strlcpy(x->name, ss, q - ss);
  701. ss = q;
  702. q = strchr(ss, ':');
  703. if (!q) {
  704. x->pass = 0;
  705. } else {
  706. *q++ = 0;
  707. x->pass = strdup(q);
  708. }
  709. if (!x->port) {
  710. x->port = atoi(ss);
  711. }
  712. }
  713. ss = p;
  714. }
  715. }
  716. /* Clear out the given server_list.
  717. */
  718. void clearq(struct server_list *xx)
  719. {
  720. struct server_list *x = NULL;
  721. while (xx) {
  722. x = xx->next;
  723. if (xx->name)
  724. free(xx->name);
  725. if (xx->pass)
  726. free(xx->pass);
  727. free(xx);
  728. xx = x;
  729. }
  730. }
  731. /* Set botserver to the next available server.
  732. *
  733. * -> if (*ptr == -1) then jump to that particular server
  734. */
  735. void next_server(int *ptr, char *servname, port_t *port, char *pass)
  736. {
  737. struct server_list *x = serverlist;
  738. if (x == NULL)
  739. return;
  740. int i = 0;
  741. /* -1 --> Go to specified server */
  742. if (*ptr == (-1)) {
  743. for (; x; x = x->next) {
  744. if (x->port == *port) {
  745. if (!strcasecmp(x->name, servname)) {
  746. *ptr = i;
  747. return;
  748. }
  749. }
  750. i++;
  751. }
  752. /* Gotta add it: */
  753. x = (struct server_list *) my_calloc(1, sizeof(struct server_list));
  754. x->next = 0;
  755. x->name = strdup(servname);
  756. x->port = *port ? *port : default_port;
  757. if (pass && pass[0]) {
  758. x->pass = strdup(pass);
  759. } else
  760. x->pass = NULL;
  761. list_append((struct list_type **) (&serverlist), (struct list_type *) x);
  762. *ptr = i;
  763. return;
  764. }
  765. /* Find where i am and boogie */
  766. i = (*ptr);
  767. while (i > 0 && x != NULL) {
  768. x = x->next;
  769. i--;
  770. }
  771. if (x != NULL) {
  772. x = x->next;
  773. (*ptr)++;
  774. } /* Go to next server */
  775. if (x == NULL) {
  776. x = serverlist;
  777. *ptr = 0;
  778. } /* Start over at the beginning */
  779. strcpy(servname, x->name);
  780. *port = x->port ? x->port : default_port;
  781. if (x->pass)
  782. strcpy(pass, x->pass);
  783. else
  784. pass[0] = 0;
  785. }
  786. /*
  787. * CTCP DCC CHAT functions
  788. */
  789. static int sanitycheck_dcc(char *nick, char *from, char *ipaddy, char *port)
  790. {
  791. /* According to the latest RFC, the clients SHOULD be able to handle
  792. * DNS names that are up to 255 characters long. This is not broken.
  793. */
  794. char badaddress[16];
  795. in_addr_t ip = my_atoul(ipaddy);
  796. int prt = atoi(port);
  797. if (prt < 1) {
  798. putlog(LOG_MISC, "*", "ALERT: (%s!%s) specified an impossible port of %u!",
  799. nick, from, prt);
  800. return 0;
  801. }
  802. simple_snprintf(badaddress, sizeof(badaddress), "%u.%u.%u.%u", (ip >> 24) & 0xff, (ip >> 16) & 0xff,
  803. (ip >> 8) & 0xff, ip & 0xff);
  804. if (ip < (1 << 24)) {
  805. putlog(LOG_MISC, "*", "ALERT: (%s!%s) specified an impossible IP of %s!",
  806. nick, from, badaddress);
  807. return 0;
  808. }
  809. return 1;
  810. }
  811. static void dcc_chat_hostresolved(int);
  812. /* This only handles CHAT requests, otherwise it's handled in filesys.
  813. */
  814. static int ctcp_DCC_CHAT(char *nick, char *from, struct userrec *u, char *object, char *keyword, char *text)
  815. {
  816. if (!ischanhub())
  817. return BIND_RET_LOG;
  818. char *action = NULL, *param = NULL, *ip = NULL, *prt = NULL;
  819. action = newsplit(&text);
  820. param = newsplit(&text);
  821. ip = newsplit(&text);
  822. prt = newsplit(&text);
  823. if (strcasecmp(action, "CHAT") || strcasecmp(object, botname) || !u)
  824. return BIND_RET_LOG;
  825. int i;
  826. bool ok = 1;
  827. struct flag_record fr = {FR_GLOBAL | FR_CHAN | FR_ANYWH, 0, 0, 0 };
  828. get_user_flagrec(u, &fr, NULL);
  829. if (ischanhub() && !glob_chuba(fr))
  830. ok = 0;
  831. if (dcc_total == max_dcc) {
  832. putlog(LOG_MISC, "*", "DCC connections full: %s %s (%s!%s)", "CHAT", param, nick, from);
  833. } else if (!ok) {
  834. putlog(LOG_MISC, "*", "%s: %s!%s", ischanhub() ? "Refused DCC chat (no access)" : "Refused DCC chat (I'm not a chathub (+c))", nick, from);
  835. } else if (u_pass_match(u, "-")) {
  836. putlog(LOG_MISC, "*", "%s: %s!%s", "Refused DCC chat (no password)", nick, from);
  837. } else if (atoi(prt) < 1024 || atoi(prt) > 65535) {
  838. /* Invalid port */
  839. putlog(LOG_MISC, "*", "%s: CHAT (%s!%s)", "DCC invalid port", nick, from);
  840. } else {
  841. if (!sanitycheck_dcc(nick, from, ip, prt))
  842. return 1;
  843. i = new_dcc(&DCC_CHAT_PASS, sizeof(struct chat_info));
  844. if (i < 0) {
  845. putlog(LOG_MISC, "*", "DCC connection: CHAT (%s!%s)", nick, ip);
  846. return BIND_RET_BREAK;
  847. }
  848. dcc[i].addr = my_atoul(ip);
  849. dcc[i].port = atoi(prt);
  850. dcc[i].sock = -1;
  851. strlcpy(dcc[i].nick, u->handle, sizeof(dcc[i].nick));
  852. strlcpy(dcc[i].host, from, sizeof(dcc[i].host));
  853. dcc[i].timeval = now;
  854. dcc[i].user = u;
  855. dcc_chat_hostresolved(i);
  856. // egg_dns_reverse(dcc[i].addr, 20, dcc_chat_dns_callback, (void *) i);
  857. }
  858. return BIND_RET_BREAK;
  859. }
  860. //static void tandem_relay_dns_callback(void *client_data, const char *host, char **ips)
  861. static void dcc_chat_hostresolved(int i)
  862. {
  863. char buf[512] = "", ip[512] = "";
  864. struct flag_record fr = {FR_GLOBAL | FR_CHAN | FR_ANYWH, 0, 0, 0 };
  865. simple_snprintf(buf, sizeof buf, "%d", dcc[i].port);
  866. simple_snprintf(ip, sizeof ip, "%lu", (0xffffffff & ((long) dcc[i].addr)));
  867. #ifdef USE_IPV6
  868. dcc[i].sock = getsock(0, AF_INET);
  869. #else
  870. dcc[i].sock = getsock(0);
  871. #endif /* USE_IPV6 */
  872. int open_telnet_return = 0;
  873. if (dcc[i].sock < 0 || (open_telnet_return = open_telnet_dcc(dcc[i].sock, ip, buf)) < 0) {
  874. if (open_telnet_return == -1)
  875. dcc[i].sock = -1;
  876. strlcpy(buf, strerror(errno), sizeof(buf));
  877. putlog(LOG_MISC, "*", "%s: CHAT (%s!%s)", "DCC connection failed", dcc[i].nick, dcc[i].host);
  878. putlog(LOG_MISC, "*", " (%s)", buf);
  879. if (dcc[i].sock != -1)
  880. killsock(dcc[i].sock);
  881. lostdcc(i);
  882. } else {
  883. bool ok = 1;
  884. dcc[i].status = STAT_ECHO;
  885. get_user_flagrec(dcc[i].user, &fr, NULL);
  886. if (ischanhub() && !glob_chuba(fr))
  887. ok = 0;
  888. if (ok)
  889. dcc[i].status |= STAT_PARTY;
  890. struct chat_info dummy;
  891. strlcpy(dcc[i].u.chat->con_chan, (chanset) ? chanset->dname : "*", sizeof(dummy.con_chan));
  892. dcc[i].timeval = now;
  893. /* Ok, we're satisfied with them now: attempt the connect */
  894. putlog(LOG_MISC, "*", "DCC connection: CHAT (%s!%s)", dcc[i].nick, dcc[i].host);
  895. dprintf(i, "%s\n", response(RES_USERNAME));
  896. }
  897. return;
  898. }
  899. /*
  900. * Server timer functions
  901. */
  902. static void end_burstmode() {
  903. if (connect_bursting) {
  904. connect_bursting = 0;
  905. msgburst = real_msgburst;
  906. msgrate = real_msgrate;
  907. }
  908. }
  909. static void server_secondly()
  910. {
  911. if (cycle_time)
  912. --cycle_time;
  913. if (!resolvserv && serv < 0 && !trying_server)
  914. connect_server();
  915. if (server_online) {
  916. if (keepnick && !use_monitor) {
  917. static int ison_cnt = 0;
  918. if (ison_time == 0) //If someone sets this to 0, all hell will break loose!
  919. ison_time = 10;
  920. if (ison_cnt >= ison_time) {
  921. server_send_ison();
  922. ison_cnt = 0;
  923. } else
  924. ++ison_cnt;
  925. } else if (!keepnick && ((now - release_time) >= RELEASE_TIME)) {
  926. release_time = 0;
  927. keepnick = 1;
  928. nick_available(1, 0);
  929. }
  930. if (!loading) {
  931. static int cnt_10 = 0;
  932. // Every 10 seconds
  933. if (cnt_10 == 9) {
  934. // Ensure that +D/+f are not conflicting
  935. if (deaf_char) {
  936. // +f or auth bots in used need to see channel chatter.
  937. bool need_chatter = doflood(NULL) || (Auth::ht_host.size() && auth_chan && strlen(auth_prefix));
  938. // In +D but am +f, need to -D
  939. if (in_deaf && (need_chatter || !use_deaf)) {
  940. dprintf(DP_SERVER, "MODE %s -%c\n", botname, deaf_char);
  941. in_deaf = 0;
  942. } else if (!in_deaf && use_deaf && !need_chatter) {
  943. // Not +D but should be, probably had +f removed.
  944. dprintf(DP_SERVER, "MODE %s +%c\n", botname, deaf_char);
  945. in_deaf = 1;
  946. }
  947. }
  948. cnt_10 = 0;
  949. } else
  950. ++cnt_10;
  951. }
  952. if (connect_bursting && (now - SERVER_CONNECT_BURST_TIME) >= connect_bursting) {
  953. end_burstmode();
  954. putlog(LOG_DEBUG, "*", "Ending server burst mode");
  955. }
  956. }
  957. }
  958. static void server_check_lag()
  959. {
  960. if (server_online && !waiting_for_awake && !trying_server) {
  961. dprintf(DP_MODE_NEXT, "PING :%li\n", (long)now);
  962. lastpingtime = now;
  963. waiting_for_awake = 1;
  964. } else if (servidx != -1 && waiting_for_awake && ((now - lastpingtime) >= stoned_timeout)) {
  965. // Not checking server_online as this will handle connect timeouts as well where the connect() works, but the server gets stoned afterwards
  966. disconnect_server(servidx, DO_LOST);
  967. putlog(LOG_SERV, "*", "Server got stoned; jumping...");
  968. }
  969. }
  970. static void server_minutely()
  971. {
  972. if (server_online) {
  973. // Ratbox sets a nick_delay (default:15min) timer when a nick splits off to prevent collisions,
  974. // We must check periodically to see if the local server has unjuped our wanted nicks.
  975. if (keepnick && (jnick_juped == 2 || nick_juped == 2)) {
  976. nick_available(1, 1);
  977. }
  978. }
  979. }
  980. void server_die()
  981. {
  982. cycle_time = 100;
  983. if (server_online) {
  984. dprintf(-serv, "QUIT :%s\n", quit_msg[0] ? quit_msg : "");
  985. sleep(2); /* Give the server time to understand */
  986. }
  987. nuke_server(NULL);
  988. }
  989. /* A report on the module status.
  990. */
  991. void server_report(int idx, int details)
  992. {
  993. char s1[64] = "", s[128] = "";
  994. if (server_online) {
  995. dprintf(idx, " Online as: %s%s%s (%s)\n", botname,
  996. botuserhost[0] ? "!" : "", botuserhost[0] ? botuserhost : "",
  997. botrealname);
  998. dprintf(idx, " My userip: %s!%s\n", botname, botuserip);
  999. if (nick_juped)
  1000. dprintf(idx, " NICK IS JUPED: %s %s\n", origbotname, keepnick ? "(trying)" : "");
  1001. if (jnick_juped)
  1002. dprintf(idx, " JUPENICK IS JUPED: %s %s\n", jupenick, keepnick ? "(trying)" : "");
  1003. nick_juped = jnick_juped = 0;
  1004. daysdur(now, server_online, s1, sizeof(s1));
  1005. simple_snprintf(s, sizeof s, "(connected %s)", s1);
  1006. if (server_lag && !waiting_for_awake) {
  1007. if (server_lag == (-1))
  1008. simple_snprintf(s1, sizeof s1, " (bad pong replies)");
  1009. else
  1010. simple_snprintf(s1, sizeof s1, " (lag: %ds)", server_lag);
  1011. strlcat(s, s1, sizeof(s));
  1012. }
  1013. }
  1014. if ((trying_server || server_online) && (servidx != (-1))) {
  1015. dprintf(idx, " Server %s:%d %s\n", dcc[servidx].host, dcc[servidx].port,
  1016. trying_server ? "(trying)" : s);
  1017. } else
  1018. dprintf(idx, " No server currently.\n");
  1019. if (server_online)
  1020. dprintf(idx, " burst: %d flood_count: %d\n", burst, flood_count);
  1021. for (size_t i = 0; i < (sizeof(qdsc) / sizeof(qdsc[0])); ++i) {
  1022. if (qdsc[i].q->tot)
  1023. dprintf(idx, " %s queue is at %d%%, %d msgs\n",
  1024. qdsc[i].name,
  1025. (int) ((float) (qdsc[i].q->tot * 100.0) / (float) qdsc[i].maxqmsg),
  1026. (int) qdsc[i].q->tot);
  1027. }
  1028. if (details) {
  1029. dprintf(idx, " Flood is: %d msg/%ds, %d ctcp/%ds\n",
  1030. flood_msg.count, flood_msg.time, flood_ctcp.count, flood_ctcp.time);
  1031. }
  1032. }
  1033. static void msgq_clear(struct msgq_head *qh)
  1034. {
  1035. register struct msgq *qq = NULL;
  1036. for (register struct msgq *q = qh->head; q; q = qq) {
  1037. qq = q->next;
  1038. free(q->msg);
  1039. free(q);
  1040. }
  1041. qh->head = qh->last = NULL;
  1042. qh->tot = qh->warned = 0;
  1043. }
  1044. static cmd_t my_ctcps[] =
  1045. {
  1046. {"DCC", "", (Function) ctcp_DCC_CHAT, "server:DCC", LEAF},
  1047. {NULL, NULL, NULL, NULL, 0}
  1048. };
  1049. void server_init()
  1050. {
  1051. strlcpy(botrealname, "A deranged product of evil coders", sizeof(botrealname));
  1052. /*
  1053. * Init of all the variables *must* be done in _start rather than
  1054. * globally.
  1055. */
  1056. BT_msg = bind_table_add("msg", 4, "ssUs", MATCH_FLAGS, 0);
  1057. BT_raw = bind_table_add("raw", 2, "ss", 0, BIND_STACKABLE);
  1058. BT_ctcr = bind_table_add("ctcr", 6, "ssUsss", 0, BIND_STACKABLE);
  1059. BT_ctcp = bind_table_add("ctcp", 6, "ssUsss", 0, BIND_STACKABLE);
  1060. add_builtins("raw", my_raw_binds);
  1061. add_builtins("dcc", C_dcc_serv);
  1062. add_builtins("ctcp", my_ctcps);
  1063. egg_timeval_t howlong;
  1064. howlong.sec = 0;
  1065. howlong.usec = DEQ_RATE * 1000;
  1066. timer_create_repeater(&howlong, "server_queue", (Function) deq_msg);
  1067. timer_create_secs(1, "server_secondly", (Function) server_secondly);
  1068. timer_create_secs(30, "server_check_lag", (Function) server_check_lag);
  1069. timer_create_secs(60, "server_minutely", (Function) server_minutely);
  1070. // timer_create_secs(60, "minutely_checks", (Function) minutely_checks);
  1071. }