daemon.c 86 KB

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