daemon.c 90 KB

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