daemon.c 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109
  1. /** BEGIN COPYRIGHT BLOCK
  2. * This Program is free software; you can redistribute it and/or modify it under
  3. * the terms of the GNU General Public License as published by the Free Software
  4. * Foundation; version 2 of the License.
  5. *
  6. * This Program is distributed in the hope that it will be useful, but WITHOUT
  7. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  8. * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  9. *
  10. * You should have received a copy of the GNU General Public License along with
  11. * this Program; if not, write to the Free Software Foundation, Inc., 59 Temple
  12. * Place, Suite 330, Boston, MA 02111-1307 USA.
  13. *
  14. * In addition, as a special exception, Red Hat, Inc. gives You the additional
  15. * right to link the code of this Program with code not covered under the GNU
  16. * General Public License ("Non-GPL Code") and to distribute linked combinations
  17. * including the two, subject to the limitations in this paragraph. Non-GPL Code
  18. * permitted under this exception must only link to the code of this Program
  19. * through those well defined interfaces identified in the file named EXCEPTION
  20. * found in the source code files (the "Approved Interfaces"). The files of
  21. * Non-GPL Code may instantiate templates or use macros or inline functions from
  22. * the Approved Interfaces without causing the resulting work to be covered by
  23. * the GNU General Public License. Only Red Hat, Inc. may make changes or
  24. * additions to the list of Approved Interfaces. You must obey the GNU General
  25. * Public License in all respects for all of the Program code and other code used
  26. * in conjunction with the Program except the Non-GPL Code covered by this
  27. * exception. If you modify this file, you may extend this exception to your
  28. * version of the file, but you are not obligated to do so. If you do not wish to
  29. * provide this exception without modification, you must delete this exception
  30. * statement from your version and license this file solely under the GPL without
  31. * exception.
  32. *
  33. *
  34. * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission.
  35. * Copyright (C) 2005 Red Hat, Inc.
  36. * All rights reserved.
  37. * END COPYRIGHT BLOCK **/
  38. #ifdef HAVE_CONFIG_H
  39. # include <config.h>
  40. #endif
  41. #include <string.h>
  42. #include <sys/types.h>
  43. #ifdef _WIN32
  44. #include <windows.h>
  45. #include <process.h> /* for getpid */
  46. #include "proto-ntutil.h"
  47. #include "ntslapdmessages.h"
  48. #else
  49. #include <unistd.h>
  50. #include <sys/socket.h>
  51. #include <errno.h>
  52. #include <netinet/in.h>
  53. #include <arpa/inet.h>
  54. #include <sys/types.h>
  55. #include <netinet/tcp.h>
  56. #include <netdb.h>
  57. #include <sys/time.h>
  58. #include <sys/wait.h>
  59. #include <pthread.h>
  60. #endif
  61. #include <time.h>
  62. #include <signal.h>
  63. #if defined(IRIX6_2) || defined(IRIX6_3)
  64. #include <sys/param.h>
  65. #endif
  66. #if defined(_AIX)
  67. #include <sys/select.h>
  68. #include <sys/param.h>
  69. #endif
  70. #include <fcntl.h>
  71. #define TCPLEN_T int
  72. #if !defined( _WIN32 )
  73. #ifdef NEED_FILIO
  74. #include <sys/filio.h>
  75. #else /* NEED_FILIO */
  76. #include <sys/ioctl.h>
  77. #endif /* NEED_FILIO */
  78. #endif /* !defined( _WIN32 ) */
  79. /* for some reason, linux tty stuff defines CTIME */
  80. #ifdef LINUX
  81. #undef CTIME
  82. #endif
  83. #include "slap.h"
  84. #include "slapi-plugin.h"
  85. #include "snmp_collator.h"
  86. #include <private/pprio.h>
  87. #include <ssl.h>
  88. #include "fe.h"
  89. #if defined(ENABLE_LDAPI)
  90. #include "getsocketpeer.h"
  91. #endif /* ENABLE_LDAPI */
  92. /*
  93. * Define the backlog number for use in listen() call.
  94. * We use the same definition as in ldapserver/include/base/systems.h
  95. */
  96. #ifndef DAEMON_LISTEN_SIZE
  97. #define DAEMON_LISTEN_SIZE 128
  98. #endif
  99. #if defined (LDAP_IOCP)
  100. #define SLAPD_WAKEUP_TIMER 250
  101. #else
  102. #define SLAPD_WAKEUP_TIMER 250
  103. #endif
  104. int slapd_wakeup_timer = SLAPD_WAKEUP_TIMER; /* time in ms to wakeup */
  105. #ifdef notdef /* GGOODREPL */
  106. /*
  107. * time in secs to do housekeeping:
  108. * this must be greater than slapd_wakeup_timer
  109. */
  110. short slapd_housekeeping_timer = 10;
  111. #endif /* notdef GGOODREPL */
  112. /* Do we support timeout on socket send() ? */
  113. int have_send_timeouts = 0;
  114. PRFileDesc* signalpipe[2];
  115. static int writesignalpipe = SLAPD_INVALID_SOCKET;
  116. static int readsignalpipe = SLAPD_INVALID_SOCKET;
  117. #define FDS_SIGNAL_PIPE 0
  118. static int get_configured_connection_table_size();
  119. #ifdef RESOLVER_NEEDS_LOW_FILE_DESCRIPTORS
  120. static void get_loopback_by_addr( void );
  121. #endif
  122. #ifdef XP_WIN32
  123. static int createlistensocket(unsigned short port, const PRNetAddr *listenaddr);
  124. #endif
  125. static PRFileDesc **createprlistensockets(unsigned short port,
  126. PRNetAddr **listenaddr, int secure, int local);
  127. static const char *netaddr2string(const PRNetAddr *addr, char *addrbuf,
  128. size_t addrbuflen);
  129. static void set_shutdown (int);
  130. static void setup_pr_read_pds(Connection_Table *ct, PRFileDesc **n_tcps, PRFileDesc **s_tcps, PRFileDesc **i_unix, PRIntn *num_to_read);
  131. #ifdef HPUX10
  132. static void* catch_signals();
  133. #endif
  134. #if defined( _WIN32 )
  135. HANDLE hServDoneEvent = NULL;
  136. #endif
  137. static int createsignalpipe( void );
  138. #if defined( _WIN32 )
  139. /* Set an event to hook the NT Service termination */
  140. void *slapd_service_exit_wait()
  141. {
  142. #if defined( PURIFYING )
  143. #include <sys/types.h>
  144. #include <sys/stat.h>
  145. char module[_MAX_FNAME];
  146. char exit_file_name[_MAX_FNAME];
  147. char drive[_MAX_DRIVE];
  148. char dir[_MAX_DIR];
  149. char fname[_MAX_FNAME];
  150. char ext[_MAX_EXT];
  151. struct stat statbuf;
  152. memset( module, 0, sizeof( module ) );
  153. memset( exit_file_name, 0, sizeof( exit_file_name ) );
  154. GetModuleFileName(GetModuleHandle( NULL ), module, sizeof( module ) );
  155. _splitpath( module, drive, dir, fname, ext );
  156. PR_snprintf( exit_file_name, sizeof(exit_file_name), "%s%s%s", drive, dir, "exitnow.txt" );
  157. LDAPDebug( LDAP_DEBUG_ANY, "PURIFYING - Create %s to terminate the process.\n", exit_file_name, 0, 0 );
  158. while ( TRUE )
  159. {
  160. if( stat( exit_file_name, &statbuf ) < 0)
  161. {
  162. Sleep( 5000 ); /* 5 Seconds */
  163. continue;
  164. }
  165. LDAPDebug( LDAP_DEBUG_ANY, "slapd shutting down immediately, "
  166. "\"%s\" exists - don't forget to delete it\n", exit_file_name, 0, 0 );
  167. g_set_shutdown( SLAPI_SHUTDOWN_SIGNAL );
  168. return NULL;
  169. }
  170. #else /* PURIFYING */
  171. DWORD dwWait;
  172. char szDoneEvent[256];
  173. PR_snprintf(szDoneEvent, sizeof(szDoneEvent), "NS_%s", pszServerName);
  174. hServDoneEvent = CreateEvent( NULL, // default security attributes (LocalSystem)
  175. TRUE, // manual reset event
  176. FALSE, // not-signalled
  177. szDoneEvent );// named after the service itself.
  178. /* Wait indefinitely until hServDoneEvent is signaled. */
  179. dwWait = WaitForSingleObject( hServDoneEvent, // event object
  180. INFINITE ); // wait indefinitely
  181. /* The termination event has been signalled, log this occurrence, and signal to exit. */
  182. ReportSlapdEvent( EVENTLOG_INFORMATION_TYPE, MSG_SERVER_SHUTDOWN_STARTING, 0, NULL );
  183. g_set_shutdown( SLAPI_SHUTDOWN_SIGNAL );
  184. return NULL;
  185. #endif /* PURIFYING */
  186. }
  187. #endif /* _WIN32 */
  188. static char *
  189. get_pid_file()
  190. {
  191. return(pid_file);
  192. }
  193. static int daemon_configure_send_timeout(int s,size_t timeout /* Miliseconds*/)
  194. {
  195. /* Currently this function is only good for NT, and expects the s argument to be a SOCKET */
  196. #if defined(_WIN32)
  197. return setsockopt(
  198. s,
  199. SOL_SOCKET,
  200. SO_SNDTIMEO,
  201. (char*) &timeout,
  202. sizeof(timeout)
  203. );
  204. #else
  205. return 0;
  206. #endif
  207. }
  208. #if defined (_WIN32)
  209. /* This function is a workaround for accept problem on NT.
  210. Accept call fires on NT during syn scan even though the connection is not
  211. open. This causes a resource leak. For more details, see bug 391414.
  212. Experimentally, we determined that, in case of syn scan, the local
  213. address is set to 0. This in undocumented and my change in the future
  214. The function returns 0 if this is normal connection
  215. 1 if this is syn_scan connection
  216. -1 in case of any other error
  217. */
  218. static int
  219. syn_scan (int sock)
  220. {
  221. int rc;
  222. struct sockaddr_in addr;
  223. int size = sizeof (addr);
  224. if (sock == SLAPD_INVALID_SOCKET)
  225. return -1;
  226. rc = getsockname (sock, (struct sockaddr*)&addr, &size);
  227. if (rc != 0)
  228. return -1;
  229. else if (addr.sin_addr.s_addr == 0)
  230. return 1;
  231. else
  232. return 0;
  233. }
  234. #endif
  235. static int
  236. accept_and_configure(int s, PRFileDesc *pr_acceptfd, PRNetAddr *pr_netaddr,
  237. int addrlen, int secure, int local, PRFileDesc **pr_clonefd)
  238. {
  239. int ns = 0;
  240. PRIntervalTime pr_timeout = PR_MillisecondsToInterval(slapd_wakeup_timer);
  241. #if !defined( XP_WIN32 ) /* UNIX */
  242. (*pr_clonefd) = PR_Accept(pr_acceptfd, pr_netaddr, pr_timeout);
  243. if( !(*pr_clonefd) ) {
  244. PRErrorCode prerr = PR_GetError();
  245. LDAPDebug( LDAP_DEBUG_ANY, "PR_Accept() failed, "
  246. SLAPI_COMPONENT_NAME_NSPR " error %d (%s)\n",
  247. prerr, slapd_pr_strerror(prerr), 0 );
  248. return(SLAPD_INVALID_SOCKET);
  249. }
  250. ns = configure_pr_socket( pr_clonefd, secure, local );
  251. #else /* Windows */
  252. if( secure ) {
  253. (*pr_clonefd) = PR_Accept(pr_acceptfd, pr_netaddr, pr_timeout);
  254. if( !(*pr_clonefd) ) {
  255. PRErrorCode prerr = PR_GetError();
  256. LDAPDebug( LDAP_DEBUG_ANY, "PR_Accept() failed, "
  257. SLAPI_COMPONENT_NAME_NSPR " error %d (%s)\n",
  258. prerr, slapd_pr_strerror(prerr), 0 );
  259. /* Bug 613324: Call PR_NT_CancelIo if an error occurs */
  260. if( (prerr == PR_IO_TIMEOUT_ERROR ) ||
  261. (prerr == PR_PENDING_INTERRUPT_ERROR) ) {
  262. if( (PR_NT_CancelIo( pr_acceptfd )) != PR_SUCCESS) {
  263. prerr = PR_GetError();
  264. LDAPDebug( LDAP_DEBUG_ANY,
  265. "PR_NT_CancelIo() failed, "
  266. SLAPI_COMPONENT_NAME_NSPR
  267. " error %d (%s)\n",
  268. prerr, slapd_pr_strerror(prerr), 0 );
  269. }
  270. }
  271. return(SLAPD_INVALID_SOCKET);
  272. }
  273. ns = configure_pr_socket( pr_clonefd, secure, local );
  274. } else { /* !secure */
  275. struct sockaddr *addr; /* NOT IPv6 enabled */
  276. addr = (struct sockaddr *) slapi_ch_malloc( sizeof(struct sockaddr) );
  277. ns = accept (s, addr, (TCPLEN_T *)&addrlen);
  278. if (ns == SLAPD_INVALID_SOCKET) {
  279. int oserr = errno;
  280. LDAPDebug( LDAP_DEBUG_ANY,
  281. "accept(%d) failed errno %d (%s)\n",
  282. s, oserr, slapd_system_strerror(oserr));
  283. }
  284. else if (syn_scan (ns))
  285. {
  286. /* this is a work around for accept problem with SYN scan on NT.
  287. See bug 391414 for more details */
  288. LDAPDebug(LDAP_DEBUG_ANY, "syn-scan request is received - ignored\n", 0, 0, 0);
  289. closesocket (ns);
  290. ns = SLAPD_INVALID_SOCKET;
  291. }
  292. PRLDAP_SET_PORT( pr_netaddr, ((struct sockaddr_in *)addr)->sin_port );
  293. PR_ConvertIPv4AddrToIPv6(((struct sockaddr_in *)addr)->sin_addr.s_addr, &(pr_netaddr->ipv6.ip));
  294. (*pr_clonefd) = NULL;
  295. slapi_ch_free( (void **)&addr );
  296. configure_ns_socket( &ns );
  297. }
  298. #endif
  299. return ns;
  300. }
  301. /*
  302. * This is the shiny new re-born daemon function, without all the hair
  303. */
  304. #ifdef _WIN32
  305. static void setup_read_fds(Connection_Table *ct, fd_set *readfds, int n_tcps, int s_tcps );
  306. static void handle_read_ready(Connection_Table *ct, fd_set *readfds);
  307. static void set_timeval_ms(struct timeval *t, int ms);
  308. #endif
  309. /* GGOODREPL static void handle_timeout( void ); */
  310. static void handle_pr_read_ready(Connection_Table *ct, PRIntn num_poll);
  311. static int handle_new_connection(Connection_Table *ct, int tcps, PRFileDesc *pr_acceptfd, int secure, int local );
  312. #ifdef _WIN32
  313. static void unfurl_banners(Connection_Table *ct,daemon_ports_t *ports, int n_tcps, PRFileDesc *s_tcps);
  314. #else
  315. static void unfurl_banners(Connection_Table *ct,daemon_ports_t *ports, PRFileDesc **n_tcps, PRFileDesc **s_tcps, PRFileDesc **i_unix);
  316. #endif
  317. static int write_pid_file();
  318. static int init_shutdown_detect();
  319. #ifdef _WIN32
  320. static int clear_signal(fd_set *readfdset);
  321. #else
  322. static int clear_signal(struct POLL_STRUCT *fds);
  323. #endif
  324. /* Globals which are used to store the sockets between
  325. * calls to daemon_pre_setuid_init() and the daemon thread
  326. * creation. */
  327. int daemon_pre_setuid_init(daemon_ports_t *ports)
  328. {
  329. int rc = 0;
  330. if (0 != ports->n_port) {
  331. #if defined( XP_WIN32 )
  332. ports->n_socket = createlistensocket((unsigned short)ports->n_port,
  333. &ports->n_listenaddr);
  334. #else
  335. ports->n_socket = createprlistensockets(ports->n_port,
  336. ports->n_listenaddr, 0, 0);
  337. #endif
  338. }
  339. if ( config_get_security() && (0 != ports->s_port) ) {
  340. ports->s_socket = createprlistensockets((unsigned short)ports->s_port,
  341. ports->s_listenaddr, 1, 0);
  342. #ifdef XP_WIN32
  343. ports->s_socket_native = PR_FileDesc2NativeHandle(ports->s_socket);
  344. #endif
  345. } else {
  346. ports->s_socket = SLAPD_INVALID_SOCKET;
  347. #ifdef XP_WIN32
  348. ports->s_socket_native = SLAPD_INVALID_SOCKET;
  349. #endif
  350. }
  351. #ifndef XP_WIN32
  352. #if defined(ENABLE_LDAPI)
  353. /* ldapi */
  354. if(0 != ports->i_port) {
  355. ports->i_socket = createprlistensockets(1, ports->i_listenaddr, 0, 1);
  356. }
  357. #endif /* ENABLE_LDAPI */
  358. #endif
  359. return( rc );
  360. }
  361. /* Decide whether we're running on a platform which supports send with timeouts */
  362. static void detect_timeout_support()
  363. {
  364. /* Currently we know that NT4.0 or higher DOES support timeouts */
  365. #if defined _WIN32
  366. /* Get the OS revision */
  367. OSVERSIONINFO ver;
  368. ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
  369. GetVersionEx(&ver);
  370. if (ver.dwPlatformId == VER_PLATFORM_WIN32_NT && ver.dwMajorVersion >= 4) {
  371. have_send_timeouts = 1;
  372. }
  373. #else
  374. /* Some UNIXen do, but for now I don't feel confident which , and whether timeouts really work there */
  375. #endif
  376. }
  377. /*
  378. * The time_shutdown static variable is used to signal the time thread
  379. * to shutdown. We used to shut down the time thread when g_get_shutdown()
  380. * returned a non-zero value, but that caused the clock to stop, so to speak,
  381. * and all error log entries to have the same timestamp once the shutdown
  382. * process began.
  383. */
  384. static int time_shutdown = 0;
  385. void *
  386. time_thread(void *nothing)
  387. {
  388. PRIntervalTime interval;
  389. interval = PR_SecondsToInterval(1);
  390. while(!time_shutdown) {
  391. poll_current_time();
  392. csngen_update_time ();
  393. DS_Sleep(interval);
  394. }
  395. /*NOTREACHED*/
  396. return(NULL);
  397. }
  398. void slapd_daemon( daemon_ports_t *ports )
  399. {
  400. /* We are passed some ports---one for regular connections, one
  401. * for SSL connections, one for ldapi connections.
  402. */
  403. /* Previously there was a ton of code #defined on NET_SSL.
  404. * This looked horrible, so now I'm doing it this way:
  405. * If you want me to do SSL, pass me something in the ssl port number.
  406. * If you don't, pass me zero.
  407. */
  408. #if defined( XP_WIN32 )
  409. int n_tcps = 0;
  410. int s_tcps_native = 0;
  411. PRFileDesc *s_tcps = NULL;
  412. #else
  413. PRFileDesc *tcps = 0;
  414. PRFileDesc **n_tcps = NULL;
  415. PRFileDesc **s_tcps = NULL;
  416. PRFileDesc **i_unix = NULL;
  417. PRFileDesc **fdesp = NULL;
  418. #endif
  419. PRIntn num_poll = 0;
  420. PRIntervalTime pr_timeout = PR_MillisecondsToInterval(slapd_wakeup_timer);
  421. PRThread *time_thread_p;
  422. int threads;
  423. int in_referral_mode = config_check_referral_mode();
  424. int connection_table_size = get_configured_connection_table_size();
  425. the_connection_table= connection_table_new(connection_table_size);
  426. #ifdef RESOLVER_NEEDS_LOW_FILE_DESCRIPTORS
  427. /*
  428. * Some DNS resolver implementations, such as the one built into
  429. * Solaris <= 8, need to use one or more low numbered file
  430. * descriptors internally (probably because they use a deficient
  431. * implementation of stdio). So we make a call now that uses the
  432. * resolver so it has an opportunity to grab whatever low file
  433. * descriptors it needs (before we use up all of the low numbered
  434. * ones for incoming client connections and so on).
  435. */
  436. get_loopback_by_addr();
  437. #endif
  438. /* Retrieve the sockets from their hiding place */
  439. n_tcps = ports->n_socket;
  440. s_tcps = ports->s_socket;
  441. #ifdef XP_WIN32
  442. s_tcps_native = ports->s_socket_native;
  443. #else
  444. #if defined(ENABLE_LDAPI)
  445. i_unix = ports->i_socket;
  446. #endif /* ENABLE_LDAPI */
  447. #endif
  448. createsignalpipe();
  449. init_shutdown_detect();
  450. if (
  451. #if defined( XP_WIN32 )
  452. (n_tcps == SLAPD_INVALID_SOCKET) &&
  453. #else
  454. (n_tcps == NULL) &&
  455. #if defined(ENABLE_LDAPI)
  456. (i_unix == NULL) &&
  457. #endif /* ENABLE_LDAPI */
  458. #endif
  459. (s_tcps == NULL) ) { /* nothing to do */
  460. LDAPDebug( LDAP_DEBUG_ANY,
  461. "no port to listen on\n", 0, 0, 0 );
  462. exit( 1 );
  463. }
  464. unfurl_banners(the_connection_table,ports,n_tcps,s_tcps,i_unix);
  465. init_op_threads ();
  466. detect_timeout_support();
  467. /* Start the time thread */
  468. time_thread_p = PR_CreateThread(PR_SYSTEM_THREAD,
  469. (VFP) (void *) time_thread, NULL,
  470. PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD,
  471. PR_JOINABLE_THREAD,
  472. SLAPD_DEFAULT_THREAD_STACKSIZE);
  473. if ( NULL == time_thread_p ) {
  474. PRErrorCode errorCode = PR_GetError();
  475. LDAPDebug(LDAP_DEBUG_ANY, "Unable to create time thread - Shutting Down ("
  476. SLAPI_COMPONENT_NAME_NSPR " error %d - %s)\n",
  477. errorCode, slapd_pr_strerror(errorCode), 0);
  478. g_set_shutdown( SLAPI_SHUTDOWN_EXIT );
  479. }
  480. /* We are now ready to accept imcoming connections */
  481. #if defined( XP_WIN32 )
  482. if ( n_tcps != SLAPD_INVALID_SOCKET
  483. && listen( n_tcps, DAEMON_LISTEN_SIZE ) == -1 ) {
  484. int oserr = errno;
  485. char addrbuf[ 256 ];
  486. slapi_log_error(SLAPI_LOG_FATAL, "slapd_daemon",
  487. "listen() on %s port %d failed: OS error %d (%s)\n",
  488. netaddr2string(&ports->n_listenaddr, addrbuf, sizeof(addrbuf)),
  489. ports->n_port, oserr, slapd_system_strerror( oserr ) );
  490. g_set_shutdown( SLAPI_SHUTDOWN_EXIT );
  491. }
  492. #else
  493. if ( n_tcps != NULL ) {
  494. PRFileDesc **fdesp;
  495. PRNetAddr **nap = ports->n_listenaddr;
  496. for (fdesp = n_tcps; fdesp && *fdesp; fdesp++, nap++) {
  497. if ( PR_Listen( *fdesp, DAEMON_LISTEN_SIZE ) == PR_FAILURE ) {
  498. PRErrorCode prerr = PR_GetError();
  499. char addrbuf[ 256 ];
  500. slapi_log_error(SLAPI_LOG_FATAL, "slapd_daemon",
  501. "PR_Listen() on %s port %d failed: %s error %d (%s)\n",
  502. netaddr2string(*nap, addrbuf, sizeof(addrbuf)),
  503. ports->n_port, SLAPI_COMPONENT_NAME_NSPR, prerr,
  504. slapd_pr_strerror( prerr ));
  505. g_set_shutdown( SLAPI_SHUTDOWN_EXIT );
  506. }
  507. }
  508. }
  509. #endif
  510. if ( s_tcps != NULL ) {
  511. PRFileDesc **fdesp;
  512. PRNetAddr **sap = ports->s_listenaddr;
  513. for (fdesp = s_tcps; fdesp && *fdesp; fdesp++, sap++) {
  514. if ( PR_Listen( *fdesp, DAEMON_LISTEN_SIZE ) == PR_FAILURE ) {
  515. PRErrorCode prerr = PR_GetError();
  516. char addrbuf[ 256 ];
  517. slapi_log_error(SLAPI_LOG_FATAL, "slapd_daemon",
  518. "PR_Listen() on %s port %d failed: %s error %d (%s)\n",
  519. netaddr2string(*sap, addrbuf, sizeof(addrbuf)),
  520. ports->s_port, SLAPI_COMPONENT_NAME_NSPR, prerr,
  521. slapd_pr_strerror( prerr ));
  522. g_set_shutdown( SLAPI_SHUTDOWN_EXIT );
  523. }
  524. }
  525. }
  526. #if !defined( XP_WIN32 )
  527. #if defined(ENABLE_LDAPI)
  528. if( i_unix != NULL ) {
  529. PRFileDesc **fdesp;
  530. PRNetAddr **iap = ports->i_listenaddr;
  531. for (fdesp = i_unix; fdesp && *fdesp; fdesp++, iap++) {
  532. if ( PR_Listen(*fdesp, DAEMON_LISTEN_SIZE) == PR_FAILURE) {
  533. PRErrorCode prerr = PR_GetError();
  534. slapi_log_error(SLAPI_LOG_FATAL, "slapd_daemon",
  535. "listen() on %s failed: error %d (%s)\n",
  536. (*iap)->local.path,
  537. prerr,
  538. slapd_pr_strerror( prerr ));
  539. g_set_shutdown( SLAPI_SHUTDOWN_EXIT );
  540. }
  541. }
  542. }
  543. #endif /* ENABLE_LDAPI */
  544. #endif
  545. /* Now we write the pid file, indicating that the server is finally and listening for connections */
  546. write_pid_file();
  547. /* The meat of the operation is in a loop on a call to select */
  548. while(!g_get_shutdown())
  549. {
  550. #ifdef _WIN32
  551. fd_set readfds;
  552. struct timeval wakeup_timer;
  553. int oserr;
  554. #endif
  555. int select_return = 0;
  556. int secure = 0; /* is a new connection an SSL one ? */
  557. int local = 0; /* is new connection an ldapi one? */
  558. int i;
  559. #ifndef _WIN32
  560. PRErrorCode prerr;
  561. #endif
  562. #ifdef _WIN32
  563. set_timeval_ms(&wakeup_timer, slapd_wakeup_timer);
  564. setup_read_fds(the_connection_table,&readfds,n_tcps, s_tcps_native);
  565. /* This select needs to timeout to give the server a chance to test for shutdown */
  566. select_return = select(connection_table_size, &readfds, NULL, 0, &wakeup_timer);
  567. #else
  568. setup_pr_read_pds(the_connection_table,n_tcps,s_tcps,i_unix,&num_poll);
  569. select_return = POLL_FN(the_connection_table->fd, num_poll, pr_timeout);
  570. #endif
  571. switch (select_return) {
  572. case 0: /* Timeout */
  573. /* GGOODREPL handle_timeout(); */
  574. break;
  575. case -1: /* Error */
  576. #ifdef _WIN32
  577. oserr = errno;
  578. LDAPDebug( LDAP_DEBUG_TRACE,
  579. "select failed errno %d (%s)\n", oserr,
  580. slapd_system_strerror(oserr), 0 );
  581. #else
  582. prerr = PR_GetError();
  583. LDAPDebug( LDAP_DEBUG_TRACE, "PR_Poll() failed, "
  584. SLAPI_COMPONENT_NAME_NSPR " error %d (%s)\n",
  585. prerr, slapd_system_strerror(prerr), 0 );
  586. #endif
  587. break;
  588. default: /* either a new connection or some new data ready */
  589. /* Figure out if we are dealing with one of the listen sockets */
  590. #ifdef _WIN32
  591. /* If so, then handle a new connection */
  592. if ( n_tcps != SLAPD_INVALID_SOCKET && FD_ISSET( n_tcps,&readfds ) ) {
  593. handle_new_connection(the_connection_table,n_tcps,NULL,0,0);
  594. }
  595. /* If so, then handle a new connection */
  596. if ( s_tcps != SLAPD_INVALID_SOCKET && FD_ISSET( s_tcps_native,&readfds ) ) {
  597. handle_new_connection(the_connection_table,SLAPD_INVALID_SOCKET,s_tcps,1,0);
  598. }
  599. /* handle new data ready */
  600. handle_read_ready(the_connection_table,&readfds);
  601. clear_signal(&readfds);
  602. #else
  603. tcps = NULL;
  604. /* info for n_tcps is always in fd[n_tcps ~ n_tcpe] */
  605. if( NULL != n_tcps ) {
  606. for (i = the_connection_table->n_tcps;
  607. i < the_connection_table->n_tcpe; i++) {
  608. if (the_connection_table->fd[i].out_flags &
  609. SLAPD_POLL_FLAGS ) {
  610. /* tcps = n_tcps[i - the_connection_table->n_tcps]; */
  611. tcps = the_connection_table->fd[i].fd;
  612. break;
  613. }
  614. }
  615. }
  616. /* info for s_tcps is always in fd[s_tcps ~ s_tcpe] */
  617. if ( NULL == tcps && NULL != s_tcps ) {
  618. for (i = the_connection_table->s_tcps;
  619. i < the_connection_table->s_tcpe; i++) {
  620. if (the_connection_table->fd[i].out_flags &
  621. SLAPD_POLL_FLAGS ) {
  622. /* tcps = s_tcps[i - the_connection_table->s_tcps]; */
  623. tcps = the_connection_table->fd[i].fd;
  624. secure = 1;
  625. break;
  626. }
  627. }
  628. }
  629. #if defined(ENABLE_LDAPI)
  630. /* info for i_unix is always in fd[i_unixs ~ i_unixe] */
  631. if ( NULL == tcps && NULL != i_unix ) {
  632. for (i = the_connection_table->i_unixs;
  633. i < the_connection_table->i_unixe; i++) {
  634. if (the_connection_table->fd[i].out_flags &
  635. SLAPD_POLL_FLAGS ) {
  636. /* tcps = i_unix[i - the_connection_table->i_unixs]; */
  637. tcps = the_connection_table->fd[i].fd;
  638. local = 1;
  639. break;
  640. }
  641. }
  642. }
  643. #endif /* ENABLE_LDAPI */
  644. /* If so, then handle a new connection */
  645. if ( tcps != NULL ) {
  646. handle_new_connection(the_connection_table,SLAPD_INVALID_SOCKET,tcps,secure,local);
  647. }
  648. /* handle new data ready */
  649. handle_pr_read_ready(the_connection_table, connection_table_size);
  650. clear_signal(the_connection_table->fd);
  651. #endif
  652. break;
  653. }
  654. }
  655. /* We get here when the server is shutting down */
  656. /* Do what we have to do before death */
  657. connection_table_abandon_all_operations(the_connection_table); /* abandon all operations in progress */
  658. if ( ! in_referral_mode ) {
  659. ps_stop_psearch_system(); /* stop any persistent searches */
  660. }
  661. #ifdef _WIN32
  662. if ( n_tcps != SLAPD_INVALID_SOCKET ) {
  663. closesocket( n_tcps );
  664. }
  665. if ( s_tcps != NULL ) {
  666. PR_Close( s_tcps );
  667. }
  668. #else
  669. for (fdesp = n_tcps; fdesp && *fdesp; fdesp++) {
  670. PR_Close( *fdesp );
  671. }
  672. slapi_ch_free ((void**)&n_tcps);
  673. for (fdesp = i_unix; fdesp && *fdesp; fdesp++) {
  674. PR_Close( *fdesp );
  675. }
  676. slapi_ch_free ((void**)&i_unix);
  677. for (fdesp = s_tcps; fdesp && *fdesp; fdesp++) {
  678. PR_Close( *fdesp );
  679. }
  680. slapi_ch_free ((void**)&s_tcps);
  681. /* freeing NetAddrs */
  682. {
  683. PRNetAddr **nap;
  684. for (nap = ports->n_listenaddr; nap && *nap; nap++) {
  685. slapi_ch_free ((void**)nap);
  686. }
  687. slapi_ch_free ((void**)&ports->n_listenaddr);
  688. for (nap = ports->s_listenaddr; nap && *nap; nap++) {
  689. slapi_ch_free ((void**)nap);
  690. }
  691. slapi_ch_free ((void**)&ports->s_listenaddr);
  692. #if defined(ENABLE_LDAPI)
  693. for (nap = ports->i_listenaddr; nap && *nap; nap++) {
  694. slapi_ch_free ((void**)nap);
  695. }
  696. slapi_ch_free ((void**)&ports->i_listenaddr);
  697. #endif
  698. }
  699. #endif
  700. /* Might compete with housecleaning thread, but so far so good */
  701. be_flushall();
  702. op_thread_cleanup();
  703. housekeeping_stop(); /* Run this after op_thread_cleanup() logged sth */
  704. #ifndef _WIN32
  705. threads = g_get_active_threadcnt();
  706. if ( threads > 0 ) {
  707. LDAPDebug( LDAP_DEBUG_ANY,
  708. "slapd shutting down - waiting for %d thread%s to terminate\n",
  709. threads, ( threads > 1 ) ? "s" : "", 0 );
  710. }
  711. #endif
  712. threads = g_get_active_threadcnt();
  713. while ( threads > 0 ) {
  714. PRPollDesc xpd;
  715. char x;
  716. int spe = 0;
  717. /* try to read from the signal pipe, in case threads are
  718. * blocked on it. */
  719. xpd.fd = signalpipe[0];
  720. xpd.in_flags = PR_POLL_READ;
  721. xpd.out_flags = 0;
  722. spe = PR_Poll(&xpd, 1, PR_INTERVAL_NO_WAIT);
  723. if (spe > 0) {
  724. spe = PR_Read(signalpipe[0], &x, 1);
  725. if (spe < 0) {
  726. PRErrorCode prerr = PR_GetError();
  727. LDAPDebug( LDAP_DEBUG_ANY, "listener could not clear signal pipe, "
  728. SLAPI_COMPONENT_NAME_NSPR " error %d (%s)\n",
  729. prerr, slapd_system_strerror(prerr), 0 );
  730. break;
  731. }
  732. } else if (spe == -1) {
  733. PRErrorCode prerr = PR_GetError();
  734. LDAPDebug( LDAP_DEBUG_ANY, "PR_Poll() failed, "
  735. SLAPI_COMPONENT_NAME_NSPR " error %d (%s)\n",
  736. prerr, slapd_system_strerror(prerr), 0 );
  737. break;
  738. } else {
  739. /* no data */
  740. }
  741. DS_Sleep(PR_INTERVAL_NO_WAIT);
  742. if ( threads != g_get_active_threadcnt() ) {
  743. LDAPDebug( LDAP_DEBUG_TRACE,
  744. "slapd shutting down - waiting for %d threads to terminate\n",
  745. g_get_active_threadcnt(), 0, 0 );
  746. threads = g_get_active_threadcnt();
  747. }
  748. }
  749. LDAPDebug( LDAP_DEBUG_ANY,
  750. "slapd shutting down - closing down internal subsystems and plugins\n",
  751. 0, 0, 0 );
  752. log_access_flush();
  753. /* let backends do whatever cleanup they need to do */
  754. LDAPDebug( LDAP_DEBUG_TRACE,"slapd shutting down - waiting for backends to close down\n", 0, 0,0 );
  755. eq_stop();
  756. if ( ! in_referral_mode ) {
  757. task_shutdown();
  758. uniqueIDGenCleanup ();
  759. }
  760. plugin_closeall( 1 /* Close Backends */, 1 /* Close Gloabls */);
  761. if ( ! in_referral_mode ) {
  762. /* Close SNMP collator after the plugins closed...
  763. * Replication plugin still performs internal ops that
  764. * may try to increment snmp stats.
  765. * Fix for defect 523780
  766. */
  767. snmp_collator_stop();
  768. mapping_tree_free ();
  769. }
  770. be_cleanupall ();
  771. LDAPDebug( LDAP_DEBUG_TRACE, "slapd shutting down - backends closed down\n",
  772. 0, 0, 0 );
  773. referrals_free();
  774. connection_table_free(the_connection_table);
  775. the_connection_table= NULL;
  776. /* tell the time thread to shutdown and then wait for it */
  777. time_shutdown = 1;
  778. PR_JoinThread( time_thread_p );
  779. #ifdef _WIN32
  780. WSACleanup();
  781. #endif
  782. }
  783. int signal_listner()
  784. {
  785. /* Replaces previous macro---called to bump the thread out of select */
  786. #if defined( _WIN32 )
  787. if ( PR_Write( signalpipe[1], "", 1) != 1 ) {
  788. /* this now means that the pipe is full
  789. * this is not a problem just go-on
  790. */
  791. LDAPDebug( LDAP_DEBUG_CONNS,
  792. "listener could not write to signal pipe %d\n",
  793. errno, 0, 0 );
  794. }
  795. #else
  796. if ( write( writesignalpipe, "", 1) != 1 ) {
  797. /* this now means that the pipe is full
  798. * this is not a problem just go-on
  799. */
  800. LDAPDebug( LDAP_DEBUG_CONNS,
  801. "listener could not write to signal pipe %d\n",
  802. errno, 0, 0 );
  803. }
  804. #endif
  805. return( 0 );
  806. }
  807. #ifdef _WIN32
  808. static int clear_signal(fd_set *readfdset)
  809. #else
  810. static int clear_signal(struct POLL_STRUCT *fds)
  811. #endif
  812. {
  813. #ifdef _WIN32
  814. if ( FD_ISSET(readsignalpipe, readfdset)) {
  815. #else
  816. if ( fds[FDS_SIGNAL_PIPE].out_flags & SLAPD_POLL_FLAGS ) {
  817. #endif
  818. char buf[200];
  819. LDAPDebug( LDAP_DEBUG_CONNS,
  820. "listener got signaled\n",
  821. 0, 0, 0 );
  822. #ifdef _WIN32
  823. if ( PR_Read( signalpipe[0], buf, 20 ) < 1 ) {
  824. #else
  825. if ( read( readsignalpipe, buf, 200 ) < 1 ) {
  826. #endif
  827. LDAPDebug( LDAP_DEBUG_ANY,
  828. "listener could not clear signal pipe\n",
  829. 0, 0, 0 );
  830. }
  831. }
  832. return 0;
  833. }
  834. #ifdef _WIN32
  835. static void set_timeval_ms(struct timeval *t, int ms)
  836. {
  837. t->tv_sec = ms/1000;
  838. t->tv_usec = (ms % 1000)*1000;
  839. }
  840. #endif
  841. #ifdef _WIN32
  842. static void setup_read_fds(Connection_Table *ct, fd_set *readfds, int n_tcps, int s_tcps)
  843. {
  844. Connection *c= NULL;
  845. Connection *next= NULL;
  846. int accept_new_connections;
  847. static int last_accept_new_connections = -1;
  848. slapdFrontendConfig_t *slapdFrontendConfig = getFrontendConfig();
  849. LBER_SOCKET socketdesc = SLAPD_INVALID_SOCKET;
  850. FD_ZERO( readfds );
  851. accept_new_connections = ((ct->size - g_get_current_conn_count())
  852. > slapdFrontendConfig->reservedescriptors);
  853. if ( ! accept_new_connections ) {
  854. if ( last_accept_new_connections ) {
  855. LDAPDebug( LDAP_DEBUG_ANY, "Not listening for new "
  856. "connections - too many fds open\n", 0, 0, 0 );
  857. }
  858. } else {
  859. if ( ! last_accept_new_connections &&
  860. last_accept_new_connections != -1 ) {
  861. LDAPDebug( LDAP_DEBUG_ANY, "Listening for new "
  862. "connections again\n", 0, 0, 0 );
  863. }
  864. }
  865. last_accept_new_connections = accept_new_connections;
  866. if (n_tcps != SLAPD_INVALID_SOCKET && accept_new_connections) {
  867. FD_SET( n_tcps, readfds );
  868. LDAPDebug( LDAP_DEBUG_HOUSE,
  869. "listening for connections on %d\n", n_tcps, 0, 0 );
  870. }
  871. if (s_tcps != SLAPD_INVALID_SOCKET && accept_new_connections) {
  872. FD_SET( s_tcps, readfds );
  873. LDAPDebug( LDAP_DEBUG_HOUSE,
  874. "listening for connections on %d\n", s_tcps, 0, 0 );
  875. }
  876. if ((s_tcps != SLAPD_INVALID_SOCKET)
  877. && (readsignalpipe != SLAPD_INVALID_SOCKET)) {
  878. FD_SET( readsignalpipe, readfds );
  879. }
  880. /* Walk down the list of active connections to find
  881. * out which connections we should poll over. If a connection
  882. * is no longer in use, we should remove it from the linked
  883. * list. */
  884. c= connection_table_get_first_active_connection (ct);
  885. while (c)
  886. {
  887. next = connection_table_get_next_active_connection (ct, c);
  888. if ( c->c_mutex == NULL )
  889. {
  890. connection_table_move_connection_out_of_active_list(ct,c);
  891. }
  892. else
  893. {
  894. PR_Lock( c->c_mutex );
  895. if ( c->c_flags & CONN_FLAG_CLOSING )
  896. {
  897. /* A worker thread has marked that this connection
  898. * should be closed by calling disconnect_server.
  899. * move this connection out of the active list
  900. * the last thread to use the connection will close it
  901. */
  902. connection_table_move_connection_out_of_active_list(ct,c);
  903. }
  904. else if ( c->c_sd == SLAPD_INVALID_SOCKET )
  905. {
  906. connection_table_move_connection_out_of_active_list(ct,c);
  907. }
  908. else
  909. {
  910. #if defined(LDAP_IOCP) /* When we have IO completion ports, we don't want to do this */
  911. if ( !c->c_gettingber && (c->c_flags & CONN_FLAG_SSL) )
  912. #else
  913. if ( !c->c_gettingber )
  914. #endif
  915. {
  916. FD_SET( c->c_sd, readfds );
  917. }
  918. }
  919. PR_Unlock( c->c_mutex );
  920. }
  921. c = next;
  922. }
  923. }
  924. #endif /* _WIN32 */
  925. static int first_time_setup_pr_read_pds = 1;
  926. static int listen_addr_count = 0;
  927. static void
  928. setup_pr_read_pds(Connection_Table *ct, PRFileDesc **n_tcps, PRFileDesc **s_tcps, PRFileDesc **i_unix, PRIntn *num_to_read)
  929. {
  930. Connection *c= NULL;
  931. Connection *next= NULL;
  932. LBER_SOCKET socketdesc = SLAPD_INVALID_SOCKET;
  933. int accept_new_connections;
  934. static int last_accept_new_connections = -1;
  935. PRIntn count = 0;
  936. slapdFrontendConfig_t *slapdFrontendConfig = getFrontendConfig();
  937. int max_threads_per_conn = config_get_maxthreadsperconn();
  938. accept_new_connections = ((ct->size - g_get_current_conn_count())
  939. > slapdFrontendConfig->reservedescriptors);
  940. if ( ! accept_new_connections ) {
  941. if ( last_accept_new_connections ) {
  942. LDAPDebug( LDAP_DEBUG_ANY, "Not listening for new "
  943. "connections - too many fds open\n", 0, 0, 0 );
  944. /* reinitialize n_tcps and s_tcps to the pds */
  945. first_time_setup_pr_read_pds = 1;
  946. }
  947. } else {
  948. if ( ! last_accept_new_connections &&
  949. last_accept_new_connections != -1 ) {
  950. LDAPDebug( LDAP_DEBUG_ANY, "Listening for new "
  951. "connections again\n", 0, 0, 0 );
  952. /* reinitialize n_tcps and s_tcps to the pds */
  953. first_time_setup_pr_read_pds = 1;
  954. }
  955. }
  956. last_accept_new_connections = accept_new_connections;
  957. /* initialize the mapping from connection table entries to fds entries */
  958. if (first_time_setup_pr_read_pds)
  959. {
  960. int i;
  961. for (i = 0; i < ct->size; i++)
  962. {
  963. ct->c[i].c_fdi = SLAPD_INVALID_SOCKET_INDEX;
  964. }
  965. /* The fds entry for the signalpipe is always FDS_SIGNAL_PIPE (== 0) */
  966. count = FDS_SIGNAL_PIPE;
  967. #if !defined(_WIN32)
  968. ct->fd[count].fd = signalpipe[0];
  969. ct->fd[count].in_flags = SLAPD_POLL_FLAGS;
  970. ct->fd[count].out_flags = 0;
  971. #else
  972. ct->fd[count].fd = NULL;
  973. #endif
  974. count++;
  975. /* The fds entry for n_tcps starts with n_tcps and less than n_tcpe */
  976. ct->n_tcps = count;
  977. if (n_tcps != NULL && accept_new_connections)
  978. {
  979. PRFileDesc **fdesc = NULL;
  980. for (fdesc = n_tcps; fdesc && *fdesc; fdesc++, count++) {
  981. ct->fd[count].fd = *fdesc;
  982. ct->fd[count].in_flags = SLAPD_POLL_FLAGS;
  983. ct->fd[count].out_flags = 0;
  984. LDAPDebug( LDAP_DEBUG_HOUSE,
  985. "listening for connections on %d\n", socketdesc, 0, 0 );
  986. }
  987. } else {
  988. ct->fd[count].fd = NULL;
  989. count++;
  990. }
  991. ct->n_tcpe = count;
  992. ct->s_tcps = count;
  993. /* The fds entry for s_tcps starts with s_tcps and less than s_tcpe */
  994. if (s_tcps != NULL && accept_new_connections)
  995. {
  996. PRFileDesc **fdesc = NULL;
  997. for (fdesc = s_tcps; fdesc && *fdesc; fdesc++, count++) {
  998. ct->fd[count].fd = *fdesc;
  999. ct->fd[count].in_flags = SLAPD_POLL_FLAGS;
  1000. ct->fd[count].out_flags = 0;
  1001. LDAPDebug( LDAP_DEBUG_HOUSE,
  1002. "listening for SSL connections on %d\n", socketdesc, 0, 0 );
  1003. }
  1004. } else {
  1005. ct->fd[count].fd = NULL;
  1006. count++;
  1007. }
  1008. ct->s_tcpe = count;
  1009. #if !defined(_WIN32)
  1010. #if defined(ENABLE_LDAPI)
  1011. ct->i_unixs = count;
  1012. /* The fds entry for i_unix starts with i_unixs and less than i_unixe */
  1013. if (i_unix != NULL && accept_new_connections)
  1014. {
  1015. PRFileDesc **fdesc = NULL;
  1016. for (fdesc = i_unix; fdesc && *fdesc; fdesc++, count++) {
  1017. ct->fd[count].fd = *fdesc;
  1018. ct->fd[count].in_flags = SLAPD_POLL_FLAGS;
  1019. ct->fd[count].out_flags = 0;
  1020. LDAPDebug( LDAP_DEBUG_HOUSE,
  1021. "listening for LDAPI connections on %d\n", socketdesc, 0, 0 );
  1022. }
  1023. } else {
  1024. ct->fd[count].fd = NULL;
  1025. count++;
  1026. }
  1027. ct->i_unixe = count;
  1028. #endif
  1029. #endif
  1030. first_time_setup_pr_read_pds = 0;
  1031. listen_addr_count = count;
  1032. }
  1033. /* count is the number of entries we've place in the fds array.
  1034. * listen_addr_count is counted up when
  1035. * first_time_setup_pr_read_pds is TURE. */
  1036. count = listen_addr_count;
  1037. /* Walk down the list of active connections to find
  1038. * out which connections we should poll over. If a connection
  1039. * is no longer in use, we should remove it from the linked
  1040. * list. */
  1041. c = connection_table_get_first_active_connection (ct);
  1042. while (c)
  1043. {
  1044. next = connection_table_get_next_active_connection (ct, c);
  1045. if ( c->c_mutex == NULL )
  1046. {
  1047. connection_table_move_connection_out_of_active_list(ct,c);
  1048. }
  1049. else
  1050. {
  1051. PR_Lock( c->c_mutex );
  1052. if (c->c_flags & CONN_FLAG_CLOSING)
  1053. {
  1054. /* A worker thread has marked that this connection
  1055. * should be closed by calling disconnect_server.
  1056. * move this connection out of the active list
  1057. * the last thread to use the connection will close it
  1058. */
  1059. connection_table_move_connection_out_of_active_list(ct,c);
  1060. }
  1061. else if ( c->c_sd == SLAPD_INVALID_SOCKET )
  1062. {
  1063. connection_table_move_connection_out_of_active_list(ct,c);
  1064. }
  1065. else if ( c->c_prfd != NULL)
  1066. {
  1067. if ((!c->c_gettingber)
  1068. && (c->c_threadnumber < max_threads_per_conn))
  1069. {
  1070. ct->fd[count].fd = c->c_prfd;
  1071. ct->fd[count].in_flags = SLAPD_POLL_FLAGS;
  1072. /* slot i of the connection table is mapped to slot
  1073. * count of the fds array */
  1074. c->c_fdi = count;
  1075. count++;
  1076. }
  1077. else
  1078. {
  1079. c->c_fdi = SLAPD_INVALID_SOCKET_INDEX;
  1080. }
  1081. }
  1082. if (c->c_timelimit > 0) /* check timeout for PAGED RESULTS */
  1083. {
  1084. time_t ctime = current_time();
  1085. if (ctime > c->c_timelimit)
  1086. {
  1087. /* Exceeded the timelimit; disconnect the client */
  1088. disconnect_server_nomutex(c, c->c_connid, -1,
  1089. SLAPD_DISCONNECT_IO_TIMEOUT, 0);
  1090. }
  1091. }
  1092. PR_Unlock( c->c_mutex );
  1093. }
  1094. c = next;
  1095. }
  1096. if( num_to_read )
  1097. (*num_to_read) = count;
  1098. }
  1099. #ifdef notdef /* GGOODREPL */
  1100. static void
  1101. handle_timeout( void )
  1102. {
  1103. static time_t prevtime = 0;
  1104. static time_t housekeeping_fire_time = 0;
  1105. time_t curtime = current_time();
  1106. if (0 == prevtime) {
  1107. prevtime = time (&housekeeping_fire_time);
  1108. }
  1109. if ( difftime(curtime, prevtime) >=
  1110. slapd_housekeeping_timer ) {
  1111. int num_active_threads;
  1112. snmp_collator_update();
  1113. prevtime = curtime;
  1114. num_active_threads = g_get_active_threadcnt();
  1115. if ( (num_active_threads == 0) ||
  1116. (difftime(curtime, housekeeping_fire_time) >=
  1117. slapd_housekeeping_timer*3) ) {
  1118. housekeeping_fire_time = curtime;
  1119. housekeeping_start(curtime);
  1120. }
  1121. }
  1122. }
  1123. #endif /* notdef */
  1124. static int idletimeout_reslimit_handle = -1;
  1125. /*
  1126. * Register the idletimeout with the binder-based resource limits
  1127. * subsystem. A SLAPI_RESLIMIT_STATUS_... code is returned.
  1128. */
  1129. int
  1130. daemon_register_reslimits( void )
  1131. {
  1132. return( slapi_reslimit_register( SLAPI_RESLIMIT_TYPE_INT, "nsIdleTimeout",
  1133. &idletimeout_reslimit_handle ));
  1134. }
  1135. /*
  1136. * Compute the idle timeout for the connection.
  1137. *
  1138. * Note: this function must always be called with conn->c_mutex locked.
  1139. */
  1140. static int
  1141. compute_idletimeout( slapdFrontendConfig_t *fecfg, Connection *conn )
  1142. {
  1143. int idletimeout;
  1144. if ( slapi_reslimit_get_integer_limit( conn, idletimeout_reslimit_handle,
  1145. &idletimeout ) != SLAPI_RESLIMIT_STATUS_SUCCESS ) {
  1146. /*
  1147. * No limit associated with binder/connection or some other error
  1148. * occurred. If the user is anonymous and anonymous limits are
  1149. * set, attempt to set the bind based resource limits. We do this
  1150. * here since a BIND operation is not required prior to other
  1151. * operations. We want to set the anonymous limits early on so
  1152. * that they are put into effect if a BIND is never sent. If
  1153. * this is not an anonymous user and no bind-based limits are set,
  1154. * use the default idle timeout.
  1155. */
  1156. char *anon_dn = config_get_anon_limits_dn();
  1157. if ((conn->c_dn == NULL) && anon_dn && (strlen(anon_dn) > 0)) {
  1158. Slapi_DN *anon_sdn = slapi_sdn_new_dn_byref( anon_dn );
  1159. reslimit_update_from_dn( conn, anon_sdn );
  1160. if ( slapi_reslimit_get_integer_limit( conn,
  1161. idletimeout_reslimit_handle, &idletimeout ) !=
  1162. SLAPI_RESLIMIT_STATUS_SUCCESS ) {
  1163. idletimeout = fecfg->idletimeout;
  1164. }
  1165. slapi_sdn_free( &anon_sdn );
  1166. } else if ( conn->c_isroot ) {
  1167. idletimeout = 0; /* no limit for Directory Manager */
  1168. } else {
  1169. idletimeout = fecfg->idletimeout;
  1170. }
  1171. slapi_ch_free_string( &anon_dn );
  1172. }
  1173. return( idletimeout );
  1174. }
  1175. #ifdef _WIN32
  1176. static void
  1177. handle_read_ready(Connection_Table *ct, fd_set *readfds)
  1178. {
  1179. Connection *c= NULL;
  1180. time_t curtime = current_time();
  1181. slapdFrontendConfig_t *slapdFrontendConfig = getFrontendConfig();
  1182. int idletimeout;
  1183. #ifdef LDAP_DEBUG
  1184. if ( slapd_ldap_debug & LDAP_DEBUG_CONNS )
  1185. {
  1186. connection_table_dump_activity_to_errors_log(ct);
  1187. }
  1188. #endif /* LDAP_DEBUG */
  1189. /* Instead of going through the whole connection table to see which
  1190. * connections we can read from, we'll only check the slots in the
  1191. * linked list */
  1192. c = connection_table_get_first_active_connection (ct);
  1193. while ( c!=NULL )
  1194. {
  1195. if ( c->c_mutex != NULL )
  1196. {
  1197. PR_Lock( c->c_mutex );
  1198. if (connection_is_active_nolock (c) && c->c_gettingber == 0 )
  1199. {
  1200. /* read activity */
  1201. short readready= ( FD_ISSET( c->c_sd, readfds ) );
  1202. /* read activity */
  1203. if ( readready )
  1204. {
  1205. LDAPDebug( LDAP_DEBUG_CONNS, "read activity on %d\n", c->c_ci, 0, 0 );
  1206. c->c_idlesince = curtime;
  1207. /* This is where the work happens ! */
  1208. connection_activity( c );
  1209. /* idle timeout */
  1210. }
  1211. else if (( idletimeout = compute_idletimeout(
  1212. slapdFrontendConfig, c )) > 0 &&
  1213. (curtime - c->c_idlesince) >= idletimeout &&
  1214. NULL == c->c_ops )
  1215. {
  1216. disconnect_server_nomutex( c, c->c_connid, -1,
  1217. SLAPD_DISCONNECT_IDLE_TIMEOUT, EAGAIN );
  1218. }
  1219. }
  1220. PR_Unlock( c->c_mutex );
  1221. }
  1222. c = connection_table_get_next_active_connection (ct, c);
  1223. }
  1224. }
  1225. #endif /* _WIN32 */
  1226. static void
  1227. handle_pr_read_ready(Connection_Table *ct, PRIntn num_poll)
  1228. {
  1229. Connection *c;
  1230. time_t curtime = current_time();
  1231. slapdFrontendConfig_t *slapdFrontendConfig = getFrontendConfig();
  1232. int idletimeout;
  1233. #if defined( XP_WIN32 )
  1234. int i;
  1235. #endif
  1236. #if LDAP_DEBUG
  1237. if ( slapd_ldap_debug & LDAP_DEBUG_CONNS )
  1238. {
  1239. connection_table_dump_activity_to_errors_log(ct);
  1240. }
  1241. #endif /* LDAP_DEBUG */
  1242. #if defined( XP_WIN32 )
  1243. /*
  1244. * WIN32: this function is only called for SSL connections and
  1245. * num_poll indicates exactly how many PR fds we polled on.
  1246. */
  1247. for ( i = 0; i < num_poll; i++ )
  1248. {
  1249. short readready;
  1250. readready = (ct->fd[i].out_flags & SLAPD_POLL_FLAGS);
  1251. /* Find the connection we are referring to */
  1252. for ( c = connection_table_get_first_active_connection (ct); c != NULL;
  1253. c = connection_table_get_next_active_connection (ct, c) )
  1254. {
  1255. if ( c->c_mutex != NULL )
  1256. {
  1257. PR_Lock( c->c_mutex );
  1258. if ( c->c_prfd == ct->fd[i].fd )
  1259. {
  1260. break; /* c_mutex is still locked! */
  1261. }
  1262. PR_Unlock( c->c_mutex );
  1263. }
  1264. }
  1265. if ( c == NULL )
  1266. { /* connection not found! */
  1267. LDAPDebug( LDAP_DEBUG_CONNS, "handle_pr_read_ready: "
  1268. "connection not found for poll slot %d\n", i,0,0 );
  1269. }
  1270. else
  1271. {
  1272. /* c_mutex is still locked... check for activity and errors */
  1273. if ( !readready && ct->fd[i].out_flags && c->c_prfd == ct->fd[i].fd )
  1274. {
  1275. /* some error occured */
  1276. LDAPDebug( LDAP_DEBUG_CONNS,
  1277. "poll says connection on sd %d is bad "
  1278. "(closing)\n", c->c_sd, 0, 0 );
  1279. disconnect_server_nomutex( c, c->c_connid, -1, SLAPD_DISCONNECT_POLL, EPIPE );
  1280. }
  1281. else if ( readready && c->c_prfd == ct->fd[i].fd )
  1282. {
  1283. /* read activity */
  1284. LDAPDebug( LDAP_DEBUG_CONNS,
  1285. "read activity on %d\n", i, 0, 0 );
  1286. c->c_idlesince = curtime;
  1287. /* This is where the work happens ! */
  1288. connection_activity( c );
  1289. }
  1290. else if (( idletimeout = compute_idletimeout( slapdFrontendConfig,
  1291. c )) > 0 &&
  1292. c->c_prfd == ct->fd[i].fd &&
  1293. (curtime - c->c_idlesince) >= idletimeout &&
  1294. NULL == c->c_ops )
  1295. {
  1296. /* idle timeout */
  1297. disconnect_server_nomutex( c, c->c_connid, -1,
  1298. SLAPD_DISCONNECT_IDLE_TIMEOUT, EAGAIN );
  1299. }
  1300. PR_Unlock( c->c_mutex );
  1301. }
  1302. }
  1303. #else
  1304. /*
  1305. * non-WIN32: this function is called for all connections, so we
  1306. * traverse the entire active connection list to find any errors,
  1307. * activity, etc.
  1308. */
  1309. for ( c = connection_table_get_first_active_connection (ct); c != NULL;
  1310. c = connection_table_get_next_active_connection (ct, c) )
  1311. {
  1312. if ( c->c_mutex != NULL )
  1313. {
  1314. PR_Lock( c->c_mutex );
  1315. if ( connection_is_active_nolock (c) && c->c_gettingber == 0 )
  1316. {
  1317. PRInt16 out_flags;
  1318. short readready;
  1319. if (c->c_fdi != SLAPD_INVALID_SOCKET_INDEX)
  1320. {
  1321. out_flags = ct->fd[c->c_fdi].out_flags;
  1322. }
  1323. else
  1324. {
  1325. out_flags = 0;
  1326. }
  1327. readready = ( out_flags & SLAPD_POLL_FLAGS );
  1328. if ( !readready && out_flags )
  1329. {
  1330. /* some error occured */
  1331. LDAPDebug( LDAP_DEBUG_CONNS,
  1332. "POLL_FN() says connection on sd %d is bad "
  1333. "(closing)\n", c->c_sd, 0, 0 );
  1334. disconnect_server_nomutex( c, c->c_connid, -1,
  1335. SLAPD_DISCONNECT_POLL, EPIPE );
  1336. }
  1337. else if ( readready )
  1338. {
  1339. /* read activity */
  1340. LDAPDebug( LDAP_DEBUG_CONNS,
  1341. "read activity on %d\n", c->c_ci, 0, 0 );
  1342. c->c_idlesince = curtime;
  1343. /* This is where the work happens ! */
  1344. /* MAB: 25 jan 01, error handling added */
  1345. if ((connection_activity( c )) == -1) {
  1346. /* This might happen as a result of
  1347. * trying to acquire a closing connection
  1348. */
  1349. LDAPDebug (LDAP_DEBUG_ANY,
  1350. "connection_activity: abandoning conn %" NSPRIu64 " as fd=%d is already closing\n",
  1351. c->c_connid,c->c_sd,0);
  1352. /* The call disconnect_server should do nothing,
  1353. * as the connection c should be already set to CLOSING */
  1354. disconnect_server_nomutex( c, c->c_connid, -1,
  1355. SLAPD_DISCONNECT_POLL, EPIPE );
  1356. }
  1357. }
  1358. else if (( idletimeout = compute_idletimeout(
  1359. slapdFrontendConfig, c )) > 0 &&
  1360. (curtime - c->c_idlesince) >= idletimeout &&
  1361. NULL == c->c_ops )
  1362. {
  1363. /* idle timeout */
  1364. disconnect_server_nomutex( c, c->c_connid, -1,
  1365. SLAPD_DISCONNECT_IDLE_TIMEOUT, EAGAIN );
  1366. }
  1367. }
  1368. PR_Unlock( c->c_mutex );
  1369. }
  1370. }
  1371. #endif
  1372. }
  1373. /*
  1374. * wrapper functions required so we can implement ioblock_timeout and
  1375. * avoid blocking forever.
  1376. */
  1377. #define SLAPD_POLLIN 0
  1378. #define SLAPD_POLLOUT 1
  1379. /* Return 1 if the given handle is ready for input or output,
  1380. * or if it becomes ready within g_ioblock_timeout [msec].
  1381. * Return -1 if handle is not ready and g_ioblock_timeout > 0,
  1382. * or something goes seriously wrong. Otherwise, return 0.
  1383. * If -1 is returned, PR_GetError() explains why.
  1384. * Revision: handle changed to void * to allow 64bit support
  1385. */
  1386. static int
  1387. slapd_poll( void *handle, int output )
  1388. {
  1389. int rc;
  1390. int ioblock_timeout = config_get_ioblocktimeout();
  1391. #if defined( XP_WIN32 )
  1392. if( !secure ) {
  1393. fd_set handle_set;
  1394. struct timeval timeout;
  1395. int windows_handle = (int) handle;
  1396. memset (&timeout, 0, sizeof(timeout));
  1397. if (ioblock_timeout > 0) {
  1398. timeout.tv_sec = ioblock_timeout / 1000;
  1399. timeout.tv_usec = (ioblock_timeout % 1000) * 1000;
  1400. }
  1401. FD_ZERO(&handle_set);
  1402. FD_SET(windows_handle, &handle_set);
  1403. rc = output ? select(FD_SETSIZE, NULL, &handle_set, NULL, &timeout)
  1404. : select(FD_SETSIZE, &handle_set, NULL, NULL, &timeout);
  1405. } else {
  1406. struct POLL_STRUCT pr_pd;
  1407. PRIntervalTime timeout = PR_MillisecondsToInterval( ioblock_timeout );
  1408. if (timeout < 0) timeout = 0;
  1409. pr_pd.fd = (PRFileDesc *)handle;
  1410. pr_pd.in_flags = output ? PR_POLL_WRITE : PR_POLL_READ;
  1411. pr_pd.out_flags = 0;
  1412. rc = POLL_FN(&pr_pd, 1, timeout);
  1413. }
  1414. #else
  1415. struct POLL_STRUCT pr_pd;
  1416. PRIntervalTime timeout = PR_MillisecondsToInterval(ioblock_timeout);
  1417. pr_pd.fd = (PRFileDesc *)handle;
  1418. pr_pd.in_flags = output ? PR_POLL_WRITE : PR_POLL_READ;
  1419. pr_pd.out_flags = 0;
  1420. rc = POLL_FN(&pr_pd, 1, timeout);
  1421. #endif
  1422. if (rc < 0) {
  1423. #if defined( XP_WIN32 )
  1424. if( !secure ) {
  1425. int oserr = errno;
  1426. LDAPDebug(LDAP_DEBUG_CONNS, "slapd_poll(%d) error %d (%s)\n",
  1427. handle, oserr, slapd_system_strerror(oserr));
  1428. if ( SLAPD_SYSTEM_WOULD_BLOCK_ERROR(oserr)) {
  1429. rc = 0; /* try again */
  1430. }
  1431. } else {
  1432. PRErrorCode prerr = PR_GetError();
  1433. LDAPDebug(LDAP_DEBUG_CONNS, "slapd_poll(%d) "
  1434. SLAPI_COMPONENT_NAME_NSPR " error %d (%s)\n",
  1435. handle, prerr, slapd_pr_strerror(prerr));
  1436. if ( prerr == PR_PENDING_INTERRUPT_ERROR ||
  1437. SLAPD_PR_WOULD_BLOCK_ERROR(prerr)) {
  1438. rc = 0; /* try again */
  1439. }
  1440. }
  1441. #else
  1442. PRErrorCode prerr = PR_GetError();
  1443. LDAPDebug(LDAP_DEBUG_ANY, "slapd_poll(%d) "
  1444. SLAPI_COMPONENT_NAME_NSPR " error %d (%s)\n",
  1445. handle, prerr, slapd_pr_strerror(prerr));
  1446. if ( prerr == PR_PENDING_INTERRUPT_ERROR ||
  1447. SLAPD_PR_WOULD_BLOCK_ERROR(prerr)) {
  1448. rc = 0; /* try again */
  1449. }
  1450. #endif
  1451. } else if (rc == 0 && ioblock_timeout > 0) {
  1452. PRIntn ihandle;
  1453. #if !defined( XP_WIN32 )
  1454. ihandle = PR_FileDesc2NativeHandle((PRFileDesc *)handle);
  1455. #else
  1456. if( secure )
  1457. ihandle = PR_FileDesc2NativeHandle((PRFileDesc *)handle);
  1458. else
  1459. ihandle = (PRIntn)handle;
  1460. #endif
  1461. LDAPDebug(LDAP_DEBUG_ANY, "slapd_poll(%d) timed out\n",
  1462. ihandle, 0, 0);
  1463. #if defined( XP_WIN32 )
  1464. /*
  1465. * Bug 624303 - This connection will be cleaned up soon.
  1466. * During cleanup (see connection_cleanup()), SSL3_SendAlert()
  1467. * will be called by PR_Close(), and its default wTimeout
  1468. * in sslSocket associated with the handle
  1469. * is no time out (I gave up after waited for 30 minutes).
  1470. * It was during this closing period that server won't
  1471. * response to new connection requests.
  1472. * PR_Send() null is a hack here to change the default wTimeout
  1473. * (see ssl_Send()) to one second which affects PR_Close()
  1474. * only in the current scenario.
  1475. */
  1476. if( secure ) {
  1477. PR_Send ((PRFileDesc *)handle, NULL, 0, 0, PR_SecondsToInterval(1));
  1478. }
  1479. #endif
  1480. PR_SetError(PR_IO_TIMEOUT_ERROR, EAGAIN); /* timeout */
  1481. rc = -1;
  1482. }
  1483. return rc;
  1484. }
  1485. /*
  1486. * Revision: handle changed to void * and first
  1487. * argument which used to be integer system fd is now ignored.
  1488. */
  1489. #if defined(USE_OPENLDAP)
  1490. static int
  1491. write_function( int ignore, void *buffer, int count, void *handle )
  1492. #else
  1493. static int
  1494. write_function( int ignore, const void *buffer, int count, struct lextiof_socket_private *handle )
  1495. #endif
  1496. {
  1497. int sentbytes = 0;
  1498. int bytes;
  1499. int fd = PR_FileDesc2NativeHandle((PRFileDesc *)handle);
  1500. if (handle == SLAPD_INVALID_SOCKET) {
  1501. PR_SetError(PR_NOT_SOCKET_ERROR, EBADF);
  1502. } else {
  1503. while (1) {
  1504. if (slapd_poll(handle, SLAPD_POLLOUT) < 0) { /* error */
  1505. break;
  1506. }
  1507. bytes = PR_Write((PRFileDesc *)handle, (char *)buffer + sentbytes,
  1508. count - sentbytes);
  1509. if (bytes > 0) {
  1510. sentbytes += bytes;
  1511. } else if (bytes < 0) {
  1512. PRErrorCode prerr = PR_GetError();
  1513. LDAPDebug(LDAP_DEBUG_CONNS, "PR_Write(%d) "
  1514. SLAPI_COMPONENT_NAME_NSPR " error %d (%s)\n",
  1515. fd, prerr, slapd_pr_strerror( prerr ));
  1516. if ( !SLAPD_PR_WOULD_BLOCK_ERROR(prerr)) {
  1517. LDAPDebug(LDAP_DEBUG_ANY, "PR_Write(%d) "
  1518. SLAPI_COMPONENT_NAME_NSPR " error %d (%s)\n",
  1519. fd, prerr, slapd_pr_strerror( prerr ));
  1520. if (sentbytes < count) {
  1521. LDAPDebug(LDAP_DEBUG_CONNS,
  1522. "PR_Write(%d) - wrote only %d bytes (expected %d bytes) - 0 (EOF)\n", /* disconnected */
  1523. fd, sentbytes, count);
  1524. }
  1525. break; /* fatal error */
  1526. }
  1527. } else if (bytes == 0) { /* disconnect */
  1528. PRErrorCode prerr = PR_GetError();
  1529. LDAPDebug(LDAP_DEBUG_CONNS,
  1530. "PR_Write(%d) - 0 (EOF) %d:%s\n", /* disconnected */
  1531. fd, prerr, slapd_pr_strerror(prerr));
  1532. PR_SetError(PR_PIPE_ERROR, EPIPE);
  1533. break;
  1534. }
  1535. if (sentbytes == count) { /* success */
  1536. return count;
  1537. } else if (sentbytes > count) { /* too many bytes */
  1538. LDAPDebug(LDAP_DEBUG_ANY,
  1539. "PR_Write(%d) overflow - sent %d bytes (expected %d bytes) - error\n",
  1540. fd, sentbytes, count);
  1541. PR_SetError(PR_BUFFER_OVERFLOW_ERROR, EMSGSIZE);
  1542. break;
  1543. }
  1544. }
  1545. }
  1546. return -1;
  1547. }
  1548. #if defined(USE_OPENLDAP)
  1549. /* The argument is a pointer to the socket descriptor */
  1550. static int
  1551. openldap_io_setup(Sockbuf_IO_Desc *sbiod, void *arg)
  1552. {
  1553. PR_ASSERT(sbiod);
  1554. if (arg != NULL) {
  1555. sbiod->sbiod_pvt = arg;
  1556. }
  1557. return 0;
  1558. }
  1559. static ber_slen_t
  1560. openldap_write_function(Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
  1561. {
  1562. Connection *conn = NULL;
  1563. PRFileDesc *fd = NULL;
  1564. PR_ASSERT(sbiod);
  1565. PR_ASSERT(sbiod->sbiod_pvt);
  1566. conn = (Connection *)sbiod->sbiod_pvt;
  1567. PR_ASSERT(conn->c_prfd);
  1568. fd = (PRFileDesc *)conn->c_prfd;
  1569. PR_ASSERT(fd != SLAPD_INVALID_SOCKET);
  1570. return write_function(0, buf, len, fd);
  1571. }
  1572. static int
  1573. openldap_io_ctrl(Sockbuf_IO_Desc *sbiod, int opt, void *arg)
  1574. {
  1575. PR_ASSERT(0); /* not sure if this is needed */
  1576. return -1;
  1577. }
  1578. static int
  1579. openldap_io_close(Sockbuf_IO_Desc *sbiod)
  1580. {
  1581. return 0; /* closing done in connection_cleanup() */
  1582. }
  1583. static Sockbuf_IO openldap_sockbuf_io = {
  1584. openldap_io_setup, /* sbi_setup */
  1585. NULL, /* sbi_remove */
  1586. openldap_io_ctrl, /* sbi_ctrl */
  1587. openldap_read_function, /* sbi_read */ /* see connection.c */
  1588. openldap_write_function, /* sbi_write */
  1589. openldap_io_close /* sbi_close */
  1590. };
  1591. #endif /* USE_OPENLDAP */
  1592. int connection_type = -1; /* The type number assigned by the Factory for 'Connection' */
  1593. void
  1594. daemon_register_connection()
  1595. {
  1596. if(connection_type==-1)
  1597. {
  1598. /* The factory is given the name of the object type, in
  1599. * return for a type handle. Whenever the object is created
  1600. * or destroyed the factory is called with the handle so
  1601. * that it may call the constructors or destructors registered
  1602. * with it.
  1603. */
  1604. connection_type= factory_register_type(SLAPI_EXT_CONNECTION,offsetof(Connection,c_extension));
  1605. }
  1606. }
  1607. #if defined(ENABLE_LDAPI)
  1608. int
  1609. slapd_identify_local_user(Connection *conn)
  1610. {
  1611. int ret = -1;
  1612. uid_t uid = 0;
  1613. gid_t gid = 0;
  1614. conn->c_local_valid = 0;
  1615. if(0 == slapd_get_socket_peer(conn->c_prfd, &uid, &gid))
  1616. {
  1617. conn->c_local_uid = uid;
  1618. conn->c_local_gid = gid;
  1619. conn->c_local_valid = 1;
  1620. ret = 0;
  1621. }
  1622. return ret;
  1623. }
  1624. #if defined(ENABLE_AUTOBIND)
  1625. int
  1626. slapd_bind_local_user(Connection *conn)
  1627. {
  1628. int ret = -1;
  1629. uid_t uid = conn->c_local_uid;
  1630. gid_t gid = conn->c_local_gid;
  1631. if (!conn->c_local_valid)
  1632. {
  1633. goto bail;
  1634. }
  1635. /* observe configuration for auto binding */
  1636. /* bind at all? */
  1637. if(config_get_ldapi_bind_switch())
  1638. {
  1639. /* map users to a dn
  1640. root may also map to an entry
  1641. */
  1642. /* require real entry? */
  1643. if(config_get_ldapi_map_entries())
  1644. {
  1645. /* get uid type to map to (e.g. uidNumber) */
  1646. char *utype = config_get_ldapi_uidnumber_type();
  1647. /* get gid type to map to (e.g. gidNumber) */
  1648. char *gtype = config_get_ldapi_gidnumber_type();
  1649. /* get base dn for search */
  1650. char *base_dn = config_get_ldapi_search_base_dn();
  1651. /* search vars */
  1652. Slapi_PBlock *search_pb = 0;
  1653. Slapi_Entry **entries = 0;
  1654. int result;
  1655. /* filter manipulation vars */
  1656. char *one_type = 0;
  1657. char *filter_tpl = 0;
  1658. char *filter = 0;
  1659. /* create filter, matching whatever is given */
  1660. if(utype && gtype)
  1661. {
  1662. filter_tpl = "(&(%s=%u)(%s=%u))";
  1663. }
  1664. else
  1665. {
  1666. if(utype || gtype)
  1667. {
  1668. filter_tpl = "(%s=%u)";
  1669. if(utype)
  1670. one_type = utype;
  1671. else
  1672. one_type = gtype;
  1673. }
  1674. else
  1675. {
  1676. goto entry_map_free;
  1677. }
  1678. }
  1679. if(one_type)
  1680. {
  1681. if(one_type == utype)
  1682. filter = slapi_ch_smprintf(filter_tpl,
  1683. utype, uid);
  1684. else
  1685. filter = slapi_ch_smprintf(filter_tpl,
  1686. gtype, gid);
  1687. }
  1688. else
  1689. {
  1690. filter = slapi_ch_smprintf(filter_tpl,
  1691. utype, uid, gtype, gid);
  1692. }
  1693. /* search for single entry matching types */
  1694. search_pb = slapi_pblock_new();
  1695. slapi_search_internal_set_pb(
  1696. search_pb,
  1697. base_dn,
  1698. LDAP_SCOPE_SUBTREE,
  1699. filter,
  1700. NULL, 0, NULL, NULL,
  1701. (void*)plugin_get_default_component_id(),
  1702. 0);
  1703. slapi_search_internal_pb(search_pb);
  1704. slapi_pblock_get(
  1705. search_pb,
  1706. SLAPI_PLUGIN_INTOP_RESULT,
  1707. &result);
  1708. if(LDAP_SUCCESS == result)
  1709. slapi_pblock_get(
  1710. search_pb,
  1711. SLAPI_PLUGIN_INTOP_SEARCH_ENTRIES,
  1712. &entries);
  1713. if(entries)
  1714. {
  1715. /* zero or multiple entries fail */
  1716. if(entries[0] && 0 == entries[1])
  1717. {
  1718. /* observe account locking */
  1719. ret = slapi_check_account_lock(
  1720. 0, /* pb not req */
  1721. entries[0],
  1722. 0, /* no response control */
  1723. 0, /* don't check password policy */
  1724. 0 /* don't send ldap result */
  1725. );
  1726. if(0 == ret)
  1727. {
  1728. char *auth_dn = slapi_ch_strdup(
  1729. slapi_entry_get_ndn(
  1730. entries[0]));
  1731. auth_dn = slapi_dn_normalize(
  1732. auth_dn);
  1733. bind_credentials_set_nolock(
  1734. conn,
  1735. SLAPD_AUTH_OS,
  1736. auth_dn,
  1737. NULL, NULL,
  1738. NULL , entries[0]);
  1739. ret = 0;
  1740. }
  1741. }
  1742. }
  1743. entry_map_free:
  1744. /* auth_dn consumed by bind creds set */
  1745. slapi_free_search_results_internal(search_pb);
  1746. slapi_pblock_destroy(search_pb);
  1747. slapi_ch_free_string(&filter);
  1748. slapi_ch_free_string(&utype);
  1749. slapi_ch_free_string(&gtype);
  1750. slapi_ch_free_string(&base_dn);
  1751. }
  1752. if(ret && 0 == uid)
  1753. {
  1754. /* map unix root (uidNumber:0)? */
  1755. char *root_dn = config_get_ldapi_root_dn();
  1756. if(root_dn)
  1757. {
  1758. Slapi_DN *edn = slapi_sdn_new_dn_byref(
  1759. slapi_dn_normalize(root_dn));
  1760. Slapi_Entry *e = 0;
  1761. /* root might be locked too! :) */
  1762. ret = slapi_search_internal_get_entry(
  1763. edn, 0,
  1764. &e,
  1765. (void*)plugin_get_default_component_id()
  1766. );
  1767. if(0 == ret && e)
  1768. {
  1769. ret = slapi_check_account_lock(
  1770. 0, /* pb not req */
  1771. e,
  1772. 0, /* no response control */
  1773. 0, /* don't check password policy */
  1774. 0 /* don't send ldap result */
  1775. );
  1776. if(1 == ret)
  1777. /* sorry root,
  1778. * just not cool enough
  1779. */
  1780. goto root_map_free;
  1781. }
  1782. /* it's ok not to find the entry,
  1783. * dn doesn't have to have an entry
  1784. * e.g. cn=Directory Manager
  1785. */
  1786. bind_credentials_set_nolock(
  1787. conn, SLAPD_AUTH_OS, root_dn,
  1788. NULL, NULL, NULL , e);
  1789. root_map_free:
  1790. /* root_dn consumed by bind creds set */
  1791. slapi_sdn_free(&edn);
  1792. slapi_entry_free(e);
  1793. ret = 0;
  1794. }
  1795. }
  1796. #if defined(ENABLE_AUTO_DN_SUFFIX)
  1797. if(ret)
  1798. {
  1799. /* create phony auth dn? */
  1800. char *base = config_get_ldapi_auto_dn_suffix();
  1801. if(base)
  1802. {
  1803. char *tpl = "gidNumber=%u+uidNumber=%u,";
  1804. int len =
  1805. strlen(tpl) +
  1806. strlen(base) +
  1807. 51 /* uid,gid,null,w/padding */
  1808. ;
  1809. char *dn_str = (char*)slapi_ch_malloc(
  1810. len);
  1811. char *auth_dn = (char*)slapi_ch_malloc(
  1812. len);
  1813. dn_str[0] = 0;
  1814. strcpy(dn_str, tpl);
  1815. strcat(dn_str, base);
  1816. sprintf(auth_dn, dn_str, gid, uid);
  1817. auth_dn = slapi_dn_normalize(auth_dn);
  1818. bind_credentials_set_nolock(
  1819. conn,
  1820. SLAPD_AUTH_OS,
  1821. auth_dn,
  1822. NULL, NULL, NULL , NULL);
  1823. /* auth_dn consumed by bind creds set */
  1824. slapi_ch_free_string(&dn_str);
  1825. slapi_ch_free_string(&base);
  1826. ret = 0;
  1827. }
  1828. }
  1829. #endif
  1830. }
  1831. bail:
  1832. /* if all fails, the peer is anonymous */
  1833. if(conn->c_dn)
  1834. {
  1835. /* log the auto bind */
  1836. slapi_log_access(LDAP_DEBUG_STATS, "conn=%" PRIu64 " AUTOBIND dn=\"%s\"\n", conn->c_connid, conn->c_dn);
  1837. }
  1838. return ret;
  1839. }
  1840. #endif /* ENABLE_AUTOBIND */
  1841. #endif /* ENABLE_LDAPI */
  1842. /* NOTE: this routine is not reentrant */
  1843. static int
  1844. handle_new_connection(Connection_Table *ct, int tcps, PRFileDesc *pr_acceptfd, int secure, int local)
  1845. {
  1846. int ns = 0;
  1847. Connection *conn = NULL;
  1848. /* struct sockaddr_in from;*/
  1849. PRNetAddr from;
  1850. PRFileDesc *pr_clonefd = NULL;
  1851. memset(&from, 0, sizeof(from)); /* reset to nulls so we can see what was set */
  1852. if ( (ns = accept_and_configure( tcps, pr_acceptfd, &from,
  1853. sizeof(from), secure, local, &pr_clonefd)) == SLAPD_INVALID_SOCKET ) {
  1854. return -1;
  1855. }
  1856. /* get a new Connection from the Connection Table */
  1857. conn= connection_table_get_connection(ct,ns);
  1858. if(conn==NULL)
  1859. {
  1860. PR_Close(pr_acceptfd);
  1861. return -1;
  1862. }
  1863. PR_Lock( conn->c_mutex );
  1864. #if defined( XP_WIN32 )
  1865. if( !secure )
  1866. ber_sockbuf_set_option(conn->c_sb,LBER_SOCKBUF_OPT_DESC,&ns);
  1867. #endif
  1868. conn->c_sd = ns;
  1869. conn->c_prfd = pr_clonefd;
  1870. conn->c_flags &= ~CONN_FLAG_CLOSING;
  1871. /* Store the fact that this new connection is an SSL connection */
  1872. if (secure) {
  1873. conn->c_flags |= CONN_FLAG_SSL;
  1874. }
  1875. #ifndef _WIN32
  1876. /*
  1877. * clear the "returned events" field in ns' slot within the poll fds
  1878. * array so that handle_read_ready() doesn't look at out_flags for an
  1879. * old connection by mistake and do something bad such as close the
  1880. * connection we just accepted.
  1881. */
  1882. /* Dont have to worry about this now because of our mapping from
  1883. * the connection table to the fds array. This new connection
  1884. * won't have a mapping. */
  1885. /* fds[ns].out_flags = 0; */
  1886. #endif
  1887. #if defined(USE_OPENLDAP)
  1888. ber_sockbuf_add_io( conn->c_sb, &openldap_sockbuf_io,
  1889. LBER_SBIOD_LEVEL_PROVIDER, conn );
  1890. #else /* !USE_OPENLDAP */
  1891. {
  1892. struct lber_x_ext_io_fns func_pointers;
  1893. memset(&func_pointers, 0, sizeof(func_pointers));
  1894. func_pointers.lbextiofn_size = LBER_X_EXTIO_FNS_SIZE;
  1895. func_pointers.lbextiofn_read = NULL; /* see connection_read_function */
  1896. func_pointers.lbextiofn_write = write_function;
  1897. func_pointers.lbextiofn_writev = NULL;
  1898. #ifdef _WIN32
  1899. func_pointers.lbextiofn_socket_arg = (struct lextiof_socket_private *) ns;
  1900. #else
  1901. func_pointers.lbextiofn_socket_arg = (struct lextiof_socket_private *) pr_clonefd;
  1902. #endif
  1903. ber_sockbuf_set_option( conn->c_sb,
  1904. LBER_SOCKBUF_OPT_EXT_IO_FNS, &func_pointers);
  1905. }
  1906. #endif /* !USE_OPENLDAP */
  1907. if( secure && config_get_SSLclientAuth() != SLAPD_SSLCLIENTAUTH_OFF ) {
  1908. /* Prepare to handle the client's certificate (if any): */
  1909. int rv;
  1910. rv = slapd_ssl_handshakeCallback (conn->c_prfd, (void*)handle_handshake_done, conn);
  1911. if (rv < 0) {
  1912. PRErrorCode prerr = PR_GetError();
  1913. LDAPDebug (LDAP_DEBUG_ANY, "SSL_HandshakeCallback() %d "
  1914. SLAPI_COMPONENT_NAME_NSPR " error %d (%s)\n",
  1915. rv, prerr, slapd_pr_strerror( prerr ));
  1916. }
  1917. rv = slapd_ssl_badCertHook (conn->c_prfd, (void*)handle_bad_certificate, conn);
  1918. if (rv < 0) {
  1919. PRErrorCode prerr = PR_GetError();
  1920. LDAPDebug (LDAP_DEBUG_ANY, "SSL_BadCertHook(%i) %i "
  1921. SLAPI_COMPONENT_NAME_NSPR " error %d\n",
  1922. conn->c_sd, rv, prerr);
  1923. }
  1924. }
  1925. connection_reset(conn, ns, &from, sizeof(from), secure);
  1926. /* Call the plugin extension constructors */
  1927. conn->c_extension = factory_create_extension(connection_type,conn,NULL /* Parent */);
  1928. /* Add this connection slot to the doubly linked list of active connections. This
  1929. * list is used to find the connections that should be used in the poll call. This
  1930. * connection will be added directly after slot 0 which serves as the head of the list */
  1931. if ( conn != NULL && conn->c_next == NULL && conn->c_prev == NULL )
  1932. {
  1933. /* Now give the new connection to the connection code */
  1934. connection_table_move_connection_on_to_active_list(the_connection_table,conn);
  1935. }
  1936. #if defined(ENABLE_LDAPI)
  1937. #if !defined( XP_WIN32 )
  1938. /* ldapi */
  1939. if( local )
  1940. {
  1941. conn->c_unix_local = 1;
  1942. slapd_identify_local_user(conn);
  1943. }
  1944. #endif
  1945. #endif /* ENABLE_LDAPI */
  1946. PR_Unlock( conn->c_mutex );
  1947. connection_new_private(conn);
  1948. g_increment_current_conn_count();
  1949. return 0;
  1950. }
  1951. static int init_shutdown_detect()
  1952. {
  1953. #ifdef _WIN32
  1954. PRThread *service_exit_wait_tid;
  1955. #else
  1956. /* First of all, we must reset the signal mask to get rid of any blockages
  1957. * the process may have inherited from its parent (such as the console), which
  1958. * might result in the process not delivering those blocked signals, and thus,
  1959. * misbehaving....
  1960. */
  1961. {
  1962. int rc;
  1963. sigset_t proc_mask;
  1964. LDAPDebug( LDAP_DEBUG_TRACE, "Reseting signal mask....\n", 0, 0, 0);
  1965. (void)sigemptyset( &proc_mask );
  1966. rc = pthread_sigmask( SIG_SETMASK, &proc_mask, NULL );
  1967. LDAPDebug( LDAP_DEBUG_TRACE, " %s \n",
  1968. rc ? "Failed to reset signal mask":"....Done (signal mask reset)!!", 0, 0 );
  1969. }
  1970. #endif
  1971. #ifdef _WIN32
  1972. /* Create a thread to wait on the Win32 event which will
  1973. be signalled by the watchdog when the Service is
  1974. being halted. */
  1975. service_exit_wait_tid = PR_CreateThread( PR_USER_THREAD,
  1976. (VFP) (void *) slapd_service_exit_wait, (void *) NULL,
  1977. PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, PR_UNJOINABLE_THREAD,
  1978. SLAPD_DEFAULT_THREAD_STACKSIZE);
  1979. if( service_exit_wait_tid == NULL ) {
  1980. LDAPDebug( LDAP_DEBUG_ANY,
  1981. "Error: PR_CreateThread(slapd_service_exit_wait) failed\n", 0, 0, 0 );
  1982. }
  1983. #elif defined ( HPUX10 )
  1984. PR_CreateThread ( PR_USER_THREAD,
  1985. catch_signals,
  1986. NULL,
  1987. PR_PRIORITY_NORMAL,
  1988. PR_GLOBAL_THREAD,
  1989. PR_UNJOINABLE_THREAD,
  1990. SLAPD_DEFAULT_THREAD_STACKSIZE);
  1991. #else
  1992. #ifdef HPUX11
  1993. /* In the optimized builds for HPUX, the signal handler doesn't seem
  1994. * to get set correctly unless the primordial thread gets a chance
  1995. * to run before we make the call to SIGNAL. (At this point the
  1996. * the primordial thread has spawned the daemon thread which called
  1997. * this function.) The call to DS_Sleep will give the primordial
  1998. * thread a chance to run.
  1999. */
  2000. DS_Sleep(0);
  2001. #endif
  2002. (void) SIGNAL( SIGPIPE, SIG_IGN );
  2003. (void) SIGNAL( SIGCHLD, slapd_wait4child );
  2004. #ifndef LINUX
  2005. /* linux uses USR1/USR2 for thread synchronization, so we aren't
  2006. * allowed to mess with those.
  2007. */
  2008. (void) SIGNAL( SIGUSR1, slapd_do_nothing );
  2009. (void) SIGNAL( SIGUSR2, set_shutdown );
  2010. #endif
  2011. (void) SIGNAL( SIGTERM, set_shutdown );
  2012. (void) SIGNAL( SIGHUP, set_shutdown );
  2013. #endif /* _WIN32 */
  2014. return 0;
  2015. }
  2016. #if defined( XP_WIN32 )
  2017. static void
  2018. unfurl_banners(Connection_Table *ct,daemon_ports_t *ports, int n_tcps, PRFileDesc *s_tcps)
  2019. #else
  2020. static void
  2021. unfurl_banners(Connection_Table *ct,daemon_ports_t *ports, PRFileDesc **n_tcps, PRFileDesc **s_tcps, PRFileDesc **i_unix)
  2022. #endif
  2023. {
  2024. slapdFrontendConfig_t *slapdFrontendConfig = getFrontendConfig();
  2025. char addrbuf[ 256 ];
  2026. int isfirsttime = 1;
  2027. if ( ct->size <= slapdFrontendConfig->reservedescriptors ) {
  2028. #ifdef _WIN32
  2029. LDAPDebug( LDAP_DEBUG_ANY,
  2030. "ERROR: Not enough descriptors to accept any connections. "
  2031. "This may be because the maxdescriptors configuration "
  2032. "directive is too small, or the reservedescriptors "
  2033. "configuration directive is too large. "
  2034. "Try increasing the number of descriptors available to "
  2035. "the slapd process. The current value is %d. %d "
  2036. "descriptors are currently reserved for internal "
  2037. "slapd use, so the total number of descriptors available "
  2038. "to the process must be greater than %d.\n",
  2039. ct->size, slapdFrontendConfig->reservedescriptors, slapdFrontendConfig->reservedescriptors );
  2040. #else /* _WIN32 */
  2041. LDAPDebug( LDAP_DEBUG_ANY,
  2042. "ERROR: Not enough descriptors to accept any connections. "
  2043. "This may be because the maxdescriptors configuration "
  2044. "directive is too small, the hard limit on descriptors is "
  2045. "too small (see limit(1)), or the reservedescriptors "
  2046. "configuration directive is too large. "
  2047. "Try increasing the number of descriptors available to "
  2048. "the slapd process. The current value is %d. %d "
  2049. "descriptors are currently reserved for internal "
  2050. "slapd use, so the total number of descriptors available "
  2051. "to the process must be greater than %d.\n",
  2052. ct->size, slapdFrontendConfig->reservedescriptors, slapdFrontendConfig->reservedescriptors );
  2053. #endif /* _WIN32 */
  2054. exit( 1 );
  2055. }
  2056. /*
  2057. * This final startup message gives a definite signal to the admin
  2058. * program that the server is up. It must contain the string
  2059. * "slapd started." because some of the administrative programs
  2060. * depend on this. See ldap/admin/lib/dsalib_updown.c.
  2061. */
  2062. #if !defined( XP_WIN32 )
  2063. if ( n_tcps != NULL ) { /* standard LDAP */
  2064. PRNetAddr **nap = NULL;
  2065. for (nap = ports->n_listenaddr; nap && *nap; nap++) {
  2066. if (isfirsttime) {
  2067. LDAPDebug( LDAP_DEBUG_ANY,
  2068. "slapd started. Listening on %s port %d for LDAP requests\n",
  2069. netaddr2string(*nap, addrbuf, sizeof(addrbuf)),
  2070. ports->n_port, 0 );
  2071. isfirsttime = 0;
  2072. } else {
  2073. LDAPDebug( LDAP_DEBUG_ANY,
  2074. "Listening on %s port %d for LDAP requests\n",
  2075. netaddr2string(*nap, addrbuf, sizeof(addrbuf)),
  2076. ports->n_port, 0 );
  2077. }
  2078. }
  2079. }
  2080. if ( s_tcps != NULL ) { /* LDAP over SSL; separate port */
  2081. PRNetAddr **sap = NULL;
  2082. for (sap = ports->s_listenaddr; sap && *sap; sap++) {
  2083. if (isfirsttime) {
  2084. LDAPDebug( LDAP_DEBUG_ANY,
  2085. "slapd started. Listening on %s port %d for LDAPS requests\n",
  2086. netaddr2string(*sap, addrbuf, sizeof(addrbuf)),
  2087. ports->s_port, 0 );
  2088. isfirsttime = 0;
  2089. } else {
  2090. LDAPDebug( LDAP_DEBUG_ANY,
  2091. "Listening on %s port %d for LDAPS requests\n",
  2092. netaddr2string(*sap, addrbuf, sizeof(addrbuf)),
  2093. ports->s_port, 0 );
  2094. }
  2095. }
  2096. }
  2097. #else
  2098. if ( n_tcps != SLAPD_INVALID_SOCKET ) { /* standard LDAP; XP_WIN32 */
  2099. LDAPDebug( LDAP_DEBUG_ANY,
  2100. "slapd started. Listening on %s port %d for LDAP requests\n",
  2101. netaddr2string(&ports->n_listenaddr, addrbuf, sizeof(addrbuf)),
  2102. ports->n_port, 0 );
  2103. }
  2104. if ( s_tcps != NULL ) { /* LDAP over SSL; separate port */
  2105. LDAPDebug( LDAP_DEBUG_ANY,
  2106. "Listening on %s port %d for LDAPS requests\n",
  2107. netaddr2string(&ports->s_listenaddr, addrbuf, sizeof(addrbuf)),
  2108. ports->s_port, 0 );
  2109. }
  2110. #endif
  2111. #if !defined( XP_WIN32 )
  2112. #if defined(ENABLE_LDAPI)
  2113. if ( i_unix != NULL ) { /* LDAPI */
  2114. PRNetAddr **iap = ports->i_listenaddr;
  2115. LDAPDebug( LDAP_DEBUG_ANY,
  2116. "%sListening on %s for LDAPI requests\n", isfirsttime?"slapd started. ":"",
  2117. (*iap)->local.path, 0 );
  2118. }
  2119. #endif /* ENABLE_LDAPI */
  2120. #endif
  2121. }
  2122. #if defined( _WIN32 )
  2123. /* On Windows, we signal the SCM when we're ready to accept connections */
  2124. static int
  2125. write_pid_file()
  2126. {
  2127. if( SlapdIsAService() )
  2128. {
  2129. /* Initialization complete and successful. Set service to running */
  2130. LDAPServerStatus.dwCurrentState = SERVICE_RUNNING;
  2131. LDAPServerStatus.dwCheckPoint = 0;
  2132. LDAPServerStatus.dwWaitHint = 0;
  2133. if (!SetServiceStatus(hLDAPServerServiceStatus, &LDAPServerStatus)) {
  2134. ReportSlapdEvent(EVENTLOG_INFORMATION_TYPE, MSG_SERVER_START_FAILED, 1,
  2135. "Could not set Service status.");
  2136. exit(1);
  2137. }
  2138. }
  2139. ReportSlapdEvent(EVENTLOG_INFORMATION_TYPE, MSG_SERVER_STARTED, 0, NULL );
  2140. return 0;
  2141. }
  2142. #else /* WIN32 */
  2143. /* On UNIX, we create a file with our PID in it */
  2144. static int
  2145. write_pid_file()
  2146. {
  2147. FILE *fp = NULL;
  2148. /*
  2149. * The following section of code is closely coupled with the
  2150. * admin programs. Please do not make changes here without
  2151. * consulting the start/stop code for the admin code.
  2152. */
  2153. if ( (fp = fopen( get_pid_file(), "w" )) != NULL ) {
  2154. fprintf( fp, "%d\n", getpid() );
  2155. fclose( fp );
  2156. if ( chmod(get_pid_file(), S_IWUSR|S_IRUSR|S_IRGRP|S_IROTH) != 0 ) {
  2157. unlink(get_pid_file());
  2158. } else {
  2159. return 0;
  2160. }
  2161. }
  2162. return -1;
  2163. }
  2164. #endif /* WIN32 */
  2165. static void
  2166. set_shutdown (int sig)
  2167. {
  2168. /* don't log anything from a signal handler:
  2169. * you could be holding a lock when the signal was trapped. more
  2170. * specifically, you could be holding the logfile lock (and deadlock
  2171. * yourself).
  2172. */
  2173. #if 0
  2174. LDAPDebug( LDAP_DEBUG_ANY, "slapd got shutdown signal\n", 0, 0, 0 );
  2175. #endif
  2176. g_set_shutdown( SLAPI_SHUTDOWN_SIGNAL );
  2177. #ifndef _WIN32
  2178. #ifndef LINUX
  2179. /* don't mess with USR1/USR2 on linux, used by libpthread */
  2180. (void) SIGNAL( SIGUSR2, set_shutdown );
  2181. #endif
  2182. (void) SIGNAL( SIGTERM, set_shutdown );
  2183. (void) SIGNAL( SIGHUP, set_shutdown );
  2184. #endif
  2185. }
  2186. #ifndef LINUX
  2187. void
  2188. slapd_do_nothing (int sig)
  2189. {
  2190. /* don't log anything from a signal handler:
  2191. * you could be holding a lock when the signal was trapped. more
  2192. * specifically, you could be holding the logfile lock (and deadlock
  2193. * yourself).
  2194. */
  2195. #if 0
  2196. LDAPDebug( LDAP_DEBUG_TRACE, "slapd got SIGUSR1\n", 0, 0, 0 );
  2197. #endif
  2198. #ifndef _WIN32
  2199. (void) SIGNAL( SIGUSR1, slapd_do_nothing );
  2200. #endif
  2201. #if 0
  2202. /*
  2203. * Actually do a little more: dump the conn struct and
  2204. * send it to a tmp file
  2205. */
  2206. connection_table_dump(connection_table);
  2207. #endif
  2208. }
  2209. #endif /* LINUX */
  2210. #ifndef _WIN32
  2211. void
  2212. slapd_wait4child(int sig)
  2213. {
  2214. WAITSTATUSTYPE status;
  2215. /* don't log anything from a signal handler:
  2216. * you could be holding a lock when the signal was trapped. more
  2217. * specifically, you could be holding the logfile lock (and deadlock
  2218. * yourself).
  2219. */
  2220. #if 0
  2221. LDAPDebug( LDAP_DEBUG_ARGS, "listener: catching SIGCHLD\n", 0, 0, 0 );
  2222. #endif
  2223. #ifdef USE_WAITPID
  2224. while (waitpid ((pid_t) -1, 0, WAIT_FLAGS) > 0)
  2225. #else /* USE_WAITPID */
  2226. while ( wait3( &status, WAIT_FLAGS, 0 ) > 0 )
  2227. #endif /* USE_WAITPID */
  2228. ; /* NULL */
  2229. (void) SIGNAL( SIGCHLD, slapd_wait4child );
  2230. }
  2231. #endif
  2232. #ifdef XP_WIN32
  2233. static int
  2234. createlistensocket(unsigned short port, const PRNetAddr *listenaddr)
  2235. {
  2236. int tcps;
  2237. struct sockaddr_in addr;
  2238. char *logname = "createlistensocket";
  2239. char addrbuf[ 256 ];
  2240. if (!port) goto suppressed;
  2241. PR_ASSERT( listenaddr != NULL );
  2242. /* create TCP socket */
  2243. if ((tcps = socket(AF_INET, SOCK_STREAM, 0))
  2244. == SLAPD_INVALID_SOCKET) {
  2245. int oserr = errno;
  2246. slapi_log_error(SLAPI_LOG_FATAL, logname,
  2247. "socket() failed: OS error %d (%s)\n",
  2248. oserr, slapd_system_strerror( oserr ));
  2249. goto failed;
  2250. }
  2251. /* initialize listener address */
  2252. (void) memset( (void *) &addr, '\0', sizeof(addr) );
  2253. addr.sin_family = AF_INET;
  2254. addr.sin_port = htons( port );
  2255. if (listenaddr->raw.family == PR_AF_INET) {
  2256. addr.sin_addr.s_addr = listenaddr->inet.ip;
  2257. } else if (PR_IsNetAddrType(listenaddr,PR_IpAddrAny)) {
  2258. addr.sin_addr.s_addr = INADDR_ANY;
  2259. } else {
  2260. if (!PR_IsNetAddrType(listenaddr,PR_IpAddrV4Mapped)) {
  2261. /*
  2262. * When Win32 supports IPv6, we will be able to use IPv6
  2263. * addresses here. But not yet.
  2264. */
  2265. slapi_log_error(SLAPI_LOG_FATAL, logname,
  2266. "unable to listen on %s port %d (IPv6 addresses "
  2267. "are not supported on this platform)\n",
  2268. netaddr2string(listenaddr, addrbuf, sizeof(addrbuf)),
  2269. port );
  2270. goto failed;
  2271. }
  2272. addr.sin_addr.s_addr = listenaddr->ipv6.ip.pr_s6_addr32[3];
  2273. }
  2274. LDAPDebug( LDAP_DEBUG_TRACE, "%s - binding to %s:%d\n",
  2275. logname, inet_ntoa( addr.sin_addr ), port )
  2276. if ( bind( tcps, (struct sockaddr *) &addr, sizeof(addr) ) == -1 ) {
  2277. int oserr = errno;
  2278. slapi_log_error(SLAPI_LOG_FATAL, logname,
  2279. "bind() on %s port %d failed: OS error %d (%s)\n",
  2280. inet_ntoa( addr.sin_addr ), port, oserr,
  2281. slapd_system_strerror( oserr ));
  2282. goto failed;
  2283. }
  2284. return tcps;
  2285. failed:
  2286. WSACleanup();
  2287. exit( 1 );
  2288. suppressed:
  2289. return -1;
  2290. } /* createlistensocket */
  2291. #endif /* XP_WIN32 */
  2292. static PRFileDesc **
  2293. createprlistensockets(PRUint16 port, PRNetAddr **listenaddr,
  2294. int secure, int local)
  2295. {
  2296. PRFileDesc **sock;
  2297. PRNetAddr sa_server;
  2298. PRErrorCode prerr = 0;
  2299. PRSocketOptionData pr_socketoption;
  2300. char addrbuf[ 256 ];
  2301. char *logname = "createprlistensockets";
  2302. int sockcnt = 0;
  2303. int socktype;
  2304. char *socktype_str = NULL;
  2305. PRNetAddr **lap;
  2306. int i;
  2307. if (!port) goto suppressed;
  2308. PR_ASSERT( listenaddr != NULL );
  2309. /* need to know the count */
  2310. sockcnt = 0;
  2311. for (lap = listenaddr; lap && *lap; lap++) {
  2312. sockcnt++;
  2313. }
  2314. if (0 == sockcnt) {
  2315. slapi_log_error(SLAPI_LOG_FATAL, logname,
  2316. "There is no address to listen\n");
  2317. goto failed;
  2318. }
  2319. sock = (PRFileDesc **)slapi_ch_calloc(sockcnt + 1, sizeof(PRFileDesc *));
  2320. pr_socketoption.option = PR_SockOpt_Reuseaddr;
  2321. pr_socketoption.value.reuse_addr = 1;
  2322. for (i = 0, lap = listenaddr; lap && *lap && i < sockcnt; i++, lap++) {
  2323. /* create TCP socket */
  2324. socktype = PR_NetAddrFamily(*lap);
  2325. #if defined(ENABLE_LDAPI)
  2326. if (PR_AF_LOCAL == socktype) {
  2327. socktype_str = "PR_AF_LOCAL";
  2328. } else
  2329. #endif
  2330. if (PR_AF_INET6 == socktype) {
  2331. socktype_str = "PR_AF_INET6";
  2332. } else {
  2333. socktype_str = "PR_AF_INET";
  2334. }
  2335. if ((sock[i] = PR_OpenTCPSocket(socktype)) == SLAPD_INVALID_SOCKET) {
  2336. prerr = PR_GetError();
  2337. slapi_log_error(SLAPI_LOG_FATAL, logname,
  2338. "PR_OpenTCPSocket(%s) failed: %s error %d (%s)\n",
  2339. socktype_str,
  2340. SLAPI_COMPONENT_NAME_NSPR, prerr, slapd_pr_strerror(prerr));
  2341. goto failed;
  2342. }
  2343. if ( PR_SetSocketOption(sock[i], &pr_socketoption ) == PR_FAILURE) {
  2344. prerr = PR_GetError();
  2345. slapi_log_error(SLAPI_LOG_FATAL, logname,
  2346. "PR_SetSocketOption(PR_SockOpt_Reuseaddr) failed: %s error %d (%s)\n",
  2347. SLAPI_COMPONENT_NAME_NSPR, prerr, slapd_pr_strerror( prerr ));
  2348. goto failed;
  2349. }
  2350. /* set up listener address, including port */
  2351. memcpy(&sa_server, *lap, sizeof(sa_server));
  2352. if(!local)
  2353. PRLDAP_SET_PORT( &sa_server, port );
  2354. if ( PR_Bind(sock[i], &sa_server) == PR_FAILURE) {
  2355. prerr = PR_GetError();
  2356. if(!local)
  2357. {
  2358. slapi_log_error(SLAPI_LOG_FATAL, logname,
  2359. "PR_Bind() on %s port %d failed: %s error %d (%s)\n",
  2360. netaddr2string(&sa_server, addrbuf, sizeof(addrbuf)), port,
  2361. SLAPI_COMPONENT_NAME_NSPR, prerr, slapd_pr_strerror(prerr));
  2362. }
  2363. #if defined(ENABLE_LDAPI)
  2364. else
  2365. {
  2366. slapi_log_error(SLAPI_LOG_FATAL, logname,
  2367. "PR_Bind() on %s file %s failed: %s error %d (%s)\n",
  2368. netaddr2string(&sa_server, addrbuf, sizeof(addrbuf)),
  2369. sa_server.local.path,
  2370. SLAPI_COMPONENT_NAME_NSPR, prerr, slapd_pr_strerror(prerr));
  2371. }
  2372. #endif /* ENABLE_LDAPI */
  2373. goto failed;
  2374. }
  2375. }
  2376. #if defined(ENABLE_LDAPI)
  2377. if(local) { /* ldapi */
  2378. if(chmod((*listenaddr)->local.path,
  2379. S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH))
  2380. {
  2381. slapi_log_error(SLAPI_LOG_FATAL, logname, "err: %d", errno);
  2382. }
  2383. }
  2384. #endif /* ENABLE_LDAPI */
  2385. return( sock );
  2386. failed:
  2387. #ifdef XP_WIN32
  2388. WSACleanup();
  2389. #endif /* XP_WIN32 */
  2390. exit( 1 );
  2391. suppressed:
  2392. return (PRFileDesc **)-1;
  2393. } /* createprlistensockets */
  2394. /*
  2395. * Initialize the *addr structure based on listenhost.
  2396. * Returns: 0 if successful and -1 if not (after logging an error message).
  2397. */
  2398. int
  2399. slapd_listenhost2addr(const char *listenhost, PRNetAddr ***addr)
  2400. {
  2401. char *logname = "slapd_listenhost2addr";
  2402. PRErrorCode prerr = 0;
  2403. int rval = 0;
  2404. PRNetAddr *netaddr = (PRNetAddr *)slapi_ch_calloc(1, sizeof(PRNetAddr));
  2405. PR_ASSERT( addr != NULL );
  2406. *addr = NULL;
  2407. if (NULL == listenhost) {
  2408. /* listen on all interfaces */
  2409. if ( PR_SUCCESS != PR_SetNetAddr(PR_IpAddrAny, PR_AF_INET6, 0, netaddr)) {
  2410. prerr = PR_GetError();
  2411. slapi_log_error( SLAPI_LOG_FATAL, logname,
  2412. "PR_SetNetAddr(PR_IpAddrAny) failed - %s error %d (%s)\n",
  2413. SLAPI_COMPONENT_NAME_NSPR, prerr, slapd_pr_strerror(prerr));
  2414. rval = -1;
  2415. slapi_ch_free ((void**)&netaddr);
  2416. }
  2417. *addr = (PRNetAddr **)slapi_ch_calloc(2, sizeof (PRNetAddr *));
  2418. (*addr)[0] = netaddr;
  2419. } else if (PR_SUCCESS == PR_StringToNetAddr(listenhost, netaddr)) {
  2420. /* PR_StringNetAddr newer than NSPR v4.6.2 supports both IPv4&v6 */;
  2421. *addr = (PRNetAddr **)slapi_ch_calloc(2, sizeof (PRNetAddr *));
  2422. (*addr)[0] = netaddr;
  2423. } else {
  2424. PRAddrInfo *infop = PR_GetAddrInfoByName( listenhost,
  2425. PR_AF_UNSPEC, (PR_AI_ADDRCONFIG|PR_AI_NOCANONNAME) );
  2426. if ( NULL != infop ) {
  2427. void *iter = NULL;
  2428. int addrcnt = 0;
  2429. int i = 0;
  2430. memset( netaddr, 0, sizeof( PRNetAddr ));
  2431. /* need to count the address, first */
  2432. while ( (iter = PR_EnumerateAddrInfo( iter, infop, 0, netaddr ))
  2433. != NULL ) {
  2434. addrcnt++;
  2435. }
  2436. if ( 0 == addrcnt ) {
  2437. slapi_log_error( SLAPI_LOG_FATAL, logname,
  2438. "PR_EnumerateAddrInfo for %s failed - %s error %d (%s)\n",
  2439. listenhost, SLAPI_COMPONENT_NAME_NSPR, prerr,
  2440. slapd_pr_strerror(prerr));
  2441. rval = -1;
  2442. } else {
  2443. *addr = (PRNetAddr **)slapi_ch_calloc(addrcnt + 1, sizeof (PRNetAddr *));
  2444. iter = NULL; /* from the beginning */
  2445. memset( netaddr, 0, sizeof( PRNetAddr ));
  2446. for ( i = 0; i < addrcnt; i++ ) {
  2447. iter = PR_EnumerateAddrInfo( iter, infop, 0, netaddr );
  2448. if ( NULL == iter ) {
  2449. break;
  2450. }
  2451. (*addr)[i] = netaddr;
  2452. netaddr = (PRNetAddr *)slapi_ch_calloc(1, sizeof(PRNetAddr));
  2453. }
  2454. slapi_ch_free((void **)&netaddr); /* not used */
  2455. }
  2456. PR_FreeAddrInfo( infop );
  2457. } else {
  2458. slapi_log_error( SLAPI_LOG_FATAL, logname,
  2459. "PR_GetAddrInfoByName(%s) failed - %s error %d (%s)\n",
  2460. listenhost, SLAPI_COMPONENT_NAME_NSPR, prerr,
  2461. slapd_pr_strerror(prerr));
  2462. rval = -1;
  2463. }
  2464. }
  2465. return rval;
  2466. }
  2467. /*
  2468. * Map addr to a string equivalent and place the result in addrbuf.
  2469. */
  2470. static const char *
  2471. netaddr2string(const PRNetAddr *addr, char *addrbuf, size_t addrbuflen)
  2472. {
  2473. const char *retstr;
  2474. if (NULL == addr || PR_IsNetAddrType(addr, PR_IpAddrAny)) {
  2475. retstr = "All Interfaces";
  2476. } else if (PR_IsNetAddrType(addr, PR_IpAddrLoopback)) {
  2477. if ( addr->raw.family == PR_AF_INET6 &&
  2478. !PR_IsNetAddrType(addr, PR_IpAddrV4Mapped)) {
  2479. retstr = "IPv6 Loopback";
  2480. } else {
  2481. retstr = "Loopback";
  2482. }
  2483. } else if (PR_SUCCESS == PR_NetAddrToString( addr, addrbuf, addrbuflen)) {
  2484. if (0 == strncmp( addrbuf, "::ffff:", 7 )) {
  2485. /* IPv4 address mapped into IPv6 address space */
  2486. retstr = addrbuf + 7;
  2487. } else {
  2488. /* full blown IPv6 address */
  2489. retstr = addrbuf;
  2490. }
  2491. } else { /* punt */
  2492. retstr = "address conversion failed";
  2493. }
  2494. return(retstr);
  2495. }
  2496. static int
  2497. createsignalpipe( void )
  2498. {
  2499. #if defined( _WIN32 )
  2500. if ( PR_NewTCPSocketPair(&signalpipe[0])) {
  2501. PRErrorCode prerr = PR_GetError();
  2502. LDAPDebug( LDAP_DEBUG_ANY, "PR_CreatePipe() failed, "
  2503. SLAPI_COMPONENT_NAME_NSPR " error %d (%s)\n",
  2504. prerr, slapd_pr_strerror(prerr), SLAPD_DEFAULT_THREAD_STACKSIZE );
  2505. return( -1 );
  2506. }
  2507. writesignalpipe = PR_FileDesc2NativeHandle(signalpipe[1]);
  2508. readsignalpipe = PR_FileDesc2NativeHandle(signalpipe[0]);
  2509. #else
  2510. if ( PR_CreatePipe( &signalpipe[0], &signalpipe[1] ) != 0 ) {
  2511. PRErrorCode prerr = PR_GetError();
  2512. LDAPDebug( LDAP_DEBUG_ANY, "PR_CreatePipe() failed, "
  2513. SLAPI_COMPONENT_NAME_NSPR " error %d (%s)\n",
  2514. prerr, slapd_pr_strerror(prerr), SLAPD_DEFAULT_THREAD_STACKSIZE );
  2515. return( -1 );
  2516. }
  2517. writesignalpipe = PR_FileDesc2NativeHandle(signalpipe[1]);
  2518. readsignalpipe = PR_FileDesc2NativeHandle(signalpipe[0]);
  2519. fcntl(writesignalpipe, F_SETFD, O_NONBLOCK);
  2520. fcntl(readsignalpipe, F_SETFD, O_NONBLOCK);
  2521. #endif
  2522. return( 0 );
  2523. }
  2524. #ifdef HPUX10
  2525. #include <pthread.h> /* for sigwait */
  2526. /*
  2527. * Set up a thread to catch signals
  2528. * SIGUSR1 (ignore), SIGCHLD (call slapd_wait4child),
  2529. * SIGUSR2 (set slapd_shutdown), SIGTERM (set slapd_shutdown),
  2530. * SIGHUP (set slapd_shutdown)
  2531. */
  2532. static void *
  2533. catch_signals()
  2534. {
  2535. sigset_t caught_signals;
  2536. int sig;
  2537. sigemptyset( &caught_signals );
  2538. while ( !g_get_shutdown() ) {
  2539. /* Set the signals we're interested in catching */
  2540. sigaddset( &caught_signals, SIGUSR1 );
  2541. sigaddset( &caught_signals, SIGCHLD );
  2542. sigaddset( &caught_signals, SIGUSR2 );
  2543. sigaddset( &caught_signals, SIGTERM );
  2544. sigaddset( &caught_signals, SIGHUP );
  2545. (void)sigprocmask( SIG_BLOCK, &caught_signals, NULL );
  2546. if (( sig = sigwait( &caught_signals )) < 0 ) {
  2547. LDAPDebug( LDAP_DEBUG_ANY, "catch_signals: sigwait returned -1\n",
  2548. 0, 0, 0 );
  2549. continue;
  2550. } else {
  2551. LDAPDebug( LDAP_DEBUG_TRACE, "catch_signals: detected signal %d\n",
  2552. sig, 0, 0 );
  2553. switch ( sig ) {
  2554. case SIGUSR1:
  2555. continue; /* ignore SIGUSR1 */
  2556. case SIGUSR2: /* fallthrough */
  2557. case SIGTERM: /* fallthrough */
  2558. case SIGHUP:
  2559. g_set_shutdown( SLAPI_SHUTDOWN_SIGNAL );
  2560. return NULL;
  2561. case SIGCHLD:
  2562. slapd_wait4child( sig );
  2563. break;
  2564. default:
  2565. LDAPDebug( LDAP_DEBUG_ANY,
  2566. "catch_signals: unknown signal (%d) received\n",
  2567. sig, 0, 0 );
  2568. }
  2569. }
  2570. }
  2571. }
  2572. #endif /* HPUX */
  2573. static int
  2574. get_configured_connection_table_size()
  2575. {
  2576. int size;
  2577. size = config_get_conntablesize();
  2578. /*
  2579. * Cap the table size at nsslapd-maxdescriptors.
  2580. */
  2581. #if !defined(_WIN32) && !defined(AIX)
  2582. {
  2583. int maxdesc = config_get_maxdescriptors();
  2584. if ( maxdesc >= 0 && size > maxdesc ) {
  2585. size = maxdesc;
  2586. }
  2587. }
  2588. #endif
  2589. return size;
  2590. }
  2591. PRFileDesc * get_ssl_listener_fd()
  2592. {
  2593. PRFileDesc * listener;
  2594. listener = the_connection_table->fd[the_connection_table->s_tcps].fd;
  2595. return listener;
  2596. }
  2597. int configure_pr_socket( PRFileDesc **pr_socket, int secure, int local )
  2598. {
  2599. int ns = 0;
  2600. int reservedescriptors = config_get_reservedescriptors();
  2601. int enable_nagle = config_get_nagle();
  2602. PRSocketOptionData pr_socketoption;
  2603. #if defined(LINUX)
  2604. /* On Linux we use TCP_CORK so we must enable nagle */
  2605. enable_nagle = 1;
  2606. #endif
  2607. ns = PR_FileDesc2NativeHandle( *pr_socket );
  2608. #if !defined(_WIN32)
  2609. /*
  2610. * Some OS or third party libraries may require that low
  2611. * numbered file descriptors be available, e.g., the DNS resolver
  2612. * library on most operating systems. Therefore, we try to
  2613. * replace the file descriptor returned by accept() with a
  2614. * higher numbered one. If this fails, we log an error and
  2615. * continue (not considered a truly fatal error).
  2616. */
  2617. if ( reservedescriptors > 0 && ns < reservedescriptors ) {
  2618. int newfd = fcntl( ns, F_DUPFD, reservedescriptors );
  2619. if ( newfd > 0 ) {
  2620. PRFileDesc *nspr_layer_fd = PR_GetIdentitiesLayer( *pr_socket,
  2621. PR_NSPR_IO_LAYER );
  2622. if ( NULL == nspr_layer_fd ) {
  2623. slapi_log_error( SLAPI_LOG_FATAL, "configure_pr_socket",
  2624. "Unable to move socket file descriptor %d above %d:"
  2625. " PR_GetIdentitiesLayer( %p, PR_NSPR_IO_LAYER )"
  2626. " failed\n", ns, reservedescriptors, *pr_socket );
  2627. close( newfd ); /* can't fix things up in NSPR -- close copy */
  2628. } else {
  2629. PR_ChangeFileDescNativeHandle( nspr_layer_fd, newfd );
  2630. close( ns ); /* dup succeeded -- close the original */
  2631. ns = newfd;
  2632. }
  2633. } else {
  2634. int oserr = errno;
  2635. slapi_log_error(SLAPI_LOG_FATAL, "configure_pr_socket",
  2636. "Unable to move socket file descriptor %d above %d:"
  2637. " OS error %d (%s)\n", ns, reservedescriptors, oserr,
  2638. slapd_system_strerror( oserr ) );
  2639. }
  2640. }
  2641. #endif /* !_WIN32 */
  2642. if ( secure ) {
  2643. pr_socketoption.option = PR_SockOpt_Nonblocking;
  2644. pr_socketoption.value.non_blocking = 0;
  2645. if ( PR_SetSocketOption( *pr_socket, &pr_socketoption ) == PR_FAILURE ) {
  2646. PRErrorCode prerr = PR_GetError();
  2647. LDAPDebug( LDAP_DEBUG_ANY,
  2648. "PR_SetSocketOption(PR_SockOpt_Nonblocking) failed, "
  2649. SLAPI_COMPONENT_NAME_NSPR " error %d (%s)\n",
  2650. prerr, slapd_pr_strerror(prerr), 0 );
  2651. }
  2652. } else {
  2653. /* We always want to have non-blocking I/O */
  2654. pr_socketoption.option = PR_SockOpt_Nonblocking;
  2655. pr_socketoption.value.non_blocking = 1;
  2656. if ( PR_SetSocketOption( *pr_socket, &pr_socketoption ) == PR_FAILURE ) {
  2657. PRErrorCode prerr = PR_GetError();
  2658. LDAPDebug( LDAP_DEBUG_ANY,
  2659. "PR_SetSocketOption(PR_SockOpt_Nonblocking) failed, "
  2660. SLAPI_COMPONENT_NAME_NSPR " error %d (%s)\n",
  2661. prerr, slapd_pr_strerror(prerr), 0 );
  2662. }
  2663. if ( have_send_timeouts ) {
  2664. daemon_configure_send_timeout(ns,config_get_ioblocktimeout());
  2665. }
  2666. } /* else (secure) */
  2667. if ( !enable_nagle && !local ) {
  2668. pr_socketoption.option = PR_SockOpt_NoDelay;
  2669. pr_socketoption.value.no_delay = 1;
  2670. if ( PR_SetSocketOption( *pr_socket, &pr_socketoption ) == PR_FAILURE) {
  2671. PRErrorCode prerr = PR_GetError();
  2672. LDAPDebug( LDAP_DEBUG_ANY,
  2673. "PR_SetSocketOption(PR_SockOpt_NoDelay) failed, "
  2674. SLAPI_COMPONENT_NAME_NSPR " error %d (%s)\n",
  2675. prerr, slapd_pr_strerror( prerr ), 0 );
  2676. }
  2677. } else if( !local) {
  2678. pr_socketoption.option = PR_SockOpt_NoDelay;
  2679. pr_socketoption.value.no_delay = 0;
  2680. if ( PR_SetSocketOption( *pr_socket, &pr_socketoption ) == PR_FAILURE) {
  2681. PRErrorCode prerr = PR_GetError();
  2682. LDAPDebug( LDAP_DEBUG_ANY,
  2683. "PR_SetSocketOption(PR_SockOpt_NoDelay) failed, "
  2684. SLAPI_COMPONENT_NAME_NSPR " error %d (%s)\n",
  2685. prerr, slapd_pr_strerror( prerr ), 0 );
  2686. }
  2687. } /* else (!enable_nagle) */
  2688. return ns;
  2689. }
  2690. void configure_ns_socket( int * ns )
  2691. {
  2692. int enable_nagle = config_get_nagle();
  2693. int on;
  2694. #if defined(LINUX)
  2695. /* On Linux we use TCP_CORK so we must enable nagle */
  2696. enable_nagle = 1;
  2697. #endif
  2698. if ( have_send_timeouts ) {
  2699. daemon_configure_send_timeout( *ns, config_get_ioblocktimeout() );
  2700. }
  2701. if ( !enable_nagle ) {
  2702. on = 1;
  2703. setsockopt( *ns, IPPROTO_TCP, TCP_NODELAY, (char * ) &on, sizeof(on) );
  2704. } else {
  2705. on = 0;
  2706. setsockopt( *ns, IPPROTO_TCP, TCP_NODELAY, (char * ) &on, sizeof(on) );
  2707. } /* else (!enable_nagle) */
  2708. return;
  2709. }
  2710. #ifdef RESOLVER_NEEDS_LOW_FILE_DESCRIPTORS
  2711. /*
  2712. * A function that uses the DNS resolver in a simple way. This is only
  2713. * used to ensure that the DNS resolver has opened its files, etc.
  2714. * using low numbered file descriptors.
  2715. */
  2716. static void
  2717. get_loopback_by_addr( void )
  2718. {
  2719. #ifdef GETHOSTBYADDR_BUF_T
  2720. struct hostent hp;
  2721. GETHOSTBYADDR_BUF_T hbuf;
  2722. #endif
  2723. unsigned long ipaddr;
  2724. struct in_addr ia;
  2725. int herrno, rc = 0;
  2726. memset( (char *)&hp, 0, sizeof(hp));
  2727. ipaddr = htonl( INADDR_LOOPBACK );
  2728. (void) GETHOSTBYADDR( (char *)&ipaddr, sizeof( ipaddr ),
  2729. AF_INET, &hp, hbuf, sizeof(hbuf), &herrno );
  2730. }
  2731. #endif /* RESOLVER_NEEDS_LOW_FILE_DESCRIPTORS */