You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

2876 lines
103 KiB

  1. /** BEGIN COPYRIGHT BLOCK
  2. * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission.
  3. * Copyright (C) 2005 Red Hat, Inc.
  4. * All rights reserved.
  5. *
  6. * License: GPL (version 3 or any later version).
  7. * See LICENSE for details.
  8. * END COPYRIGHT BLOCK **/
  9. #ifdef HAVE_CONFIG_H
  10. #include <config.h>
  11. #endif
  12. #include <string.h>
  13. #include <sys/types.h>
  14. #include <unistd.h>
  15. #include <sys/socket.h>
  16. #include <errno.h>
  17. #include <netinet/in.h>
  18. #include <arpa/inet.h>
  19. #include <sys/types.h>
  20. #include <netinet/tcp.h>
  21. #include <netdb.h>
  22. #include <sys/time.h>
  23. #include <sys/wait.h>
  24. #include <pthread.h>
  25. #include <stdint.h>
  26. #if defined(HAVE_MNTENT_H)
  27. #include <mntent.h>
  28. #endif
  29. #include <time.h>
  30. #include <signal.h>
  31. #include <fcntl.h>
  32. #define TCPLEN_T int
  33. #ifdef NEED_FILIO
  34. #include <sys/filio.h>
  35. #else /* NEED_FILIO */
  36. #include <sys/ioctl.h>
  37. #endif /* NEED_FILIO */
  38. /* for some reason, linux tty stuff defines CTIME */
  39. #include <stdio.h>
  40. #if defined(LINUX) || defined(__FreeBSD__)
  41. #ifdef LINUX
  42. #undef CTIME
  43. #endif /* linux*/
  44. #include <sys/param.h>
  45. #include <sys/mount.h>
  46. #else /* Linux or fbsd */
  47. #include <sys/mnttab.h>
  48. #endif
  49. #include <sys/statvfs.h>
  50. #include "slap.h"
  51. #include "slapi-plugin.h"
  52. #include "snmp_collator.h"
  53. #include <private/pprio.h>
  54. #include <ssl.h>
  55. #include "fe.h"
  56. #if defined(ENABLE_LDAPI)
  57. #include "getsocketpeer.h"
  58. #endif /* ENABLE_LDAPI */
  59. #if defined(LDAP_IOCP)
  60. #define SLAPD_WAKEUP_TIMER 250
  61. #else
  62. #define SLAPD_WAKEUP_TIMER 250
  63. #endif
  64. int slapd_wakeup_timer = SLAPD_WAKEUP_TIMER; /* time in ms to wakeup */
  65. #ifdef notdef /* GGOODREPL */
  66. /*
  67. * time in secs to do housekeeping:
  68. * this must be greater than slapd_wakeup_timer
  69. */
  70. short slapd_housekeeping_timer = 10;
  71. #endif /* notdef GGOODREPL */
  72. PRFileDesc *signalpipe[2];
  73. static int writesignalpipe = SLAPD_INVALID_SOCKET;
  74. static int readsignalpipe = SLAPD_INVALID_SOCKET;
  75. #define FDS_SIGNAL_PIPE 0
  76. static PRThread *disk_thread_p = NULL;
  77. static PRCondVar *diskmon_cvar = NULL;
  78. static PRLock *diskmon_mutex = NULL;
  79. void disk_monitoring_stop(void);
  80. typedef struct listener_info
  81. {
  82. PRStackElem stackelem; /* must be first in struct for PRStack to work */
  83. int idx; /* index of this listener in the ct->fd array */
  84. PRFileDesc *listenfd; /* the listener fd */
  85. int secure;
  86. int local;
  87. Connection_Table *ct; /* for listen job callback */
  88. struct ns_job_t *ns_job; /* the ns accept job */
  89. } listener_info;
  90. static size_t listeners = 0; /* number of listener sockets */
  91. static listener_info *listener_idxs = NULL; /* array of indexes of listener sockets in the ct->fd array */
  92. #define SLAPD_POLL_LISTEN_READY(xxflagsxx) (xxflagsxx & PR_POLL_READ)
  93. static int get_configured_connection_table_size(void);
  94. #ifdef RESOLVER_NEEDS_LOW_FILE_DESCRIPTORS
  95. static void get_loopback_by_addr(void);
  96. #endif
  97. static PRFileDesc **createprlistensockets(unsigned short port,
  98. PRNetAddr **listenaddr,
  99. int secure,
  100. int local);
  101. static const char *netaddr2string(const PRNetAddr *addr, char *addrbuf, size_t addrbuflen);
  102. static void set_shutdown(int);
  103. static void setup_pr_read_pds(Connection_Table *ct, PRFileDesc **n_tcps, PRFileDesc **s_tcps, PRFileDesc **i_unix, PRIntn *num_to_read);
  104. #ifdef HPUX10
  105. static void *catch_signals();
  106. #endif
  107. static int createsignalpipe(void);
  108. static char *
  109. get_pid_file(void)
  110. {
  111. return (pid_file);
  112. }
  113. static int
  114. accept_and_configure(int s __attribute__((unused)), PRFileDesc *pr_acceptfd, PRNetAddr *pr_netaddr, int addrlen __attribute__((unused)), int secure, int local, PRFileDesc **pr_clonefd)
  115. {
  116. int ns = 0;
  117. PRIntervalTime pr_timeout = PR_MillisecondsToInterval(slapd_wakeup_timer);
  118. (*pr_clonefd) = PR_Accept(pr_acceptfd, pr_netaddr, pr_timeout);
  119. if (!(*pr_clonefd)) {
  120. PRErrorCode prerr = PR_GetError();
  121. slapi_log_err(SLAPI_LOG_ERR, "accept_and_configure", "PR_Accept() failed, " SLAPI_COMPONENT_NAME_NSPR " error %d (%s)\n",
  122. prerr, slapd_pr_strerror(prerr));
  123. return (SLAPD_INVALID_SOCKET);
  124. }
  125. ns = configure_pr_socket(pr_clonefd, secure, local);
  126. return ns;
  127. }
  128. /*
  129. * This is the shiny new re-born daemon function, without all the hair
  130. */
  131. static int handle_new_connection(Connection_Table *ct, int tcps, PRFileDesc *pr_acceptfd, int secure, int local, Connection **newconn);
  132. static void handle_pr_read_ready(Connection_Table *ct, PRIntn num_poll);
  133. static int clear_signal(struct POLL_STRUCT *fds);
  134. static void unfurl_banners(Connection_Table *ct, daemon_ports_t *ports, PRFileDesc **n_tcps, PRFileDesc **s_tcps, PRFileDesc **i_unix);
  135. static int write_pid_file(void);
  136. static int init_shutdown_detect(void);
  137. /* Globals which are used to store the sockets between
  138. * calls to daemon_pre_setuid_init() and the daemon thread
  139. * creation. */
  140. int
  141. daemon_pre_setuid_init(daemon_ports_t *ports)
  142. {
  143. int rc = 0;
  144. if (0 != ports->n_port) {
  145. ports->n_socket = createprlistensockets(ports->n_port,
  146. ports->n_listenaddr, 0, 0);
  147. }
  148. if (config_get_security() && (0 != ports->s_port)) {
  149. ports->s_socket = createprlistensockets((unsigned short)ports->s_port,
  150. ports->s_listenaddr, 1, 0);
  151. } else {
  152. ports->s_socket = SLAPD_INVALID_SOCKET;
  153. }
  154. #if defined(ENABLE_LDAPI)
  155. /* ldapi */
  156. if (0 != ports->i_port) {
  157. ports->i_socket = createprlistensockets(1, ports->i_listenaddr, 0, 1);
  158. }
  159. #endif /* ENABLE_LDAPI */
  160. return (rc);
  161. }
  162. /*
  163. * The time_shutdown static variable is used to signal the time thread
  164. * to shutdown. We used to shut down the time thread when g_get_shutdown()
  165. * returned a non-zero value, but that caused the clock to stop, so to speak,
  166. * and all error log entries to have the same timestamp once the shutdown
  167. * process began.
  168. */
  169. static int time_shutdown = 0;
  170. /*
  171. * Return a copy of the mount point for the specified directory
  172. */
  173. #if LINUX
  174. char *
  175. disk_mon_get_mount_point(char *dir)
  176. {
  177. struct mntent *mnt;
  178. struct stat s;
  179. dev_t dev_id;
  180. FILE *fp;
  181. if (stat(dir, &s) != 0) {
  182. return NULL;
  183. }
  184. dev_id = s.st_dev;
  185. if ((fp = setmntent("/proc/mounts", "r")) == NULL) {
  186. return NULL;
  187. }
  188. while ((mnt = getmntent(fp))) {
  189. if (stat(mnt->mnt_dir, &s) != 0) {
  190. continue;
  191. }
  192. if (s.st_dev == dev_id) {
  193. endmntent(fp);
  194. return (slapi_ch_strdup(mnt->mnt_dir));
  195. }
  196. }
  197. endmntent(fp);
  198. return NULL;
  199. }
  200. #elif __FreeBSD__
  201. char *
  202. disk_mon_get_mount_point(char *dir)
  203. {
  204. struct statfs sb;
  205. if (statfs(dir, &sb) != 0) {
  206. return NULL;
  207. }
  208. return slapi_ch_strdup(sb.f_mntonname);
  209. }
  210. #endif
  211. /*
  212. * Get the mount point of the directory, and add it to the
  213. * list. Skip duplicate mount points.
  214. */
  215. void
  216. disk_mon_add_dir(char ***list, char *directory)
  217. {
  218. char *dir = disk_mon_get_mount_point(directory);
  219. if (dir == NULL) {
  220. return;
  221. }
  222. if (!charray_inlist(*list, dir)) {
  223. slapi_ch_array_add(list, dir);
  224. } else {
  225. slapi_ch_free((void **)&dir);
  226. }
  227. }
  228. /*
  229. * We gather all the log, txn log, config, and db directories
  230. */
  231. void
  232. disk_mon_get_dirs(char ***list)
  233. {
  234. slapdFrontendConfig_t *config = getFrontendConfig();
  235. Slapi_Backend *be = NULL;
  236. char *cookie = NULL;
  237. char *dir = NULL;
  238. /* Add /var just to be safe */
  239. #ifdef LOCALSTATEDIR
  240. disk_mon_add_dir(list, LOCALSTATEDIR);
  241. #else
  242. disk_mon_add_dir(list, "/var");
  243. #endif
  244. /* config and backend directories */
  245. CFG_LOCK_READ(config);
  246. disk_mon_add_dir(list, config->configdir);
  247. disk_mon_add_dir(list, config->accesslog);
  248. disk_mon_add_dir(list, config->errorlog);
  249. disk_mon_add_dir(list, config->auditlog);
  250. disk_mon_add_dir(list, config->auditfaillog);
  251. CFG_UNLOCK_READ(config);
  252. be = slapi_get_first_backend(&cookie);
  253. while (be) {
  254. if (slapi_back_get_info(be, BACK_INFO_DIRECTORY, (void **)&dir) == LDAP_SUCCESS) {
  255. /* db directory */
  256. disk_mon_add_dir(list, dir);
  257. }
  258. if (slapi_back_get_info(be, BACK_INFO_LOG_DIRECTORY, (void **)&dir) == LDAP_SUCCESS) {
  259. /* txn log dir */
  260. disk_mon_add_dir(list, dir);
  261. }
  262. be = (backend *)slapi_get_next_backend(cookie);
  263. }
  264. slapi_ch_free((void **)&cookie);
  265. }
  266. /*
  267. * This function gets the stats of the directory and returns total space,
  268. * available space, and used space of the directory.
  269. */
  270. int32_t
  271. disk_get_info(char *dir, uint64_t *total_space, uint64_t *avail_space, uint64_t *used_space)
  272. {
  273. int32_t rc = LDAP_SUCCESS;
  274. struct statvfs buf;
  275. uint64_t freeBytes = 0;
  276. uint64_t blockSize = 0;
  277. uint64_t blocks = 0;
  278. if (statvfs(dir, &buf) != -1) {
  279. LL_UI2L(freeBytes, buf.f_bavail);
  280. LL_UI2L(blockSize, buf.f_bsize);
  281. LL_UI2L(blocks, buf.f_blocks);
  282. LL_MUL(*total_space, blocks, blockSize);
  283. LL_MUL(*avail_space, freeBytes, blockSize);
  284. *used_space = *total_space - *avail_space;
  285. } else {
  286. *total_space = 0;
  287. *avail_space = 0;
  288. *used_space = 0;
  289. rc = -1;
  290. }
  291. return rc;
  292. }
  293. /*
  294. * This function checks the list of directories to see if any are below the
  295. * threshold. We return the directory/free disk space of the most critical
  296. * directory.
  297. */
  298. char *
  299. disk_mon_check_diskspace(char **dirs, uint64_t threshold, uint64_t *disk_space)
  300. {
  301. struct statvfs buf;
  302. uint64_t worst_disk_space = threshold;
  303. uint64_t freeBytes = 0;
  304. uint64_t blockSize = 0;
  305. char *worst_dir = NULL;
  306. int hit_threshold = 0;
  307. int i = 0;
  308. for (i = 0; dirs && dirs[i]; i++) {
  309. if (statvfs(dirs[i], &buf) != -1) {
  310. LL_UI2L(freeBytes, buf.f_bavail);
  311. LL_UI2L(blockSize, buf.f_bsize);
  312. LL_MUL(freeBytes, freeBytes, blockSize);
  313. if (LL_UCMP(freeBytes, <, threshold)) {
  314. hit_threshold = 1;
  315. if (LL_UCMP(freeBytes, <, worst_disk_space)) {
  316. worst_disk_space = freeBytes;
  317. worst_dir = dirs[i];
  318. }
  319. }
  320. }
  321. }
  322. if (hit_threshold) {
  323. *disk_space = worst_disk_space;
  324. return worst_dir;
  325. } else {
  326. *disk_space = 0;
  327. return NULL;
  328. }
  329. }
  330. #define LOGGING_OFF 0
  331. #define LOGGING_ON 1
  332. /*
  333. * Disk Space Monitoring Thread
  334. *
  335. * We need to monitor the free disk space of critical disks.
  336. *
  337. * If we get below the free disk space threshold, start taking measures
  338. * to avoid additional disk space consumption by stopping verbose logging,
  339. * access/audit logging, and deleting rotated logs.
  340. *
  341. * If this is not enough, then we need to shut slapd down to avoid
  342. * possibly corrupting the db.
  343. *
  344. * Future - it would be nice to be able to email an alert.
  345. */
  346. void
  347. disk_monitoring_thread(void *nothing __attribute__((unused)))
  348. {
  349. char **dirs = NULL;
  350. char *dirstr = NULL;
  351. uint64_t previous_mark = 0;
  352. uint64_t disk_space = 0;
  353. int64_t threshold = 0;
  354. uint64_t halfway = 0;
  355. time_t start = 0;
  356. time_t now = 0;
  357. int deleted_rotated_logs = 0;
  358. int readonly_on_threshold = 0;
  359. int logging_critical = 0;
  360. int passed_threshold = 0;
  361. int verbose_logging = 0;
  362. int using_accesslog = 0;
  363. int using_auditlog = 0;
  364. int using_auditfaillog = 0;
  365. int logs_disabled = 0;
  366. int grace_period = 0;
  367. int first_pass = 1;
  368. int ok_now = 0;
  369. int32_t immediate_shutdown = 0;
  370. Slapi_Backend *be = NULL;
  371. char *cookie = NULL;
  372. int32_t be_list_count = 0; /* Has the function scope and used to track adding new backends to read-only */
  373. int32_t be_index = 0; /* Is used locally to free backends and set back to read-write */
  374. Slapi_Backend *be_list[BE_LIST_SIZE + 1] = {0};
  375. while (!g_get_shutdown()) {
  376. if (!first_pass) {
  377. PR_Lock(diskmon_mutex);
  378. PR_WaitCondVar(diskmon_cvar, PR_SecondsToInterval(10));
  379. PR_Unlock(diskmon_mutex);
  380. /*
  381. * We need to subtract from disk_space to account for the
  382. * logging we just did, it doesn't hurt if we subtract a
  383. * little more than necessary.
  384. */
  385. previous_mark = disk_space - 512;
  386. ok_now = 0;
  387. } else {
  388. first_pass = 0;
  389. }
  390. /*
  391. * Get the config settings, as they could have changed
  392. */
  393. readonly_on_threshold = config_get_disk_threshold_readonly();
  394. logging_critical = config_get_disk_logging_critical();
  395. grace_period = 60 * config_get_disk_grace_period(); /* convert it to seconds */
  396. verbose_logging = config_get_errorlog_level();
  397. threshold = config_get_disk_threshold();
  398. halfway = threshold / 2;
  399. if (config_get_auditlog_logging_enabled()) {
  400. using_auditlog = 1;
  401. }
  402. if (config_get_auditfaillog_logging_enabled()) {
  403. using_auditfaillog = 1;
  404. }
  405. if (config_get_accesslog_logging_enabled()) {
  406. using_accesslog = 1;
  407. }
  408. /*
  409. * Check the disk space. Always refresh the list, as backends can be added
  410. */
  411. slapi_ch_array_free(dirs);
  412. dirs = NULL;
  413. disk_mon_get_dirs(&dirs);
  414. dirstr = disk_mon_check_diskspace(dirs, threshold, &disk_space);
  415. if (dirstr == NULL) {
  416. /*
  417. * Good, none of our disks are within the threshold,
  418. * disable readonly mode if it's on and reset the logging if we turned it off
  419. */
  420. if (passed_threshold) {
  421. if (readonly_on_threshold) {
  422. be_index = 0;
  423. if (be_list[be_index] != NULL) {
  424. while ((be = be_list[be_index++])) {
  425. slapi_log_err(SLAPI_LOG_INFO, "disk_monitoring_thread",
  426. "Putting the backend '%s' back to read-write mode\n", be->be_name);
  427. slapi_mtn_be_set_readonly(be, 0);
  428. }
  429. }
  430. }
  431. if (logs_disabled) {
  432. slapi_log_err(SLAPI_LOG_INFO, "disk_monitoring_thread",
  433. "Disk space is now within acceptable levels. Restoring the log settings.\n");
  434. if (using_accesslog) {
  435. config_set_accesslog_enabled(LOGGING_ON);
  436. }
  437. if (using_auditlog) {
  438. config_set_auditlog_enabled(LOGGING_ON);
  439. }
  440. if (using_auditfaillog) {
  441. config_set_auditfaillog_enabled(LOGGING_ON);
  442. }
  443. } else {
  444. slapi_log_err(SLAPI_LOG_INFO, "disk_monitoring_thread", "Disk space is now within acceptable levels.\n");
  445. }
  446. deleted_rotated_logs = 0;
  447. passed_threshold = 0;
  448. previous_mark = 0;
  449. logs_disabled = 0;
  450. be_list_count = 0;
  451. }
  452. continue;
  453. } else {
  454. passed_threshold = 1;
  455. }
  456. /*
  457. * Check if we are already critical
  458. */
  459. if (disk_space < 4096) { /* 4 k */
  460. slapi_log_err(SLAPI_LOG_ALERT, "disk_monitoring_thread",
  461. "Disk space is critically low on disk (%s), remaining space: %" PRIu64 " Kb. Signaling slapd for shutdown...\n",
  462. dirstr, (disk_space / 1024));
  463. immediate_shutdown = 1;
  464. goto cleanup;
  465. }
  466. /* If we are low, set all of the backends to readonly mode
  467. * Some file system, hosting backend, are possibly not full but we switch them readonly as well.
  468. * Only exception are in memory backend dse, schema, defaut_backend.
  469. */
  470. if (readonly_on_threshold) {
  471. be = slapi_get_first_backend(&cookie);
  472. while (be) {
  473. if (strcasecmp(be->be_name, DSE_BACKEND) != 0 &&
  474. strcasecmp(be->be_name, DSE_SCHEMA) != 0 &&
  475. strcasecmp(be->be_name, DEFBACKEND_NAME) != 0 &&
  476. !slapi_be_get_readonly(be))
  477. {
  478. if (be_list_count == BE_LIST_SIZE) { /* error - too many backends */
  479. slapi_log_err(SLAPI_LOG_ERR, "disk_monitoring_thread",
  480. "Too many backends match search request - cannot proceed");
  481. } else {
  482. slapi_log_err(SLAPI_LOG_ALERT, "disk_monitoring_thread",
  483. "Putting the backend '%s' to read-only mode\n", be->be_name);
  484. slapi_mtn_be_set_readonly(be, 1);
  485. be_list[be_list_count++] = be;
  486. }
  487. }
  488. be = (Slapi_Backend *)slapi_get_next_backend(cookie);
  489. }
  490. be_list[be_list_count] = NULL;
  491. slapi_ch_free_string(&cookie);
  492. }
  493. /*
  494. * If we are low, see if we are using verbose error logging, and turn it off
  495. * if logging is not critical
  496. */
  497. if (verbose_logging != 0 &&
  498. verbose_logging != LDAP_DEBUG_ANY &&
  499. verbose_logging != SLAPD_DEFAULT_FE_ERRORLOG_LEVEL &&
  500. verbose_logging != SLAPD_DEFAULT_ERRORLOG_LEVEL)
  501. {
  502. slapi_log_err(SLAPI_LOG_ALERT, "disk_monitoring_thread",
  503. "Disk space is low on disk (%s), remaining space: %" PRIu64 " Kb, "
  504. "temporarily setting error loglevel to the default level.\n",
  505. dirstr, (disk_space / 1024));
  506. /* Setting the log level back to zero, actually sets the value to LDAP_DEBUG_ANY */
  507. config_set_errorlog_level(CONFIG_LOGLEVEL_ATTRIBUTE, "0", NULL, CONFIG_APPLY);
  508. continue;
  509. }
  510. /*
  511. * If we are low, there's no verbose logging, logs are not critical, then disable the
  512. * access/audit logs, log another error, and continue.
  513. */
  514. if (!logs_disabled && !logging_critical) {
  515. slapi_log_err(SLAPI_LOG_ALERT, "disk_monitoring_thread",
  516. "Disk space is too low on disk (%s), remaining space: %" PRIu64 " Kb, disabling access and audit logging.\n",
  517. dirstr, (disk_space / 1024));
  518. config_set_accesslog_enabled(LOGGING_OFF);
  519. config_set_auditlog_enabled(LOGGING_OFF);
  520. config_set_auditfaillog_enabled(LOGGING_OFF);
  521. logs_disabled = 1;
  522. continue;
  523. }
  524. /*
  525. * If we are low, we turned off verbose logging, logs are not critical, and we disabled
  526. * access/audit logging, then delete the rotated logs, log another error, and continue.
  527. */
  528. if (!deleted_rotated_logs && !logging_critical) {
  529. slapi_log_err(SLAPI_LOG_ALERT, "disk_monitoring_thread",
  530. "Disk space is too low on disk (%s), remaining space: %" PRIu64 " Kb, deleting rotated logs.\n",
  531. dirstr, (disk_space / 1024));
  532. log__delete_rotated_logs();
  533. deleted_rotated_logs = 1;
  534. continue;
  535. }
  536. /*
  537. * Ok, we've done what we can, log a message if we continue to lose available disk space
  538. */
  539. if (disk_space < previous_mark) {
  540. slapi_log_err(SLAPI_LOG_ALERT, "disk_monitoring_thread",
  541. "Disk space is too low on disk (%s), remaining space: %" PRIu64 " Kb\n",
  542. dirstr, (disk_space / 1024));
  543. }
  544. /*
  545. * If we are below the halfway mark, and we did everything else,
  546. * go into shutdown mode. If the disk space doesn't get critical,
  547. * wait for the grace period before shutting down. This gives an
  548. * admin the chance to clean things up.
  549. */
  550. if (disk_space < halfway) {
  551. slapi_log_err(SLAPI_LOG_ALERT, "disk_monitoring_thread",
  552. "Disk space on (%s) is too far below the threshold(%" PRIu64 " bytes). "
  553. "Waiting %d minutes for disk space to be cleaned up before shutting slapd down...\n",
  554. dirstr, threshold, (grace_period / 60));
  555. start = slapi_current_utc_time();
  556. now = start;
  557. while ((now - start) < grace_period) {
  558. if (g_get_shutdown()) {
  559. be_index = 0;
  560. if (be_list[be_index] != NULL) {
  561. while ((be = be_list[be_index++])) {
  562. slapi_be_free(&be);
  563. }
  564. }
  565. return;
  566. }
  567. /*
  568. * Sleep for a little bit, but we don't want to run out of disk space
  569. * while sleeping for the entire grace period
  570. */
  571. DS_Sleep(PR_SecondsToInterval(1));
  572. /*
  573. * Now check disk space again in hopes some space was freed up
  574. */
  575. dirstr = disk_mon_check_diskspace(dirs, threshold, &disk_space);
  576. if (!dirstr) {
  577. /*
  578. * Excellent, we are back to acceptable levels, reset everything...
  579. *
  580. */
  581. if (readonly_on_threshold) {
  582. be_index = 0;
  583. if (be_list[be_index] != NULL) {
  584. while ((be = be_list[be_index++])) {
  585. slapi_log_err(SLAPI_LOG_INFO, "disk_monitoring_thread",
  586. "Putting the backend '%s' back to read-write mode\n", be->be_name);
  587. slapi_mtn_be_set_readonly(be, 0);
  588. }
  589. }
  590. }
  591. slapi_log_err(SLAPI_LOG_INFO, "disk_monitoring_thread",
  592. "Available disk space is now acceptable (%" PRIu64 " bytes). Aborting shutdown, and restoring the log settings.\n",
  593. disk_space);
  594. if (logs_disabled && using_accesslog) {
  595. config_set_accesslog_enabled(LOGGING_ON);
  596. }
  597. if (logs_disabled && using_auditlog) {
  598. config_set_auditlog_enabled(LOGGING_ON);
  599. }
  600. if (logs_disabled && using_auditfaillog) {
  601. config_set_auditfaillog_enabled(LOGGING_ON);
  602. }
  603. deleted_rotated_logs = 0;
  604. passed_threshold = 0;
  605. logs_disabled = 0;
  606. previous_mark = 0;
  607. ok_now = 1;
  608. start = 0;
  609. now = 0;
  610. be_list_count = 0;
  611. break;
  612. } else if (disk_space < 4096) { /* 4 k */
  613. /*
  614. * Disk space is critical, log an error, and shut it down now!
  615. */
  616. slapi_log_err(SLAPI_LOG_ALERT, "disk_monitoring_thread",
  617. "Disk space is critically low on disk (%s), remaining space: %" PRIu64 " Kb. Signaling slapd for shutdown...\n",
  618. dirstr, (disk_space / 1024));
  619. immediate_shutdown = 1;
  620. goto cleanup;
  621. }
  622. now = slapi_current_utc_time();
  623. }
  624. if (ok_now) {
  625. /*
  626. * Disk space is acceptable, resume normal processing
  627. */
  628. continue;
  629. }
  630. /*
  631. * If disk space was freed up we would of detected in the above while loop. So shut it down.
  632. */
  633. slapi_log_err(SLAPI_LOG_ALERT, "disk_monitoring_thread",
  634. "Disk space is still too low (%" PRIu64 " Kb). Signaling slapd for shutdown...\n",
  635. (disk_space / 1024));
  636. goto cleanup;
  637. }
  638. }
  639. cleanup:
  640. if (readonly_on_threshold) {
  641. be_index = 0;
  642. if (be_list[be_index] != NULL) {
  643. while ((be = be_list[be_index++])) {
  644. if (immediate_shutdown) {
  645. slapi_log_err(SLAPI_LOG_ALERT, "disk_monitoring_thread",
  646. "'%s' backend is set to read-only mode. "
  647. "It should be set manually to read-write mode after the instance's start.\n", be->be_name);
  648. } else {
  649. slapi_log_err(SLAPI_LOG_INFO, "disk_monitoring_thread",
  650. "Putting the backend '%s' back to read-write mode\n", be->be_name);
  651. slapi_mtn_be_set_readonly(be, 0);
  652. }
  653. }
  654. }
  655. }
  656. be_index = 0;
  657. if (be_list[be_index] != NULL) {
  658. while ((be = be_list[be_index++])) {
  659. slapi_be_free(&be);
  660. }
  661. }
  662. g_set_shutdown(SLAPI_SHUTDOWN_DISKFULL);
  663. return;
  664. }
  665. static void
  666. handle_listeners(Connection_Table *ct)
  667. {
  668. size_t idx;
  669. for (idx = 0; idx < listeners; ++idx) {
  670. int fdidx = listener_idxs[idx].idx;
  671. PRFileDesc *listenfd = listener_idxs[idx].listenfd;
  672. int secure = listener_idxs[idx].secure;
  673. int local = listener_idxs[idx].local;
  674. if (fdidx && listenfd) {
  675. if (SLAPD_POLL_LISTEN_READY(ct->fd[fdidx].out_flags)) {
  676. /* accept() the new connection, put it on the active list for handle_pr_read_ready */
  677. int rc = handle_new_connection(ct, SLAPD_INVALID_SOCKET, listenfd, secure, local, NULL);
  678. if (rc) {
  679. slapi_log_err(SLAPI_LOG_CONNS, "handle_listeners", "Error accepting new connection listenfd=%d\n",
  680. PR_FileDesc2NativeHandle(listenfd));
  681. continue;
  682. }
  683. }
  684. }
  685. }
  686. return;
  687. }
  688. /*
  689. * Convert any pre-existing DES passwords to AES.
  690. *
  691. * Grab the "password" attributes and search all the backends for
  692. * these attributes and convert them to AES if they are DES encoded.
  693. */
  694. static void
  695. convert_pbe_des_to_aes(void)
  696. {
  697. Slapi_Entry **entries = NULL;
  698. struct slapdplugin *plugin = NULL;
  699. char **attrs = NULL;
  700. char *val = NULL;
  701. int converted_des_passwd = 0;
  702. int result = -1;
  703. int have_aes = 0;
  704. int have_des = 0;
  705. int i = 0, ii = 0;
  706. /*
  707. * Check that AES plugin is enabled, and grab all the unique
  708. * password attributes.
  709. */
  710. for (plugin = get_plugin_list(PLUGIN_LIST_REVER_PWD_STORAGE_SCHEME);
  711. plugin != NULL;
  712. plugin = plugin->plg_next) {
  713. char *arg = NULL;
  714. if (plugin->plg_started && strcasecmp(plugin->plg_name, "AES") == 0) {
  715. /* We have the AES plugin, and its enabled */
  716. have_aes = 1;
  717. }
  718. if (plugin->plg_started && strcasecmp(plugin->plg_name, "DES") == 0) {
  719. /* We have the DES plugin, and its enabled */
  720. have_des = 1;
  721. }
  722. /* Gather all the unique password attributes from all the PBE plugins */
  723. for (i = 0, arg = plugin->plg_argv[i];
  724. i < plugin->plg_argc;
  725. arg = plugin->plg_argv[++i]) {
  726. if (charray_inlist(attrs, arg)) {
  727. continue;
  728. }
  729. charray_add(&attrs, slapi_ch_strdup(arg));
  730. }
  731. }
  732. if (have_aes && have_des) {
  733. /*
  734. * Find any entries in cn=config that contain DES passwords and convert
  735. * them to AES
  736. */
  737. slapi_log_err(SLAPI_LOG_HOUSE, "convert_pbe_des_to_aes",
  738. "Converting DES passwords to AES...\n");
  739. for (i = 0; attrs && attrs[i]; i++) {
  740. char *filter = PR_smprintf("%s=*", attrs[i]);
  741. Slapi_PBlock *pb = slapi_pblock_new();
  742. slapi_search_internal_set_pb(pb, "cn=config",
  743. LDAP_SCOPE_SUBTREE, filter, NULL, 0, NULL, NULL,
  744. (void *)plugin_get_default_component_id(),
  745. SLAPI_OP_FLAG_IGNORE_UNINDEXED);
  746. slapi_search_internal_pb(pb);
  747. slapi_pblock_get(pb, SLAPI_PLUGIN_INTOP_SEARCH_ENTRIES, &entries);
  748. for (ii = 0; entries && entries[ii]; ii++) {
  749. if ((val = (char *)slapi_entry_attr_get_ref(entries[ii], attrs[i]))) {
  750. if (strlen(val) >= 5 && strncmp(val, "{DES}", 5) == 0) {
  751. /*
  752. * We have a DES encoded password, convert it to AES
  753. */
  754. Slapi_Value *sval = NULL;
  755. LDAPMod mod_replace;
  756. LDAPMod *mods[2];
  757. char *replace_val[2];
  758. char *passwd = NULL;
  759. int rc = 0;
  760. /* decode the DES password */
  761. if (pw_rever_decode(val, &passwd, attrs[i]) == -1) {
  762. slapi_log_err(SLAPI_LOG_ERR, "convert_pbe_des_to_aes",
  763. "Failed to decode existing DES password for (%s)\n",
  764. slapi_entry_get_dn(entries[ii]));
  765. rc = -1;
  766. }
  767. /* encode the password */
  768. if (rc == 0) {
  769. sval = slapi_value_new_string(passwd);
  770. if (pw_rever_encode(&sval, attrs[i]) == -1) {
  771. slapi_log_err(SLAPI_LOG_ERR, "convert_pbe_des_to_aes",
  772. "failed to encode AES password for (%s)\n",
  773. slapi_entry_get_dn(entries[ii]));
  774. rc = -1;
  775. }
  776. }
  777. if (rc == 0) {
  778. Slapi_PBlock *mod_pb = slapi_pblock_new();
  779. /* replace the attribute in the entry */
  780. replace_val[0] = (char *)slapi_value_get_string(sval);
  781. replace_val[1] = NULL;
  782. mod_replace.mod_op = LDAP_MOD_REPLACE;
  783. mod_replace.mod_type = attrs[i];
  784. mod_replace.mod_values = replace_val;
  785. mods[0] = &mod_replace;
  786. mods[1] = 0;
  787. slapi_modify_internal_set_pb(mod_pb, slapi_entry_get_dn(entries[ii]),
  788. mods, 0, 0, (void *)plugin_get_default_component_id(), 0);
  789. slapi_modify_internal_pb(mod_pb);
  790. slapi_pblock_get(mod_pb, SLAPI_PLUGIN_INTOP_RESULT, &result);
  791. slapi_pblock_destroy(mod_pb);
  792. if (LDAP_SUCCESS != result) {
  793. slapi_log_err(SLAPI_LOG_ERR, "convert_pbe_des_to_aes",
  794. "Failed to convert password for (%s) error (%d)\n",
  795. slapi_entry_get_dn(entries[ii]), result);
  796. } else {
  797. slapi_log_err(SLAPI_LOG_HOUSE, "convert_pbe_des_to_aes",
  798. "Successfully converted password for (%s)\n",
  799. slapi_entry_get_dn(entries[ii]));
  800. converted_des_passwd = 1;
  801. }
  802. }
  803. slapi_ch_free_string(&passwd);
  804. slapi_value_free(&sval);
  805. }
  806. }
  807. }
  808. slapi_free_search_results_internal(pb);
  809. slapi_pblock_destroy(pb);
  810. slapi_ch_free_string(&filter);
  811. }
  812. if (!converted_des_passwd) {
  813. slapi_log_err(SLAPI_LOG_HOUSE, "convert_pbe_des_to_aes",
  814. "No DES passwords found to convert.\n");
  815. }
  816. }
  817. charray_free(attrs);
  818. }
  819. void
  820. slapd_daemon(daemon_ports_t *ports)
  821. {
  822. /* We are passed some ports---one for regular connections, one
  823. * for SSL connections, one for ldapi connections.
  824. */
  825. /* Previously there was a ton of code #defined on NET_SSL.
  826. * This looked horrible, so now I'm doing it this way:
  827. * If you want me to do SSL, pass me something in the ssl port number.
  828. * If you don't, pass me zero.
  829. */
  830. PRFileDesc **n_tcps = NULL;
  831. PRFileDesc **s_tcps = NULL;
  832. PRFileDesc **i_unix = NULL;
  833. PRFileDesc **fdesp = NULL;
  834. PRIntn num_poll = 0;
  835. PRIntervalTime pr_timeout = PR_MillisecondsToInterval(slapd_wakeup_timer);
  836. uint64_t threads;
  837. int in_referral_mode = config_check_referral_mode();
  838. int connection_table_size = get_configured_connection_table_size();
  839. the_connection_table = connection_table_new(connection_table_size);
  840. /*
  841. * Log a warning if we detect nunc-stans
  842. */
  843. if (config_get_enable_nunc_stans()) {
  844. slapi_log_err(SLAPI_LOG_WARNING, "slapd_daemon", "cn=config: nsslapd-enable-nunc-stans is on. nunc-stans has been deprecated and this flag is now ignored.\n");
  845. slapi_log_err(SLAPI_LOG_WARNING, "slapd_daemon", "cn=config: nsslapd-enable-nunc-stans should be set to off or deleted from cn=config.\n");
  846. }
  847. #ifdef RESOLVER_NEEDS_LOW_FILE_DESCRIPTORS
  848. /*
  849. * Some DNS resolver implementations, such as the one built into
  850. * Solaris <= 8, need to use one or more low numbered file
  851. * descriptors internally (probably because they use a deficient
  852. * implementation of stdio). So we make a call now that uses the
  853. * resolver so it has an opportunity to grab whatever low file
  854. * descriptors it needs (before we use up all of the low numbered
  855. * ones for incoming client connections and so on).
  856. */
  857. get_loopback_by_addr();
  858. #endif
  859. /* Retrieve the sockets from their hiding place */
  860. n_tcps = ports->n_socket;
  861. s_tcps = ports->s_socket;
  862. #if defined(ENABLE_LDAPI)
  863. i_unix = ports->i_socket;
  864. #endif /* ENABLE_LDAPI */
  865. createsignalpipe();
  866. /* Setup our signal interception. */
  867. init_shutdown_detect();
  868. if (
  869. (n_tcps == NULL) &&
  870. #if defined(ENABLE_LDAPI)
  871. (i_unix == NULL) &&
  872. #endif /* ENABLE_LDAPI */
  873. (s_tcps == NULL)) { /* nothing to do */
  874. slapi_log_err(SLAPI_LOG_ERR, "slapd_daemon", "No port to listen on\n");
  875. exit(1);
  876. }
  877. init_op_threads();
  878. /*
  879. * If we are monitoring disk space, then create the mutex, the cvar,
  880. * and the monitoring thread.
  881. */
  882. if (config_get_disk_monitoring()) {
  883. if ((diskmon_mutex = PR_NewLock()) == NULL) {
  884. slapi_log_err(SLAPI_LOG_ERR, "slapd_daemon",
  885. "Cannot create new lock for disk space monitoring. " SLAPI_COMPONENT_NAME_NSPR " error %d (%s)\n",
  886. PR_GetError(), slapd_pr_strerror(PR_GetError()));
  887. g_set_shutdown(SLAPI_SHUTDOWN_EXIT);
  888. }
  889. if (diskmon_mutex) {
  890. if ((diskmon_cvar = PR_NewCondVar(diskmon_mutex)) == NULL) {
  891. slapi_log_err(SLAPI_LOG_EMERG, "slapd_daemon",
  892. "Cannot create new condition variable for disk space monitoring. " SLAPI_COMPONENT_NAME_NSPR " error %d (%s)\n",
  893. PR_GetError(), slapd_pr_strerror(PR_GetError()));
  894. g_set_shutdown(SLAPI_SHUTDOWN_EXIT);
  895. }
  896. }
  897. if (diskmon_mutex && diskmon_cvar) {
  898. disk_thread_p = PR_CreateThread(PR_SYSTEM_THREAD,
  899. (VFP)(void *)disk_monitoring_thread, NULL,
  900. PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD,
  901. PR_JOINABLE_THREAD,
  902. SLAPD_DEFAULT_THREAD_STACKSIZE);
  903. if (NULL == disk_thread_p) {
  904. PRErrorCode errorCode = PR_GetError();
  905. slapi_log_err(SLAPI_LOG_EMERG, "slapd_daemon", "Unable to create disk monitoring thread - Shutting Down (" SLAPI_COMPONENT_NAME_NSPR " error %d - %s)\n",
  906. errorCode, slapd_pr_strerror(errorCode));
  907. g_set_shutdown(SLAPI_SHUTDOWN_EXIT);
  908. }
  909. }
  910. }
  911. /* We are now ready to accept incoming connections */
  912. if (n_tcps != NULL) {
  913. PRNetAddr **nap = ports->n_listenaddr;
  914. for (fdesp = n_tcps; fdesp && *fdesp; fdesp++, nap++) {
  915. if (PR_Listen(*fdesp, config_get_listen_backlog_size()) == PR_FAILURE) {
  916. PRErrorCode prerr = PR_GetError();
  917. char addrbuf[256];
  918. slapi_log_err(SLAPI_LOG_EMERG, "slapd_daemon",
  919. "PR_Listen() on %s port %d failed: %s error %d (%s)\n",
  920. netaddr2string(*nap, addrbuf, sizeof(addrbuf)),
  921. ports->n_port, SLAPI_COMPONENT_NAME_NSPR, prerr,
  922. slapd_pr_strerror(prerr));
  923. g_set_shutdown(SLAPI_SHUTDOWN_EXIT);
  924. }
  925. listeners++;
  926. }
  927. }
  928. if (s_tcps != NULL) {
  929. PRNetAddr **sap = ports->s_listenaddr;
  930. for (fdesp = s_tcps; fdesp && *fdesp; fdesp++, sap++) {
  931. if (PR_Listen(*fdesp, config_get_listen_backlog_size()) == PR_FAILURE) {
  932. PRErrorCode prerr = PR_GetError();
  933. char addrbuf[256];
  934. slapi_log_err(SLAPI_LOG_EMERG, "slapd_daemon",
  935. "PR_Listen() on %s port %d failed: %s error %d (%s)\n",
  936. netaddr2string(*sap, addrbuf, sizeof(addrbuf)),
  937. ports->s_port, SLAPI_COMPONENT_NAME_NSPR, prerr,
  938. slapd_pr_strerror(prerr));
  939. g_set_shutdown(SLAPI_SHUTDOWN_EXIT);
  940. }
  941. listeners++;
  942. }
  943. }
  944. #if defined(ENABLE_LDAPI)
  945. if (i_unix != NULL) {
  946. PRNetAddr **iap = ports->i_listenaddr;
  947. for (fdesp = i_unix; fdesp && *fdesp; fdesp++, iap++) {
  948. if (PR_Listen(*fdesp, config_get_listen_backlog_size()) == PR_FAILURE) {
  949. PRErrorCode prerr = PR_GetError();
  950. slapi_log_err(SLAPI_LOG_EMERG, "slapd_daemon",
  951. "listen() on %s failed: error %d (%s)\n",
  952. (*iap)->local.path,
  953. prerr,
  954. slapd_pr_strerror(prerr));
  955. g_set_shutdown(SLAPI_SHUTDOWN_EXIT);
  956. }
  957. listeners++;
  958. }
  959. }
  960. #endif /* ENABLE_LDAPI */
  961. listener_idxs = (listener_info *)slapi_ch_calloc(listeners, sizeof(*listener_idxs));
  962. /*
  963. * Convert old DES encoded passwords to AES
  964. */
  965. convert_pbe_des_to_aes();
  966. /* Now we write the pid file, indicating that the server is finally and listening for connections */
  967. write_pid_file();
  968. /* The server is ready and listening for connections. Logging "slapd started" message. */
  969. unfurl_banners(the_connection_table, ports, n_tcps, s_tcps, i_unix);
  970. #ifdef WITH_SYSTEMD
  971. sd_notifyf(0, "READY=1\n"
  972. "STATUS=slapd started: Ready to process requests\n"
  973. "MAINPID=%lu",
  974. (unsigned long)getpid());
  975. #endif
  976. /* The meat of the operation is in a loop on a call to select */
  977. while (!g_get_shutdown()) {
  978. int select_return = 0;
  979. PRErrorCode prerr;
  980. setup_pr_read_pds(the_connection_table, n_tcps, s_tcps, i_unix, &num_poll);
  981. select_return = POLL_FN(the_connection_table->fd, num_poll, pr_timeout);
  982. switch (select_return) {
  983. case 0: /* Timeout */
  984. break;
  985. case -1: /* Error */
  986. prerr = PR_GetError();
  987. slapi_log_err(SLAPI_LOG_TRACE, "slapd_daemon", "PR_Poll() failed, " SLAPI_COMPONENT_NAME_NSPR " error %d (%s)\n",
  988. prerr, slapd_system_strerror(prerr));
  989. break;
  990. default: /* either a new connection or some new data ready */
  991. /* handle new connections from the listeners */
  992. handle_listeners(the_connection_table);
  993. /* handle new data ready */
  994. handle_pr_read_ready(the_connection_table, connection_table_size);
  995. clear_signal(the_connection_table->fd);
  996. break;
  997. }
  998. }
  999. /* We get here when the server is shutting down */
  1000. /* Do what we have to do before death */
  1001. #ifdef WITH_SYSTEMD
  1002. sd_notify(0, "STOPPING=1");
  1003. #endif
  1004. connection_table_abandon_all_operations(the_connection_table); /* abandon all operations in progress */
  1005. if (!in_referral_mode) {
  1006. ps_stop_psearch_system(); /* stop any persistent searches */
  1007. }
  1008. /* free the listener indexes */
  1009. slapi_ch_free((void **)&listener_idxs);
  1010. for (fdesp = n_tcps; fdesp && *fdesp; fdesp++) {
  1011. PR_Close(*fdesp);
  1012. }
  1013. slapi_ch_free((void **)&n_tcps);
  1014. for (fdesp = i_unix; fdesp && *fdesp; fdesp++) {
  1015. PR_Close(*fdesp);
  1016. }
  1017. slapi_ch_free((void **)&i_unix);
  1018. for (fdesp = s_tcps; fdesp && *fdesp; fdesp++) {
  1019. PR_Close(*fdesp);
  1020. }
  1021. slapi_ch_free((void **)&s_tcps);
  1022. /* freeing NetAddrs */
  1023. {
  1024. PRNetAddr **nap;
  1025. for (nap = ports->n_listenaddr; nap && *nap; nap++) {
  1026. slapi_ch_free((void **)nap);
  1027. }
  1028. slapi_ch_free((void **)&ports->n_listenaddr);
  1029. for (nap = ports->s_listenaddr; nap && *nap; nap++) {
  1030. slapi_ch_free((void **)nap);
  1031. }
  1032. slapi_ch_free((void **)&ports->s_listenaddr);
  1033. #if defined(ENABLE_LDAPI)
  1034. for (nap = ports->i_listenaddr; nap && *nap; nap++) {
  1035. slapi_ch_free((void **)nap);
  1036. }
  1037. slapi_ch_free((void **)&ports->i_listenaddr);
  1038. #endif
  1039. }
  1040. op_thread_cleanup();
  1041. housekeeping_stop(); /* Run this after op_thread_cleanup() logged sth */
  1042. disk_monitoring_stop();
  1043. /*
  1044. * Now that they are abandonded, we need to mark them as done.
  1045. * In NS while it's safe to allow excess jobs to be cleaned by
  1046. * by the walk and ns_job_done of remaining queued events, the
  1047. * issue is that if we allow something to live past this point
  1048. * the CT is freed from underneath, and bad things happen (tm).
  1049. *
  1050. * NOTE: We do this after we stop psearch, because there could
  1051. * be a race between flagging the psearch done, and users still
  1052. * try to send on the connection. Similar with op_threads.
  1053. */
  1054. connection_table_disconnect_all(the_connection_table);
  1055. if (!in_referral_mode) {
  1056. /* signal tasks to start shutting down */
  1057. task_cancel_all();
  1058. }
  1059. threads = g_get_active_threadcnt();
  1060. if (threads > 0) {
  1061. slapi_log_err(SLAPI_LOG_INFO, "slapd_daemon",
  1062. "slapd shutting down - waiting for %" PRIu64 " thread%s to terminate\n",
  1063. threads, (threads > 1) ? "s" : "");
  1064. }
  1065. threads = g_get_active_threadcnt();
  1066. while (threads > 0) {
  1067. PRPollDesc xpd;
  1068. char x;
  1069. int spe = 0;
  1070. /* try to read from the signal pipe, in case threads are
  1071. * blocked on it. */
  1072. xpd.fd = signalpipe[0];
  1073. xpd.in_flags = PR_POLL_READ;
  1074. xpd.out_flags = 0;
  1075. spe = PR_Poll(&xpd, 1, PR_INTERVAL_NO_WAIT);
  1076. if (spe > 0) {
  1077. spe = PR_Read(signalpipe[0], &x, 1);
  1078. if (spe < 0) {
  1079. PRErrorCode prerr = PR_GetError();
  1080. slapi_log_err(SLAPI_LOG_ERR, "slapd_daemon", "listener could not clear signal pipe, " SLAPI_COMPONENT_NAME_NSPR " error %d (%s)\n",
  1081. prerr, slapd_system_strerror(prerr));
  1082. break;
  1083. }
  1084. } else if (spe == -1) {
  1085. PRErrorCode prerr = PR_GetError();
  1086. slapi_log_err(SLAPI_LOG_ERR, "slapd_daemon", "PR_Poll() failed, " SLAPI_COMPONENT_NAME_NSPR " error %d (%s)\n",
  1087. prerr, slapd_system_strerror(prerr));
  1088. break;
  1089. } else {
  1090. /* no data */
  1091. }
  1092. DS_Sleep(PR_INTERVAL_NO_WAIT);
  1093. if (threads != g_get_active_threadcnt()) {
  1094. slapi_log_err(SLAPI_LOG_TRACE, "slapd_daemon",
  1095. "slapd shutting down - waiting for %" PRIu64 " threads to terminate\n",
  1096. g_get_active_threadcnt());
  1097. threads = g_get_active_threadcnt();
  1098. }
  1099. }
  1100. slapi_log_err(SLAPI_LOG_INFO, "slapd_daemon",
  1101. "slapd shutting down - closing down internal subsystems and plugins\n");
  1102. /* let backends do whatever cleanup they need to do */
  1103. slapi_log_err(SLAPI_LOG_TRACE, "slapd_daemon",
  1104. "slapd shutting down - waiting for backends to close down\n");
  1105. eq_stop();
  1106. if (!in_referral_mode) {
  1107. task_shutdown();
  1108. uniqueIDGenCleanup();
  1109. }
  1110. plugin_closeall(1 /* Close Backends */, 1 /* Close Globals */);
  1111. /*
  1112. * connection_table_free could use callbacks in the backend.
  1113. * (e.g., be_search_results_release)
  1114. * Thus, it needs to be called before be_cleanupall.
  1115. */
  1116. connection_table_free(the_connection_table);
  1117. the_connection_table = NULL;
  1118. if (!in_referral_mode) {
  1119. /* Close SNMP collator after the plugins closed...
  1120. * Replication plugin still performs internal ops that
  1121. * may try to increment snmp stats.
  1122. * Fix for defect 523780
  1123. */
  1124. snmp_collator_stop();
  1125. mapping_tree_free();
  1126. }
  1127. /* In theory, threads could be working "up to" this point
  1128. * so we only flush access logs when we can guarantee that the buffered
  1129. * content is "complete".
  1130. */
  1131. log_access_flush();
  1132. be_cleanupall();
  1133. plugin_dependency_freeall();
  1134. connection_post_shutdown_cleanup();
  1135. slapi_log_err(SLAPI_LOG_TRACE, "slapd_daemon", "slapd shutting down - backends closed down\n");
  1136. referrals_free();
  1137. schema_destroy_dse_lock();
  1138. /* tell the time thread to shutdown and then wait for it */
  1139. time_shutdown = 1;
  1140. if (g_get_shutdown() == SLAPI_SHUTDOWN_DISKFULL) {
  1141. /* This is a server-induced shutdown, we need to manually remove the pid file */
  1142. if (unlink(get_pid_file())) {
  1143. slapi_log_err(SLAPI_LOG_ERR, "slapd_daemon", "Failed to remove pid file %s\n", get_pid_file());
  1144. }
  1145. }
  1146. }
  1147. int
  1148. signal_listner()
  1149. {
  1150. /* Replaces previous macro---called to bump the thread out of select */
  1151. if (write(writesignalpipe, "", 1) != 1) {
  1152. /* this now means that the pipe is full
  1153. * this is not a problem just go-on
  1154. */
  1155. slapi_log_err(SLAPI_LOG_CONNS,
  1156. "signal_listner", "Listener could not write to signal pipe %d\n",
  1157. errno);
  1158. }
  1159. return (0);
  1160. }
  1161. static int
  1162. clear_signal(struct POLL_STRUCT *fds)
  1163. {
  1164. if (fds[FDS_SIGNAL_PIPE].out_flags & SLAPD_POLL_FLAGS) {
  1165. char buf[200];
  1166. slapi_log_err(SLAPI_LOG_CONNS, "clear_signal", "Listener got signaled\n");
  1167. if (read(readsignalpipe, buf, 200) < 1) {
  1168. slapi_log_err(SLAPI_LOG_ERR, "clear_signal", "Listener could not clear signal pipe\n");
  1169. }
  1170. }
  1171. return 0;
  1172. }
  1173. static int first_time_setup_pr_read_pds = 1;
  1174. static int listen_addr_count = 0;
  1175. static void
  1176. setup_pr_read_pds(Connection_Table *ct, PRFileDesc **n_tcps, PRFileDesc **s_tcps, PRFileDesc **i_unix, PRIntn *num_to_read)
  1177. {
  1178. Connection *c = NULL;
  1179. Connection *next = NULL;
  1180. LBER_SOCKET socketdesc = SLAPD_INVALID_SOCKET;
  1181. int accept_new_connections;
  1182. static int last_accept_new_connections = -1;
  1183. PRIntn count = 0;
  1184. slapdFrontendConfig_t *slapdFrontendConfig = getFrontendConfig();
  1185. size_t n_listeners = 0;
  1186. accept_new_connections = ((ct->size - g_get_current_conn_count()) > slapdFrontendConfig->reservedescriptors);
  1187. if (!accept_new_connections) {
  1188. if (last_accept_new_connections) {
  1189. slapi_log_err(SLAPI_LOG_ERR, "setup_pr_read_pds",
  1190. "Not listening for new connections - too many fds open\n");
  1191. /* reinitialize n_tcps and s_tcps to the pds */
  1192. first_time_setup_pr_read_pds = 1;
  1193. }
  1194. } else {
  1195. if (!last_accept_new_connections &&
  1196. last_accept_new_connections != -1) {
  1197. slapi_log_err(SLAPI_LOG_ERR, "setup_pr_read_pds",
  1198. "Listening for new connections again\n");
  1199. /* reinitialize n_tcps and s_tcps to the pds */
  1200. first_time_setup_pr_read_pds = 1;
  1201. }
  1202. }
  1203. last_accept_new_connections = accept_new_connections;
  1204. /* initialize the mapping from connection table entries to fds entries */
  1205. if (first_time_setup_pr_read_pds) {
  1206. int i;
  1207. for (i = 0; i < ct->size; i++) {
  1208. ct->c[i].c_fdi = SLAPD_INVALID_SOCKET_INDEX;
  1209. }
  1210. /* The fds entry for the signalpipe is always FDS_SIGNAL_PIPE (== 0) */
  1211. count = FDS_SIGNAL_PIPE;
  1212. ct->fd[count].fd = signalpipe[0];
  1213. ct->fd[count].in_flags = SLAPD_POLL_FLAGS;
  1214. ct->fd[count].out_flags = 0;
  1215. count++;
  1216. /* The fds entry for n_tcps starts with n_tcps and less than n_tcpe */
  1217. ct->n_tcps = count;
  1218. if (n_tcps != NULL && accept_new_connections) {
  1219. PRFileDesc **fdesc = NULL;
  1220. for (fdesc = n_tcps; fdesc && *fdesc; fdesc++, count++) {
  1221. ct->fd[count].fd = *fdesc;
  1222. ct->fd[count].in_flags = SLAPD_POLL_FLAGS;
  1223. ct->fd[count].out_flags = 0;
  1224. listener_idxs[n_listeners].listenfd = *fdesc;
  1225. listener_idxs[n_listeners].idx = count;
  1226. n_listeners++;
  1227. slapi_log_err(SLAPI_LOG_HOUSE,
  1228. "setup_pr_read_pds", "Listening for connections on %d\n", socketdesc);
  1229. }
  1230. } else {
  1231. ct->fd[count].fd = NULL;
  1232. count++;
  1233. }
  1234. ct->n_tcpe = count;
  1235. ct->s_tcps = count;
  1236. /* The fds entry for s_tcps starts with s_tcps and less than s_tcpe */
  1237. if (s_tcps != NULL && accept_new_connections) {
  1238. PRFileDesc **fdesc = NULL;
  1239. for (fdesc = s_tcps; fdesc && *fdesc; fdesc++, count++) {
  1240. ct->fd[count].fd = *fdesc;
  1241. ct->fd[count].in_flags = SLAPD_POLL_FLAGS;
  1242. ct->fd[count].out_flags = 0;
  1243. listener_idxs[n_listeners].listenfd = *fdesc;
  1244. listener_idxs[n_listeners].idx = count;
  1245. listener_idxs[n_listeners].secure = 1;
  1246. n_listeners++;
  1247. slapi_log_err(SLAPI_LOG_HOUSE,
  1248. "setup_pr_read_pds", "Listening for SSL connections on %d\n", socketdesc);
  1249. }
  1250. } else {
  1251. ct->fd[count].fd = NULL;
  1252. count++;
  1253. }
  1254. ct->s_tcpe = count;
  1255. #if defined(ENABLE_LDAPI)
  1256. ct->i_unixs = count;
  1257. /* The fds entry for i_unix starts with i_unixs and less than i_unixe */
  1258. if (i_unix != NULL && accept_new_connections) {
  1259. PRFileDesc **fdesc = NULL;
  1260. for (fdesc = i_unix; fdesc && *fdesc; fdesc++, count++) {
  1261. ct->fd[count].fd = *fdesc;
  1262. ct->fd[count].in_flags = SLAPD_POLL_FLAGS;
  1263. ct->fd[count].out_flags = 0;
  1264. listener_idxs[n_listeners].listenfd = *fdesc;
  1265. listener_idxs[n_listeners].idx = count;
  1266. listener_idxs[n_listeners].local = 1;
  1267. n_listeners++;
  1268. slapi_log_err(SLAPI_LOG_HOUSE,
  1269. "setup_pr_read_pds", "Listening for LDAPI connections on %d\n", socketdesc);
  1270. }
  1271. } else {
  1272. ct->fd[count].fd = NULL;
  1273. count++;
  1274. }
  1275. ct->i_unixe = count;
  1276. #endif
  1277. first_time_setup_pr_read_pds = 0;
  1278. listen_addr_count = count;
  1279. if (n_listeners < listeners) {
  1280. listener_idxs[n_listeners].idx = 0;
  1281. listener_idxs[n_listeners].listenfd = NULL;
  1282. }
  1283. }
  1284. /* count is the number of entries we've place in the fds array.
  1285. * listen_addr_count is counted up when
  1286. * first_time_setup_pr_read_pds is TURE. */
  1287. count = listen_addr_count;
  1288. /* Walk down the list of active connections to find
  1289. * out which connections we should poll over. If a connection
  1290. * is no longer in use, we should remove it from the linked
  1291. * list. */
  1292. c = connection_table_get_first_active_connection(ct);
  1293. while (c) {
  1294. next = connection_table_get_next_active_connection(ct, c);
  1295. if (c->c_state == CONN_STATE_FREE) {
  1296. connection_table_move_connection_out_of_active_list(ct, c);
  1297. } else {
  1298. /* we try to acquire the connection mutex, if it is already
  1299. * acquired by another thread, don't wait
  1300. */
  1301. if (pthread_mutex_trylock(&(c->c_mutex)) == EBUSY) {
  1302. c = next;
  1303. continue;
  1304. }
  1305. if (c->c_flags & CONN_FLAG_CLOSING) {
  1306. /* A worker thread has marked that this connection
  1307. * should be closed by calling disconnect_server.
  1308. * move this connection out of the active list
  1309. * the last thread to use the connection will close it
  1310. */
  1311. connection_table_move_connection_out_of_active_list(ct, c);
  1312. } else if (c->c_sd == SLAPD_INVALID_SOCKET) {
  1313. connection_table_move_connection_out_of_active_list(ct, c);
  1314. } else if (c->c_prfd != NULL) {
  1315. if ((!c->c_gettingber) && (c->c_threadnumber < c->c_max_threads_per_conn)) {
  1316. int add_fd = 1;
  1317. /* check timeout for PAGED RESULTS */
  1318. if (pagedresults_is_timedout_nolock(c)) {
  1319. /* Exceeded the timelimit; disconnect the client */
  1320. disconnect_server_nomutex(c, c->c_connid, -1,
  1321. SLAPD_DISCONNECT_IO_TIMEOUT,
  1322. 0);
  1323. connection_table_move_connection_out_of_active_list(ct,
  1324. c);
  1325. add_fd = 0; /* do not poll on this fd */
  1326. }
  1327. if (add_fd) {
  1328. ct->fd[count].fd = c->c_prfd;
  1329. ct->fd[count].in_flags = SLAPD_POLL_FLAGS;
  1330. /* slot i of the connection table is mapped to slot
  1331. * count of the fds array */
  1332. c->c_fdi = count;
  1333. count++;
  1334. }
  1335. } else {
  1336. if (c->c_threadnumber >= c->c_max_threads_per_conn) {
  1337. c->c_maxthreadsblocked++;
  1338. }
  1339. c->c_fdi = SLAPD_INVALID_SOCKET_INDEX;
  1340. }
  1341. }
  1342. pthread_mutex_unlock(&(c->c_mutex));
  1343. }
  1344. c = next;
  1345. }
  1346. if (num_to_read)
  1347. (*num_to_read) = count;
  1348. }
  1349. static int idletimeout_reslimit_handle = -1;
  1350. /*
  1351. * Register the idletimeout with the binder-based resource limits
  1352. * subsystem. A SLAPI_RESLIMIT_STATUS_... code is returned.
  1353. */
  1354. int
  1355. daemon_register_reslimits(void)
  1356. {
  1357. return (slapi_reslimit_register(SLAPI_RESLIMIT_TYPE_INT, "nsIdleTimeout",
  1358. &idletimeout_reslimit_handle));
  1359. }
  1360. static void
  1361. handle_pr_read_ready(Connection_Table *ct, PRIntn num_poll __attribute__((unused)))
  1362. {
  1363. Connection *c;
  1364. time_t curtime = slapi_current_utc_time();
  1365. #if LDAP_ERROR_LOGGING
  1366. if (slapd_ldap_debug & LDAP_DEBUG_CONNS) {
  1367. connection_table_dump_activity_to_errors_log(ct);
  1368. }
  1369. #endif /* LDAP_ERROR_LOGGING */
  1370. /*
  1371. * This function is called for all connections, so we traverse the entire
  1372. * active connection list to find any errors, activity, etc.
  1373. */
  1374. for (c = connection_table_get_first_active_connection(ct); c != NULL;
  1375. c = connection_table_get_next_active_connection(ct, c)) {
  1376. if (c->c_state != CONN_STATE_FREE) {
  1377. /* this check can be done without acquiring the mutex */
  1378. if (c->c_gettingber) {
  1379. continue;
  1380. }
  1381. pthread_mutex_lock(&(c->c_mutex));
  1382. if (connection_is_active_nolock(c) && c->c_gettingber == 0) {
  1383. PRInt16 out_flags;
  1384. short readready;
  1385. if (c->c_fdi != SLAPD_INVALID_SOCKET_INDEX) {
  1386. out_flags = ct->fd[c->c_fdi].out_flags;
  1387. } else {
  1388. out_flags = 0;
  1389. }
  1390. readready = (out_flags & SLAPD_POLL_FLAGS);
  1391. if (!readready && out_flags) {
  1392. /* some error occured */
  1393. slapi_log_err(SLAPI_LOG_CONNS,
  1394. "handle_pr_read_ready", "POLL_FN() says connection on sd %d is bad "
  1395. "(closing)\n",
  1396. c->c_sd);
  1397. disconnect_server_nomutex(c, c->c_connid, -1,
  1398. SLAPD_DISCONNECT_POLL, EPIPE);
  1399. } else if (readready) {
  1400. /* read activity */
  1401. slapi_log_err(SLAPI_LOG_CONNS,
  1402. "handle_pr_read_ready", "read activity on %d\n", c->c_ci);
  1403. c->c_idlesince = curtime;
  1404. /* This is where the work happens ! */
  1405. /* MAB: 25 jan 01, error handling added */
  1406. if ((connection_activity(c, c->c_max_threads_per_conn)) == -1) {
  1407. /* This might happen as a result of
  1408. * trying to acquire a closing connection
  1409. */
  1410. slapi_log_err(SLAPI_LOG_ERR,
  1411. "handle_pr_read_ready", "connection_activity: abandoning conn %" PRIu64 " as "
  1412. "fd=%d is already closing\n",
  1413. c->c_connid, c->c_sd);
  1414. /* The call disconnect_server should do nothing,
  1415. * as the connection c should be already set to CLOSING */
  1416. disconnect_server_nomutex(c, c->c_connid, -1,
  1417. SLAPD_DISCONNECT_POLL, EPIPE);
  1418. }
  1419. } else if (c->c_idletimeout > 0 &&
  1420. (curtime - c->c_idlesince) >= c->c_idletimeout &&
  1421. NULL == c->c_ops) {
  1422. /* idle timeout */
  1423. disconnect_server_nomutex(c, c->c_connid, -1,
  1424. SLAPD_DISCONNECT_IDLE_TIMEOUT, EAGAIN);
  1425. }
  1426. }
  1427. pthread_mutex_unlock(&(c->c_mutex));
  1428. }
  1429. }
  1430. }
  1431. /*
  1432. * wrapper functions required so we can implement ioblock_timeout and
  1433. * avoid blocking forever.
  1434. */
  1435. #define SLAPD_POLLIN 0
  1436. #define SLAPD_POLLOUT 1
  1437. /* Return 1 if the given handle is ready for input or output,
  1438. * or if it becomes ready within g_ioblock_timeout [msec].
  1439. * Return -1 if handle is not ready and g_ioblock_timeout > 0,
  1440. * or something goes seriously wrong. Otherwise, return 0.
  1441. * If -1 is returned, PR_GetError() explains why.
  1442. * Revision: handle changed to void * to allow 64bit support
  1443. *
  1444. * Caller (flush_ber) must hold conn->c_pdumutex
  1445. */
  1446. static int
  1447. slapd_poll(void *handle, int output)
  1448. {
  1449. int rc;
  1450. int ioblock_timeout = config_get_ioblocktimeout();
  1451. struct POLL_STRUCT pr_pd;
  1452. PRIntervalTime timeout = PR_MillisecondsToInterval(ioblock_timeout);
  1453. pr_pd.fd = (PRFileDesc *)handle;
  1454. pr_pd.in_flags = output ? PR_POLL_WRITE : PR_POLL_READ;
  1455. pr_pd.out_flags = 0;
  1456. rc = POLL_FN(&pr_pd, 1, timeout);
  1457. if (rc < 0) {
  1458. PRErrorCode prerr = PR_GetError();
  1459. slapi_log_err(SLAPI_LOG_ERR, "slapd_poll",
  1460. "(%d) - %s error %d (%s)\n",
  1461. (int)(uintptr_t)handle, SLAPI_COMPONENT_NAME_NSPR, prerr, slapd_pr_strerror(prerr));
  1462. if (prerr == PR_PENDING_INTERRUPT_ERROR ||
  1463. SLAPD_PR_WOULD_BLOCK_ERROR(prerr)) {
  1464. rc = 0; /* try again */
  1465. }
  1466. } else if (rc == 0 && ioblock_timeout > 0) {
  1467. PRIntn ihandle;
  1468. ihandle = PR_FileDesc2NativeHandle((PRFileDesc *)handle);
  1469. slapi_log_err(SLAPI_LOG_ERR, "slapd_poll", "(%d) - Timed out\n", ihandle);
  1470. PR_SetError(PR_IO_TIMEOUT_ERROR, EAGAIN); /* timeout */
  1471. rc = -1;
  1472. }
  1473. return rc;
  1474. }
  1475. /*
  1476. * Revision: handle changed to void * and first
  1477. * argument which used to be integer system fd is now ignored.
  1478. */
  1479. static int
  1480. write_function(int ignore __attribute__((unused)), void *buffer, int count, void *handle)
  1481. {
  1482. int sentbytes = 0;
  1483. int bytes;
  1484. int fd = PR_FileDesc2NativeHandle((PRFileDesc *)handle);
  1485. if (handle == SLAPD_INVALID_SOCKET) {
  1486. PR_SetError(PR_NOT_SOCKET_ERROR, EBADF);
  1487. } else {
  1488. while (1) {
  1489. if (slapd_poll(handle, SLAPD_POLLOUT) < 0) { /* error */
  1490. break;
  1491. }
  1492. bytes = PR_Write((PRFileDesc *)handle, (char *)buffer + sentbytes,
  1493. count - sentbytes);
  1494. if (bytes > 0) {
  1495. sentbytes += bytes;
  1496. } else if (bytes < 0) {
  1497. PRErrorCode prerr = PR_GetError();
  1498. slapi_log_err(SLAPI_LOG_CONNS, "write_function", "PR_Write(%d) " SLAPI_COMPONENT_NAME_NSPR " error %d (%s)\n",
  1499. fd, prerr, slapd_pr_strerror(prerr));
  1500. if (!SLAPD_PR_WOULD_BLOCK_ERROR(prerr)) {
  1501. if (prerr != PR_CONNECT_RESET_ERROR) {
  1502. /* 'TCP connection reset by peer': no need to log */
  1503. slapi_log_err(SLAPI_LOG_ERR, "write_function", "PR_Write(%d) " SLAPI_COMPONENT_NAME_NSPR " error %d (%s)\n",
  1504. fd, prerr, slapd_pr_strerror(prerr));
  1505. }
  1506. if (sentbytes < count) {
  1507. slapi_log_err(SLAPI_LOG_CONNS,
  1508. "write_function", "PR_Write(%d) - wrote only %d bytes (expected %d bytes) - 0 (EOF)\n", /* disconnected */
  1509. fd, sentbytes, count);
  1510. }
  1511. break; /* fatal error */
  1512. }
  1513. } else if (bytes == 0) { /* disconnect */
  1514. PRErrorCode prerr = PR_GetError();
  1515. slapi_log_err(SLAPI_LOG_CONNS,
  1516. "write_function", "PR_Write(%d) - 0 (EOF) %d:%s\n", /* disconnected */
  1517. fd, prerr, slapd_pr_strerror(prerr));
  1518. PR_SetError(PR_PIPE_ERROR, EPIPE);
  1519. break;
  1520. }
  1521. if (sentbytes == count) { /* success */
  1522. return count;
  1523. } else if (sentbytes > count) { /* too many bytes */
  1524. slapi_log_err(SLAPI_LOG_ERR,
  1525. "write_function", "PR_Write(%d) overflow - sent %d bytes (expected %d bytes) - error\n",
  1526. fd, sentbytes, count);
  1527. PR_SetError(PR_BUFFER_OVERFLOW_ERROR, EMSGSIZE);
  1528. break;
  1529. }
  1530. }
  1531. }
  1532. return -1;
  1533. }
  1534. /* The argument is a pointer to the socket descriptor */
  1535. static int
  1536. openldap_io_setup(Sockbuf_IO_Desc *sbiod, void *arg)
  1537. {
  1538. PR_ASSERT(sbiod);
  1539. if (arg != NULL) {
  1540. sbiod->sbiod_pvt = arg;
  1541. }
  1542. return 0;
  1543. }
  1544. static ber_slen_t
  1545. openldap_write_function(Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
  1546. {
  1547. Connection *conn = NULL;
  1548. PRFileDesc *fd = NULL;
  1549. PR_ASSERT(sbiod);
  1550. PR_ASSERT(sbiod->sbiod_pvt);
  1551. conn = (Connection *)sbiod->sbiod_pvt;
  1552. PR_ASSERT(conn->c_prfd);
  1553. fd = (PRFileDesc *)conn->c_prfd;
  1554. PR_ASSERT(fd != SLAPD_INVALID_SOCKET);
  1555. return write_function(0, buf, len, fd);
  1556. }
  1557. static int
  1558. openldap_io_ctrl(Sockbuf_IO_Desc *sbiod __attribute__((unused)), int opt __attribute__((unused)), void *arg __attribute__((unused)))
  1559. {
  1560. PR_ASSERT(0); /* not sure if this is needed */
  1561. return -1;
  1562. }
  1563. static int
  1564. openldap_io_close(Sockbuf_IO_Desc *sbiod __attribute__((unused)))
  1565. {
  1566. return 0; /* closing done in connection_cleanup() */
  1567. }
  1568. static Sockbuf_IO openldap_sockbuf_io = {
  1569. openldap_io_setup, /* sbi_setup */
  1570. NULL, /* sbi_remove */
  1571. openldap_io_ctrl, /* sbi_ctrl */
  1572. openldap_read_function, /* sbi_read */ /* see connection.c */
  1573. openldap_write_function, /* sbi_write */
  1574. openldap_io_close /* sbi_close */
  1575. };
  1576. int connection_type = -1; /* The type number assigned by the Factory for 'Connection' */
  1577. void
  1578. daemon_register_connection()
  1579. {
  1580. if (connection_type == -1) {
  1581. /* The factory is given the name of the object type, in
  1582. * return for a type handle. Whenever the object is created
  1583. * or destroyed the factory is called with the handle so
  1584. * that it may call the constructors or destructors registered
  1585. * with it.
  1586. */
  1587. connection_type = factory_register_type(SLAPI_EXT_CONNECTION, offsetof(Connection, c_extension));
  1588. }
  1589. }
  1590. #if defined(ENABLE_LDAPI)
  1591. int
  1592. slapd_identify_local_user(Connection *conn)
  1593. {
  1594. int ret = -1;
  1595. uid_t uid = 0;
  1596. gid_t gid = 0;
  1597. conn->c_local_valid = 0;
  1598. if (0 == slapd_get_socket_peer(conn->c_prfd, &uid, &gid)) {
  1599. conn->c_local_uid = uid;
  1600. conn->c_local_gid = gid;
  1601. conn->c_local_valid = 1;
  1602. ret = 0;
  1603. }
  1604. return ret;
  1605. }
  1606. #if defined(ENABLE_AUTOBIND)
  1607. int
  1608. slapd_bind_local_user(Connection *conn)
  1609. {
  1610. int ret = -1;
  1611. uid_t uid = conn->c_local_uid;
  1612. gid_t gid = conn->c_local_gid;
  1613. uid_t proc_uid = geteuid();
  1614. gid_t proc_gid = getegid();
  1615. if (!conn->c_local_valid) {
  1616. goto bail;
  1617. }
  1618. /* observe configuration for auto binding */
  1619. /* bind at all? */
  1620. if (config_get_ldapi_bind_switch()) {
  1621. /* map users to a dn
  1622. root may also map to an entry
  1623. */
  1624. /* require real entry? */
  1625. if (config_get_ldapi_map_entries()) {
  1626. /* get uid type to map to (e.g. uidNumber) */
  1627. char *utype = config_get_ldapi_uidnumber_type();
  1628. /* get gid type to map to (e.g. gidNumber) */
  1629. char *gtype = config_get_ldapi_gidnumber_type();
  1630. /* get base dn for search */
  1631. char *base_dn = config_get_ldapi_search_base_dn();
  1632. /* search vars */
  1633. Slapi_PBlock *search_pb = 0;
  1634. Slapi_Entry **entries = 0;
  1635. int result;
  1636. /* filter manipulation vars */
  1637. char *one_type = 0;
  1638. char *filter_tpl = 0;
  1639. char *filter = 0;
  1640. /* create filter, matching whatever is given */
  1641. if (utype && gtype) {
  1642. filter_tpl = "(&(%s=%u)(%s=%u))";
  1643. } else {
  1644. if (utype || gtype) {
  1645. filter_tpl = "(%s=%u)";
  1646. if (utype)
  1647. one_type = utype;
  1648. else
  1649. one_type = gtype;
  1650. } else {
  1651. goto entry_map_free;
  1652. }
  1653. }
  1654. if (one_type) {
  1655. if (one_type == utype)
  1656. filter = slapi_ch_smprintf(filter_tpl,
  1657. utype, uid);
  1658. else
  1659. filter = slapi_ch_smprintf(filter_tpl,
  1660. gtype, gid);
  1661. } else {
  1662. filter = slapi_ch_smprintf(filter_tpl,
  1663. utype, uid, gtype, gid);
  1664. }
  1665. /* search for single entry matching types */
  1666. search_pb = slapi_pblock_new();
  1667. slapi_search_internal_set_pb(
  1668. search_pb,
  1669. base_dn,
  1670. LDAP_SCOPE_SUBTREE,
  1671. filter,
  1672. NULL, 0, NULL, NULL,
  1673. (void *)plugin_get_default_component_id(),
  1674. 0);
  1675. slapi_search_internal_pb(search_pb);
  1676. slapi_pblock_get(
  1677. search_pb,
  1678. SLAPI_PLUGIN_INTOP_RESULT,
  1679. &result);
  1680. if (LDAP_SUCCESS == result)
  1681. slapi_pblock_get(
  1682. search_pb,
  1683. SLAPI_PLUGIN_INTOP_SEARCH_ENTRIES,
  1684. &entries);
  1685. if (entries) {
  1686. /* zero or multiple entries fail */
  1687. if (entries[0] && 0 == entries[1]) {
  1688. /* observe account locking */
  1689. ret = slapi_check_account_lock(
  1690. 0, /* pb not req */
  1691. entries[0],
  1692. 0, /* no response control */
  1693. 0, /* don't check password policy */
  1694. 0 /* don't send ldap result */
  1695. );
  1696. if (0 == ret) {
  1697. char *auth_dn = slapi_ch_strdup(
  1698. slapi_entry_get_ndn(
  1699. entries[0]));
  1700. auth_dn = slapi_dn_normalize(
  1701. auth_dn);
  1702. bind_credentials_set_nolock(
  1703. conn,
  1704. SLAPD_AUTH_OS,
  1705. auth_dn,
  1706. NULL, NULL,
  1707. NULL, entries[0]);
  1708. ret = 0;
  1709. }
  1710. }
  1711. }
  1712. entry_map_free:
  1713. /* auth_dn consumed by bind creds set */
  1714. slapi_free_search_results_internal(search_pb);
  1715. slapi_pblock_destroy(search_pb);
  1716. slapi_ch_free_string(&filter);
  1717. slapi_ch_free_string(&utype);
  1718. slapi_ch_free_string(&gtype);
  1719. slapi_ch_free_string(&base_dn);
  1720. }
  1721. /*
  1722. * We map the current process uid also to directory manager.
  1723. * This is secure as it requires local machine OR same-container volume
  1724. * access and the correct uid access. If you have access to the uid/gid
  1725. * and are on the same machine you could always just reset the rootdn hashes
  1726. * anyway ... so this is no reduction in security.
  1727. */
  1728. if (ret && (0 == uid || proc_uid == uid || proc_gid == gid)) {
  1729. /* map unix root (uidNumber:0)? */
  1730. char *root_dn = config_get_ldapi_root_dn();
  1731. if (root_dn) {
  1732. Slapi_DN *edn = slapi_sdn_new_dn_byref(
  1733. slapi_dn_normalize(root_dn));
  1734. Slapi_Entry *e = 0;
  1735. /* root might be locked too! :) */
  1736. ret = slapi_search_internal_get_entry(
  1737. edn, 0,
  1738. &e,
  1739. (void *)plugin_get_default_component_id()
  1740. );
  1741. if (0 == ret && e) {
  1742. ret = slapi_check_account_lock(
  1743. 0, /* pb not req */
  1744. e,
  1745. 0, /* no response control */
  1746. 0, /* don't check password policy */
  1747. 0 /* don't send ldap result */
  1748. );
  1749. if (1 == ret)
  1750. /* sorry root,
  1751. * just not cool enough
  1752. */
  1753. goto root_map_free;
  1754. }
  1755. /* it's ok not to find the entry,
  1756. * dn doesn't have to have an entry
  1757. * e.g. cn=Directory Manager
  1758. */
  1759. bind_credentials_set_nolock(
  1760. conn, SLAPD_AUTH_OS, root_dn,
  1761. NULL, NULL, NULL, e);
  1762. root_map_free:
  1763. /* root_dn consumed by bind creds set */
  1764. slapi_sdn_free(&edn);
  1765. slapi_entry_free(e);
  1766. ret = 0;
  1767. }
  1768. }
  1769. #if defined(ENABLE_AUTO_DN_SUFFIX)
  1770. if (ret) {
  1771. /* create phony auth dn? */
  1772. char *base = config_get_ldapi_auto_dn_suffix();
  1773. if (base) {
  1774. char *tpl = "gidNumber=%u+uidNumber=%u,";
  1775. int len =
  1776. strlen(tpl) +
  1777. strlen(base) +
  1778. 51 /* uid,gid,null,w/padding */
  1779. ;
  1780. char *dn_str = (char *)slapi_ch_malloc(
  1781. len);
  1782. char *auth_dn = (char *)slapi_ch_malloc(
  1783. len);
  1784. dn_str[0] = 0;
  1785. strcpy(dn_str, tpl);
  1786. strcat(dn_str, base);
  1787. sprintf(auth_dn, dn_str, gid, uid);
  1788. auth_dn = slapi_dn_normalize(auth_dn);
  1789. bind_credentials_set_nolock(
  1790. conn,
  1791. SLAPD_AUTH_OS,
  1792. auth_dn,
  1793. NULL, NULL, NULL, NULL);
  1794. /* auth_dn consumed by bind creds set */
  1795. slapi_ch_free_string(&dn_str);
  1796. slapi_ch_free_string(&base);
  1797. ret = 0;
  1798. }
  1799. }
  1800. #endif
  1801. }
  1802. bail:
  1803. /* if all fails, the peer is anonymous */
  1804. if (conn->c_dn) {
  1805. /* log the auto bind */
  1806. slapi_log_access(LDAP_DEBUG_STATS, "conn=%" PRIu64 " AUTOBIND dn=\"%s\"\n", conn->c_connid, conn->c_dn);
  1807. }
  1808. return ret;
  1809. }
  1810. #endif /* ENABLE_AUTOBIND */
  1811. #endif /* ENABLE_LDAPI */
  1812. void
  1813. handle_closed_connection(Connection *conn)
  1814. {
  1815. ber_sockbuf_remove_io(conn->c_sb, &openldap_sockbuf_io, LBER_SBIOD_LEVEL_PROVIDER);
  1816. }
  1817. /* NOTE: this routine is not reentrant */
  1818. static int
  1819. handle_new_connection(Connection_Table *ct, int tcps, PRFileDesc *pr_acceptfd, int secure, int local, Connection **newconn)
  1820. {
  1821. int ns = 0;
  1822. Connection *conn = NULL;
  1823. /* struct sockaddr_in from;*/
  1824. PRNetAddr from = {{0}};
  1825. PRFileDesc *pr_clonefd = NULL;
  1826. slapdFrontendConfig_t *fecfg = getFrontendConfig();
  1827. ber_len_t maxbersize;
  1828. if (newconn) {
  1829. *newconn = NULL;
  1830. }
  1831. if ((ns = accept_and_configure(tcps, pr_acceptfd, &from,
  1832. sizeof(from), secure, local, &pr_clonefd)) == SLAPD_INVALID_SOCKET) {
  1833. return -1;
  1834. }
  1835. /* get a new Connection from the Connection Table */
  1836. conn = connection_table_get_connection(ct, ns);
  1837. if (conn == NULL) {
  1838. PR_Close(pr_acceptfd);
  1839. return -1;
  1840. }
  1841. pthread_mutex_lock(&(conn->c_mutex));
  1842. /*
  1843. * Set the default idletimeout and the handle. We'll update c_idletimeout
  1844. * after each bind so we can correctly set the resource limit.
  1845. */
  1846. conn->c_idletimeout = fecfg->idletimeout;
  1847. conn->c_idletimeout_handle = idletimeout_reslimit_handle;
  1848. conn->c_sd = ns;
  1849. conn->c_prfd = pr_clonefd;
  1850. conn->c_flags &= ~CONN_FLAG_CLOSING;
  1851. /* Set per connection static config */
  1852. conn->c_maxbersize = config_get_maxbersize();
  1853. conn->c_ioblocktimeout = config_get_ioblocktimeout();
  1854. conn->c_minssf = config_get_minssf();
  1855. conn->c_enable_nagle = config_get_nagle();
  1856. conn->c_minssf_exclude_rootdse = config_get_minssf_exclude_rootdse();
  1857. conn->c_anon_access = config_get_anon_access_switch();
  1858. conn->c_max_threads_per_conn = config_get_maxthreadsperconn();
  1859. /* Store the fact that this new connection is an SSL connection */
  1860. if (secure) {
  1861. conn->c_flags |= CONN_FLAG_SSL;
  1862. }
  1863. /*
  1864. * clear the "returned events" field in ns' slot within the poll fds
  1865. * array so that handle_read_ready() doesn't look at out_flags for an
  1866. * old connection by mistake and do something bad such as close the
  1867. * connection we just accepted.
  1868. */
  1869. /* Dont have to worry about this now because of our mapping from
  1870. * the connection table to the fds array. This new connection
  1871. * won't have a mapping. */
  1872. /* fds[ns].out_flags = 0; */
  1873. ber_sockbuf_add_io(conn->c_sb, &openldap_sockbuf_io,
  1874. LBER_SBIOD_LEVEL_PROVIDER, conn);
  1875. maxbersize = conn->c_maxbersize;
  1876. ber_sockbuf_ctrl(conn->c_sb, LBER_SB_OPT_SET_MAX_INCOMING, &maxbersize);
  1877. if (secure && config_get_SSLclientAuth() != SLAPD_SSLCLIENTAUTH_OFF) {
  1878. /* Prepare to handle the client's certificate (if any): */
  1879. int rv;
  1880. rv = slapd_ssl_handshakeCallback(conn->c_prfd, (void *)handle_handshake_done, conn);
  1881. if (rv < 0) {
  1882. PRErrorCode prerr = PR_GetError();
  1883. slapi_log_err(SLAPI_LOG_ERR, "handle_new_connection", "SSL_HandshakeCallback() %d " SLAPI_COMPONENT_NAME_NSPR " error %d (%s)\n",
  1884. rv, prerr, slapd_pr_strerror(prerr));
  1885. }
  1886. rv = slapd_ssl_badCertHook(conn->c_prfd, (void *)handle_bad_certificate, conn);
  1887. if (rv < 0) {
  1888. PRErrorCode prerr = PR_GetError();
  1889. slapi_log_err(SLAPI_LOG_ERR, "handle_new_connection", "SSL_BadCertHook(%i) %i " SLAPI_COMPONENT_NAME_NSPR " error %d\n",
  1890. conn->c_sd, rv, prerr);
  1891. }
  1892. }
  1893. connection_reset(conn, ns, &from, sizeof(from), secure);
  1894. /* Call the plugin extension constructors */
  1895. conn->c_extension = factory_create_extension(connection_type, conn, NULL /* Parent */);
  1896. #if defined(ENABLE_LDAPI)
  1897. /* ldapi */
  1898. if (local) {
  1899. conn->c_unix_local = 1;
  1900. conn->c_local_ssf = config_get_localssf();
  1901. slapd_identify_local_user(conn);
  1902. }
  1903. #endif /* ENABLE_LDAPI */
  1904. connection_new_private(conn);
  1905. /* Add this connection slot to the doubly linked list of active connections. This
  1906. * list is used to find the connections that should be used in the poll call. This
  1907. * connection will be added directly after slot 0 which serves as the head of the list.
  1908. * This must be done as the very last thing before we unlock the mutex, because once it
  1909. * is added to the active list, it is live. */
  1910. if (conn != NULL && conn->c_next == NULL && conn->c_prev == NULL) {
  1911. /* Now give the new connection to the connection code */
  1912. connection_table_move_connection_on_to_active_list(the_connection_table, conn);
  1913. }
  1914. pthread_mutex_unlock(&(conn->c_mutex));
  1915. g_increment_current_conn_count();
  1916. if (newconn) {
  1917. *newconn = conn;
  1918. }
  1919. return 0;
  1920. }
  1921. static int
  1922. init_shutdown_detect(void)
  1923. {
  1924. /* First of all, we must reset the signal mask to get rid of any blockages
  1925. * the process may have inherited from its parent (such as the console), which
  1926. * might result in the process not delivering those blocked signals, and thus,
  1927. * misbehaving....
  1928. */
  1929. {
  1930. int rc;
  1931. sigset_t proc_mask;
  1932. slapi_log_err(SLAPI_LOG_TRACE, "init_shutdown_detect", "Reseting signal mask....\n");
  1933. (void)sigemptyset(&proc_mask);
  1934. rc = pthread_sigmask(SIG_SETMASK, &proc_mask, NULL);
  1935. slapi_log_err(SLAPI_LOG_TRACE, "init_shutdown_detect", "%s \n",
  1936. rc ? "Failed to reset signal mask" : "....Done (signal mask reset)!!");
  1937. }
  1938. #if defined(HPUX10)
  1939. PR_CreateThread(PR_USER_THREAD,
  1940. catch_signals,
  1941. NULL,
  1942. PR_PRIORITY_NORMAL,
  1943. PR_GLOBAL_THREAD,
  1944. PR_UNJOINABLE_THREAD,
  1945. SLAPD_DEFAULT_THREAD_STACKSIZE);
  1946. #else
  1947. #ifdef HPUX11
  1948. /* In the optimized builds for HPUX, the signal handler doesn't seem
  1949. * to get set correctly unless the primordial thread gets a chance
  1950. * to run before we make the call to SIGNAL. (At this point the
  1951. * the primordial thread has spawned the daemon thread which called
  1952. * this function.) The call to DS_Sleep will give the primordial
  1953. * thread a chance to run.
  1954. */
  1955. DS_Sleep(0);
  1956. #endif
  1957. (void)SIGNAL(SIGPIPE, SIG_IGN);
  1958. (void)SIGNAL(SIGCHLD, slapd_wait4child);
  1959. #ifndef LINUX
  1960. /* linux uses USR1/USR2 for thread synchronization, so we aren't
  1961. * allowed to mess with those.
  1962. */
  1963. (void)SIGNAL(SIGUSR1, slapd_do_nothing);
  1964. (void)SIGNAL(SIGUSR2, set_shutdown);
  1965. #endif
  1966. (void)SIGNAL(SIGTERM, set_shutdown);
  1967. (void)SIGNAL(SIGHUP, set_shutdown);
  1968. #endif /* HPUX */
  1969. return 0;
  1970. }
  1971. static void
  1972. unfurl_banners(Connection_Table *ct, daemon_ports_t *ports, PRFileDesc **n_tcps, PRFileDesc **s_tcps, PRFileDesc **i_unix)
  1973. {
  1974. slapdFrontendConfig_t *slapdFrontendConfig = getFrontendConfig();
  1975. char addrbuf[256];
  1976. int isfirsttime = 1;
  1977. if (ct->size <= slapdFrontendConfig->reservedescriptors) {
  1978. slapi_log_err(SLAPI_LOG_ERR, "slapd_daemon",
  1979. "Not enough descriptors to accept any connections. "
  1980. "This may be because the maxdescriptors configuration "
  1981. "directive is too small, the hard limit on descriptors is "
  1982. "too small (see limit(1)), or the reservedescriptors "
  1983. "configuration directive is too large. "
  1984. "Try increasing the number of descriptors available to "
  1985. "the slapd process. The current value is %d. %d "
  1986. "descriptors are currently reserved for internal "
  1987. "slapd use, so the total number of descriptors available "
  1988. "to the process must be greater than %d.\n",
  1989. ct->size, slapdFrontendConfig->reservedescriptors, slapdFrontendConfig->reservedescriptors);
  1990. exit(1);
  1991. }
  1992. /*
  1993. * This final startup message gives a definite signal to the admin
  1994. * program that the server is up. It must contain the string
  1995. * "slapd started." because some of the administrative programs
  1996. * depend on this. See ldap/admin/lib/dsalib_updown.c.
  1997. */
  1998. if (n_tcps != NULL) { /* standard LDAP */
  1999. PRNetAddr **nap = NULL;
  2000. for (nap = ports->n_listenaddr; nap && *nap; nap++) {
  2001. if (isfirsttime) {
  2002. slapi_log_err(SLAPI_LOG_INFO, "slapd_daemon",
  2003. "slapd started. Listening on %s port %d for LDAP requests\n",
  2004. netaddr2string(*nap, addrbuf, sizeof(addrbuf)),
  2005. ports->n_port);
  2006. isfirsttime = 0;
  2007. } else {
  2008. slapi_log_err(SLAPI_LOG_INFO, "slapd_daemon",
  2009. "Listening on %s port %d for LDAP requests\n",
  2010. netaddr2string(*nap, addrbuf, sizeof(addrbuf)),
  2011. ports->n_port);
  2012. }
  2013. }
  2014. }
  2015. if (s_tcps != NULL) { /* LDAP over SSL; separate port */
  2016. PRNetAddr **sap = NULL;
  2017. for (sap = ports->s_listenaddr; sap && *sap; sap++) {
  2018. if (isfirsttime) {
  2019. slapi_log_err(SLAPI_LOG_INFO, "slapd_daemon",
  2020. "slapd started. Listening on %s port %d for LDAPS requests\n",
  2021. netaddr2string(*sap, addrbuf, sizeof(addrbuf)),
  2022. ports->s_port);
  2023. isfirsttime = 0;
  2024. } else {
  2025. slapi_log_err(SLAPI_LOG_INFO, "slapd_daemon",
  2026. "Listening on %s port %d for LDAPS requests\n",
  2027. netaddr2string(*sap, addrbuf, sizeof(addrbuf)),
  2028. ports->s_port);
  2029. }
  2030. }
  2031. }
  2032. #if defined(ENABLE_LDAPI)
  2033. if (i_unix != NULL) { /* LDAPI */
  2034. PRNetAddr **iap = ports->i_listenaddr;
  2035. slapi_log_err(SLAPI_LOG_INFO, "slapd_daemon",
  2036. "%sListening on %s for LDAPI requests\n", isfirsttime ? "slapd started. " : "",
  2037. (*iap)->local.path);
  2038. }
  2039. #endif /* ENABLE_LDAPI */
  2040. }
  2041. /* On UNIX, we create a file with our PID in it */
  2042. static int
  2043. write_pid_file(void)
  2044. {
  2045. FILE *fp = NULL;
  2046. /*
  2047. * The following section of code is closely coupled with the
  2048. * admin programs. Please do not make changes here without
  2049. * consulting the start/stop code for the admin code.
  2050. */
  2051. if ((fp = fopen(get_pid_file(), "w")) != NULL) {
  2052. fprintf(fp, "%d\n", getpid());
  2053. fclose(fp);
  2054. if (chmod(get_pid_file(), S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH) != 0) {
  2055. unlink(get_pid_file());
  2056. } else {
  2057. return 0;
  2058. }
  2059. }
  2060. return -1;
  2061. }
  2062. static void
  2063. set_shutdown(int sig __attribute__((unused)))
  2064. {
  2065. /* don't log anything from a signal handler:
  2066. * you could be holding a lock when the signal was trapped. more
  2067. * specifically, you could be holding the logfile lock (and deadlock
  2068. * yourself).
  2069. */
  2070. #if 0
  2071. slapi_log_err(SLAPI_LOG_INFO, "slapd_daemon", "slapd got shutdown signal\n");
  2072. #endif
  2073. if (g_get_shutdown() == 0) {
  2074. g_set_shutdown(SLAPI_SHUTDOWN_SIGNAL);
  2075. }
  2076. #ifndef LINUX
  2077. /* don't mess with USR1/USR2 on linux, used by libpthread */
  2078. (void)SIGNAL(SIGUSR2, set_shutdown);
  2079. #endif
  2080. (void)SIGNAL(SIGTERM, set_shutdown);
  2081. (void)SIGNAL(SIGHUP, set_shutdown);
  2082. }
  2083. #ifndef LINUX
  2084. void
  2085. slapd_do_nothing(int sig)
  2086. {
  2087. /* don't log anything from a signal handler:
  2088. * you could be holding a lock when the signal was trapped. more
  2089. * specifically, you could be holding the logfile lock (and deadlock
  2090. * yourself).
  2091. */
  2092. #if 0
  2093. slapi_log_err(SLAPI_LOG_TRACE, "slapd_daemon", "slapd got SIGUSR1\n");
  2094. #endif
  2095. (void)SIGNAL(SIGUSR1, slapd_do_nothing);
  2096. #if 0
  2097. /*
  2098. * Actually do a little more: dump the conn struct and
  2099. * send it to a tmp file
  2100. */
  2101. connection_table_dump(connection_table);
  2102. #endif
  2103. }
  2104. #endif /* LINUX */
  2105. void
  2106. slapd_wait4child(int sig __attribute__((unused)))
  2107. {
  2108. WAITSTATUSTYPE status;
  2109. /* don't log anything from a signal handler:
  2110. * you could be holding a lock when the signal was trapped. more
  2111. * specifically, you could be holding the logfile lock (and deadlock
  2112. * yourself).
  2113. */
  2114. #if 0
  2115. slapi_log_err(SLAPI_LOG_ARGS, "slapd_daemon", "listener: catching SIGCHLD\n");
  2116. #endif
  2117. #ifdef USE_WAITPID
  2118. while (waitpid((pid_t)-1, 0, WAIT_FLAGS) > 0)
  2119. #else /* USE_WAITPID */
  2120. while (wait3(&status, WAIT_FLAGS, 0) > 0)
  2121. #endif /* USE_WAITPID */
  2122. ; /* NULL */
  2123. (void)SIGNAL(SIGCHLD, slapd_wait4child);
  2124. }
  2125. static PRFileDesc **
  2126. createprlistensockets(PRUint16 port, PRNetAddr **listenaddr, int secure __attribute__((unused)), int local)
  2127. {
  2128. PRFileDesc **sock;
  2129. PRNetAddr sa_server;
  2130. PRErrorCode prerr = 0;
  2131. PRSocketOptionData pr_socketoption;
  2132. char addrbuf[256];
  2133. char *logname = "createprlistensockets";
  2134. int sockcnt = 0;
  2135. int socktype;
  2136. char *socktype_str = NULL;
  2137. PRNetAddr **lap;
  2138. int i;
  2139. if (!port)
  2140. goto suppressed;
  2141. PR_ASSERT(listenaddr != NULL);
  2142. /* need to know the count */
  2143. sockcnt = 0;
  2144. for (lap = listenaddr; lap && *lap; lap++) {
  2145. sockcnt++;
  2146. }
  2147. if (0 == sockcnt) {
  2148. slapi_log_err(SLAPI_LOG_ERR, logname,
  2149. "There is no address to listen\n");
  2150. goto failed;
  2151. }
  2152. sock = (PRFileDesc **)slapi_ch_calloc(sockcnt + 1, sizeof(PRFileDesc *));
  2153. pr_socketoption.option = PR_SockOpt_Reuseaddr;
  2154. pr_socketoption.value.reuse_addr = 1;
  2155. for (i = 0, lap = listenaddr; lap && *lap && i < sockcnt; i++, lap++) {
  2156. /* create TCP socket */
  2157. socktype = PR_NetAddrFamily(*lap);
  2158. #if defined(ENABLE_LDAPI)
  2159. if (PR_AF_LOCAL == socktype) {
  2160. socktype_str = "PR_AF_LOCAL";
  2161. } else
  2162. #endif
  2163. if (PR_AF_INET6 == socktype) {
  2164. socktype_str = "PR_AF_INET6";
  2165. } else {
  2166. socktype_str = "PR_AF_INET";
  2167. }
  2168. if ((sock[i] = PR_OpenTCPSocket(socktype)) == SLAPD_INVALID_SOCKET) {
  2169. prerr = PR_GetError();
  2170. slapi_log_err(SLAPI_LOG_ERR, logname,
  2171. "PR_OpenTCPSocket(%s) failed: %s error %d (%s)\n",
  2172. socktype_str,
  2173. SLAPI_COMPONENT_NAME_NSPR, prerr, slapd_pr_strerror(prerr));
  2174. goto failed;
  2175. }
  2176. if (PR_SetSocketOption(sock[i], &pr_socketoption) == PR_FAILURE) {
  2177. prerr = PR_GetError();
  2178. slapi_log_err(SLAPI_LOG_ERR, logname,
  2179. "PR_SetSocketOption(PR_SockOpt_Reuseaddr) failed: %s error %d (%s)\n",
  2180. SLAPI_COMPONENT_NAME_NSPR, prerr, slapd_pr_strerror(prerr));
  2181. goto failed;
  2182. }
  2183. /* set up listener address, including port */
  2184. memcpy(&sa_server, *lap, sizeof(sa_server));
  2185. if (!local)
  2186. PRLDAP_SET_PORT(&sa_server, port);
  2187. if (PR_Bind(sock[i], &sa_server) == PR_FAILURE) {
  2188. prerr = PR_GetError();
  2189. if (!local) {
  2190. slapi_log_err(SLAPI_LOG_ERR, logname,
  2191. "PR_Bind() on %s port %d failed: %s error %d (%s)\n",
  2192. netaddr2string(&sa_server, addrbuf, sizeof(addrbuf)), port,
  2193. SLAPI_COMPONENT_NAME_NSPR, prerr, slapd_pr_strerror(prerr));
  2194. }
  2195. #if defined(ENABLE_LDAPI)
  2196. else {
  2197. slapi_log_err(SLAPI_LOG_ERR, logname,
  2198. "PR_Bind() on %s file %s failed: %s error %d (%s)\n",
  2199. netaddr2string(&sa_server, addrbuf, sizeof(addrbuf)),
  2200. sa_server.local.path,
  2201. SLAPI_COMPONENT_NAME_NSPR, prerr, slapd_pr_strerror(prerr));
  2202. }
  2203. #endif /* ENABLE_LDAPI */
  2204. goto failed;
  2205. }
  2206. }
  2207. #if defined(ENABLE_LDAPI)
  2208. if (local) { /* ldapi */
  2209. if (chmod((*listenaddr)->local.path,
  2210. S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)) {
  2211. slapi_log_err(SLAPI_LOG_ERR, logname, "err: %d", errno);
  2212. }
  2213. }
  2214. #endif /* ENABLE_LDAPI */
  2215. return (sock);
  2216. failed:
  2217. exit(1);
  2218. suppressed:
  2219. return (PRFileDesc **)-1;
  2220. } /* createprlistensockets */
  2221. /*
  2222. * Initialize the *addr structure based on listenhost.
  2223. * Returns: 0 if successful and -1 if not (after logging an error message).
  2224. */
  2225. int
  2226. slapd_listenhost2addr(const char *listenhost, PRNetAddr ***addr)
  2227. {
  2228. char *logname = "slapd_listenhost2addr";
  2229. PRErrorCode prerr = 0;
  2230. int rval = 0;
  2231. PRNetAddr *netaddr = (PRNetAddr *)slapi_ch_calloc(1, sizeof(PRNetAddr));
  2232. PR_ASSERT(addr != NULL);
  2233. *addr = NULL;
  2234. if (NULL == listenhost) {
  2235. /* listen on all interfaces */
  2236. if (PR_SUCCESS != PR_SetNetAddr(PR_IpAddrAny, PR_AF_INET6, 0, netaddr)) {
  2237. prerr = PR_GetError();
  2238. slapi_log_err(SLAPI_LOG_ERR, logname,
  2239. "PR_SetNetAddr(PR_IpAddrAny) failed - %s error %d (%s)\n",
  2240. SLAPI_COMPONENT_NAME_NSPR, prerr, slapd_pr_strerror(prerr));
  2241. rval = -1;
  2242. slapi_ch_free((void **)&netaddr);
  2243. }
  2244. *addr = (PRNetAddr **)slapi_ch_calloc(2, sizeof(PRNetAddr *));
  2245. (*addr)[0] = netaddr;
  2246. } else if (PR_SUCCESS == PR_StringToNetAddr(listenhost, netaddr)) {
  2247. /* PR_StringNetAddr newer than NSPR v4.6.2 supports both IPv4&v6 */;
  2248. *addr = (PRNetAddr **)slapi_ch_calloc(2, sizeof(PRNetAddr *));
  2249. (*addr)[0] = netaddr;
  2250. } else {
  2251. PRAddrInfo *infop = PR_GetAddrInfoByName(listenhost,
  2252. PR_AF_UNSPEC, (PR_AI_ADDRCONFIG | PR_AI_NOCANONNAME));
  2253. if (NULL != infop) {
  2254. void *iter = NULL;
  2255. int addrcnt = 0;
  2256. int i = 0;
  2257. /* need to count the address, first */
  2258. while ((iter = PR_EnumerateAddrInfo(iter, infop, 0, netaddr)) != NULL) {
  2259. addrcnt++;
  2260. }
  2261. if (0 == addrcnt) {
  2262. slapi_log_err(SLAPI_LOG_ERR, logname,
  2263. "PR_EnumerateAddrInfo for %s failed - %s error %d (%s)\n",
  2264. listenhost, SLAPI_COMPONENT_NAME_NSPR, prerr,
  2265. slapd_pr_strerror(prerr));
  2266. rval = -1;
  2267. } else {
  2268. char **strnetaddrs = NULL;
  2269. *addr = (PRNetAddr **)slapi_ch_calloc(addrcnt + 1, sizeof(PRNetAddr *));
  2270. iter = NULL; /* from the beginning */
  2271. memset(netaddr, 0, sizeof(PRNetAddr));
  2272. for (i = 0; i < addrcnt; i++) {
  2273. char abuf[256];
  2274. char *abp = abuf;
  2275. iter = PR_EnumerateAddrInfo(iter, infop, 0, netaddr);
  2276. if (NULL == iter) {
  2277. break;
  2278. }
  2279. /*
  2280. * Check if the netaddr is duplicated or not.
  2281. * IPv4 mapped IPv6 could be the identical to IPv4 addr.
  2282. */
  2283. netaddr2string(netaddr, abuf, sizeof(abuf));
  2284. if (PR_IsNetAddrType(netaddr, PR_IpAddrV4Mapped)) {
  2285. /* IPv4 mapped IPv6; redundant to IPv4;
  2286. * cut the "::ffff:" part. */
  2287. abp = strrchr(abuf, ':');
  2288. if (abp) {
  2289. abp++;
  2290. } else {
  2291. abp = abuf;
  2292. }
  2293. }
  2294. if (charray_inlist(strnetaddrs, abp)) {
  2295. slapi_log_err(SLAPI_LOG_ERR,
  2296. "slapd_listenhost2addr",
  2297. "detected duplicated address %s "
  2298. "[%s]\n",
  2299. abuf, abp);
  2300. } else {
  2301. slapi_log_err(SLAPI_LOG_TRACE,
  2302. "slapd_listenhost2addr",
  2303. "registering address %s\n", abp);
  2304. slapi_ch_array_add(&strnetaddrs, slapi_ch_strdup(abp));
  2305. (*addr)[i] = netaddr;
  2306. netaddr =
  2307. (PRNetAddr *)slapi_ch_calloc(1, sizeof(PRNetAddr));
  2308. }
  2309. }
  2310. slapi_ch_free((void **)&netaddr); /* not used */
  2311. slapi_ch_array_free(strnetaddrs);
  2312. }
  2313. PR_FreeAddrInfo(infop);
  2314. } else {
  2315. slapi_log_err(SLAPI_LOG_ERR, logname,
  2316. "PR_GetAddrInfoByName(%s) failed - %s error %d (%s)\n",
  2317. listenhost, SLAPI_COMPONENT_NAME_NSPR, prerr,
  2318. slapd_pr_strerror(prerr));
  2319. rval = -1;
  2320. }
  2321. }
  2322. return rval;
  2323. }
  2324. /*
  2325. * Map addr to a string equivalent and place the result in addrbuf.
  2326. */
  2327. static const char *
  2328. netaddr2string(const PRNetAddr *addr, char *addrbuf, size_t addrbuflen)
  2329. {
  2330. const char *retstr;
  2331. if (NULL == addr || PR_IsNetAddrType(addr, PR_IpAddrAny)) {
  2332. retstr = "All Interfaces";
  2333. } else if (PR_IsNetAddrType(addr, PR_IpAddrLoopback)) {
  2334. if (addr->raw.family == PR_AF_INET6 &&
  2335. !PR_IsNetAddrType(addr, PR_IpAddrV4Mapped)) {
  2336. retstr = "IPv6 Loopback";
  2337. } else {
  2338. retstr = "Loopback";
  2339. }
  2340. } else if (PR_SUCCESS == PR_NetAddrToString(addr, addrbuf, addrbuflen)) {
  2341. if (0 == strncmp(addrbuf, "::ffff:", 7)) {
  2342. /* IPv4 address mapped into IPv6 address space */
  2343. retstr = addrbuf + 7;
  2344. } else {
  2345. /* full blown IPv6 address */
  2346. retstr = addrbuf;
  2347. }
  2348. } else { /* punt */
  2349. retstr = "address conversion failed";
  2350. }
  2351. return (retstr);
  2352. }
  2353. static int
  2354. createsignalpipe(void)
  2355. {
  2356. if (PR_CreatePipe(&signalpipe[0], &signalpipe[1]) != 0) {
  2357. PRErrorCode prerr = PR_GetError();
  2358. slapi_log_err(SLAPI_LOG_ERR, "createsignalpipe",
  2359. "PR_CreatePipe() failed, %s error %d (%s)\n",
  2360. SLAPI_COMPONENT_NAME_NSPR, prerr, slapd_pr_strerror(prerr));
  2361. return (-1);
  2362. }
  2363. writesignalpipe = PR_FileDesc2NativeHandle(signalpipe[1]);
  2364. readsignalpipe = PR_FileDesc2NativeHandle(signalpipe[0]);
  2365. if (fcntl(writesignalpipe, F_SETFD, O_NONBLOCK) == -1) {
  2366. slapi_log_err(SLAPI_LOG_ERR, "createsignalpipe",
  2367. "Failed to set FD for write pipe (%d).\n", errno);
  2368. }
  2369. if (fcntl(readsignalpipe, F_SETFD, O_NONBLOCK) == -1) {
  2370. slapi_log_err(SLAPI_LOG_ERR, "createsignalpipe",
  2371. "Failed to set FD for read pipe (%d).\n", errno);
  2372. }
  2373. return (0);
  2374. }
  2375. #ifdef HPUX10
  2376. #include <pthread.h> /* for sigwait */
  2377. /*
  2378. * Set up a thread to catch signals
  2379. * SIGUSR1 (ignore), SIGCHLD (call slapd_wait4child),
  2380. * SIGUSR2 (set slapd_shutdown), SIGTERM (set slapd_shutdown),
  2381. * SIGHUP (set slapd_shutdown)
  2382. */
  2383. static void *
  2384. catch_signals()
  2385. {
  2386. sigset_t caught_signals;
  2387. int sig;
  2388. sigemptyset(&caught_signals);
  2389. while (!g_get_shutdown()) {
  2390. /* Set the signals we're interested in catching */
  2391. sigaddset(&caught_signals, SIGUSR1);
  2392. sigaddset(&caught_signals, SIGCHLD);
  2393. sigaddset(&caught_signals, SIGUSR2);
  2394. sigaddset(&caught_signals, SIGTERM);
  2395. sigaddset(&caught_signals, SIGHUP);
  2396. (void)sigprocmask(SIG_BLOCK, &caught_signals, NULL);
  2397. if ((sig = sigwait(&caught_signals)) < 0) {
  2398. slapi_log_err(SLAPI_LOG_ERR, "catch_signals", "sigwait returned -1\n");
  2399. continue;
  2400. } else {
  2401. slapi_log_err(SLAPI_LOG_TRACE, "catch_signals", "detected signal %d\n", sig);
  2402. switch (sig) {
  2403. case SIGUSR1:
  2404. continue; /* ignore SIGUSR1 */
  2405. case SIGUSR2: /* fallthrough */
  2406. case SIGTERM: /* fallthrough */
  2407. case SIGHUP:
  2408. g_set_shutdown(SLAPI_SHUTDOWN_SIGNAL);
  2409. return NULL;
  2410. case SIGCHLD:
  2411. slapd_wait4child(sig);
  2412. break;
  2413. default:
  2414. slapi_log_err(SLAPI_LOG_ERR,
  2415. "catch_signals", "Unknown signal (%d) received\n", sig);
  2416. }
  2417. }
  2418. }
  2419. }
  2420. #endif /* HPUX */
  2421. static int
  2422. get_configured_connection_table_size(void)
  2423. {
  2424. int size = config_get_conntablesize();
  2425. int maxdesc = config_get_maxdescriptors();
  2426. /*
  2427. * Cap the table size at nsslapd-maxdescriptors.
  2428. */
  2429. if (maxdesc >= 0 && size > maxdesc) {
  2430. size = maxdesc;
  2431. }
  2432. return size;
  2433. }
  2434. PRFileDesc *
  2435. get_ssl_listener_fd()
  2436. {
  2437. PRFileDesc *listener;
  2438. listener = the_connection_table->fd[the_connection_table->s_tcps].fd;
  2439. return listener;
  2440. }
  2441. int
  2442. configure_pr_socket(PRFileDesc **pr_socket, int secure, int local)
  2443. {
  2444. int ns = 0;
  2445. int reservedescriptors = config_get_reservedescriptors();
  2446. int enable_nagle = config_get_nagle();
  2447. PRSocketOptionData pr_socketoption;
  2448. ns = PR_FileDesc2NativeHandle(*pr_socket);
  2449. /*
  2450. * Some OS or third party libraries may require that low
  2451. * numbered file descriptors be available, e.g., the DNS resolver
  2452. * library on most operating systems. Therefore, we try to
  2453. * replace the file descriptor returned by accept() with a
  2454. * higher numbered one. If this fails, we log an error and
  2455. * continue (not considered a truly fatal error).
  2456. */
  2457. if (reservedescriptors > 0 && ns < reservedescriptors) {
  2458. int newfd = fcntl(ns, F_DUPFD, reservedescriptors);
  2459. if (newfd > 0) {
  2460. PRFileDesc *nspr_layer_fd = PR_GetIdentitiesLayer(*pr_socket,
  2461. PR_NSPR_IO_LAYER);
  2462. if (NULL == nspr_layer_fd) {
  2463. slapi_log_err(SLAPI_LOG_ERR, "configure_pr_socket",
  2464. "Unable to move socket file descriptor %d above %d:"
  2465. " PR_GetIdentitiesLayer( %p, PR_NSPR_IO_LAYER )"
  2466. " failed\n",
  2467. ns, reservedescriptors, *pr_socket);
  2468. close(newfd); /* can't fix things up in NSPR -- close copy */
  2469. } else {
  2470. PR_ChangeFileDescNativeHandle(nspr_layer_fd, newfd);
  2471. close(ns); /* dup succeeded -- close the original */
  2472. ns = newfd;
  2473. }
  2474. } else {
  2475. int oserr = errno;
  2476. slapi_log_err(SLAPI_LOG_ERR, "configure_pr_socket",
  2477. "Unable to move socket file descriptor %d above %d:"
  2478. " OS error %d (%s)\n",
  2479. ns, reservedescriptors, oserr,
  2480. slapd_system_strerror(oserr));
  2481. }
  2482. }
  2483. /* Set keep_alive to keep old connections from lingering */
  2484. pr_socketoption.option = PR_SockOpt_Keepalive;
  2485. pr_socketoption.value.keep_alive = 1;
  2486. if (PR_SetSocketOption(*pr_socket, &pr_socketoption) == PR_FAILURE) {
  2487. PRErrorCode prerr = PR_GetError();
  2488. slapi_log_err(SLAPI_LOG_ERR,
  2489. "configure_pr_socket", "PR_SetSocketOption(PR_SockOpt_Keepalive failed, " SLAPI_COMPONENT_NAME_NSPR " error %d (%s)\n",
  2490. prerr, slapd_pr_strerror(prerr));
  2491. }
  2492. if (secure) {
  2493. pr_socketoption.option = PR_SockOpt_Nonblocking;
  2494. pr_socketoption.value.non_blocking = 1;
  2495. if (PR_SetSocketOption(*pr_socket, &pr_socketoption) == PR_FAILURE) {
  2496. PRErrorCode prerr = PR_GetError();
  2497. slapi_log_err(SLAPI_LOG_ERR,
  2498. "configure_pr_socket", "PR_SetSocketOption(PR_SockOpt_Nonblocking) failed, " SLAPI_COMPONENT_NAME_NSPR " error %d (%s)\n",
  2499. prerr, slapd_pr_strerror(prerr));
  2500. }
  2501. } else {
  2502. /* We always want to have non-blocking I/O */
  2503. pr_socketoption.option = PR_SockOpt_Nonblocking;
  2504. pr_socketoption.value.non_blocking = 1;
  2505. if (PR_SetSocketOption(*pr_socket, &pr_socketoption) == PR_FAILURE) {
  2506. PRErrorCode prerr = PR_GetError();
  2507. slapi_log_err(SLAPI_LOG_ERR,
  2508. "configure_pr_socket", "PR_SetSocketOption(PR_SockOpt_Nonblocking) failed, " SLAPI_COMPONENT_NAME_NSPR " error %d (%s)\n",
  2509. prerr, slapd_pr_strerror(prerr));
  2510. }
  2511. } /* else (secure) */
  2512. if (!enable_nagle && !local) {
  2513. pr_socketoption.option = PR_SockOpt_NoDelay;
  2514. pr_socketoption.value.no_delay = 1;
  2515. if (PR_SetSocketOption(*pr_socket, &pr_socketoption) == PR_FAILURE) {
  2516. PRErrorCode prerr = PR_GetError();
  2517. slapi_log_err(SLAPI_LOG_ERR,
  2518. "configure_pr_socket", "PR_SetSocketOption(PR_SockOpt_NoDelay) failed, " SLAPI_COMPONENT_NAME_NSPR " error %d (%s)\n",
  2519. prerr, slapd_pr_strerror(prerr));
  2520. }
  2521. } else if (!local) {
  2522. pr_socketoption.option = PR_SockOpt_NoDelay;
  2523. pr_socketoption.value.no_delay = 0;
  2524. if (PR_SetSocketOption(*pr_socket, &pr_socketoption) == PR_FAILURE) {
  2525. PRErrorCode prerr = PR_GetError();
  2526. slapi_log_err(SLAPI_LOG_ERR,
  2527. "configure_pr_socket", "PR_SetSocketOption(PR_SockOpt_NoDelay) failed, " SLAPI_COMPONENT_NAME_NSPR " error %d (%s)\n",
  2528. prerr, slapd_pr_strerror(prerr));
  2529. }
  2530. } /* else (!enable_nagle) */
  2531. return ns;
  2532. }
  2533. void
  2534. configure_ns_socket(int *ns)
  2535. {
  2536. int enable_nagle = config_get_nagle();
  2537. int on, rc;
  2538. #if defined(LINUX)
  2539. /* On Linux we use TCP_CORK so we must enable nagle */
  2540. enable_nagle = 1;
  2541. #endif
  2542. /* set the nagle */
  2543. if (!enable_nagle) {
  2544. on = 1;
  2545. } else {
  2546. on = 0;
  2547. }
  2548. /* check for errors */
  2549. if ((rc = setsockopt(*ns, IPPROTO_TCP, TCP_NODELAY, (char *)&on, sizeof(on)) != 0)) {
  2550. slapi_log_err(SLAPI_LOG_ERR, "configure_ns_socket", "Failed to configure socket (%d).\n", rc);
  2551. }
  2552. return;
  2553. }
  2554. #ifdef RESOLVER_NEEDS_LOW_FILE_DESCRIPTORS
  2555. /*
  2556. * A function that uses the DNS resolver in a simple way. This is only
  2557. * used to ensure that the DNS resolver has opened its files, etc.
  2558. * using low numbered file descriptors.
  2559. */
  2560. static void
  2561. get_loopback_by_addr(void)
  2562. {
  2563. #ifdef GETHOSTBYADDR_BUF_T
  2564. struct hostent hp = {0};
  2565. GETHOSTBYADDR_BUF_T hbuf;
  2566. #endif
  2567. unsigned long ipaddr;
  2568. struct in_addr ia;
  2569. int herrno = 0;
  2570. int rc = 0;
  2571. ipaddr = htonl(INADDR_LOOPBACK);
  2572. (void)GETHOSTBYADDR((char *)&ipaddr, sizeof(ipaddr),
  2573. AF_INET, &hp, hbuf, sizeof(hbuf), &herrno);
  2574. }
  2575. #endif /* RESOLVER_NEEDS_LOW_FILE_DESCRIPTORS */
  2576. void
  2577. disk_monitoring_stop(void)
  2578. {
  2579. if (disk_thread_p) {
  2580. PR_Lock(diskmon_mutex);
  2581. PR_NotifyCondVar(diskmon_cvar);
  2582. PR_Unlock(diskmon_mutex);
  2583. }
  2584. }