ngircd.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  1. /*
  2. * ngIRCd -- The Next Generation IRC Daemon
  3. * Copyright (c)2001-2009 Alexander Barton (alex@barton.de).
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. * Please read the file COPYING, README and AUTHORS for more information.
  10. */
  11. #include "portab.h"
  12. /**
  13. * @file
  14. * The main program, including the C function main() which is called
  15. * by the loader of the operating system.
  16. */
  17. #include "imp.h"
  18. #include <assert.h>
  19. #include <errno.h>
  20. #include <stdio.h>
  21. #include <stdlib.h>
  22. #include <signal.h>
  23. #include <string.h>
  24. #include <unistd.h>
  25. #include <time.h>
  26. #include <sys/types.h>
  27. #include <sys/stat.h>
  28. #include <sys/wait.h>
  29. #include <fcntl.h>
  30. #include <pwd.h>
  31. #include <grp.h>
  32. #if defined(DEBUG) && defined(HAVE_MTRACE)
  33. #include <mcheck.h>
  34. #endif
  35. #include "defines.h"
  36. #include "resolve.h"
  37. #include "conn.h"
  38. #include "conf-ssl.h"
  39. #include "client.h"
  40. #include "channel.h"
  41. #include "conf.h"
  42. #include "lists.h"
  43. #include "log.h"
  44. #include "parse.h"
  45. #include "irc.h"
  46. #ifdef ZEROCONF
  47. #include "rendezvous.h"
  48. #endif
  49. #include "exp.h"
  50. #include "ngircd.h"
  51. static void Initialize_Signal_Handler PARAMS(( void ));
  52. static void Signal_Handler PARAMS(( int Signal ));
  53. static void Show_Version PARAMS(( void ));
  54. static void Show_Help PARAMS(( void ));
  55. static void Pidfile_Create PARAMS(( pid_t pid ));
  56. static void Pidfile_Delete PARAMS(( void ));
  57. static void Fill_Version PARAMS(( void ));
  58. static void Setup_FDStreams PARAMS(( void ));
  59. static bool NGIRCd_Init PARAMS(( bool ));
  60. /**
  61. * The main() function of ngIRCd.
  62. * Here all starts: this function is called by the operating system loader,
  63. * it is the first portion of code executed of ngIRCd.
  64. * @param argc The number of arguments passed to ngIRCd on the command line.
  65. * @param argv An array containing all the arguments passed to ngIRCd.
  66. * @return Global exit code of ngIRCd, zero on success.
  67. */
  68. GLOBAL int
  69. main( int argc, const char *argv[] )
  70. {
  71. bool ok, configtest = false;
  72. bool NGIRCd_NoDaemon = false;
  73. int i;
  74. size_t n;
  75. #if defined(DEBUG) && defined(HAVE_MTRACE)
  76. /* enable GNU libc memory tracing when running in debug mode
  77. * and functionality available */
  78. mtrace();
  79. #endif
  80. umask( 0077 );
  81. NGIRCd_SignalQuit = NGIRCd_SignalRestart = NGIRCd_SignalRehash = false;
  82. NGIRCd_Passive = false;
  83. #ifdef DEBUG
  84. NGIRCd_Debug = false;
  85. #endif
  86. #ifdef SNIFFER
  87. NGIRCd_Sniffer = false;
  88. #endif
  89. strlcpy( NGIRCd_ConfFile, SYSCONFDIR, sizeof( NGIRCd_ConfFile ));
  90. strlcat( NGIRCd_ConfFile, CONFIG_FILE, sizeof( NGIRCd_ConfFile ));
  91. Fill_Version( );
  92. /* parse conmmand line */
  93. for( i = 1; i < argc; i++ )
  94. {
  95. ok = false;
  96. if(( argv[i][0] == '-' ) && ( argv[i][1] == '-' ))
  97. {
  98. /* long option */
  99. if( strcmp( argv[i], "--config" ) == 0 )
  100. {
  101. if( i + 1 < argc )
  102. {
  103. /* Ok, there's an parameter left */
  104. strlcpy( NGIRCd_ConfFile, argv[i + 1], sizeof( NGIRCd_ConfFile ));
  105. /* next parameter */
  106. i++; ok = true;
  107. }
  108. }
  109. if( strcmp( argv[i], "--configtest" ) == 0 )
  110. {
  111. configtest = true;
  112. ok = true;
  113. }
  114. #ifdef DEBUG
  115. if( strcmp( argv[i], "--debug" ) == 0 )
  116. {
  117. NGIRCd_Debug = true;
  118. ok = true;
  119. }
  120. #endif
  121. if( strcmp( argv[i], "--help" ) == 0 )
  122. {
  123. Show_Version( );
  124. puts( "" ); Show_Help( ); puts( "" );
  125. exit( 1 );
  126. }
  127. if( strcmp( argv[i], "--nodaemon" ) == 0 )
  128. {
  129. NGIRCd_NoDaemon = true;
  130. ok = true;
  131. }
  132. if( strcmp( argv[i], "--passive" ) == 0 )
  133. {
  134. NGIRCd_Passive = true;
  135. ok = true;
  136. }
  137. #ifdef SNIFFER
  138. if( strcmp( argv[i], "--sniffer" ) == 0 )
  139. {
  140. NGIRCd_Sniffer = true;
  141. ok = true;
  142. }
  143. #endif
  144. if( strcmp( argv[i], "--version" ) == 0 )
  145. {
  146. Show_Version( );
  147. exit( 1 );
  148. }
  149. }
  150. else if(( argv[i][0] == '-' ) && ( argv[i][1] != '-' ))
  151. {
  152. /* short option */
  153. for( n = 1; n < strlen( argv[i] ); n++ )
  154. {
  155. ok = false;
  156. #ifdef DEBUG
  157. if (argv[i][n] == 'd') {
  158. NGIRCd_Debug = true;
  159. ok = true;
  160. }
  161. #endif
  162. if (argv[i][n] == 'f') {
  163. if(( ! argv[i][n + 1] ) && ( i + 1 < argc ))
  164. {
  165. /* Ok, next character is a blank */
  166. strlcpy( NGIRCd_ConfFile, argv[i + 1], sizeof( NGIRCd_ConfFile ));
  167. /* go to the following parameter */
  168. i++;
  169. n = strlen( argv[i] );
  170. ok = true;
  171. }
  172. }
  173. if (argv[i][n] == 'h') {
  174. Show_Version();
  175. puts(""); Show_Help(); puts("");
  176. exit(1);
  177. }
  178. if (argv[i][n] == 'n') {
  179. NGIRCd_NoDaemon = true;
  180. ok = true;
  181. }
  182. if (argv[i][n] == 'p') {
  183. NGIRCd_Passive = true;
  184. ok = true;
  185. }
  186. #ifdef SNIFFER
  187. if (argv[i][n] == 's') {
  188. NGIRCd_Sniffer = true;
  189. ok = true;
  190. }
  191. #endif
  192. if (argv[i][n] == 't') {
  193. configtest = true;
  194. ok = true;
  195. }
  196. if (argv[i][n] == 'V') {
  197. Show_Version();
  198. exit(1);
  199. }
  200. if (! ok) {
  201. printf( "%s: invalid option \"-%c\"!\n", PACKAGE_NAME, argv[i][n] );
  202. printf( "Try \"%s --help\" for more information.\n", PACKAGE_NAME );
  203. exit( 1 );
  204. }
  205. }
  206. }
  207. if( ! ok )
  208. {
  209. printf( "%s: invalid option \"%s\"!\n", PACKAGE_NAME, argv[i] );
  210. printf( "Try \"%s --help\" for more information.\n", PACKAGE_NAME );
  211. exit( 1 );
  212. }
  213. }
  214. /* Debug-Level (for IRCs "VERSION" command) */
  215. NGIRCd_DebugLevel[0] = '\0';
  216. #ifdef DEBUG
  217. if( NGIRCd_Debug ) strcpy( NGIRCd_DebugLevel, "1" );
  218. #endif
  219. #ifdef SNIFFER
  220. if( NGIRCd_Sniffer )
  221. {
  222. NGIRCd_Debug = true;
  223. strcpy( NGIRCd_DebugLevel, "2" );
  224. }
  225. #endif
  226. if( configtest )
  227. {
  228. Show_Version( ); puts( "" );
  229. exit( Conf_Test( ));
  230. }
  231. while( ! NGIRCd_SignalQuit )
  232. {
  233. /* Initialize global variables */
  234. NGIRCd_Start = time( NULL );
  235. (void)strftime( NGIRCd_StartStr, 64, "%a %b %d %Y at %H:%M:%S (%Z)", localtime( &NGIRCd_Start ));
  236. NGIRCd_SignalRehash = false;
  237. NGIRCd_SignalRestart = false;
  238. NGIRCd_SignalQuit = false;
  239. /* Initialize modules, part I */
  240. Log_Init( ! NGIRCd_NoDaemon );
  241. Conf_Init( );
  242. /* Initialize the "main program": chroot environment, user and
  243. * group ID, ... */
  244. if (!NGIRCd_Init(NGIRCd_NoDaemon)) {
  245. Log(LOG_ALERT, "Fatal: Initialization failed");
  246. exit(1);
  247. }
  248. /* Initialize modules, part II: these functions are eventually
  249. * called with already dropped privileges ... */
  250. Channel_Init( );
  251. Client_Init( );
  252. #ifdef ZEROCONF
  253. Rendezvous_Init( );
  254. #endif
  255. Conn_Init( );
  256. #ifdef DEBUG
  257. /* Redirect stderr handle to "error file" for debugging
  258. * when not running in "no daemon" mode: */
  259. if( ! NGIRCd_NoDaemon ) Log_InitErrorfile( );
  260. #endif
  261. Initialize_Signal_Handler( );
  262. /*
  263. * create protocol and server identification.
  264. * The syntax used by ngIRCd in PASS commands and the extended flags
  265. * are described in doc/Protocol.txt
  266. */
  267. #ifdef IRCPLUS
  268. snprintf( NGIRCd_ProtoID, sizeof NGIRCd_ProtoID, "%s%s %s|%s:%s", PROTOVER, PROTOIRCPLUS, PACKAGE_NAME, PACKAGE_VERSION, IRCPLUSFLAGS );
  269. #ifdef ZLIB
  270. strcat( NGIRCd_ProtoID, "Z" );
  271. #endif
  272. if( Conf_OperCanMode ) strcat( NGIRCd_ProtoID, "o" );
  273. #else
  274. snprintf( NGIRCd_ProtoID, sizeof NGIRCd_ProtoID, "%s%s %s|%s", PROTOVER, PROTOIRC, PACKAGE_NAME, PACKAGE_VERSION );
  275. #endif
  276. strlcat( NGIRCd_ProtoID, " P", sizeof NGIRCd_ProtoID );
  277. #ifdef ZLIB
  278. strlcat( NGIRCd_ProtoID, "Z", sizeof NGIRCd_ProtoID );
  279. #endif
  280. LogDebug("Protocol and server ID is \"%s\".", NGIRCd_ProtoID);
  281. Channel_InitPredefined( );
  282. if( Conn_InitListeners( ) < 1 )
  283. {
  284. Log( LOG_ALERT, "Server isn't listening on a single port!" );
  285. Log( LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME );
  286. Pidfile_Delete( );
  287. exit( 1 );
  288. }
  289. /* Hauptschleife */
  290. Conn_Handler( );
  291. /* Alles abmelden */
  292. Conn_Exit( );
  293. #ifdef ZEROCONF
  294. Rendezvous_Exit( );
  295. #endif
  296. Client_Exit( );
  297. Channel_Exit( );
  298. Log_Exit( );
  299. }
  300. Pidfile_Delete( );
  301. return 0;
  302. } /* main */
  303. /**
  304. * Generate ngIRCd "version string".
  305. * This string is generated once and then stored in NGIRCd_Version for
  306. * further usage, for example by the IRC command VERSION and the --version
  307. * command line switch.
  308. */
  309. static void
  310. Fill_Version( void )
  311. {
  312. NGIRCd_VersionAddition[0] = '\0';
  313. #ifdef SYSLOG
  314. strlcpy( NGIRCd_VersionAddition, "SYSLOG", sizeof NGIRCd_VersionAddition );
  315. #endif
  316. #ifdef ZLIB
  317. if( NGIRCd_VersionAddition[0] )
  318. strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
  319. strlcat( NGIRCd_VersionAddition, "ZLIB", sizeof NGIRCd_VersionAddition );
  320. #endif
  321. #ifdef SSL_SUPPORT
  322. if ( NGIRCd_VersionAddition[0] ) strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
  323. strlcat( NGIRCd_VersionAddition, "SSL", sizeof NGIRCd_VersionAddition );
  324. #endif
  325. #ifdef TCPWRAP
  326. if( NGIRCd_VersionAddition[0] )
  327. strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
  328. strlcat( NGIRCd_VersionAddition, "TCPWRAP", sizeof NGIRCd_VersionAddition );
  329. #endif
  330. #ifdef ZEROCONF
  331. if( NGIRCd_VersionAddition[0] )
  332. strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
  333. strlcat( NGIRCd_VersionAddition, "ZEROCONF", sizeof NGIRCd_VersionAddition );
  334. #endif
  335. #ifdef IDENTAUTH
  336. if( NGIRCd_VersionAddition[0] )
  337. strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
  338. strlcat( NGIRCd_VersionAddition, "IDENT", sizeof NGIRCd_VersionAddition );
  339. #endif
  340. #ifdef DEBUG
  341. if( NGIRCd_VersionAddition[0] )
  342. strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
  343. strlcat( NGIRCd_VersionAddition, "DEBUG", sizeof NGIRCd_VersionAddition );
  344. #endif
  345. #ifdef SNIFFER
  346. if( NGIRCd_VersionAddition[0] )
  347. strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
  348. strlcat( NGIRCd_VersionAddition, "SNIFFER", sizeof NGIRCd_VersionAddition );
  349. #endif
  350. #ifdef STRICT_RFC
  351. if( NGIRCd_VersionAddition[0] )
  352. strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
  353. strlcat( NGIRCd_VersionAddition, "RFC", sizeof NGIRCd_VersionAddition );
  354. #endif
  355. #ifdef IRCPLUS
  356. if( NGIRCd_VersionAddition[0] )
  357. strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
  358. strlcat( NGIRCd_VersionAddition, "IRCPLUS", sizeof NGIRCd_VersionAddition );
  359. #endif
  360. #ifdef WANT_IPV6
  361. if (NGIRCd_VersionAddition[0])
  362. strlcat(NGIRCd_VersionAddition, "+", sizeof(NGIRCd_VersionAddition));
  363. strlcat(NGIRCd_VersionAddition, "IPv6", sizeof(NGIRCd_VersionAddition));
  364. #endif
  365. if( NGIRCd_VersionAddition[0] )
  366. strlcat( NGIRCd_VersionAddition, "-", sizeof( NGIRCd_VersionAddition ));
  367. strlcat( NGIRCd_VersionAddition, TARGET_CPU, sizeof( NGIRCd_VersionAddition ));
  368. strlcat( NGIRCd_VersionAddition, "/", sizeof( NGIRCd_VersionAddition ));
  369. strlcat( NGIRCd_VersionAddition, TARGET_VENDOR, sizeof( NGIRCd_VersionAddition ));
  370. strlcat( NGIRCd_VersionAddition, "/", sizeof( NGIRCd_VersionAddition ));
  371. strlcat( NGIRCd_VersionAddition, TARGET_OS, sizeof( NGIRCd_VersionAddition ));
  372. snprintf(NGIRCd_Version, sizeof NGIRCd_Version, "%s %s-%s",
  373. PACKAGE_NAME, PACKAGE_VERSION, NGIRCd_VersionAddition);
  374. } /* Fill_Version */
  375. /**
  376. * Reload the server configuration file.
  377. */
  378. GLOBAL void
  379. NGIRCd_Rehash( void )
  380. {
  381. char old_name[CLIENT_ID_LEN];
  382. unsigned old_nicklen;
  383. Log( LOG_NOTICE|LOG_snotice, "Re-reading configuration NOW!" );
  384. NGIRCd_SignalRehash = false;
  385. /* Remember old server name and nick name length */
  386. strlcpy( old_name, Conf_ServerName, sizeof old_name );
  387. old_nicklen = Conf_MaxNickLength;
  388. /* Re-read configuration ... */
  389. if (!Conf_Rehash( ))
  390. return;
  391. /* Close down all listening sockets */
  392. Conn_ExitListeners( );
  393. /* Recover old server name and nick name length: these values can't
  394. * be changed during run-time */
  395. if (strcmp(old_name, Conf_ServerName) != 0 ) {
  396. strlcpy(Conf_ServerName, old_name, sizeof Conf_ServerName);
  397. Log(LOG_ERR, "Can't change \"ServerName\" on runtime! Ignored new name.");
  398. }
  399. if (old_nicklen != Conf_MaxNickLength) {
  400. Conf_MaxNickLength = old_nicklen;
  401. Log(LOG_ERR, "Can't change \"MaxNickLength\" on runtime! Ignored new value.");
  402. }
  403. /* Create new pre-defined channels */
  404. Channel_InitPredefined( );
  405. if (!ConnSSL_InitLibrary())
  406. Log(LOG_WARNING, "Re-Initializing SSL failed, using old keys");
  407. /* Start listening on sockets */
  408. Conn_InitListeners( );
  409. /* Sync configuration with established connections */
  410. Conn_SyncServerStruct( );
  411. Log( LOG_NOTICE|LOG_snotice, "Re-reading of configuration done." );
  412. } /* NGIRCd_Rehash */
  413. /**
  414. * Initialize the signal handler.
  415. */
  416. static void
  417. Initialize_Signal_Handler( void )
  418. {
  419. #ifdef HAVE_SIGACTION
  420. struct sigaction saction;
  421. memset( &saction, 0, sizeof( saction ));
  422. saction.sa_handler = Signal_Handler;
  423. #ifdef SA_RESTART
  424. saction.sa_flags |= SA_RESTART;
  425. #endif
  426. #ifdef SA_NOCLDWAIT
  427. saction.sa_flags |= SA_NOCLDWAIT;
  428. #endif
  429. sigaction(SIGINT, &saction, NULL);
  430. sigaction(SIGQUIT, &saction, NULL);
  431. sigaction(SIGTERM, &saction, NULL);
  432. sigaction(SIGHUP, &saction, NULL);
  433. sigaction(SIGCHLD, &saction, NULL);
  434. /* we handle write errors properly; ignore SIGPIPE */
  435. saction.sa_handler = SIG_IGN;
  436. sigaction(SIGPIPE, &saction, NULL);
  437. #else
  438. signal(SIGINT, Signal_Handler);
  439. signal(SIGQUIT, Signal_Handler);
  440. signal(SIGTERM, Signal_Handler);
  441. signal(SIGHUP, Signal_Handler);
  442. signal(SIGCHLD, Signal_Handler);
  443. signal(SIGPIPE, SIG_IGN);
  444. #endif
  445. } /* Initialize_Signal_Handler */
  446. /**
  447. * Signal handler of ngIRCd.
  448. * This function is called whenever ngIRCd catches a signal sent by the
  449. * user and/or the system to it. For example SIGTERM and SIGHUP.
  450. * @param Signal Number of the signal to handle.
  451. */
  452. static void
  453. Signal_Handler( int Signal )
  454. {
  455. switch( Signal )
  456. {
  457. case SIGTERM:
  458. case SIGINT:
  459. case SIGQUIT:
  460. /* shut down sever */
  461. NGIRCd_SignalQuit = true;
  462. break;
  463. case SIGHUP:
  464. /* re-read configuration */
  465. NGIRCd_SignalRehash = true;
  466. break;
  467. case SIGCHLD:
  468. /* child-process exited, avoid zombies */
  469. while (waitpid( -1, NULL, WNOHANG) > 0)
  470. ;
  471. break;
  472. #ifdef DEBUG
  473. default:
  474. /* unbekanntes bzw. unbehandeltes Signal */
  475. Log( LOG_DEBUG, "Got signal %d! Ignored.", Signal );
  476. #endif
  477. }
  478. } /* Signal_Handler */
  479. /**
  480. * Display copyright and version information of ngIRCd on the console.
  481. */
  482. static void
  483. Show_Version( void )
  484. {
  485. puts( NGIRCd_Version );
  486. puts( "Copyright (c)2001-2009 Alexander Barton (<alex@barton.de>) and Contributors." );
  487. puts( "Homepage: <http://ngircd.barton.de/>\n" );
  488. puts( "This is free software; see the source for copying conditions. There is NO" );
  489. puts( "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." );
  490. } /* Show_Version */
  491. /**
  492. * Display a short help text on the console.
  493. * This help depends on the configuration of the executable and only shows
  494. * options that are actually enabled.
  495. */
  496. static void
  497. Show_Help( void )
  498. {
  499. #ifdef DEBUG
  500. puts( " -d, --debug log extra debug messages" );
  501. #endif
  502. puts( " -f, --config <f> use file <f> as configuration file" );
  503. puts( " -n, --nodaemon don't fork and don't detach from controlling terminal" );
  504. puts( " -p, --passive disable automatic connections to other servers" );
  505. #ifdef SNIFFER
  506. puts( " -s, --sniffer enable network sniffer and display all IRC traffic" );
  507. #endif
  508. puts( " -t, --configtest read, validate and display configuration; then exit" );
  509. puts( " -V, --version output version information and exit" );
  510. puts( " -h, --help display this help and exit" );
  511. } /* Show_Help */
  512. /**
  513. * Delete the file containing the process ID (PID).
  514. */
  515. static void
  516. Pidfile_Delete( void )
  517. {
  518. /* Pidfile configured? */
  519. if( ! Conf_PidFile[0] ) return;
  520. #ifdef DEBUG
  521. Log( LOG_DEBUG, "Removing PID file (%s) ...", Conf_PidFile );
  522. #endif
  523. if( unlink( Conf_PidFile ))
  524. Log( LOG_ERR, "Error unlinking PID file (%s): %s", Conf_PidFile, strerror( errno ));
  525. } /* Pidfile_Delete */
  526. /**
  527. * Create the file containing the process ID of ngIRCd ("PID file").
  528. * @param pid The process ID to be stored in this file.
  529. */
  530. static void
  531. Pidfile_Create(pid_t pid)
  532. {
  533. int pidfd;
  534. char pidbuf[64];
  535. int len;
  536. /* Pidfile configured? */
  537. if( ! Conf_PidFile[0] ) return;
  538. #ifdef DEBUG
  539. Log( LOG_DEBUG, "Creating PID file (%s) ...", Conf_PidFile );
  540. #endif
  541. pidfd = open( Conf_PidFile, O_RDWR|O_CREAT|O_EXCL, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
  542. if ( pidfd < 0 ) {
  543. Log( LOG_ERR, "Error writing PID file (%s): %s", Conf_PidFile, strerror( errno ));
  544. return;
  545. }
  546. len = snprintf(pidbuf, sizeof pidbuf, "%ld\n", (long)pid);
  547. if (len < 0 || len >= (int)sizeof pidbuf) {
  548. Log( LOG_ERR, "Error converting pid");
  549. return;
  550. }
  551. if (write(pidfd, pidbuf, (size_t)len) != (ssize_t)len)
  552. Log( LOG_ERR, "Can't write PID file (%s): %s", Conf_PidFile, strerror( errno ));
  553. if( close(pidfd) != 0 )
  554. Log( LOG_ERR, "Error closing PID file (%s): %s", Conf_PidFile, strerror( errno ));
  555. } /* Pidfile_Create */
  556. /**
  557. * Redirect stdin, stdout and stderr to apropriate file handles.
  558. */
  559. static void
  560. Setup_FDStreams( void )
  561. {
  562. int fd;
  563. /* Test if we can open /dev/null for reading and writing. If not
  564. * we are most probably chrooted already and the server has been
  565. * restarted. So we simply don't try to redirect stdXXX ... */
  566. fd = open( "/dev/null", O_RDWR );
  567. if ( fd < 0 ) {
  568. Log(LOG_WARNING, "Could not open /dev/null: %s", strerror(errno));
  569. return;
  570. }
  571. fflush(stdout);
  572. fflush(stderr);
  573. /* Create new stdin(0), stdout(1) and stderr(2) descriptors */
  574. dup2( fd, 0 ); dup2( fd, 1 ); dup2( fd, 2 );
  575. /* Close newly opened file descriptor if not stdin/out/err */
  576. if( fd > 2 ) close( fd );
  577. } /* Setup_FDStreams */
  578. static bool
  579. NGIRCd_getNobodyID(uid_t *uid, gid_t *gid )
  580. {
  581. struct passwd *pwd;
  582. #ifdef __CYGWIN__
  583. /* Cygwin kludge.
  584. * It can return EINVAL instead of EPERM
  585. * so, if we are already unprivileged,
  586. * use id of current user.
  587. */
  588. if (geteuid() && getuid()) {
  589. *uid = getuid();
  590. *gid = getgid();
  591. return true;
  592. }
  593. #endif
  594. pwd = getpwnam("nobody");
  595. if (!pwd) return false;
  596. if ( !pwd->pw_uid || !pwd->pw_gid)
  597. return false;
  598. *uid = pwd->pw_uid;
  599. *gid = pwd->pw_gid;
  600. endpwent();
  601. return true;
  602. }
  603. static bool
  604. NGIRCd_Init( bool NGIRCd_NoDaemon )
  605. {
  606. static bool initialized;
  607. bool chrooted = false;
  608. struct passwd *pwd;
  609. struct group *grp;
  610. int real_errno;
  611. pid_t pid;
  612. if (initialized)
  613. return true;
  614. if (!ConnSSL_InitLibrary())
  615. Log(LOG_WARNING,
  616. "Warning: Error during SSL initialization, continuing ...");
  617. if( Conf_Chroot[0] ) {
  618. if( chdir( Conf_Chroot ) != 0 ) {
  619. Log( LOG_ERR, "Can't chdir() in ChrootDir (%s): %s", Conf_Chroot, strerror( errno ));
  620. return false;
  621. }
  622. if( chroot( Conf_Chroot ) != 0 ) {
  623. if (errno != EPERM) {
  624. Log( LOG_ERR, "Can't change root directory to \"%s\": %s",
  625. Conf_Chroot, strerror( errno ));
  626. return false;
  627. }
  628. } else {
  629. chrooted = true;
  630. Log( LOG_INFO, "Changed root and working directory to \"%s\".", Conf_Chroot );
  631. }
  632. }
  633. if (Conf_UID == 0) {
  634. Log(LOG_INFO, "ServerUID must not be 0, using \"nobody\" instead.", Conf_UID);
  635. if (! NGIRCd_getNobodyID(&Conf_UID, &Conf_GID)) {
  636. Log(LOG_WARNING, "Could not get user/group ID of user \"nobody\": %s",
  637. errno ? strerror(errno) : "not found" );
  638. return false;
  639. }
  640. }
  641. if (getgid() != Conf_GID) {
  642. /* Change group ID */
  643. if (setgid(Conf_GID) != 0) {
  644. real_errno = errno;
  645. Log( LOG_ERR, "Can't change group ID to %u: %s", Conf_GID, strerror( errno ));
  646. if (real_errno != EPERM)
  647. return false;
  648. }
  649. }
  650. if (getuid() != Conf_UID) {
  651. /* Change user ID */
  652. if (setuid(Conf_UID) != 0) {
  653. real_errno = errno;
  654. Log(LOG_ERR, "Can't change user ID to %u: %s", Conf_UID, strerror(errno));
  655. if (real_errno != EPERM)
  656. return false;
  657. }
  658. }
  659. initialized = true;
  660. /* Normally a child process is forked which isn't any longer
  661. * connected to ther controlling terminal. Use "--nodaemon"
  662. * to disable this "daemon mode" (useful for debugging). */
  663. if ( ! NGIRCd_NoDaemon ) {
  664. pid = fork( );
  665. if( pid > 0 ) {
  666. /* "Old" process: exit. */
  667. exit( 0 );
  668. }
  669. if( pid < 0 ) {
  670. /* Error!? */
  671. fprintf( stderr, "%s: Can't fork: %s!\nFatal error, exiting now ...\n",
  672. PACKAGE_NAME, strerror( errno ));
  673. exit( 1 );
  674. }
  675. /* New child process */
  676. #ifndef NeXT
  677. (void)setsid( );
  678. #else
  679. setpgrp(0, getpid());
  680. #endif
  681. chdir( "/" );
  682. /* Detach stdin, stdout and stderr */
  683. Setup_FDStreams( );
  684. }
  685. pid = getpid();
  686. Pidfile_Create( pid );
  687. /* Check UID/GID we are running as, can be different from values
  688. * configured (e. g. if we were already started with a UID>0. */
  689. Conf_UID = getuid();
  690. Conf_GID = getgid();
  691. pwd = getpwuid( Conf_UID );
  692. grp = getgrgid( Conf_GID );
  693. Log(LOG_INFO, "Running as user %s(%ld), group %s(%ld), with PID %ld.",
  694. pwd ? pwd->pw_name : "unknown", (long)Conf_UID,
  695. grp ? grp->gr_name : "unknown", (long)Conf_GID, (long)pid);
  696. if (chrooted) {
  697. Log(LOG_INFO, "Running with root directory \"%s\".",
  698. Conf_Chroot );
  699. return true;
  700. } else
  701. Log(LOG_INFO, "Not running with changed root directory.");
  702. /* Change working directory to home directory of the user
  703. * we are running as (only when running in daemon mode and not in chroot) */
  704. if ( pwd ) {
  705. if (!NGIRCd_NoDaemon ) {
  706. if( chdir( pwd->pw_dir ) == 0 )
  707. Log( LOG_DEBUG, "Changed working directory to \"%s\" ...", pwd->pw_dir );
  708. else
  709. Log( LOG_INFO, "Notice: Can't change working directory to \"%s\": %s",
  710. pwd->pw_dir, strerror( errno ));
  711. }
  712. } else {
  713. Log( LOG_ERR, "Can't get user informaton for UID %d!?", Conf_UID );
  714. }
  715. return true;
  716. }
  717. /* -eof- */