daemon.c 105 KB

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