daemon.c 90 KB

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