daemon.c 104 KB

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