daemon.c 125 KB

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