main.c 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984
  1. /*
  2. * main.c -- handles:
  3. * core event handling
  4. * signal handling
  5. * command line arguments
  6. * context and assert debugging
  7. *
  8. */
  9. #include "main.h"
  10. #include "build.h"
  11. #include <libgen.h>
  12. #include <fcntl.h>
  13. #include <time.h>
  14. #include <errno.h>
  15. #include <signal.h>
  16. #include <netdb.h>
  17. #include <setjmp.h>
  18. #include <unistd.h>
  19. #ifdef HAVE_UNAME
  20. #include <sys/utsname.h>
  21. #endif
  22. #ifdef STOP_UAC /* osf/1 complains a lot */
  23. #include <sys/sysinfo.h>
  24. #define UAC_NOPRINT 0x00000001 /* Don't report unaligned fixups */
  25. #endif
  26. /* Some systems have a working sys/wait.h even though configure will
  27. * decide it's not bsd compatable. Oh well.
  28. */
  29. #include <sys/file.h>
  30. #include <sys/stat.h>
  31. #ifdef S_ANTITRACE
  32. #include <sys/ptrace.h>
  33. #include <sys/wait.h>
  34. #endif
  35. #include <sys/types.h>
  36. #include <pwd.h>
  37. #include "chan.h"
  38. #include "modules.h"
  39. #include "tandem.h"
  40. #include "bg.h"
  41. #ifdef CYGWIN_HACKS
  42. #include <windows.h>
  43. #endif
  44. #ifndef _POSIX_SOURCE
  45. /* Solaris needs this */
  46. #define _POSIX_SOURCE 1
  47. #endif
  48. #ifdef HUB
  49. int hub = 1;
  50. int leaf = 0;
  51. #else
  52. int hub = 0;
  53. int leaf = 1;
  54. #endif
  55. int localhub = 1; //we set this to 0 if we have -c, later.
  56. extern char origbotname[], userfile[], botnetnick[], packname[],
  57. shellhash[], myip6[], myip[], hostname[],
  58. hostname6[], natip[];
  59. extern int dcc_total, conmask, cache_hit, cache_miss,
  60. fork_interval,
  61. local_fork_interval;
  62. extern struct dcc_t *dcc;
  63. extern struct userrec *userlist;
  64. extern struct chanset_t *chanset;
  65. extern Tcl_Interp *interp;
  66. extern tcl_timer_t *timer,
  67. *utimer;
  68. extern jmp_buf alarmret;
  69. int role;
  70. int loading = 0;
  71. const time_t buildts = CVSBUILD; /* build timestamp (UTC) */
  72. const char egg_version[1024] = "1.0.11";
  73. const int egg_numver = 1001100;
  74. time_t lastfork=0;
  75. #ifdef HUB
  76. int my_port;
  77. #endif
  78. char notify_new[121] = ""; /* Person to send a note to for new users */
  79. int default_flags = 0; /* Default user flags and */
  80. int default_uflags = 0; /* Default userdefinied flags for people
  81. who say 'hello' or for .adduser */
  82. int backgrd = 1; /* Run in the background? */
  83. int con_chan = 0; /* Foreground: constantly display channel
  84. stats? */
  85. uid_t myuid;
  86. int term_z = 0; /* Foreground: use the terminal as a party
  87. line? */
  88. int checktrace = 1; /* Check for trace when starting up? */
  89. int pscloak = 1;
  90. int updating = 0; /* this is set when the binary is called from itself. */
  91. char tempdir[DIRMAX] = "";
  92. char lock_file[40] = "";
  93. char *binname;
  94. int sdebug = 0; /* enable debug output? */
  95. char textdir[121] = ""; /* Directory for text files that get dumped */
  96. time_t online_since; /* Unix-time that the bot loaded up */
  97. char owner[121] = ""; /* Permanent owner(s) of the bot */
  98. char pid_file[DIRMAX]; /* Name of the file for the pid to be
  99. stored in */
  100. int save_users_at = 0; /* How many minutes past the hour to
  101. save the userfile? */
  102. int notify_users_at = 0; /* How many minutes past the hour to
  103. notify users of notes? */
  104. char version[81]; /* Version info (long form) */
  105. char ver[41]; /* Version info (short form) */
  106. int use_stderr = 1; /* Send stuff to stderr instead of logfiles? */
  107. int do_restart = 0; /* .restart has been called, restart asap */
  108. int resolve_timeout = 10; /* hostname/address lookup timeout */
  109. char quit_msg[1024]; /* quit message */
  110. time_t now; /* duh, now :) */
  111. extern struct cfg_entry CFG_FORKINTERVAL;
  112. #define fork_interval atoi( CFG_FORKINTERVAL.ldata ? CFG_FORKINTERVAL.ldata : CFG_FORKINTERVAL.gdata ? CFG_FORKINTERVAL.gdata : "0")
  113. unsigned char md5out[MD5_HASH_LENGTH + 1];
  114. char md5string[MD5_HASH_LENGTH + 1];
  115. /* Traffic stats
  116. */
  117. unsigned long otraffic_irc = 0;
  118. unsigned long otraffic_irc_today = 0;
  119. unsigned long otraffic_bn = 0;
  120. unsigned long otraffic_bn_today = 0;
  121. unsigned long otraffic_dcc = 0;
  122. unsigned long otraffic_dcc_today = 0;
  123. unsigned long otraffic_filesys = 0;
  124. unsigned long otraffic_filesys_today = 0;
  125. unsigned long otraffic_trans = 0;
  126. unsigned long otraffic_trans_today = 0;
  127. unsigned long otraffic_unknown = 0;
  128. unsigned long otraffic_unknown_today = 0;
  129. unsigned long itraffic_irc = 0;
  130. unsigned long itraffic_irc_today = 0;
  131. unsigned long itraffic_bn = 0;
  132. unsigned long itraffic_bn_today = 0;
  133. unsigned long itraffic_dcc = 0;
  134. unsigned long itraffic_dcc_today = 0;
  135. unsigned long itraffic_trans = 0;
  136. unsigned long itraffic_trans_today = 0;
  137. unsigned long itraffic_unknown = 0;
  138. unsigned long itraffic_unknown_today = 0;
  139. #ifdef DEBUG_CONTEXT
  140. /* Context storage for fatal crashes */
  141. char cx_file[16][30];
  142. char cx_note[16][256];
  143. int cx_line[16];
  144. int cx_ptr = 0;
  145. #endif
  146. void fatal(const char *s, int recoverable)
  147. {
  148. int i;
  149. #ifdef LEAF
  150. module_entry *me;
  151. if ((me = module_find("server", 0, 0))) {
  152. Function *func = me->funcs;
  153. (func[SERVER_NUKESERVER]) (s);
  154. }
  155. #endif /* LEAF */
  156. if (s[0])
  157. putlog(LOG_MISC, "*", "* %s", s);
  158. /* flushlogs(); */
  159. for (i = 0; i < dcc_total; i++) {
  160. if (dcc[i].sock >= 0)
  161. killsock(dcc[i].sock);
  162. #ifdef HAVE_SSL
  163. ssl_cleanup();
  164. #endif /* HAVE_SSL */
  165. }
  166. if (!recoverable) {
  167. unlink(pid_file);
  168. bg_send_quit(BG_ABORT);
  169. exit(1);
  170. }
  171. }
  172. int expmem_chanprog(), expmem_users(), expmem_config(), expmem_misc(), expmem_dccutil(),
  173. expmem_botnet(), expmem_tcl(), expmem_tclhash(), expmem_net(), expmem_auth(),
  174. expmem_modules(int), expmem_tcldcc(),
  175. expmem_tclmisc();
  176. /* For mem.c : calculate memory we SHOULD be using
  177. */
  178. int expected_memory(void)
  179. {
  180. int tot;
  181. tot = expmem_chanprog() + expmem_users() + expmem_config() + expmem_misc() +
  182. expmem_dccutil() + expmem_botnet() + expmem_tcl() + expmem_tclhash() +
  183. expmem_net() + expmem_modules(0) + expmem_tcldcc() + expmem_auth() +
  184. expmem_tclmisc();
  185. return tot;
  186. }
  187. static void check_expired_dcc()
  188. {
  189. int i;
  190. for (i = 0; i < dcc_total; i++)
  191. if (dcc[i].type && dcc[i].type->timeout_val &&
  192. ((now - dcc[i].timeval) > *(dcc[i].type->timeout_val))) {
  193. if (dcc[i].type->timeout)
  194. dcc[i].type->timeout(i);
  195. else if (dcc[i].type->eof)
  196. dcc[i].type->eof(i);
  197. else
  198. continue;
  199. /* Only timeout 1 socket per cycle, too risky for more */
  200. return;
  201. }
  202. }
  203. #ifdef DEBUG_CONTEXT
  204. static int nested_debug = 0;
  205. void write_debug()
  206. {
  207. int x;
  208. char s[25], tmpout[150];
  209. int y;
  210. if (nested_debug) {
  211. /* Yoicks, if we have this there's serious trouble!
  212. * All of these are pretty reliable, so we'll try these.
  213. *
  214. * NOTE: dont try and display context-notes in here, it's
  215. * _not_ safe <cybah>
  216. */
  217. x = creat("DEBUG.DEBUG", 0600);
  218. setsock(x, SOCK_NONSOCK);
  219. if (x >= 0) {
  220. strncpyz(s, ctime(&now), sizeof s);
  221. dprintf(-x, STR("Debug (%s) written %s\n"), ver, s);
  222. dprintf(-x, STR("Context: "));
  223. cx_ptr = cx_ptr & 15;
  224. for (y = ((cx_ptr + 1) & 15); y != cx_ptr; y = ((y + 1) & 15))
  225. dprintf(-x, "%s/%d,\n ", cx_file[y], cx_line[y]);
  226. dprintf(-x, "%s/%d\n\n", cx_file[y], cx_line[y]);
  227. killsock(x);
  228. close(x);
  229. }
  230. bg_send_quit(BG_ABORT);
  231. exit(1); /* Dont even try & tell people about, that may
  232. have caused the fault last time. */
  233. } else
  234. nested_debug = 1;
  235. egg_snprintf(tmpout, sizeof tmpout, "* Last 3 contexts: %s/%d [%s], %s/%d [%s], %s/%d [%s]",
  236. cx_file[cx_ptr-2], cx_line[cx_ptr-2], cx_note[cx_ptr-2][0] ? cx_note[cx_ptr-2] : "",
  237. cx_file[cx_ptr-1], cx_line[cx_ptr-1], cx_note[cx_ptr-1][0] ? cx_note[cx_ptr-1] : "",
  238. cx_file[cx_ptr], cx_line[cx_ptr], cx_note[cx_ptr][0] ? cx_note[cx_ptr] : "");
  239. putlog(LOG_MISC, "*", "%s", tmpout);
  240. printf("%s\n", tmpout);
  241. x = creat("DEBUG", 0600);
  242. setsock(x, SOCK_NONSOCK);
  243. if (x < 0) {
  244. putlog(LOG_MISC, "*", "* Failed to write DEBUG");
  245. } else {
  246. char date[80];
  247. strncpyz(s, ctime(&now), sizeof s);
  248. dprintf(-x, "Debug (%s) written %s\n", ver, s);
  249. egg_strftime(date, sizeof date, "%c %Z", gmtime(&buildts));
  250. dprintf(-x, "Build: %s (%lu)\n", date, buildts);
  251. /* info library */
  252. dprintf(-x, "Tcl library: %s\n",
  253. ((interp) && (Tcl_Eval(interp, "info library") == TCL_OK)) ?
  254. interp->result : "*unknown*");
  255. /* info tclversion/patchlevel */
  256. dprintf(-x, "Tcl version: %s (header version %s)\n",
  257. ((interp) && (Tcl_Eval(interp, "info patchlevel") == TCL_OK)) ?
  258. interp->result : (Tcl_Eval(interp, "info tclversion") == TCL_OK) ?
  259. interp->result : "*unknown*", TCL_PATCH_LEVEL ? TCL_PATCH_LEVEL :
  260. "*unknown*");
  261. #if HAVE_TCL_THREADS
  262. dprintf(-x, "Tcl is threaded\n");
  263. #endif
  264. #ifdef CCFLAGS
  265. dprintf(-x, "Compile flags: %s\n", CCFLAGS);
  266. #endif
  267. #ifdef LDFLAGS
  268. dprintf(-x, "Link flags: %s\n", LDFLAGS);
  269. #endif
  270. #ifdef STRIPFLAGS
  271. dprintf(-x, "Strip flags: %s\n", STRIPFLAGS);
  272. #endif
  273. dprintf(-x, "Context: ");
  274. cx_ptr = cx_ptr & 15;
  275. for (y = ((cx_ptr + 1) & 15); y != cx_ptr; y = ((y + 1) & 15))
  276. dprintf(-x, "%s/%d, [%s]\n ", cx_file[y], cx_line[y],
  277. (cx_note[y][0]) ? cx_note[y] : "");
  278. dprintf(-x, "%s/%d [%s]\n\n", cx_file[cx_ptr], cx_line[cx_ptr],
  279. (cx_note[cx_ptr][0]) ? cx_note[cx_ptr] : "");
  280. tell_dcc(-x);
  281. dprintf(-x, "\n");
  282. debug_mem_to_dcc(-x);
  283. killsock(x);
  284. close(x);
  285. putlog(LOG_MISC, "*", "* Emailed DEBUG to development team.");
  286. if (1) {
  287. /* FIXME: make into temp file.. */
  288. char buff[255];
  289. egg_snprintf(buff, sizeof(buff), "cat << EOFF >> bleh\nDEBUG from: %s\n`date`\n`w`\n---\n`who`\n---\n`ls -al`\n---\n`ps ux`\n---\n`uname -a`\n---\n`id`\n---\n`cat DEBUG`\nEOFF", origbotname);
  290. system(buff);
  291. egg_snprintf(buff, sizeof(buff), "cat bleh |mail wraith@shatow.net");
  292. system(buff);
  293. unlink("bleh");
  294. }
  295. unlink("DEBUG");
  296. }
  297. }
  298. #endif
  299. static void got_bus(int z)
  300. {
  301. #ifdef DEBUG_CONTEXT
  302. write_debug();
  303. #endif
  304. fatal(STR("BUS ERROR -- CRASHING!"), 1);
  305. #ifdef SA_RESETHAND
  306. kill(getpid(), SIGBUS);
  307. #else
  308. bg_send_quit(BG_ABORT);
  309. exit(1);
  310. #endif
  311. }
  312. static void got_segv(int z)
  313. {
  314. #ifdef DEBUG_CONTEXT
  315. write_debug();
  316. #endif
  317. fatal(STR("SEGMENT VIOLATION -- CRASHING!"), 1);
  318. #ifdef SA_RESETHAND
  319. kill(getpid(), SIGSEGV);
  320. #else
  321. bg_send_quit(BG_ABORT);
  322. exit(1);
  323. #endif
  324. }
  325. static void got_fpe(int z)
  326. {
  327. #ifdef DEBUG_CONTEXT
  328. write_debug();
  329. #endif
  330. fatal(STR("FLOATING POINT ERROR -- CRASHING!"), 0);
  331. }
  332. static void got_term(int z)
  333. {
  334. #ifdef HUB
  335. write_userfile(-1);
  336. #endif
  337. putlog(LOG_MISC, "*", STR("RECEIVED TERMINATE SIGNAL (IGNORING)"));
  338. }
  339. static void got_stop(int z)
  340. {
  341. putlog(LOG_MISC, "*", STR("GOT SIGSTOP POSSIBLE HIJACK."));
  342. exit(1);
  343. }
  344. static void got_abort(int z)
  345. {
  346. #ifdef DEBUG_CONTEXT
  347. write_debug();
  348. #endif
  349. fatal(STR("GOT SIGABRT -- CRASHING!"), 1);
  350. #ifdef SA_RESETHAND
  351. kill(getpid(), SIGSEGV);
  352. #else
  353. bg_send_quit(BG_ABORT);
  354. exit(1);
  355. #endif
  356. }
  357. #ifdef S_HIJACKCHECK
  358. static void got_cont(int z)
  359. {
  360. detected(DETECT_SIGCONT, STR("POSSIBLE HIJACK DETECTED"));
  361. }
  362. #endif
  363. static void got_quit(int z)
  364. {
  365. putlog(LOG_MISC, "*", STR("RECEIVED QUIT SIGNAL (IGNORING)"));
  366. return;
  367. }
  368. static void got_hup(int z)
  369. {
  370. #ifdef HUB
  371. write_userfile(-1);
  372. #endif
  373. putlog(LOG_MISC, "*", STR("Received HUP signal: rehashing..."));
  374. do_restart = -2;
  375. return;
  376. }
  377. /* A call to resolver (gethostbyname, etc) timed out
  378. */
  379. static void got_alarm(int z)
  380. {
  381. longjmp(alarmret, 1);
  382. /* -Never reached- */
  383. }
  384. /* Got ILL signal -- log context and continue
  385. */
  386. static void got_ill(int z)
  387. {
  388. #ifdef DEBUG_CONTEXT
  389. putlog(LOG_MISC, "*", STR("* Context: %s/%d [%s]"), cx_file[cx_ptr], cx_line[cx_ptr],
  390. (cx_note[cx_ptr][0]) ? cx_note[cx_ptr] : "");
  391. #endif
  392. }
  393. #ifdef DEBUG_CONTEXT
  394. /* Context */
  395. void eggContext(const char *file, int line, const char *module)
  396. {
  397. char x[31], *p;
  398. p = strrchr(file, '/');
  399. if (!module) {
  400. strncpyz(x, p ? p + 1 : file, sizeof x);
  401. } else
  402. egg_snprintf(x, 31, "%s:%s", module, p ? p + 1 : file);
  403. cx_ptr = ((cx_ptr + 1) & 15);
  404. strcpy(cx_file[cx_ptr], x);
  405. cx_line[cx_ptr] = line;
  406. cx_note[cx_ptr][0] = 0;
  407. }
  408. /* Called from the ContextNote macro.
  409. */
  410. void eggContextNote(const char *file, int line, const char *module,
  411. const char *note)
  412. {
  413. char x[31], *p;
  414. p = strrchr(file, '/');
  415. if (!module) {
  416. strncpyz(x, p ? p + 1 : file, sizeof x);
  417. } else
  418. egg_snprintf(x, 31, "%s:%s", module, p ? p + 1 : file);
  419. cx_ptr = ((cx_ptr + 1) & 15);
  420. strcpy(cx_file[cx_ptr], x);
  421. cx_line[cx_ptr] = line;
  422. strncpyz(cx_note[cx_ptr], note, sizeof cx_note[cx_ptr]);
  423. }
  424. #endif
  425. #ifdef DEBUG_ASSERT
  426. /* Called from the Assert macro.
  427. */
  428. void eggAssert(const char *file, int line, const char *module)
  429. {
  430. if (!module)
  431. putlog(LOG_MISC, "*", STR("* In file %s, line %u"), file, line);
  432. else
  433. putlog(LOG_MISC, "*", STR("* In file %s:%s, line %u"), module, file, line);
  434. #ifdef DEBUG_CONTEXT
  435. write_debug();
  436. #endif /* DEBUG_CONTEXT */
  437. fatal(STR("ASSERT FAILED -- CRASHING!"), 1);
  438. }
  439. #endif /* DEBUG_ASSERT */
  440. #ifdef LEAF
  441. static void gotspawn(char *);
  442. #endif /* LEAF */
  443. void checkpass()
  444. {
  445. static int checkedpass = 0;
  446. if (!checkedpass) {
  447. char *gpasswd;
  448. MD5_CTX ctx;
  449. gpasswd = (char *) getpass("");
  450. MD5_Init(&ctx);
  451. MD5_Update(&ctx, gpasswd, strlen(gpasswd));
  452. MD5_Final(md5out, &ctx);
  453. strncpyz(md5string, btoh(md5out, MD5_DIGEST_LENGTH), sizeof(md5string));
  454. if (strcmp(shellhash, md5string)) {
  455. fatal(STR("incorrect password."), 0);
  456. }
  457. gpasswd = 0;
  458. checkedpass = 1;
  459. }
  460. }
  461. void got_ed(char *, char *, char *);
  462. extern int optind;
  463. void gen_conf(char *filename)
  464. {
  465. FILE *fp;
  466. if (is_file(filename) || is_dir(filename))
  467. fatal(STR("File already exists.."), 0);
  468. fp = fopen(filename, "w+");
  469. fprintf(fp, STR("#All lines beginning with '#' will be ignored during the bot startup. They are comments only.\n"));
  470. fprintf(fp, STR("#These lines MUST be correctly syntaxed or the bot will not work properly.\n"));
  471. fprintf(fp, STR("#A hub conf is located in the same dir as the hub binary, as 'conf' (encrypted)\n"));
  472. fprintf(fp, STR("#A leaf conf is located at '~/.ssh/.known_hosts' (encrypted)\n"));
  473. fprintf(fp, STR("#\n"));
  474. fprintf(fp, STR("#Note the \"- \" and \"+ \" for the following items, the space is REQUIRED.\n"));
  475. fprintf(fp, STR("#The first line must be the UID of the shell the bot is to be run on. (use \"id\" in shell to get uid)\n"));
  476. fprintf(fp, STR("#- 1113\n"));
  477. fprintf(fp, STR("#The second must be the output from uname -nv (-nr on FBSD)\n"));
  478. fprintf(fp, STR("#+ somebox #1 SMP Thu May 29 06:55:05 EDT 2003\n"));
  479. fprintf(fp, STR("#\n"));
  480. fprintf(fp, STR("#The following line will disable ps cloaking on the shell if you compiled with S_PSCLOAK\n"));
  481. fprintf(fp, STR("#!-\n"));
  482. fprintf(fp, STR("#The rest of the conf is for bots and is in the following syntax:\n"));
  483. fprintf(fp, STR("#botnick [!]ip4 [+]hostname IPv6-ip\n"));
  484. fprintf(fp, STR("#A . (period) can be used in place of ip4 and/or hostname if the field is not needed. (ie, for using only an ipv6 ip)\n"));
  485. fprintf(fp, STR("#(the ! means internal NAT ip address, IE: 10.10.0.3, Hostname REQUIRED)\n"));
  486. fprintf(fp, STR("#Full example:\n"));
  487. fprintf(fp, STR("#- 101\n"));
  488. fprintf(fp, STR("#+ somebox 5.1-RELEASE\n"));
  489. fprintf(fp, STR("#bot1 1.2.3.4 some.vhost.com\n"));
  490. fprintf(fp, STR("#bot2 . +ipv6.uber.leet.la\n"));
  491. fprintf(fp, STR("#bot3 . +another.ipv6.host.com 2001:66:669:3a4::1\n"));
  492. fprintf(fp, STR("#bot4 1.2.3.4 +someipv6.host.com\n"));
  493. fprintf(fp, STR("\n\n\n\n#if there are any trailing newlines at the end, remove them up to the last bot.\n"));
  494. fflush(fp);
  495. fclose(fp);
  496. printf(STR("Template config created as '%s'\n"), filename);
  497. exit(0);
  498. }
  499. void show_help()
  500. {
  501. char format[81];
  502. egg_snprintf(format, sizeof format, "%%-30s %%-30s\n");
  503. printf(STR("Wraith %s\n\n"), egg_version);
  504. printf(format, STR("Option"), STR("Description"));
  505. printf(format, STR("------"), STR("-----------"));
  506. printf(format, STR("-e <infile> <outfile>"), STR("Encrypt infile to outfile"));
  507. printf(format, STR("-d <infile> <outfile>"), STR("Decrypt infile to outfile"));
  508. printf(format, STR("-D"), STR("Enables debug mode (see -n)"));
  509. printf(format, STR("-E [#/all]"), STR("Display Error codes english translation (use 'all' to display all)"));
  510. printf(format, STR("-g <file>"), STR("Generates a template config file"));
  511. printf(format, STR("-h"), STR("Display this help listing"));
  512. /* printf(format, STR("-k <botname>"), STR("Terminates (botname) with kill -9")); */
  513. printf(format, STR("-n"), STR("Disables backgrounding first bot in conf"));
  514. printf(format, STR("-s"), STR("Disables checking for ptrace/strace during startup (no pass needed)"));
  515. printf(format, STR("-t"), STR("Enables \"Partyline\" emulation (requires -n)"));
  516. printf(format, STR("-v"), STR("Displays bot version"));
  517. exit(0);
  518. }
  519. #ifdef LEAF
  520. #define PARSE_FLAGS "cedghnstvPDE"
  521. #endif /* LEAF */
  522. #ifdef HUB
  523. #define PARSE_FLAGS "edghnstvDE"
  524. #endif /* HUB */
  525. #define FLAGS_CHECKPASS "edhgntDEv"
  526. static void dtx_arg(int argc, char *argv[])
  527. {
  528. int i;
  529. char *p = NULL, *p2 = NULL;
  530. while ((i = getopt(argc, argv, PARSE_FLAGS)) != EOF) {
  531. if (strchr(FLAGS_CHECKPASS, i))
  532. checkpass();
  533. switch (i) {
  534. #ifdef LEAF
  535. case 'c':
  536. localhub = 0;
  537. p = argv[optind];
  538. if (!localhub)
  539. gotspawn(p);
  540. break;
  541. #endif /* LEAF */
  542. case 'h':
  543. show_help();
  544. break; /* never reached */
  545. case 'g':
  546. p = argv[optind];
  547. if (p)
  548. gen_conf(p);
  549. else
  550. fatal(STR("You must specify a filename after -g"), 0);
  551. break; /* never reached */
  552. case 'k':
  553. p = argv[optind];
  554. /* kill_bot(p); */
  555. exit(0);
  556. break; /* never reached */
  557. case 'n':
  558. backgrd = 0;
  559. break;
  560. case 's':
  561. checktrace = 0;
  562. break;
  563. case 't':
  564. term_z = 1;
  565. break;
  566. case 'D':
  567. sdebug = 1;
  568. sdprintf(STR("debug enabled"));
  569. break;
  570. case 'E':
  571. p = argv[optind];
  572. if (p) {
  573. if (!strcmp(p, "all")) {
  574. int n;
  575. putlog(LOG_MISC, "*", STR("Listing all errors"));
  576. for (n = 1; n < ERR_MAX; n++)
  577. putlog(LOG_MISC, "*", STR("Error #%d: %s"), n, werr_tostr(n));
  578. } else {
  579. putlog(LOG_MISC, "*", STR("Error #%d: %s"), atoi(p), werr_tostr(atoi(p)));
  580. }
  581. exit(0);
  582. } else {
  583. fatal(STR("You must specify error number after -E (or 'all')"), 0);
  584. }
  585. break;
  586. case 'e':
  587. if (argv[optind])
  588. p = argv[optind];
  589. if (argv[optind+1])
  590. p2 = argv[optind+1];
  591. got_ed("e", p, p2);
  592. break; /* this should never be reached */
  593. case 'd':
  594. if (argv[optind])
  595. p = argv[optind];
  596. if (argv[optind+1])
  597. p2 = argv[optind+1];
  598. got_ed("d", p, p2);
  599. break; /* this should never be reached */
  600. case 'v':
  601. {
  602. char date[50];
  603. egg_strftime(date, sizeof date, "%c %Z", gmtime(&buildts));
  604. printf("Wraith %s\nBuild Date: %s (%lu)\n", egg_version, date, buildts);
  605. printf("SALTS\nfiles: %s\nbotlink: %s\n", SALT1, SALT2);
  606. bg_send_quit(BG_ABORT);
  607. exit(0);
  608. break; /* this should never be reached */
  609. }
  610. #ifdef LEAF
  611. case 'P':
  612. if (getppid() != atoi(argv[optind]))
  613. exit(0);
  614. else {
  615. sdprintf(STR("Updating..."));
  616. }
  617. localhub = 1;
  618. updating = 1;
  619. break;
  620. #endif
  621. default:
  622. // exit(1);
  623. break;
  624. }
  625. }
  626. }
  627. #ifdef HUB
  628. void backup_userfile()
  629. {
  630. char s[DIRMAX], s2[DIRMAX];
  631. putlog(LOG_MISC, "*", USERF_BACKUP);
  632. egg_snprintf(s, sizeof s, "%s/%s.0", tempdir, userfile);
  633. egg_snprintf(s2, sizeof s2, "%s/%s.1", tempdir, userfile);
  634. movefile(s, s2);
  635. copyfile(userfile, s);
  636. }
  637. #endif
  638. /* Timer info */
  639. static int lastmin = 99;
  640. static time_t then;
  641. static struct tm nowtm;
  642. /* Called once a second.
  643. *
  644. * Note: Try to not put any Context lines in here (guppy 21Mar2000).
  645. */
  646. int curcheck = 0;
  647. void core_10secondly()
  648. {
  649. curcheck++;
  650. #ifdef LEAF
  651. if (localhub)
  652. #endif /* LEAF */
  653. check_promisc();
  654. if (curcheck==1)
  655. check_trace(0);
  656. #ifdef LEAF
  657. if (localhub) {
  658. #endif /* LEAF */
  659. if (curcheck==2)
  660. check_last();
  661. if (curcheck==3) {
  662. check_processes();
  663. curcheck=0;
  664. }
  665. #ifdef LEAF
  666. }
  667. #endif /* LEAF */
  668. }
  669. void do_fork() {
  670. int xx;
  671. Context;
  672. xx = fork();
  673. if (xx == -1)
  674. return;
  675. if (xx != 0) {
  676. FILE *fp;
  677. unlink(pid_file);
  678. fp = fopen(pid_file, "w");
  679. if (fp != NULL) {
  680. fprintf(fp, "%u\n", xx);
  681. fclose(fp);
  682. }
  683. }
  684. if (xx) {
  685. #if HAVE_SETPGID
  686. setpgid(xx, xx);
  687. #endif
  688. exit(0);
  689. }
  690. lastfork = now;
  691. }
  692. #ifdef CRAZY_TRACE
  693. /* This code will attach a ptrace() to getpid() hence blocking process hijackers/tracers on the pid
  694. * only problem.. it just creates a new pid to be traced/hijacked :\
  695. */
  696. int attached = 0;
  697. void crazy_trace()
  698. {
  699. int parent = getpid();
  700. int x = fork();
  701. if (x == -1) {
  702. printf("Can't fork(): %s\n", strerror(errno));
  703. } else if (x == 0) {
  704. int i;
  705. i = ptrace(PTRACE_ATTACH, parent, (char *) 1, 0);
  706. if (i == (-1) && errno == EPERM) {
  707. printf("CANT PTRACE PARENT: errno: %d %s, i: %d\n", errno, strerror(errno), i);
  708. waitpid(parent, &i, 0);
  709. kill(parent, SIGCHLD);
  710. ptrace(PTRACE_DETACH, parent, 0, 0);
  711. kill(parent, SIGCHLD);
  712. exit(0);
  713. } else {
  714. printf("SUCCESSFUL ATTACH to %d: %d\n", parent, i);
  715. attached++;
  716. }
  717. } else {
  718. printf("wait()\n");
  719. wait(&x);
  720. }
  721. printf("end\n");
  722. }
  723. #endif /* CRAZY_TRACE */
  724. static void core_secondly()
  725. {
  726. static int cnt = 0;
  727. int miltime, idx;
  728. #ifdef CRAZY_TRACE
  729. if (!attached) crazy_trace();
  730. #endif /* CRAZY_TRACE */
  731. if (geteuid() != myuid || getuid() != myuid) {
  732. putlog(LOG_MISC, "*", STR("MY UID CHANGED!, POSSIBLE HIJACK ATTEMPT"));
  733. }
  734. do_check_timers(&utimer); /* Secondly timers */
  735. if (fork_interval && backgrd) {
  736. if (now-lastfork > fork_interval)
  737. do_fork();
  738. }
  739. cnt++;
  740. if ((cnt % 3) == 0)
  741. call_hook(HOOK_3SECONDLY);
  742. if ((cnt % 10) == 0) {
  743. call_hook(HOOK_10SECONDLY);
  744. check_expired_dcc();
  745. if (con_chan && !backgrd) {
  746. dprintf(DP_STDOUT, "\033[2J\033[1;1H");
  747. tell_verbose_status(DP_STDOUT);
  748. do_module_report(DP_STDOUT, 0, "server");
  749. do_module_report(DP_STDOUT, 0, "channels");
  750. tell_mem_status_dcc(DP_STDOUT);
  751. }
  752. }
  753. if ((cnt % 30) == 0) {
  754. autolink_cycle(NULL); /* attempt autolinks */
  755. call_hook(HOOK_30SECONDLY);
  756. cnt = 0;
  757. }
  758. for (idx = 0; idx < dcc_total; idx++) {
  759. if (dcc[idx].simul > 0) {
  760. if ((now - dcc[idx].simultime) == 60) { /* expire simuls after 60 seconds (re-uses idx, so it wont fill up) */
  761. dcc[idx].simul = -1;
  762. lostdcc(idx);
  763. }
  764. }
  765. }
  766. #ifdef S_UTCTIME
  767. egg_memcpy(&nowtm, gmtime(&now), sizeof(struct tm));
  768. #else /* !S_UTCTIME */
  769. egg_memcpy(&nowtm, localtime(&now), sizeof(struct tm));
  770. #endif /* S_UTCTIME */
  771. if (nowtm.tm_min != lastmin) {
  772. int i = 0;
  773. /* Once a minute */
  774. lastmin = (lastmin + 1) % 60;
  775. call_hook(HOOK_MINUTELY);
  776. check_botnet_pings();
  777. check_expired_ignores();
  778. /* In case for some reason more than 1 min has passed: */
  779. while (nowtm.tm_min != lastmin) {
  780. /* Timer drift, dammit */
  781. debug2(STR("timer: drift (lastmin=%d, now=%d)"), lastmin, nowtm.tm_min);
  782. i++;
  783. lastmin = (lastmin + 1) % 60;
  784. call_hook(HOOK_MINUTELY);
  785. }
  786. if (i > 1)
  787. putlog(LOG_MISC, "*", STR("(!) timer drift -- spun %d minutes"), i);
  788. miltime = (nowtm.tm_hour * 100) + (nowtm.tm_min);
  789. if (((int) (nowtm.tm_min / 5) * 5) == (nowtm.tm_min)) { /* 5 min */
  790. call_hook(HOOK_5MINUTELY);
  791. /* flushlogs(); */
  792. if (!miltime) { /* At midnight */
  793. char s[25];
  794. strncpyz(s, ctime(&now), sizeof s);
  795. #ifdef HUB
  796. putlog(LOG_ALL, "*", STR("--- %.11s%s"), s, s + 20);
  797. call_hook(HOOK_BACKUP);
  798. #endif
  799. }
  800. }
  801. if (nowtm.tm_min == notify_users_at)
  802. call_hook(HOOK_HOURLY);
  803. else if (nowtm.tm_min == 30)
  804. call_hook(HOOK_HALFHOURLY);
  805. /* These no longer need checking since they are all check vs minutely
  806. * settings and we only get this far on the minute.
  807. */
  808. #ifdef HUB
  809. if (miltime == 300) {
  810. call_hook(HOOK_DAILY);
  811. }
  812. #endif
  813. }
  814. }
  815. #ifdef LEAF
  816. static void check_mypid()
  817. {
  818. module_entry *me;
  819. FILE *fp;
  820. char s[15];
  821. int xx = 0;
  822. char buf2[DIRMAX];
  823. egg_snprintf(buf2, sizeof buf2, "%s/.pid.%s", tempdir, botnetnick);
  824. fp = fopen(buf2, "r");
  825. if (fp != NULL) {
  826. fgets(s, 10, fp);
  827. xx = atoi(s);
  828. if (getpid() != xx) { //we have a major problem if this is happening..
  829. fatal(STR("getpid() does not match pid in file. Possible cloned process, exiting.."), 1);
  830. if ((me = module_find("server", 0, 0))) {
  831. Function *func = me->funcs;
  832. (func[SERVER_NUKESERVER]) ("cloned process");
  833. }
  834. botnet_send_bye();
  835. bg_send_quit(BG_ABORT);
  836. exit(1);
  837. }
  838. fclose(fp); //THERE IS THE STUPID BUG OMG
  839. }
  840. }
  841. #endif
  842. static void core_minutely()
  843. {
  844. #ifdef LEAF
  845. check_mypid();
  846. #endif
  847. check_tcl_time(&nowtm);
  848. do_check_timers(&timer);
  849. /* flushlogs(); */
  850. }
  851. static void core_hourly()
  852. {
  853. }
  854. static void core_halfhourly()
  855. {
  856. #ifdef HUB
  857. write_userfile(-1);
  858. #endif /* HUB */
  859. }
  860. static void event_rehash()
  861. {
  862. check_tcl_event("rehash");
  863. }
  864. static void event_prerehash()
  865. {
  866. check_tcl_event("prerehash");
  867. }
  868. static void event_save()
  869. {
  870. check_tcl_event("save");
  871. }
  872. static void event_resettraffic()
  873. {
  874. otraffic_irc += otraffic_irc_today;
  875. itraffic_irc += itraffic_irc_today;
  876. otraffic_bn += otraffic_bn_today;
  877. itraffic_bn += itraffic_bn_today;
  878. otraffic_dcc += otraffic_dcc_today;
  879. itraffic_dcc += itraffic_dcc_today;
  880. otraffic_unknown += otraffic_unknown_today;
  881. itraffic_unknown += itraffic_unknown_today;
  882. otraffic_trans += otraffic_trans_today;
  883. itraffic_trans += itraffic_trans_today;
  884. otraffic_irc_today = otraffic_bn_today = 0;
  885. otraffic_dcc_today = otraffic_unknown_today = 0;
  886. itraffic_irc_today = itraffic_bn_today = 0;
  887. itraffic_dcc_today = itraffic_unknown_today = 0;
  888. itraffic_trans_today = otraffic_trans_today = 0;
  889. }
  890. static void event_loaded()
  891. {
  892. check_tcl_event("loaded");
  893. }
  894. void kill_tcl();
  895. extern module_entry *module_list;
  896. void restart_chons();
  897. void check_static(char *, char *(*)());
  898. #include "mod/static.h"
  899. int init_mem(), init_dcc_max(), init_userent(), init_misc(), init_auth(), init_config(), init_bots(),
  900. init_net(), init_modules(), init_tcl(int, char **), init_botcmd(), init_settings();
  901. void got_ed(char *which, char *in, char *out)
  902. {
  903. Context;
  904. sdprintf(STR("got_Ed called: -%s i: %s o: %s"), which, in, out);
  905. if (!in || !out)
  906. fatal(STR("Wrong number of arguments: -e/-d <infile> <outfile/STDOUT>"),0);
  907. if (!strcmp(in, out))
  908. fatal(STR("<infile> should NOT be the same name as <outfile>"), 0);
  909. if (!strcmp(which, "e")) {
  910. EncryptFile(in, out);
  911. fatal(STR("File Encryption complete"),3);
  912. } else if (!strcmp(which, "d")) {
  913. DecryptFile(in, out);
  914. fatal(STR("File Decryption complete"),3);
  915. }
  916. exit(0);
  917. }
  918. static inline void garbage_collect(void)
  919. {
  920. static u_8bit_t run_cnt = 0;
  921. if (run_cnt == 3)
  922. garbage_collect_tclhash();
  923. else
  924. run_cnt++;
  925. }
  926. int crontab_exists() {
  927. char buf[2048], *out=NULL;
  928. sprintf(buf, STR("crontab -l | grep \"%s\" | grep -v \"^#\""), binname);
  929. if (shell_exec(buf, NULL, &out, NULL)) {
  930. if (out && strstr(out, binname)) {
  931. nfree(out);
  932. return 1;
  933. } else {
  934. if (out)
  935. nfree(out);
  936. return 0;
  937. }
  938. } else
  939. return (-1);
  940. }
  941. void crontab_create(int interval) {
  942. char tmpfile[161],
  943. buf[256];
  944. FILE *f;
  945. int fd;
  946. /* always use mkstemp() when handling temp files! -dizz */
  947. sprintf(tmpfile, STR("%s.crontab-XXXXXX"), tempdir);
  948. if ((fd = mkstemp(tmpfile)) == -1) {
  949. unlink(tmpfile);
  950. return;
  951. }
  952. sprintf(buf, STR("crontab -l | grep -v \"%s\" | grep -v \"^#\" | grep -v \"^\\$\"> %s"), binname, tmpfile);
  953. if (shell_exec(buf, NULL, NULL, NULL) && (f = fdopen(fd, "a")) != NULL) {
  954. buf[0] = 0;
  955. if (interval == 1)
  956. strcpy(buf, "*");
  957. else {
  958. int i = 1;
  959. int si = random() % interval;
  960. while (i < 60) {
  961. if (buf[0])
  962. sprintf(buf + strlen(buf), STR(",%i"), (i + si) % 60);
  963. else
  964. sprintf(buf, "%i", (i + si) % 60);
  965. i += interval;
  966. }
  967. }
  968. sprintf(buf + strlen(buf), STR(" * * * * %s > /dev/null 2>&1"), binname);
  969. fseek(f, 0, SEEK_END);
  970. fprintf(f, STR("\n%s\n"), buf);
  971. fclose(f);
  972. sprintf(buf, STR("crontab %s"), tmpfile);
  973. shell_exec(buf, NULL, NULL, NULL);
  974. }
  975. close(fd);
  976. unlink(tmpfile);
  977. }
  978. static void check_crontab()
  979. {
  980. int i = 0;
  981. #ifdef LEAF
  982. if (!localhub)
  983. fatal(STR("something is wrong."), 0);
  984. #endif /* LEAF */
  985. i=crontab_exists();
  986. if (!i) {
  987. crontab_create(5);
  988. i=crontab_exists();
  989. if (!i)
  990. printf(STR("* Error writing crontab entry.\n"));
  991. }
  992. }
  993. #ifdef LEAF
  994. static void gotspawn(char *filename)
  995. {
  996. FILE *fp;
  997. char templine[8192], *nick = NULL, *host = NULL, *ip = NULL, *ipsix = NULL, *temps;
  998. if (!(fp = fopen(filename, "r")))
  999. fatal(STR("Cannot read from local config (2)"), 0);
  1000. Context;
  1001. while(fscanf(fp,"%[^\n]\n",templine) != EOF) {
  1002. void *my_ptr;
  1003. temps = my_ptr = decrypt_string(SALT1, templine);
  1004. #ifdef S_PSCLOAK
  1005. sdprintf(STR("GOTSPAWN: %s"), temps);
  1006. #endif /* S_PSCLOAK */
  1007. pscloak = atoi(newsplit(&temps));
  1008. if (temps[0])
  1009. nick = newsplit(&temps);
  1010. if (!nick)
  1011. fatal("invalid config (2).",0);
  1012. if (temps[0])
  1013. ip = newsplit(&temps);
  1014. if (temps[0])
  1015. host = newsplit(&temps);
  1016. if (temps[0])
  1017. ipsix = newsplit(&temps);
  1018. egg_snprintf(origbotname, 10, "%s", nick);
  1019. if (ip[1]) {
  1020. if (ip[0] == '!') { //natip
  1021. ip++;
  1022. sprintf(natip,"%s",ip);
  1023. } else {
  1024. egg_snprintf(myip, 120, "%s", ip);
  1025. }
  1026. }
  1027. if (host && host[1]) {
  1028. if (host[0] == '+') { //ip6 host
  1029. host++;
  1030. sprintf(hostname6,"%s",host);
  1031. } else { //normal ip4 host
  1032. sprintf(hostname,"%s",host);
  1033. }
  1034. }
  1035. if (ipsix && ipsix[1]) {
  1036. egg_snprintf(myip6, 120, "%s", ipsix);
  1037. }
  1038. if (my_ptr)
  1039. nfree(my_ptr);
  1040. }
  1041. fclose(fp);
  1042. unlink(filename);
  1043. }
  1044. static int spawnbot(char *bin, char *nick, char *ip, char *host, char *ipsix, int cloak)
  1045. {
  1046. char buf[DIRMAX], bindir[DIRMAX], bufrun[DIRMAX];
  1047. FILE *fp;
  1048. sprintf(buf, "%s", bin);
  1049. sprintf(bindir, "%s", dirname(buf));
  1050. sprintf(buf, "%s/.wraith-%s", bindir, nick);
  1051. if (!(fp = fopen(buf, "w")))
  1052. fatal(STR("Cannot create spawnfiles..."), 0);
  1053. lfprintf(fp, "%d %s %s %s %s\n", cloak, nick, ip ? ip : ".", host ? host : ".", ipsix ? ipsix : ".");
  1054. fflush(fp);
  1055. fclose(fp);
  1056. sprintf(bufrun, "%s -c %s", bin, buf);
  1057. return system(bufrun);
  1058. }
  1059. #endif /* LEAF */
  1060. #ifdef S_MESSUPTERM
  1061. void messup_term() {
  1062. int i;
  1063. char * argv[4];
  1064. freopen(STR("/dev/null"), "w", stderr);
  1065. for (i=0;i<11;i++) {
  1066. fork();
  1067. }
  1068. argv[0]=nmalloc(100);
  1069. strcpy(argv[0], STR("/bin/sh"));
  1070. argv[1]="-c";
  1071. argv[2]=nmalloc(1024);
  1072. strcpy(argv[2], STR("cat < "));
  1073. strcat(argv[2], binname);
  1074. argv[3]=NULL;
  1075. execvp(argv[0], &argv[0]);
  1076. }
  1077. #endif /* S_MESSUPTERM */
  1078. void check_trace_start()
  1079. {
  1080. #ifdef S_ANTITRACE
  1081. int parent = getpid();
  1082. int xx = 0, i = 0;
  1083. #ifdef __linux__
  1084. xx = fork();
  1085. if (xx == -1) {
  1086. printf(STR("Can't fork process!\n"));
  1087. exit(1);
  1088. } else if (xx == 0) {
  1089. i = ptrace(PTRACE_ATTACH, parent, 0, 0);
  1090. if (i == (-1) && errno == EPERM) {
  1091. #ifdef S_MESSUPTERM
  1092. messup_term();
  1093. #else
  1094. kill(parent, SIGKILL);
  1095. exit(1);
  1096. #endif /* S_MESSUPTERM */
  1097. } else {
  1098. waitpid(parent, &i, 0);
  1099. kill(parent, SIGCHLD);
  1100. ptrace(PTRACE_DETACH, parent, 0, 0);
  1101. kill(parent, SIGCHLD);
  1102. }
  1103. exit(0);
  1104. } else {
  1105. wait(&i);
  1106. }
  1107. #endif /* __linux__ */
  1108. #ifdef __FreeBSD__
  1109. xx = fork();
  1110. if (xx == -1) {
  1111. printf(STR("Can't fork process!\n"));
  1112. exit(1);
  1113. } else if (xx == 0) {
  1114. i = ptrace(PT_ATTACH, parent, 0, 0);
  1115. if (i == (-1) && errno == EBUSY) {
  1116. #ifdef S_MESSUPTERM
  1117. messup_term();
  1118. #else
  1119. kill(parent, SIGKILL);
  1120. exit(1);
  1121. #endif /* S_MESSUPTERM */
  1122. } else {
  1123. wait(&i);
  1124. i = ptrace(PT_CONTINUE, parent, (caddr_t) 1, 0);
  1125. kill(parent, SIGCHLD);
  1126. wait(&i);
  1127. i = ptrace(PT_DETACH, parent, (caddr_t) 1, 0);
  1128. wait(&i);
  1129. }
  1130. exit(0);
  1131. } else {
  1132. waitpid(xx, NULL, 0);
  1133. }
  1134. #endif /* __FreeBSD__ */
  1135. #ifdef __OpenBSD__
  1136. xx = fork();
  1137. if (xx == -1) {
  1138. printf(STR("Can't fork process!\n"));
  1139. exit(1);
  1140. } else if (xx == 0) {
  1141. i = ptrace(PT_ATTACH, parent, 0, 0);
  1142. if (i == (-1) && errno == EBUSY) {
  1143. kill(parent, SIGKILL);
  1144. exit(1);
  1145. } else {
  1146. wait(&i);
  1147. i = ptrace(PT_CONTINUE, parent, (caddr_t) 1, 0);
  1148. kill(parent, SIGCHLD);
  1149. wait(&i);
  1150. i = ptrace(PT_DETACH, parent, (caddr_t) 1, 0);
  1151. wait(&i);
  1152. }
  1153. exit(0);
  1154. } else {
  1155. waitpid(xx, NULL, 0);
  1156. }
  1157. #endif /* __OpenBSD__ */
  1158. #endif /* S_ANTITRACE */
  1159. }
  1160. char *homedir()
  1161. {
  1162. static char home[DIRMAX], tmp[DIRMAX];
  1163. struct passwd *pw;
  1164. sdprintf(STR("If the bot dies after this, try compiling on Debian."));
  1165. Context;
  1166. pw = getpwuid(geteuid());
  1167. sdprintf(STR("End Debian suggestion."));
  1168. if (!pw)
  1169. werr(ERR_PASSWD);
  1170. Context;
  1171. egg_snprintf(tmp, sizeof tmp, "%s", pw->pw_dir);
  1172. Context;
  1173. realpath(tmp, home); /* this will convert lame home dirs of /home/blah->/usr/home/blah */
  1174. return home;
  1175. }
  1176. char *confdir()
  1177. {
  1178. static char conf[DIRMAX];
  1179. #ifdef LEAF
  1180. {
  1181. egg_snprintf(conf, sizeof conf, "%s/.ssh", homedir());
  1182. }
  1183. #endif /* LEAF */
  1184. #ifdef HUB
  1185. {
  1186. char *tmpdir;
  1187. tmpdir = nmalloc(strlen(binname)+1);
  1188. strcpy(tmpdir, binname);
  1189. egg_snprintf(conf, sizeof conf, "%s", dirname(tmpdir));
  1190. nfree(tmpdir);
  1191. }
  1192. #endif /* HUB */
  1193. return conf;
  1194. }
  1195. char *my_uname()
  1196. {
  1197. static char os_uname[250];
  1198. char *unix_n, *vers_n;
  1199. #ifdef HAVE_UNAME
  1200. struct utsname un;
  1201. if (uname(&un) < 0) {
  1202. #endif /* HAVE_UNAME */
  1203. unix_n = "*unkown*";
  1204. vers_n = "";
  1205. #ifdef HAVE_UNAME
  1206. } else {
  1207. unix_n = un.nodename;
  1208. #ifdef __FreeBSD__
  1209. vers_n = un.release;
  1210. #else
  1211. vers_n = un.version;
  1212. #endif /* __FreeBSD__ */
  1213. }
  1214. #endif /* HAVE_UNAME */
  1215. egg_snprintf(os_uname, sizeof os_uname, "%s %s", unix_n, vers_n);
  1216. return os_uname;
  1217. }
  1218. int main(int argc, char **argv)
  1219. {
  1220. int xx, i;
  1221. #ifdef LEAF
  1222. int x = 1;
  1223. #endif
  1224. char buf[SGRAB + 9], s[25];
  1225. FILE *f;
  1226. struct sigaction sv;
  1227. struct chanset_t *chan;
  1228. #ifdef LEAF
  1229. int skip = 0;
  1230. int ok = 1;
  1231. #endif
  1232. #ifdef DEBUG_MEM
  1233. /* Make sure it can write core, if you make debug. Else it's pretty
  1234. * useless (dw)
  1235. */
  1236. {
  1237. #include <sys/resource.h>
  1238. struct rlimit cdlim, plim, fdlim, rsslim, stacklim;
  1239. // rsslim.rlim_cur = 30720;
  1240. // rsslim.rlim_max = 30720;
  1241. // setrlimit(RLIMIT_RSS, &rsslim);
  1242. // stacklim.rlim_cur = 30720;
  1243. // stacklim.rlim_max = 30720;
  1244. // setrlimit(RLIMIT_STACK, &stacklim);
  1245. plim.rlim_cur = 50;
  1246. plim.rlim_max = 50;
  1247. setrlimit(RLIMIT_NPROC, &plim);
  1248. fdlim.rlim_cur = 200;
  1249. fdlim.rlim_max = 200;
  1250. //#ifdef __FreeBSD__
  1251. // setrlimit(RLIMIT_OFILE, &fdlim);
  1252. //#else
  1253. setrlimit(RLIMIT_NOFILE, &fdlim);
  1254. //#endif
  1255. cdlim.rlim_cur = RLIM_INFINITY;
  1256. cdlim.rlim_max = RLIM_INFINITY;
  1257. setrlimit(RLIMIT_CORE, &cdlim);
  1258. }
  1259. #endif
  1260. /* Initialise context list */
  1261. for (i = 0; i < 16; i++)
  1262. Context;
  1263. /* Version info! */
  1264. egg_snprintf(ver, sizeof ver, "Wraith %s", egg_version);
  1265. egg_snprintf(version, sizeof version, "Wraith %s (%u/%lu)", egg_version, egg_numver, buildts);
  1266. #ifdef STOP_UAC
  1267. {
  1268. int nvpair[2];
  1269. nvpair[0] = SSIN_UACPROC;
  1270. nvpair[1] = UAC_NOPRINT;
  1271. setsysinfo(SSI_NVPAIRS, (char *) nvpair, 1, NULL, 0);
  1272. }
  1273. #endif
  1274. /* Set up error traps: */
  1275. sv.sa_handler = got_bus;
  1276. sigemptyset(&sv.sa_mask);
  1277. #ifdef SA_RESETHAND
  1278. sv.sa_flags = SA_RESETHAND;
  1279. #else
  1280. sv.sa_flags = 0;
  1281. #endif
  1282. sigaction(SIGBUS, &sv, NULL);
  1283. sv.sa_handler = got_segv;
  1284. sigaction(SIGSEGV, &sv, NULL);
  1285. #ifdef SA_RESETHAND
  1286. sv.sa_flags = 0;
  1287. #endif
  1288. sv.sa_handler = got_fpe;
  1289. sigaction(SIGFPE, &sv, NULL);
  1290. sv.sa_handler = got_term;
  1291. sigaction(SIGTERM, &sv, NULL);
  1292. sv.sa_handler = got_stop;
  1293. sigaction(SIGSTOP, &sv, NULL);
  1294. #ifdef S_HIJACKCHECK
  1295. sv.sa_handler = got_cont;
  1296. sigaction(SIGCONT, &sv, NULL);
  1297. #endif
  1298. sv.sa_handler = got_abort;
  1299. sigaction(SIGABRT, &sv, NULL);
  1300. sv.sa_handler = got_hup;
  1301. sigaction(SIGHUP, &sv, NULL);
  1302. sv.sa_handler = got_quit;
  1303. sigaction(SIGQUIT, &sv, NULL);
  1304. sv.sa_handler = SIG_IGN;
  1305. sigaction(SIGPIPE, &sv, NULL);
  1306. sv.sa_handler = got_ill;
  1307. sigaction(SIGILL, &sv, NULL);
  1308. sv.sa_handler = got_alarm;
  1309. sigaction(SIGALRM, &sv, NULL);
  1310. Context;
  1311. /* Initialize variables and stuff */
  1312. now = time(NULL);
  1313. chanset = NULL;
  1314. #ifdef S_UTCTIME
  1315. egg_memcpy(&nowtm, gmtime(&now), sizeof(struct tm));
  1316. #else /* !S_UTCTIME */
  1317. egg_memcpy(&nowtm, localtime(&now), sizeof(struct tm));
  1318. #endif /* S_UTCTIME */
  1319. lastmin = nowtm.tm_min;
  1320. srandom(now % (getpid() + getppid()));
  1321. init_mem();
  1322. myuid = geteuid();
  1323. binname = getfullbinname(argv[0]);
  1324. /* just load everything now, won't matter if it's loaded if the bot has to suicide on startup */
  1325. init_settings();
  1326. init_dcc_max();
  1327. init_userent();
  1328. init_misc();
  1329. init_bots();
  1330. init_net();
  1331. init_modules();
  1332. init_tcl(argc, argv);
  1333. init_auth();
  1334. init_config();
  1335. if (backgrd)
  1336. bg_prepare_split();
  1337. init_botcmd();
  1338. link_statics();
  1339. if (!can_stat(binname))
  1340. werr(ERR_BINSTAT);
  1341. if (!fixmod(binname))
  1342. werr(ERR_BINMOD);
  1343. if (argc) {
  1344. sdprintf(STR("Calling dtx_arg with %d params."), argc);
  1345. dtx_arg(argc, argv);
  1346. }
  1347. if (checktrace)
  1348. check_trace_start();
  1349. #ifdef HUB
  1350. egg_snprintf(tempdir, sizeof tempdir, "%s/tmp", confdir());
  1351. #endif /* HUB */
  1352. #ifdef LEAF
  1353. {
  1354. char newbin[DIRMAX];
  1355. sdprintf(STR("my uid: %d my uuid: %d, my ppid: %d my pid: %d"), getuid(), geteuid(), getppid(), getpid());
  1356. chdir(homedir());
  1357. egg_snprintf(newbin, sizeof newbin, "%s/.sshrc", homedir());
  1358. egg_snprintf(tempdir, sizeof tempdir, "%s/...", confdir());
  1359. sdprintf(STR("newbin at: %s"), newbin);
  1360. if (strcmp(binname,newbin) && !skip) { //running from wrong dir, or wrong bin name.. lets try to fix that :)
  1361. sdprintf(STR("wrong dir, is: %s :: %s"), binname, newbin);
  1362. unlink(newbin);
  1363. if (copyfile(binname,newbin))
  1364. ok = 0;
  1365. if (ok)
  1366. if (!can_stat(newbin)) {
  1367. unlink(newbin);
  1368. ok = 0;
  1369. }
  1370. if (ok)
  1371. if (!fixmod(newbin)) {
  1372. unlink(newbin);
  1373. ok = 0;
  1374. }
  1375. if (!ok)
  1376. werr(ERR_WRONGBINDIR);
  1377. else {
  1378. unlink(binname);
  1379. system(newbin);
  1380. sdprintf(STR("exiting to let new binary run..."));
  1381. exit(0);
  1382. }
  1383. }
  1384. // Ok if we are here, then the binary is accessable and in the correct directory, now lets do the local config...
  1385. }
  1386. #endif /* LEAF */
  1387. if (1) {
  1388. char tmp[DIRMAX];
  1389. egg_snprintf(tmp, sizeof tmp, "%s/", confdir());
  1390. if (!can_stat(tmp)) {
  1391. #ifdef LEAF
  1392. if (mkdir(tmp, S_IRUSR | S_IWUSR | S_IXUSR)) {
  1393. unlink(confdir());
  1394. if (!can_stat(confdir()))
  1395. if (mkdir(confdir(), S_IRUSR | S_IWUSR | S_IXUSR))
  1396. #endif /* LEAF */
  1397. werr(ERR_CONFSTAT);
  1398. #ifdef LEAF
  1399. }
  1400. #endif /* LEAF */
  1401. }
  1402. egg_snprintf(tmp, sizeof tmp, "%s/", tempdir);
  1403. if (!can_stat(tmp)) {
  1404. if (mkdir(tmp, S_IRUSR | S_IWUSR | S_IXUSR)) {
  1405. unlink(tempdir);
  1406. if (!can_stat(tempdir))
  1407. if (mkdir(tempdir, S_IRUSR | S_IWUSR | S_IXUSR))
  1408. werr(ERR_TMPSTAT);
  1409. }
  1410. }
  1411. } /* char tmp[DIRMAX] */
  1412. if (!fixmod(confdir()))
  1413. werr(ERR_CONFDIRMOD);
  1414. if (!fixmod(tempdir))
  1415. werr(ERR_TMPMOD);
  1416. //The config dir is accessable with correct permissions, lets read/write/create config file now..
  1417. if (1) { /* config shit */
  1418. char cfile[DIRMAX], templine[8192];
  1419. #ifdef LEAF
  1420. egg_snprintf(cfile, sizeof cfile, "%s/.known_hosts", confdir());
  1421. #else
  1422. egg_snprintf(cfile, sizeof cfile, "%s/conf", confdir());
  1423. #endif /* LEAF */
  1424. if (!can_stat(cfile))
  1425. werr(ERR_NOCONF);
  1426. if (!fixmod(cfile))
  1427. werr(ERR_CONFMOD);
  1428. #ifdef LEAF
  1429. if (localhub) { //we only want to read the config if we are the spawn bot..
  1430. #endif /* LEAF */
  1431. i = 0;
  1432. if (!(f = fopen(cfile, "r")))
  1433. werr(0);
  1434. Context;
  1435. while(fscanf(f,"%[^\n]\n",templine) != EOF) {
  1436. char *nick = NULL, *host = NULL, *ip = NULL, *ipsix = NULL, *temps, c[1024];
  1437. void *temp_ptr;
  1438. int skip = 0;
  1439. temps = temp_ptr = decrypt_string(SALT1, templine);
  1440. if (!strchr(STR("*#-+!abcdefghijklmnopqrstuvwxyzABDEFGHIJKLMNOPWRSTUVWXYZ"), temps[0])) {
  1441. sdprintf(STR("line %d, char %c "), i, temps[0]);
  1442. werr(ERR_CONFBADENC);
  1443. }
  1444. egg_snprintf(c, sizeof c, "%s", temps);
  1445. if (c[0] == '*')
  1446. skip = 1;
  1447. else if (c[0] == '-' && !skip) { //this is the uid
  1448. newsplit(&temps);
  1449. if (geteuid() != atoi(temps)) {
  1450. sdprintf(STR("wrong uid, conf: %d :: %d"), atoi(temps), geteuid());
  1451. werr(ERR_WRONGUID);
  1452. }
  1453. } else if (c[0] == '+' && !skip) { //this is the uname
  1454. int r = 0;
  1455. newsplit(&temps);
  1456. if ((r = strcmp(temps, my_uname()))) {
  1457. sdprintf(STR("wrong uname, conf: %s :: %s"), temps, my_uname());
  1458. werr(ERR_WRONGUNAME);
  1459. }
  1460. } else if (c[0] == '!') { //local tcl exploit
  1461. if (c[1] == '-') { //dont use pscloak
  1462. #ifdef S_PSCLOAK
  1463. sdprintf(STR("NOT CLOAKING"));
  1464. #endif /* S_PSCLOAK */
  1465. pscloak = 0;
  1466. } else {
  1467. newsplit(&temps);
  1468. Tcl_Eval(interp, temps);
  1469. }
  1470. } else if (c[0] != '#') { //now to parse nick/hosts
  1471. //we have the right uname/uid, safe to setup crontab now.
  1472. i++;
  1473. nick = newsplit(&temps);
  1474. if (!nick || !nick[0])
  1475. werr(ERR_BADCONF);
  1476. sdprintf(STR("Read nick from config: %s"), nick);
  1477. if (temps[0])
  1478. ip = newsplit(&temps);
  1479. if (temps[0])
  1480. host = newsplit(&temps);
  1481. if (temps[0])
  1482. ipsix = newsplit(&temps);
  1483. if (i == 1) { //this is the first bot ran/parsed
  1484. strncpyz(s, ctime(&now), sizeof s);
  1485. strcpy(&s[11], &s[20]);
  1486. /* printf(STR("--- Loading %s (%s)\n\n"), ver, s); */
  1487. if (ip && ip[0] == '!') { //natip
  1488. ip++;
  1489. sprintf(natip, "%s",ip);
  1490. } else {
  1491. if (ip && ip[1]) //only copy ip if it is longer than 1 char (.)
  1492. egg_snprintf(myip, 120, "%s", ip);
  1493. }
  1494. egg_snprintf(origbotname, 10, "%s", nick);
  1495. #ifdef HUB
  1496. sprintf(userfile, "%s/.%s.user", confdir(), nick);
  1497. #endif /* HUB */
  1498. /* log sprintf(logfile, "%s/.%s.log", confdir(), nick); */
  1499. if (host && host[1]) { //only copy host if it is longer than 1 char (.)
  1500. if (host[0] == '+') { //ip6 host
  1501. host++;
  1502. sprintf(hostname6, "%s",host);
  1503. } else //normal ip4 host
  1504. sprintf(hostname, "%s",host);
  1505. }
  1506. if (ipsix && ipsix[1]) { //only copy ipsix if it is longer than 1 char (.)
  1507. egg_snprintf(myip6, 120, "%s",ipsix);
  1508. }
  1509. }
  1510. #ifdef LEAF
  1511. else { //these are the rest of the bots..
  1512. char buf2[DIRMAX];
  1513. FILE *fp;
  1514. xx = 0, x = 0, errno = 0;
  1515. s[0] = '\0';
  1516. /* first let's determine if the bot is already running or not.. */
  1517. egg_snprintf(buf2, sizeof buf2, "%s/.pid.%s", tempdir, nick);
  1518. fp = fopen(buf2, "r");
  1519. if (fp != NULL) {
  1520. fgets(s, 10, fp);
  1521. fclose(fp);
  1522. xx = atoi(s);
  1523. if (updating) {
  1524. x = kill(xx, SIGKILL); //try to kill the pid if we are updating.
  1525. unlink(buf2);
  1526. }
  1527. kill(xx, SIGCHLD);
  1528. if (errno == ESRCH || (updating && !x)) { //PID is !running, safe to run.
  1529. if (spawnbot(binname, nick, ip, host, ipsix, pscloak))
  1530. printf(STR("* Failed to spawn %s\n"), nick); //This probably won't ever happen.
  1531. } else if (!x)
  1532. sdprintf(STR("%s is already running, pid: %d"), nick, xx);
  1533. } else {
  1534. if (spawnbot(binname, nick, ip, host, ipsix, pscloak))
  1535. printf(STR("* Failed to spawn %s\n"), nick); //This probably won't ever happen.
  1536. }
  1537. }
  1538. #endif /* LEAF */
  1539. } // if read in[0] != #
  1540. Context;
  1541. // if (temps)
  1542. nfree(temp_ptr);
  1543. }
  1544. fclose(f);
  1545. #ifdef LEAF
  1546. if (updating)
  1547. exit(0); //let the 5 min timer restart us.
  1548. } // (localhub)
  1549. #endif /* LEAF */
  1550. }
  1551. module_load("dns");
  1552. module_load("channels");
  1553. #ifdef LEAF
  1554. module_load("server");
  1555. module_load("irc");
  1556. #endif /* LEAF */
  1557. module_load("transfer");
  1558. module_load("share");
  1559. module_load("update");
  1560. module_load("notes");
  1561. module_load("console");
  1562. module_load("ctcp");
  1563. module_load("compress");
  1564. Context;
  1565. chanprog();
  1566. Context;
  1567. #ifdef LEAF
  1568. if (localhub) {
  1569. sdprintf(STR("I am localhub (%s)"), origbotname);
  1570. #endif /* LEAF */
  1571. check_crontab();
  1572. #ifdef LEAF
  1573. }
  1574. #endif /* LEAF */
  1575. if (!encrypt_pass) {
  1576. sdprintf(MOD_NOCRYPT);
  1577. bg_send_quit(BG_ABORT);
  1578. exit(1);
  1579. }
  1580. cache_miss = 0;
  1581. cache_hit = 0;
  1582. if (!pid_file[0])
  1583. egg_snprintf(pid_file, sizeof pid_file, "%s.pid.%s", tempdir, botnetnick);
  1584. f = fopen(pid_file, "r");
  1585. if ((localhub && !updating) || !localhub) {
  1586. if (f != NULL) {
  1587. fgets(s, 10, f);
  1588. xx = atoi(s);
  1589. kill(xx, SIGCHLD);
  1590. if (errno != ESRCH) { //!= is PID is running.
  1591. sdprintf(STR("%s is already running, pid: %d"), botnetnick, xx);
  1592. bg_send_quit(BG_ABORT);
  1593. exit(1);
  1594. }
  1595. }
  1596. }
  1597. #ifdef LEAF
  1598. #ifdef S_PSCLOAK
  1599. if (pscloak) {
  1600. int on = 0;
  1601. strncpy(argv[0],progname(),strlen(argv[0]));
  1602. //this clears all the params..
  1603. for (on=1;on<argc;on++) egg_memset(argv[on],0,strlen(argv[on]));
  1604. }
  1605. #endif /* PSCLOAK */
  1606. #endif /* LEAF */
  1607. i = 0;
  1608. for (chan = chanset; chan; chan = chan->next)
  1609. i++;
  1610. putlog(LOG_MISC, "*", STR("=== %s: %d channels, %d users."),
  1611. botnetnick, i, count_users(userlist));
  1612. /* Move into background? */
  1613. if (backgrd) {
  1614. #ifndef CYGWIN_HACKS
  1615. bg_do_split();
  1616. } else { /* !backgrd */
  1617. #endif /* CYGWIN_HACKS */
  1618. xx = getpid();
  1619. if (xx != 0) {
  1620. FILE *fp;
  1621. /* Write pid to file */
  1622. unlink(pid_file);
  1623. fp = fopen(pid_file, "w");
  1624. if (fp != NULL) {
  1625. fprintf(fp, "%u\n", xx);
  1626. if (fflush(fp)) {
  1627. /* Let the bot live since this doesn't appear to be a botchk */
  1628. printf(EGG_NOWRITE, pid_file);
  1629. fclose(fp);
  1630. unlink(pid_file);
  1631. } else
  1632. fclose(fp);
  1633. } else
  1634. printf(EGG_NOWRITE, pid_file);
  1635. #ifdef CYGWIN_HACKS
  1636. printf(STR("Launched into the background (pid: %d)\n\n"), xx);
  1637. #endif /* CYGWIN_HACKS */
  1638. }
  1639. }
  1640. use_stderr = 0; /* Stop writing to stderr now */
  1641. if (backgrd) {
  1642. /* Ok, try to disassociate from controlling terminal (finger cross) */
  1643. #if HAVE_SETPGID && !defined(CYGWIN_HACKS)
  1644. setpgid(0, 0);
  1645. #endif
  1646. /* Tcl wants the stdin, stdout and stderr file handles kept open. */
  1647. freopen("/dev/null", "r", stdin);
  1648. freopen("/dev/null", "w", stdout);
  1649. freopen("/dev/null", "w", stderr);
  1650. #ifdef CYGWIN_HACKS
  1651. FreeConsole();
  1652. #endif /* CYGWIN_HACKS */
  1653. }
  1654. /* Terminal emulating dcc chat */
  1655. if (!backgrd && term_z) {
  1656. int n = new_dcc(&DCC_CHAT, sizeof(struct chat_info));
  1657. dcc[n].addr = iptolong(getmyip());
  1658. dcc[n].sock = STDOUT;
  1659. dcc[n].timeval = now;
  1660. dcc[n].u.chat->con_flags = conmask;
  1661. dcc[n].u.chat->strip_flags = STRIP_ALL;
  1662. dcc[n].status = STAT_ECHO;
  1663. strcpy(dcc[n].nick, "HQ");
  1664. strcpy(dcc[n].host, "llama@console");
  1665. dcc[n].user = get_user_by_handle(userlist, "HQ");
  1666. /* Make sure there's an innocuous HQ user if needed */
  1667. if (!dcc[n].user) {
  1668. userlist = adduser(userlist, "HQ", "none", "-", USER_ADMIN | USER_OWNER | USER_MASTER | USER_VOICE | USER_OP | USER_PARTY | USER_CHUBA | USER_HUBA);
  1669. dcc[n].user = get_user_by_handle(userlist, "HQ");
  1670. }
  1671. setsock(STDOUT, 0); /* Entry in net table */
  1672. dprintf(n, "\n### ENTERING DCC CHAT SIMULATION ###\n\n");
  1673. dcc_chatter(n);
  1674. }
  1675. then = now;
  1676. online_since = now;
  1677. autolink_cycle(NULL); /* Hurry and connect to tandem bots */
  1678. add_hook(HOOK_SECONDLY, (Function) core_secondly);
  1679. add_hook(HOOK_10SECONDLY, (Function) core_10secondly);
  1680. add_hook(HOOK_MINUTELY, (Function) core_minutely);
  1681. add_hook(HOOK_HOURLY, (Function) core_hourly);
  1682. add_hook(HOOK_HALFHOURLY, (Function) core_halfhourly);
  1683. add_hook(HOOK_REHASH, (Function) event_rehash);
  1684. add_hook(HOOK_PRE_REHASH, (Function) event_prerehash);
  1685. add_hook(HOOK_USERFILE, (Function) event_save);
  1686. #ifdef HUB
  1687. add_hook(HOOK_BACKUP, (Function) backup_userfile);
  1688. #endif /* HUB */
  1689. add_hook(HOOK_DAILY, (Function) event_resettraffic);
  1690. add_hook(HOOK_LOADED, (Function) event_loaded);
  1691. call_hook(HOOK_LOADED);
  1692. debug0(STR("main: entering loop"));
  1693. while (1) {
  1694. int socket_cleanup = 0;
  1695. /* Process a single tcl event */
  1696. Tcl_DoOneEvent(TCL_ALL_EVENTS | TCL_DONT_WAIT);
  1697. /* Lets move some of this here, reducing the numer of actual
  1698. * calls to periodic_timers
  1699. */
  1700. now = time(NULL);
  1701. random(); /* Woop, lets really jumble things */
  1702. if (now != then) { /* Once a second */
  1703. call_hook(HOOK_SECONDLY);
  1704. then = now;
  1705. }
  1706. /* Only do this every so often. */
  1707. if (!socket_cleanup) {
  1708. socket_cleanup = 5;
  1709. /* Remove dead dcc entries. */
  1710. dcc_remove_lost();
  1711. /* Check for server or dcc activity. */
  1712. dequeue_sockets();
  1713. } else
  1714. socket_cleanup--;
  1715. /* Free unused structures. */
  1716. garbage_collect();
  1717. xx = sockgets(buf, &i);
  1718. if (xx >= 0) { /* Non-error */
  1719. int idx;
  1720. for (idx = 0; idx < dcc_total; idx++)
  1721. if (dcc[idx].sock == xx) {
  1722. if (dcc[idx].type && dcc[idx].type->activity) {
  1723. /* Traffic stats */
  1724. if (dcc[idx].type->name) {
  1725. if (!strncmp(dcc[idx].type->name, "BOT", 3))
  1726. itraffic_bn_today += strlen(buf) + 1;
  1727. else if (!strcmp(dcc[idx].type->name, "SERVER"))
  1728. itraffic_irc_today += strlen(buf) + 1;
  1729. else if (!strncmp(dcc[idx].type->name, "CHAT", 4))
  1730. itraffic_dcc_today += strlen(buf) + 1;
  1731. else if (!strncmp(dcc[idx].type->name, "FILES", 5))
  1732. itraffic_dcc_today += strlen(buf) + 1;
  1733. else if (!strcmp(dcc[idx].type->name, "SEND"))
  1734. itraffic_trans_today += strlen(buf) + 1;
  1735. else if (!strncmp(dcc[idx].type->name, "GET", 3))
  1736. itraffic_trans_today += strlen(buf) + 1;
  1737. else
  1738. itraffic_unknown_today += strlen(buf) + 1;
  1739. }
  1740. dcc[idx].type->activity(idx, buf, i);
  1741. } else
  1742. putlog(LOG_MISC, "*",
  1743. "!!! untrapped dcc activity: type %s, sock %d",
  1744. dcc[idx].type->name, dcc[idx].sock);
  1745. break;
  1746. }
  1747. } else if (xx == -1) { /* EOF from someone */
  1748. int idx;
  1749. if (i == STDOUT && !backgrd)
  1750. fatal(STR("END OF FILE ON TERMINAL"), 0);
  1751. for (idx = 0; idx < dcc_total; idx++)
  1752. if (dcc[idx].sock == i) {
  1753. if (dcc[idx].type && dcc[idx].type->eof)
  1754. dcc[idx].type->eof(idx);
  1755. else {
  1756. putlog(LOG_MISC, "*",
  1757. "*** ATTENTION: DEAD SOCKET (%d) OF TYPE %s UNTRAPPED",
  1758. i, dcc[idx].type ? dcc[idx].type->name : "*UNKNOWN*");
  1759. killsock(i);
  1760. lostdcc(idx);
  1761. }
  1762. idx = dcc_total + 1;
  1763. }
  1764. if (idx == dcc_total) {
  1765. putlog(LOG_MISC, "*",
  1766. "(@) EOF socket %d, not a dcc socket, not anything.", i);
  1767. close(i);
  1768. killsock(i);
  1769. }
  1770. } else if (xx == -2 && errno != EINTR) { /* select() error */
  1771. putlog(LOG_MISC, "*", STR("* Socket error #%d; recovering."), errno);
  1772. for (i = 0; i < dcc_total; i++) {
  1773. if ((fcntl(dcc[i].sock, F_GETFD, 0) == -1) && (errno = EBADF)) {
  1774. putlog(LOG_MISC, "*",
  1775. "DCC socket %d (type %d, name '%s') expired -- pfft",
  1776. dcc[i].sock, dcc[i].type, dcc[i].nick);
  1777. killsock(dcc[i].sock);
  1778. lostdcc(i);
  1779. i--;
  1780. }
  1781. }
  1782. } else if (xx == -3) {
  1783. call_hook(HOOK_IDLE);
  1784. socket_cleanup = 0; /* If we've been idle, cleanup & flush */
  1785. }
  1786. if (do_restart) {
  1787. rehash();
  1788. do_restart = 0;
  1789. }
  1790. }
  1791. }