daemon.c 125 KB

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