daemon.c 104 KB

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