daemon.c 104 KB

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