acme.sh 188 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989
  1. #!/usr/bin/env sh
  2. VER=2.8.3
  3. PROJECT_NAME="acme.sh"
  4. PROJECT_ENTRY="acme.sh"
  5. PROJECT="https://github.com/Neilpang/$PROJECT_NAME"
  6. DEFAULT_INSTALL_HOME="$HOME/.$PROJECT_NAME"
  7. _WINDOWS_SCHEDULER_NAME="$PROJECT_NAME.cron"
  8. _SCRIPT_="$0"
  9. _SUB_FOLDER_NOTIFY="notify"
  10. _SUB_FOLDER_DNSAPI="dnsapi"
  11. _SUB_FOLDER_DEPLOY="deploy"
  12. _SUB_FOLDERS="$_SUB_FOLDER_DNSAPI $_SUB_FOLDER_DEPLOY $_SUB_FOLDER_NOTIFY"
  13. LETSENCRYPT_CA_V1="https://acme-v01.api.letsencrypt.org/directory"
  14. LETSENCRYPT_STAGING_CA_V1="https://acme-staging.api.letsencrypt.org/directory"
  15. LETSENCRYPT_CA_V2="https://acme-v02.api.letsencrypt.org/directory"
  16. LETSENCRYPT_STAGING_CA_V2="https://acme-staging-v02.api.letsencrypt.org/directory"
  17. DEFAULT_CA=$LETSENCRYPT_CA_V2
  18. DEFAULT_STAGING_CA=$LETSENCRYPT_STAGING_CA_V2
  19. DEFAULT_USER_AGENT="$PROJECT_NAME/$VER ($PROJECT)"
  20. DEFAULT_ACCOUNT_EMAIL=""
  21. DEFAULT_ACCOUNT_KEY_LENGTH=2048
  22. DEFAULT_DOMAIN_KEY_LENGTH=2048
  23. DEFAULT_OPENSSL_BIN="openssl"
  24. _OLD_CA_HOST="https://acme-v01.api.letsencrypt.org"
  25. _OLD_STAGE_CA_HOST="https://acme-staging.api.letsencrypt.org"
  26. VTYPE_HTTP="http-01"
  27. VTYPE_DNS="dns-01"
  28. VTYPE_ALPN="tls-alpn-01"
  29. LOCAL_ANY_ADDRESS="0.0.0.0"
  30. DEFAULT_RENEW=60
  31. DEFAULT_DNS_SLEEP=120
  32. NO_VALUE="no"
  33. W_DNS="dns"
  34. W_ALPN="alpn"
  35. DNS_ALIAS_PREFIX="="
  36. MODE_STATELESS="stateless"
  37. STATE_VERIFIED="verified_ok"
  38. NGINX="nginx:"
  39. NGINX_START="#ACME_NGINX_START"
  40. NGINX_END="#ACME_NGINX_END"
  41. BEGIN_CSR="-----BEGIN CERTIFICATE REQUEST-----"
  42. END_CSR="-----END CERTIFICATE REQUEST-----"
  43. BEGIN_CERT="-----BEGIN CERTIFICATE-----"
  44. END_CERT="-----END CERTIFICATE-----"
  45. CONTENT_TYPE_JSON="application/jose+json"
  46. RENEW_SKIP=2
  47. B64CONF_START="__ACME_BASE64__START_"
  48. B64CONF_END="__ACME_BASE64__END_"
  49. ECC_SEP="_"
  50. ECC_SUFFIX="${ECC_SEP}ecc"
  51. LOG_LEVEL_1=1
  52. LOG_LEVEL_2=2
  53. LOG_LEVEL_3=3
  54. DEFAULT_LOG_LEVEL="$LOG_LEVEL_1"
  55. DEBUG_LEVEL_1=1
  56. DEBUG_LEVEL_2=2
  57. DEBUG_LEVEL_3=3
  58. DEBUG_LEVEL_DEFAULT=$DEBUG_LEVEL_1
  59. DEBUG_LEVEL_NONE=0
  60. HIDDEN_VALUE="[hidden](please add '--output-insecure' to see this value)"
  61. SYSLOG_ERROR="user.error"
  62. SYSLOG_INFO="user.info"
  63. SYSLOG_DEBUG="user.debug"
  64. #error
  65. SYSLOG_LEVEL_ERROR=3
  66. #info
  67. SYSLOG_LEVEL_INFO=6
  68. #debug
  69. SYSLOG_LEVEL_DEBUG=7
  70. #debug2
  71. SYSLOG_LEVEL_DEBUG_2=8
  72. #debug3
  73. SYSLOG_LEVEL_DEBUG_3=9
  74. SYSLOG_LEVEL_DEFAULT=$SYSLOG_LEVEL_ERROR
  75. #none
  76. SYSLOG_LEVEL_NONE=0
  77. NOTIFY_LEVEL_DISABLE=0
  78. NOTIFY_LEVEL_ERROR=1
  79. NOTIFY_LEVEL_RENEW=2
  80. NOTIFY_LEVEL_SKIP=3
  81. NOTIFY_LEVEL_DEFAULT=$NOTIFY_LEVEL_RENEW
  82. NOTIFY_MODE_BULK=0
  83. NOTIFY_MODE_CERT=1
  84. NOTIFY_MODE_DEFAULT=$NOTIFY_MODE_BULK
  85. _DEBUG_WIKI="https://github.com/Neilpang/acme.sh/wiki/How-to-debug-acme.sh"
  86. _PREPARE_LINK="https://github.com/Neilpang/acme.sh/wiki/Install-preparations"
  87. _STATELESS_WIKI="https://github.com/Neilpang/acme.sh/wiki/Stateless-Mode"
  88. _DNS_ALIAS_WIKI="https://github.com/Neilpang/acme.sh/wiki/DNS-alias-mode"
  89. _DNS_MANUAL_WIKI="https://github.com/Neilpang/acme.sh/wiki/dns-manual-mode"
  90. _NOTIFY_WIKI="https://github.com/Neilpang/acme.sh/wiki/notify"
  91. _SUDO_WIKI="https://github.com/Neilpang/acme.sh/wiki/sudo"
  92. _DNS_MANUAL_ERR="The dns manual mode can not renew automatically, you must issue it again manually. You'd better use the other modes instead."
  93. _DNS_MANUAL_WARN="It seems that you are using dns manual mode. please take care: $_DNS_MANUAL_ERR"
  94. _DNS_MANUAL_ERROR="It seems that you are using dns manual mode. Read this link first: $_DNS_MANUAL_WIKI"
  95. __INTERACTIVE=""
  96. if [ -t 1 ]; then
  97. __INTERACTIVE="1"
  98. fi
  99. __green() {
  100. if [ "${__INTERACTIVE}${ACME_NO_COLOR:-0}" = "10" -o "${ACME_FORCE_COLOR}" = "1" ]; then
  101. printf '\033[1;31;32m%b\033[0m' "$1"
  102. return
  103. fi
  104. printf -- "%b" "$1"
  105. }
  106. __red() {
  107. if [ "${__INTERACTIVE}${ACME_NO_COLOR:-0}" = "10" -o "${ACME_FORCE_COLOR}" = "1" ]; then
  108. printf '\033[1;31;40m%b\033[0m' "$1"
  109. return
  110. fi
  111. printf -- "%b" "$1"
  112. }
  113. _printargs() {
  114. _exitstatus="$?"
  115. if [ -z "$NO_TIMESTAMP" ] || [ "$NO_TIMESTAMP" = "0" ]; then
  116. printf -- "%s" "[$(date)] "
  117. fi
  118. if [ -z "$2" ]; then
  119. printf -- "%s" "$1"
  120. else
  121. printf -- "%s" "$1='$2'"
  122. fi
  123. printf "\n"
  124. # return the saved exit status
  125. return "$_exitstatus"
  126. }
  127. _dlg_versions() {
  128. echo "Diagnosis versions: "
  129. echo "openssl:$ACME_OPENSSL_BIN"
  130. if _exists "${ACME_OPENSSL_BIN:-openssl}"; then
  131. ${ACME_OPENSSL_BIN:-openssl} version 2>&1
  132. else
  133. echo "$ACME_OPENSSL_BIN doesn't exists."
  134. fi
  135. echo "apache:"
  136. if [ "$_APACHECTL" ] && _exists "$_APACHECTL"; then
  137. $_APACHECTL -V 2>&1
  138. else
  139. echo "apache doesn't exists."
  140. fi
  141. echo "nginx:"
  142. if _exists "nginx"; then
  143. nginx -V 2>&1
  144. else
  145. echo "nginx doesn't exists."
  146. fi
  147. echo "socat:"
  148. if _exists "socat"; then
  149. socat -h 2>&1
  150. else
  151. _debug "socat doesn't exists."
  152. fi
  153. }
  154. #class
  155. _syslog() {
  156. _exitstatus="$?"
  157. if [ "${SYS_LOG:-$SYSLOG_LEVEL_NONE}" = "$SYSLOG_LEVEL_NONE" ]; then
  158. return
  159. fi
  160. _logclass="$1"
  161. shift
  162. if [ -z "$__logger_i" ]; then
  163. if _contains "$(logger --help 2>&1)" "-i"; then
  164. __logger_i="logger -i"
  165. else
  166. __logger_i="logger"
  167. fi
  168. fi
  169. $__logger_i -t "$PROJECT_NAME" -p "$_logclass" "$(_printargs "$@")" >/dev/null 2>&1
  170. return "$_exitstatus"
  171. }
  172. _log() {
  173. [ -z "$LOG_FILE" ] && return
  174. _printargs "$@" >>"$LOG_FILE"
  175. }
  176. _info() {
  177. _log "$@"
  178. if [ "${SYS_LOG:-$SYSLOG_LEVEL_NONE}" -ge "$SYSLOG_LEVEL_INFO" ]; then
  179. _syslog "$SYSLOG_INFO" "$@"
  180. fi
  181. _printargs "$@"
  182. }
  183. _err() {
  184. _syslog "$SYSLOG_ERROR" "$@"
  185. _log "$@"
  186. if [ -z "$NO_TIMESTAMP" ] || [ "$NO_TIMESTAMP" = "0" ]; then
  187. printf -- "%s" "[$(date)] " >&2
  188. fi
  189. if [ -z "$2" ]; then
  190. __red "$1" >&2
  191. else
  192. __red "$1='$2'" >&2
  193. fi
  194. printf "\n" >&2
  195. return 1
  196. }
  197. _usage() {
  198. __red "$@" >&2
  199. printf "\n" >&2
  200. }
  201. _debug() {
  202. if [ "${LOG_LEVEL:-$DEFAULT_LOG_LEVEL}" -ge "$LOG_LEVEL_1" ]; then
  203. _log "$@"
  204. fi
  205. if [ "${SYS_LOG:-$SYSLOG_LEVEL_NONE}" -ge "$SYSLOG_LEVEL_DEBUG" ]; then
  206. _syslog "$SYSLOG_DEBUG" "$@"
  207. fi
  208. if [ "${DEBUG:-$DEBUG_LEVEL_NONE}" -ge "$DEBUG_LEVEL_1" ]; then
  209. _printargs "$@" >&2
  210. fi
  211. }
  212. #output the sensitive messages
  213. _secure_debug() {
  214. if [ "${LOG_LEVEL:-$DEFAULT_LOG_LEVEL}" -ge "$LOG_LEVEL_1" ]; then
  215. if [ "$OUTPUT_INSECURE" = "1" ]; then
  216. _log "$@"
  217. else
  218. _log "$1" "$HIDDEN_VALUE"
  219. fi
  220. fi
  221. if [ "${SYS_LOG:-$SYSLOG_LEVEL_NONE}" -ge "$SYSLOG_LEVEL_DEBUG" ]; then
  222. _syslog "$SYSLOG_DEBUG" "$1" "$HIDDEN_VALUE"
  223. fi
  224. if [ "${DEBUG:-$DEBUG_LEVEL_NONE}" -ge "$DEBUG_LEVEL_1" ]; then
  225. if [ "$OUTPUT_INSECURE" = "1" ]; then
  226. _printargs "$@" >&2
  227. else
  228. _printargs "$1" "$HIDDEN_VALUE" >&2
  229. fi
  230. fi
  231. }
  232. _debug2() {
  233. if [ "${LOG_LEVEL:-$DEFAULT_LOG_LEVEL}" -ge "$LOG_LEVEL_2" ]; then
  234. _log "$@"
  235. fi
  236. if [ "${SYS_LOG:-$SYSLOG_LEVEL_NONE}" -ge "$SYSLOG_LEVEL_DEBUG_2" ]; then
  237. _syslog "$SYSLOG_DEBUG" "$@"
  238. fi
  239. if [ "${DEBUG:-$DEBUG_LEVEL_NONE}" -ge "$DEBUG_LEVEL_2" ]; then
  240. _printargs "$@" >&2
  241. fi
  242. }
  243. _secure_debug2() {
  244. if [ "${LOG_LEVEL:-$DEFAULT_LOG_LEVEL}" -ge "$LOG_LEVEL_2" ]; then
  245. if [ "$OUTPUT_INSECURE" = "1" ]; then
  246. _log "$@"
  247. else
  248. _log "$1" "$HIDDEN_VALUE"
  249. fi
  250. fi
  251. if [ "${SYS_LOG:-$SYSLOG_LEVEL_NONE}" -ge "$SYSLOG_LEVEL_DEBUG_2" ]; then
  252. _syslog "$SYSLOG_DEBUG" "$1" "$HIDDEN_VALUE"
  253. fi
  254. if [ "${DEBUG:-$DEBUG_LEVEL_NONE}" -ge "$DEBUG_LEVEL_2" ]; then
  255. if [ "$OUTPUT_INSECURE" = "1" ]; then
  256. _printargs "$@" >&2
  257. else
  258. _printargs "$1" "$HIDDEN_VALUE" >&2
  259. fi
  260. fi
  261. }
  262. _debug3() {
  263. if [ "${LOG_LEVEL:-$DEFAULT_LOG_LEVEL}" -ge "$LOG_LEVEL_3" ]; then
  264. _log "$@"
  265. fi
  266. if [ "${SYS_LOG:-$SYSLOG_LEVEL_NONE}" -ge "$SYSLOG_LEVEL_DEBUG_3" ]; then
  267. _syslog "$SYSLOG_DEBUG" "$@"
  268. fi
  269. if [ "${DEBUG:-$DEBUG_LEVEL_NONE}" -ge "$DEBUG_LEVEL_3" ]; then
  270. _printargs "$@" >&2
  271. fi
  272. }
  273. _secure_debug3() {
  274. if [ "${LOG_LEVEL:-$DEFAULT_LOG_LEVEL}" -ge "$LOG_LEVEL_3" ]; then
  275. if [ "$OUTPUT_INSECURE" = "1" ]; then
  276. _log "$@"
  277. else
  278. _log "$1" "$HIDDEN_VALUE"
  279. fi
  280. fi
  281. if [ "${SYS_LOG:-$SYSLOG_LEVEL_NONE}" -ge "$SYSLOG_LEVEL_DEBUG_3" ]; then
  282. _syslog "$SYSLOG_DEBUG" "$1" "$HIDDEN_VALUE"
  283. fi
  284. if [ "${DEBUG:-$DEBUG_LEVEL_NONE}" -ge "$DEBUG_LEVEL_3" ]; then
  285. if [ "$OUTPUT_INSECURE" = "1" ]; then
  286. _printargs "$@" >&2
  287. else
  288. _printargs "$1" "$HIDDEN_VALUE" >&2
  289. fi
  290. fi
  291. }
  292. _upper_case() {
  293. # shellcheck disable=SC2018,SC2019
  294. tr 'a-z' 'A-Z'
  295. }
  296. _lower_case() {
  297. # shellcheck disable=SC2018,SC2019
  298. tr 'A-Z' 'a-z'
  299. }
  300. _startswith() {
  301. _str="$1"
  302. _sub="$2"
  303. echo "$_str" | grep "^$_sub" >/dev/null 2>&1
  304. }
  305. _endswith() {
  306. _str="$1"
  307. _sub="$2"
  308. echo "$_str" | grep -- "$_sub\$" >/dev/null 2>&1
  309. }
  310. _contains() {
  311. _str="$1"
  312. _sub="$2"
  313. echo "$_str" | grep -- "$_sub" >/dev/null 2>&1
  314. }
  315. _hasfield() {
  316. _str="$1"
  317. _field="$2"
  318. _sep="$3"
  319. if [ -z "$_field" ]; then
  320. _usage "Usage: str field [sep]"
  321. return 1
  322. fi
  323. if [ -z "$_sep" ]; then
  324. _sep=","
  325. fi
  326. for f in $(echo "$_str" | tr "$_sep" ' '); do
  327. if [ "$f" = "$_field" ]; then
  328. _debug2 "'$_str' contains '$_field'"
  329. return 0 #contains ok
  330. fi
  331. done
  332. _debug2 "'$_str' does not contain '$_field'"
  333. return 1 #not contains
  334. }
  335. # str index [sep]
  336. _getfield() {
  337. _str="$1"
  338. _findex="$2"
  339. _sep="$3"
  340. if [ -z "$_findex" ]; then
  341. _usage "Usage: str field [sep]"
  342. return 1
  343. fi
  344. if [ -z "$_sep" ]; then
  345. _sep=","
  346. fi
  347. _ffi="$_findex"
  348. while [ "$_ffi" -gt "0" ]; do
  349. _fv="$(echo "$_str" | cut -d "$_sep" -f "$_ffi")"
  350. if [ "$_fv" ]; then
  351. printf -- "%s" "$_fv"
  352. return 0
  353. fi
  354. _ffi="$(_math "$_ffi" - 1)"
  355. done
  356. printf -- "%s" "$_str"
  357. }
  358. _exists() {
  359. cmd="$1"
  360. if [ -z "$cmd" ]; then
  361. _usage "Usage: _exists cmd"
  362. return 1
  363. fi
  364. if eval type type >/dev/null 2>&1; then
  365. eval type "$cmd" >/dev/null 2>&1
  366. elif command >/dev/null 2>&1; then
  367. command -v "$cmd" >/dev/null 2>&1
  368. else
  369. which "$cmd" >/dev/null 2>&1
  370. fi
  371. ret="$?"
  372. _debug3 "$cmd exists=$ret"
  373. return $ret
  374. }
  375. #a + b
  376. _math() {
  377. _m_opts="$@"
  378. printf "%s" "$(($_m_opts))"
  379. }
  380. _h_char_2_dec() {
  381. _ch=$1
  382. case "${_ch}" in
  383. a | A)
  384. printf "10"
  385. ;;
  386. b | B)
  387. printf "11"
  388. ;;
  389. c | C)
  390. printf "12"
  391. ;;
  392. d | D)
  393. printf "13"
  394. ;;
  395. e | E)
  396. printf "14"
  397. ;;
  398. f | F)
  399. printf "15"
  400. ;;
  401. *)
  402. printf "%s" "$_ch"
  403. ;;
  404. esac
  405. }
  406. _URGLY_PRINTF=""
  407. if [ "$(printf '\x41')" != 'A' ]; then
  408. _URGLY_PRINTF=1
  409. fi
  410. _ESCAPE_XARGS=""
  411. if _exists xargs && [ "$(printf %s '\\x41' | xargs printf)" = 'A' ]; then
  412. _ESCAPE_XARGS=1
  413. fi
  414. _h2b() {
  415. if _exists xxd && xxd -r -p 2>/dev/null; then
  416. return
  417. fi
  418. hex=$(cat)
  419. ic=""
  420. jc=""
  421. _debug2 _URGLY_PRINTF "$_URGLY_PRINTF"
  422. if [ -z "$_URGLY_PRINTF" ]; then
  423. if [ "$_ESCAPE_XARGS" ] && _exists xargs; then
  424. _debug2 "xargs"
  425. echo "$hex" | _upper_case | sed 's/\([0-9A-F]\{2\}\)/\\\\\\x\1/g' | xargs printf
  426. else
  427. for h in $(echo "$hex" | _upper_case | sed 's/\([0-9A-F]\{2\}\)/ \1/g'); do
  428. if [ -z "$h" ]; then
  429. break
  430. fi
  431. printf "\x$h%s"
  432. done
  433. fi
  434. else
  435. for c in $(echo "$hex" | _upper_case | sed 's/\([0-9A-F]\)/ \1/g'); do
  436. if [ -z "$ic" ]; then
  437. ic=$c
  438. continue
  439. fi
  440. jc=$c
  441. ic="$(_h_char_2_dec "$ic")"
  442. jc="$(_h_char_2_dec "$jc")"
  443. printf '\'"$(printf "%o" "$(_math "$ic" \* 16 + $jc)")""%s"
  444. ic=""
  445. jc=""
  446. done
  447. fi
  448. }
  449. _is_solaris() {
  450. _contains "${__OS__:=$(uname -a)}" "solaris" || _contains "${__OS__:=$(uname -a)}" "SunOS"
  451. }
  452. #_ascii_hex str
  453. #this can only process ascii chars, should only be used when od command is missing as a backup way.
  454. _ascii_hex() {
  455. _debug2 "Using _ascii_hex"
  456. _str="$1"
  457. _str_len=${#_str}
  458. _h_i=1
  459. while [ "$_h_i" -le "$_str_len" ]; do
  460. _str_c="$(printf "%s" "$_str" | cut -c "$_h_i")"
  461. printf " %02x" "'$_str_c"
  462. _h_i="$(_math "$_h_i" + 1)"
  463. done
  464. }
  465. #stdin output hexstr splited by one space
  466. #input:"abc"
  467. #output: " 61 62 63"
  468. _hex_dump() {
  469. if _exists od; then
  470. od -A n -v -t x1 | tr -s " " | sed 's/ $//' | tr -d "\r\t\n"
  471. elif _exists hexdump; then
  472. _debug3 "using hexdump"
  473. hexdump -v -e '/1 ""' -e '/1 " %02x" ""'
  474. elif _exists xxd; then
  475. _debug3 "using xxd"
  476. xxd -ps -c 20 -i | sed "s/ 0x/ /g" | tr -d ",\n" | tr -s " "
  477. else
  478. _debug3 "using _ascii_hex"
  479. str=$(cat)
  480. _ascii_hex "$str"
  481. fi
  482. }
  483. #url encode, no-preserved chars
  484. #A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
  485. #41 42 43 44 45 46 47 48 49 4a 4b 4c 4d 4e 4f 50 51 52 53 54 55 56 57 58 59 5a
  486. #a b c d e f g h i j k l m n o p q r s t u v w x y z
  487. #61 62 63 64 65 66 67 68 69 6a 6b 6c 6d 6e 6f 70 71 72 73 74 75 76 77 78 79 7a
  488. #0 1 2 3 4 5 6 7 8 9 - _ . ~
  489. #30 31 32 33 34 35 36 37 38 39 2d 5f 2e 7e
  490. #stdin stdout
  491. _url_encode() {
  492. _hex_str=$(_hex_dump)
  493. _debug3 "_url_encode"
  494. _debug3 "_hex_str" "$_hex_str"
  495. for _hex_code in $_hex_str; do
  496. #upper case
  497. case "${_hex_code}" in
  498. "41")
  499. printf "%s" "A"
  500. ;;
  501. "42")
  502. printf "%s" "B"
  503. ;;
  504. "43")
  505. printf "%s" "C"
  506. ;;
  507. "44")
  508. printf "%s" "D"
  509. ;;
  510. "45")
  511. printf "%s" "E"
  512. ;;
  513. "46")
  514. printf "%s" "F"
  515. ;;
  516. "47")
  517. printf "%s" "G"
  518. ;;
  519. "48")
  520. printf "%s" "H"
  521. ;;
  522. "49")
  523. printf "%s" "I"
  524. ;;
  525. "4a")
  526. printf "%s" "J"
  527. ;;
  528. "4b")
  529. printf "%s" "K"
  530. ;;
  531. "4c")
  532. printf "%s" "L"
  533. ;;
  534. "4d")
  535. printf "%s" "M"
  536. ;;
  537. "4e")
  538. printf "%s" "N"
  539. ;;
  540. "4f")
  541. printf "%s" "O"
  542. ;;
  543. "50")
  544. printf "%s" "P"
  545. ;;
  546. "51")
  547. printf "%s" "Q"
  548. ;;
  549. "52")
  550. printf "%s" "R"
  551. ;;
  552. "53")
  553. printf "%s" "S"
  554. ;;
  555. "54")
  556. printf "%s" "T"
  557. ;;
  558. "55")
  559. printf "%s" "U"
  560. ;;
  561. "56")
  562. printf "%s" "V"
  563. ;;
  564. "57")
  565. printf "%s" "W"
  566. ;;
  567. "58")
  568. printf "%s" "X"
  569. ;;
  570. "59")
  571. printf "%s" "Y"
  572. ;;
  573. "5a")
  574. printf "%s" "Z"
  575. ;;
  576. #lower case
  577. "61")
  578. printf "%s" "a"
  579. ;;
  580. "62")
  581. printf "%s" "b"
  582. ;;
  583. "63")
  584. printf "%s" "c"
  585. ;;
  586. "64")
  587. printf "%s" "d"
  588. ;;
  589. "65")
  590. printf "%s" "e"
  591. ;;
  592. "66")
  593. printf "%s" "f"
  594. ;;
  595. "67")
  596. printf "%s" "g"
  597. ;;
  598. "68")
  599. printf "%s" "h"
  600. ;;
  601. "69")
  602. printf "%s" "i"
  603. ;;
  604. "6a")
  605. printf "%s" "j"
  606. ;;
  607. "6b")
  608. printf "%s" "k"
  609. ;;
  610. "6c")
  611. printf "%s" "l"
  612. ;;
  613. "6d")
  614. printf "%s" "m"
  615. ;;
  616. "6e")
  617. printf "%s" "n"
  618. ;;
  619. "6f")
  620. printf "%s" "o"
  621. ;;
  622. "70")
  623. printf "%s" "p"
  624. ;;
  625. "71")
  626. printf "%s" "q"
  627. ;;
  628. "72")
  629. printf "%s" "r"
  630. ;;
  631. "73")
  632. printf "%s" "s"
  633. ;;
  634. "74")
  635. printf "%s" "t"
  636. ;;
  637. "75")
  638. printf "%s" "u"
  639. ;;
  640. "76")
  641. printf "%s" "v"
  642. ;;
  643. "77")
  644. printf "%s" "w"
  645. ;;
  646. "78")
  647. printf "%s" "x"
  648. ;;
  649. "79")
  650. printf "%s" "y"
  651. ;;
  652. "7a")
  653. printf "%s" "z"
  654. ;;
  655. #numbers
  656. "30")
  657. printf "%s" "0"
  658. ;;
  659. "31")
  660. printf "%s" "1"
  661. ;;
  662. "32")
  663. printf "%s" "2"
  664. ;;
  665. "33")
  666. printf "%s" "3"
  667. ;;
  668. "34")
  669. printf "%s" "4"
  670. ;;
  671. "35")
  672. printf "%s" "5"
  673. ;;
  674. "36")
  675. printf "%s" "6"
  676. ;;
  677. "37")
  678. printf "%s" "7"
  679. ;;
  680. "38")
  681. printf "%s" "8"
  682. ;;
  683. "39")
  684. printf "%s" "9"
  685. ;;
  686. "2d")
  687. printf "%s" "-"
  688. ;;
  689. "5f")
  690. printf "%s" "_"
  691. ;;
  692. "2e")
  693. printf "%s" "."
  694. ;;
  695. "7e")
  696. printf "%s" "~"
  697. ;;
  698. #other hex
  699. *)
  700. printf '%%%s' "$_hex_code"
  701. ;;
  702. esac
  703. done
  704. }
  705. _json_encode() {
  706. _j_str="$(sed 's/"/\\"/g' | sed "s/\r/\\r/g")"
  707. _debug3 "_json_encode"
  708. _debug3 "_j_str" "$_j_str"
  709. echo "$_j_str" | _hex_dump | _lower_case | sed 's/0a/5c 6e/g' | tr -d ' ' | _h2b | tr -d "\r\n"
  710. }
  711. #options file
  712. _sed_i() {
  713. options="$1"
  714. filename="$2"
  715. if [ -z "$filename" ]; then
  716. _usage "Usage:_sed_i options filename"
  717. return 1
  718. fi
  719. _debug2 options "$options"
  720. if sed -h 2>&1 | grep "\-i\[SUFFIX]" >/dev/null 2>&1; then
  721. _debug "Using sed -i"
  722. sed -i "$options" "$filename"
  723. else
  724. _debug "No -i support in sed"
  725. text="$(cat "$filename")"
  726. echo "$text" | sed "$options" >"$filename"
  727. fi
  728. }
  729. _egrep_o() {
  730. if ! egrep -o "$1" 2>/dev/null; then
  731. sed -n 's/.*\('"$1"'\).*/\1/p'
  732. fi
  733. }
  734. #Usage: file startline endline
  735. _getfile() {
  736. filename="$1"
  737. startline="$2"
  738. endline="$3"
  739. if [ -z "$endline" ]; then
  740. _usage "Usage: file startline endline"
  741. return 1
  742. fi
  743. i="$(grep -n -- "$startline" "$filename" | cut -d : -f 1)"
  744. if [ -z "$i" ]; then
  745. _err "Can not find start line: $startline"
  746. return 1
  747. fi
  748. i="$(_math "$i" + 1)"
  749. _debug i "$i"
  750. j="$(grep -n -- "$endline" "$filename" | cut -d : -f 1)"
  751. if [ -z "$j" ]; then
  752. _err "Can not find end line: $endline"
  753. return 1
  754. fi
  755. j="$(_math "$j" - 1)"
  756. _debug j "$j"
  757. sed -n "$i,${j}p" "$filename"
  758. }
  759. #Usage: multiline
  760. _base64() {
  761. [ "" ] #urgly
  762. if [ "$1" ]; then
  763. _debug3 "base64 multiline:'$1'"
  764. ${ACME_OPENSSL_BIN:-openssl} base64 -e
  765. else
  766. _debug3 "base64 single line."
  767. ${ACME_OPENSSL_BIN:-openssl} base64 -e | tr -d '\r\n'
  768. fi
  769. }
  770. #Usage: multiline
  771. _dbase64() {
  772. if [ "$1" ]; then
  773. ${ACME_OPENSSL_BIN:-openssl} base64 -d -A
  774. else
  775. ${ACME_OPENSSL_BIN:-openssl} base64 -d
  776. fi
  777. }
  778. #file
  779. _checkcert() {
  780. _cf="$1"
  781. if [ "$DEBUG" ]; then
  782. openssl x509 -noout -text -in "$_cf"
  783. else
  784. openssl x509 -noout -text -in "$_cf" >/dev/null 2>&1
  785. fi
  786. }
  787. #Usage: hashalg [outputhex]
  788. #Output Base64-encoded digest
  789. _digest() {
  790. alg="$1"
  791. if [ -z "$alg" ]; then
  792. _usage "Usage: _digest hashalg"
  793. return 1
  794. fi
  795. outputhex="$2"
  796. if [ "$alg" = "sha256" ] || [ "$alg" = "sha1" ] || [ "$alg" = "md5" ]; then
  797. if [ "$outputhex" ]; then
  798. ${ACME_OPENSSL_BIN:-openssl} dgst -"$alg" -hex | cut -d = -f 2 | tr -d ' '
  799. else
  800. ${ACME_OPENSSL_BIN:-openssl} dgst -"$alg" -binary | _base64
  801. fi
  802. else
  803. _err "$alg is not supported yet"
  804. return 1
  805. fi
  806. }
  807. #Usage: hashalg secret_hex [outputhex]
  808. #Output binary hmac
  809. _hmac() {
  810. alg="$1"
  811. secret_hex="$2"
  812. outputhex="$3"
  813. if [ -z "$secret_hex" ]; then
  814. _usage "Usage: _hmac hashalg secret [outputhex]"
  815. return 1
  816. fi
  817. if [ "$alg" = "sha256" ] || [ "$alg" = "sha1" ]; then
  818. if [ "$outputhex" ]; then
  819. (${ACME_OPENSSL_BIN:-openssl} dgst -"$alg" -mac HMAC -macopt "hexkey:$secret_hex" 2>/dev/null || ${ACME_OPENSSL_BIN:-openssl} dgst -"$alg" -hmac "$(printf "%s" "$secret_hex" | _h2b)") | cut -d = -f 2 | tr -d ' '
  820. else
  821. ${ACME_OPENSSL_BIN:-openssl} dgst -"$alg" -mac HMAC -macopt "hexkey:$secret_hex" -binary 2>/dev/null || ${ACME_OPENSSL_BIN:-openssl} dgst -"$alg" -hmac "$(printf "%s" "$secret_hex" | _h2b)" -binary
  822. fi
  823. else
  824. _err "$alg is not supported yet"
  825. return 1
  826. fi
  827. }
  828. #Usage: keyfile hashalg
  829. #Output: Base64-encoded signature value
  830. _sign() {
  831. keyfile="$1"
  832. alg="$2"
  833. if [ -z "$alg" ]; then
  834. _usage "Usage: _sign keyfile hashalg"
  835. return 1
  836. fi
  837. _sign_openssl="${ACME_OPENSSL_BIN:-openssl} dgst -sign $keyfile "
  838. if grep "BEGIN RSA PRIVATE KEY" "$keyfile" >/dev/null 2>&1; then
  839. $_sign_openssl -$alg | _base64
  840. elif grep "BEGIN EC PRIVATE KEY" "$keyfile" >/dev/null 2>&1; then
  841. if ! _signedECText="$($_sign_openssl -sha$__ECC_KEY_LEN | ${ACME_OPENSSL_BIN:-openssl} asn1parse -inform DER)"; then
  842. _err "Sign failed: $_sign_openssl"
  843. _err "Key file: $keyfile"
  844. _err "Key content:$(wc -l <"$keyfile") lines"
  845. return 1
  846. fi
  847. _debug3 "_signedECText" "$_signedECText"
  848. _ec_r="$(echo "$_signedECText" | _head_n 2 | _tail_n 1 | cut -d : -f 4 | tr -d "\r\n")"
  849. _debug3 "_ec_r" "$_ec_r"
  850. _ec_s="$(echo "$_signedECText" | _head_n 3 | _tail_n 1 | cut -d : -f 4 | tr -d "\r\n")"
  851. _debug3 "_ec_s" "$_ec_s"
  852. printf "%s" "$_ec_r$_ec_s" | _h2b | _base64
  853. else
  854. _err "Unknown key file format."
  855. return 1
  856. fi
  857. }
  858. #keylength or isEcc flag (empty str => not ecc)
  859. _isEccKey() {
  860. _length="$1"
  861. if [ -z "$_length" ]; then
  862. return 1
  863. fi
  864. [ "$_length" != "1024" ] \
  865. && [ "$_length" != "2048" ] \
  866. && [ "$_length" != "3072" ] \
  867. && [ "$_length" != "4096" ] \
  868. && [ "$_length" != "8192" ]
  869. }
  870. # _createkey 2048|ec-256 file
  871. _createkey() {
  872. length="$1"
  873. f="$2"
  874. _debug2 "_createkey for file:$f"
  875. eccname="$length"
  876. if _startswith "$length" "ec-"; then
  877. length=$(printf "%s" "$length" | cut -d '-' -f 2-100)
  878. if [ "$length" = "256" ]; then
  879. eccname="prime256v1"
  880. fi
  881. if [ "$length" = "384" ]; then
  882. eccname="secp384r1"
  883. fi
  884. if [ "$length" = "521" ]; then
  885. eccname="secp521r1"
  886. fi
  887. fi
  888. if [ -z "$length" ]; then
  889. length=2048
  890. fi
  891. _debug "Use length $length"
  892. if ! touch "$f" >/dev/null 2>&1; then
  893. _f_path="$(dirname "$f")"
  894. _debug _f_path "$_f_path"
  895. if ! mkdir -p "$_f_path"; then
  896. _err "Can not create path: $_f_path"
  897. return 1
  898. fi
  899. fi
  900. if _isEccKey "$length"; then
  901. _debug "Using ec name: $eccname"
  902. if _opkey="$(${ACME_OPENSSL_BIN:-openssl} ecparam -name "$eccname" -genkey 2>/dev/null)"; then
  903. echo "$_opkey" >"$f"
  904. else
  905. _err "error ecc key name: $eccname"
  906. return 1
  907. fi
  908. else
  909. _debug "Using RSA: $length"
  910. if _opkey="$(${ACME_OPENSSL_BIN:-openssl} genrsa "$length" 2>/dev/null)"; then
  911. echo "$_opkey" >"$f"
  912. else
  913. _err "error rsa key: $length"
  914. return 1
  915. fi
  916. fi
  917. if [ "$?" != "0" ]; then
  918. _err "Create key error."
  919. return 1
  920. fi
  921. }
  922. #domain
  923. _is_idn() {
  924. _is_idn_d="$1"
  925. _debug2 _is_idn_d "$_is_idn_d"
  926. _idn_temp=$(printf "%s" "$_is_idn_d" | tr -d '0-9' | tr -d 'a-z' | tr -d 'A-Z' | tr -d '*.,-_')
  927. _debug2 _idn_temp "$_idn_temp"
  928. [ "$_idn_temp" ]
  929. }
  930. #aa.com
  931. #aa.com,bb.com,cc.com
  932. _idn() {
  933. __idn_d="$1"
  934. if ! _is_idn "$__idn_d"; then
  935. printf "%s" "$__idn_d"
  936. return 0
  937. fi
  938. if _exists idn; then
  939. if _contains "$__idn_d" ','; then
  940. _i_first="1"
  941. for f in $(echo "$__idn_d" | tr ',' ' '); do
  942. [ -z "$f" ] && continue
  943. if [ -z "$_i_first" ]; then
  944. printf "%s" ","
  945. else
  946. _i_first=""
  947. fi
  948. idn --quiet "$f" | tr -d "\r\n"
  949. done
  950. else
  951. idn "$__idn_d" | tr -d "\r\n"
  952. fi
  953. else
  954. _err "Please install idn to process IDN names."
  955. fi
  956. }
  957. #_createcsr cn san_list keyfile csrfile conf acmeValidationv1
  958. _createcsr() {
  959. _debug _createcsr
  960. domain="$1"
  961. domainlist="$2"
  962. csrkey="$3"
  963. csr="$4"
  964. csrconf="$5"
  965. acmeValidationv1="$6"
  966. _debug2 domain "$domain"
  967. _debug2 domainlist "$domainlist"
  968. _debug2 csrkey "$csrkey"
  969. _debug2 csr "$csr"
  970. _debug2 csrconf "$csrconf"
  971. printf "[ req_distinguished_name ]\n[ req ]\ndistinguished_name = req_distinguished_name\nreq_extensions = v3_req\n[ v3_req ]\n\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment" >"$csrconf"
  972. if [ "$acmeValidationv1" ]; then
  973. domainlist="$(_idn "$domainlist")"
  974. printf -- "\nsubjectAltName=DNS:$domainlist" >>"$csrconf"
  975. elif [ -z "$domainlist" ] || [ "$domainlist" = "$NO_VALUE" ]; then
  976. #single domain
  977. _info "Single domain" "$domain"
  978. printf -- "\nsubjectAltName=DNS:$(_idn "$domain")" >>"$csrconf"
  979. else
  980. domainlist="$(_idn "$domainlist")"
  981. _debug2 domainlist "$domainlist"
  982. if _contains "$domainlist" ","; then
  983. alt="DNS:$(_idn "$domain"),DNS:$(echo "$domainlist" | sed "s/,,/,/g" | sed "s/,/,DNS:/g")"
  984. else
  985. alt="DNS:$(_idn "$domain"),DNS:$domainlist"
  986. fi
  987. #multi
  988. _info "Multi domain" "$alt"
  989. printf -- "\nsubjectAltName=$alt" >>"$csrconf"
  990. fi
  991. if [ "$Le_OCSP_Staple" ] || [ "$Le_OCSP_Stable" ]; then
  992. _savedomainconf Le_OCSP_Staple "$Le_OCSP_Staple"
  993. _cleardomainconf Le_OCSP_Stable
  994. printf -- "\nbasicConstraints = CA:FALSE\n1.3.6.1.5.5.7.1.24=DER:30:03:02:01:05" >>"$csrconf"
  995. fi
  996. if [ "$acmeValidationv1" ]; then
  997. printf "\n1.3.6.1.5.5.7.1.31=critical,DER:04:20:${acmeValidationv1}" >>"${csrconf}"
  998. fi
  999. _csr_cn="$(_idn "$domain")"
  1000. _debug2 _csr_cn "$_csr_cn"
  1001. if _contains "$(uname -a)" "MINGW"; then
  1002. ${ACME_OPENSSL_BIN:-openssl} req -new -sha256 -key "$csrkey" -subj "//CN=$_csr_cn" -config "$csrconf" -out "$csr"
  1003. else
  1004. ${ACME_OPENSSL_BIN:-openssl} req -new -sha256 -key "$csrkey" -subj "/CN=$_csr_cn" -config "$csrconf" -out "$csr"
  1005. fi
  1006. }
  1007. #_signcsr key csr conf cert
  1008. _signcsr() {
  1009. key="$1"
  1010. csr="$2"
  1011. conf="$3"
  1012. cert="$4"
  1013. _debug "_signcsr"
  1014. _msg="$(${ACME_OPENSSL_BIN:-openssl} x509 -req -days 365 -in "$csr" -signkey "$key" -extensions v3_req -extfile "$conf" -out "$cert" 2>&1)"
  1015. _ret="$?"
  1016. _debug "$_msg"
  1017. return $_ret
  1018. }
  1019. #_csrfile
  1020. _readSubjectFromCSR() {
  1021. _csrfile="$1"
  1022. if [ -z "$_csrfile" ]; then
  1023. _usage "_readSubjectFromCSR mycsr.csr"
  1024. return 1
  1025. fi
  1026. ${ACME_OPENSSL_BIN:-openssl} req -noout -in "$_csrfile" -subject | tr ',' "\n" | _egrep_o "CN *=.*" | cut -d = -f 2 | cut -d / -f 1 | tr -d ' \n'
  1027. }
  1028. #_csrfile
  1029. #echo comma separated domain list
  1030. _readSubjectAltNamesFromCSR() {
  1031. _csrfile="$1"
  1032. if [ -z "$_csrfile" ]; then
  1033. _usage "_readSubjectAltNamesFromCSR mycsr.csr"
  1034. return 1
  1035. fi
  1036. _csrsubj="$(_readSubjectFromCSR "$_csrfile")"
  1037. _debug _csrsubj "$_csrsubj"
  1038. _dnsAltnames="$(${ACME_OPENSSL_BIN:-openssl} req -noout -text -in "$_csrfile" | grep "^ *DNS:.*" | tr -d ' \n')"
  1039. _debug _dnsAltnames "$_dnsAltnames"
  1040. if _contains "$_dnsAltnames," "DNS:$_csrsubj,"; then
  1041. _debug "AltNames contains subject"
  1042. _excapedAlgnames="$(echo "$_dnsAltnames" | tr '*' '#')"
  1043. _debug _excapedAlgnames "$_excapedAlgnames"
  1044. _escapedSubject="$(echo "$_csrsubj" | tr '*' '#')"
  1045. _debug _escapedSubject "$_escapedSubject"
  1046. _dnsAltnames="$(echo "$_excapedAlgnames," | sed "s/DNS:$_escapedSubject,//g" | tr '#' '*' | sed "s/,\$//g")"
  1047. _debug _dnsAltnames "$_dnsAltnames"
  1048. else
  1049. _debug "AltNames doesn't contain subject"
  1050. fi
  1051. echo "$_dnsAltnames" | sed "s/DNS://g"
  1052. }
  1053. #_csrfile
  1054. _readKeyLengthFromCSR() {
  1055. _csrfile="$1"
  1056. if [ -z "$_csrfile" ]; then
  1057. _usage "_readKeyLengthFromCSR mycsr.csr"
  1058. return 1
  1059. fi
  1060. _outcsr="$(${ACME_OPENSSL_BIN:-openssl} req -noout -text -in "$_csrfile")"
  1061. _debug2 _outcsr "$_outcsr"
  1062. if _contains "$_outcsr" "Public Key Algorithm: id-ecPublicKey"; then
  1063. _debug "ECC CSR"
  1064. echo "$_outcsr" | tr "\t" " " | _egrep_o "^ *ASN1 OID:.*" | cut -d ':' -f 2 | tr -d ' '
  1065. else
  1066. _debug "RSA CSR"
  1067. _rkl="$(echo "$_outcsr" | tr "\t" " " | _egrep_o "^ *Public.Key:.*" | cut -d '(' -f 2 | cut -d ' ' -f 1)"
  1068. if [ "$_rkl" ]; then
  1069. echo "$_rkl"
  1070. else
  1071. echo "$_outcsr" | tr "\t" " " | _egrep_o "RSA Public.Key:.*" | cut -d '(' -f 2 | cut -d ' ' -f 1
  1072. fi
  1073. fi
  1074. }
  1075. _ss() {
  1076. _port="$1"
  1077. if _exists "ss"; then
  1078. _debug "Using: ss"
  1079. ss -ntpl 2>/dev/null | grep ":$_port "
  1080. return 0
  1081. fi
  1082. if _exists "netstat"; then
  1083. _debug "Using: netstat"
  1084. if netstat -help 2>&1 | grep "\-p proto" >/dev/null; then
  1085. #for windows version netstat tool
  1086. netstat -an -p tcp | grep "LISTENING" | grep ":$_port "
  1087. else
  1088. if netstat -help 2>&1 | grep "\-p protocol" >/dev/null; then
  1089. netstat -an -p tcp | grep LISTEN | grep ":$_port "
  1090. elif netstat -help 2>&1 | grep -- '-P protocol' >/dev/null; then
  1091. #for solaris
  1092. netstat -an -P tcp | grep "\.$_port " | grep "LISTEN"
  1093. elif netstat -help 2>&1 | grep "\-p" >/dev/null; then
  1094. #for full linux
  1095. netstat -ntpl | grep ":$_port "
  1096. else
  1097. #for busybox (embedded linux; no pid support)
  1098. netstat -ntl 2>/dev/null | grep ":$_port "
  1099. fi
  1100. fi
  1101. return 0
  1102. fi
  1103. return 1
  1104. }
  1105. #outfile key cert cacert [password [name [caname]]]
  1106. _toPkcs() {
  1107. _cpfx="$1"
  1108. _ckey="$2"
  1109. _ccert="$3"
  1110. _cca="$4"
  1111. pfxPassword="$5"
  1112. pfxName="$6"
  1113. pfxCaname="$7"
  1114. if [ "$pfxCaname" ]; then
  1115. ${ACME_OPENSSL_BIN:-openssl} pkcs12 -export -out "$_cpfx" -inkey "$_ckey" -in "$_ccert" -certfile "$_cca" -password "pass:$pfxPassword" -name "$pfxName" -caname "$pfxCaname"
  1116. elif [ "$pfxName" ]; then
  1117. ${ACME_OPENSSL_BIN:-openssl} pkcs12 -export -out "$_cpfx" -inkey "$_ckey" -in "$_ccert" -certfile "$_cca" -password "pass:$pfxPassword" -name "$pfxName"
  1118. elif [ "$pfxPassword" ]; then
  1119. ${ACME_OPENSSL_BIN:-openssl} pkcs12 -export -out "$_cpfx" -inkey "$_ckey" -in "$_ccert" -certfile "$_cca" -password "pass:$pfxPassword"
  1120. else
  1121. ${ACME_OPENSSL_BIN:-openssl} pkcs12 -export -out "$_cpfx" -inkey "$_ckey" -in "$_ccert" -certfile "$_cca"
  1122. fi
  1123. }
  1124. #domain [password] [isEcc]
  1125. toPkcs() {
  1126. domain="$1"
  1127. pfxPassword="$2"
  1128. if [ -z "$domain" ]; then
  1129. _usage "Usage: $PROJECT_ENTRY --toPkcs -d domain [--password pfx-password]"
  1130. return 1
  1131. fi
  1132. _isEcc="$3"
  1133. _initpath "$domain" "$_isEcc"
  1134. _toPkcs "$CERT_PFX_PATH" "$CERT_KEY_PATH" "$CERT_PATH" "$CA_CERT_PATH" "$pfxPassword"
  1135. if [ "$?" = "0" ]; then
  1136. _info "Success, Pfx is exported to: $CERT_PFX_PATH"
  1137. fi
  1138. }
  1139. #domain [isEcc]
  1140. toPkcs8() {
  1141. domain="$1"
  1142. if [ -z "$domain" ]; then
  1143. _usage "Usage: $PROJECT_ENTRY --toPkcs8 -d domain [--ecc]"
  1144. return 1
  1145. fi
  1146. _isEcc="$2"
  1147. _initpath "$domain" "$_isEcc"
  1148. ${ACME_OPENSSL_BIN:-openssl} pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in "$CERT_KEY_PATH" -out "$CERT_PKCS8_PATH"
  1149. if [ "$?" = "0" ]; then
  1150. _info "Success, $CERT_PKCS8_PATH"
  1151. fi
  1152. }
  1153. #[2048]
  1154. createAccountKey() {
  1155. _info "Creating account key"
  1156. if [ -z "$1" ]; then
  1157. _usage "Usage: $PROJECT_ENTRY --createAccountKey --accountkeylength 2048"
  1158. return
  1159. fi
  1160. length=$1
  1161. _create_account_key "$length"
  1162. }
  1163. _create_account_key() {
  1164. length=$1
  1165. if [ -z "$length" ] || [ "$length" = "$NO_VALUE" ]; then
  1166. _debug "Use default length $DEFAULT_ACCOUNT_KEY_LENGTH"
  1167. length="$DEFAULT_ACCOUNT_KEY_LENGTH"
  1168. fi
  1169. _debug length "$length"
  1170. _initpath
  1171. mkdir -p "$CA_DIR"
  1172. if [ -s "$ACCOUNT_KEY_PATH" ]; then
  1173. _info "Account key exists, skip"
  1174. return 0
  1175. else
  1176. #generate account key
  1177. if _createkey "$length" "$ACCOUNT_KEY_PATH"; then
  1178. chmod 600 "$ACCOUNT_KEY_PATH"
  1179. _info "Create account key ok."
  1180. return 0
  1181. else
  1182. _err "Create account key error."
  1183. return 1
  1184. fi
  1185. fi
  1186. }
  1187. #domain [length]
  1188. createDomainKey() {
  1189. _info "Creating domain key"
  1190. if [ -z "$1" ]; then
  1191. _usage "Usage: $PROJECT_ENTRY --createDomainKey -d domain.com [ --keylength 2048 ]"
  1192. return
  1193. fi
  1194. domain=$1
  1195. _cdl=$2
  1196. if [ -z "$_cdl" ]; then
  1197. _debug "Use DEFAULT_DOMAIN_KEY_LENGTH=$DEFAULT_DOMAIN_KEY_LENGTH"
  1198. _cdl="$DEFAULT_DOMAIN_KEY_LENGTH"
  1199. fi
  1200. _initpath "$domain" "$_cdl"
  1201. if [ ! -f "$CERT_KEY_PATH" ] || [ ! -s "$CERT_KEY_PATH" ] || ([ "$FORCE" ] && ! [ "$IS_RENEW" ]) || [ "$Le_ForceNewDomainKey" = "1" ]; then
  1202. if _createkey "$_cdl" "$CERT_KEY_PATH"; then
  1203. _savedomainconf Le_Keylength "$_cdl"
  1204. _info "The domain key is here: $(__green $CERT_KEY_PATH)"
  1205. return 0
  1206. else
  1207. _err "Can not create domain key"
  1208. return 1
  1209. fi
  1210. else
  1211. if [ "$IS_RENEW" ]; then
  1212. _info "Domain key exists, skip"
  1213. return 0
  1214. else
  1215. _err "Domain key exists, do you want to overwrite the key?"
  1216. _err "Add '--force', and try again."
  1217. return 1
  1218. fi
  1219. fi
  1220. }
  1221. # domain domainlist isEcc
  1222. createCSR() {
  1223. _info "Creating csr"
  1224. if [ -z "$1" ]; then
  1225. _usage "Usage: $PROJECT_ENTRY --createCSR -d domain1.com [-d domain2.com -d domain3.com ... ]"
  1226. return
  1227. fi
  1228. domain="$1"
  1229. domainlist="$2"
  1230. _isEcc="$3"
  1231. _initpath "$domain" "$_isEcc"
  1232. if [ -f "$CSR_PATH" ] && [ "$IS_RENEW" ] && [ -z "$FORCE" ]; then
  1233. _info "CSR exists, skip"
  1234. return
  1235. fi
  1236. if [ ! -f "$CERT_KEY_PATH" ]; then
  1237. _err "The key file is not found: $CERT_KEY_PATH"
  1238. _err "Please create the key file first."
  1239. return 1
  1240. fi
  1241. _createcsr "$domain" "$domainlist" "$CERT_KEY_PATH" "$CSR_PATH" "$DOMAIN_SSL_CONF"
  1242. }
  1243. _url_replace() {
  1244. tr '/+' '_-' | tr -d '= '
  1245. }
  1246. _time2str() {
  1247. #BSD
  1248. if date -u -r "$1" 2>/dev/null; then
  1249. return
  1250. fi
  1251. #Linux
  1252. if date -u -d@"$1" 2>/dev/null; then
  1253. return
  1254. fi
  1255. #Solaris
  1256. if _exists adb; then
  1257. _t_s_a=$(echo "0t${1}=Y" | adb)
  1258. echo "$_t_s_a"
  1259. fi
  1260. #Busybox
  1261. if echo "$1" | awk '{ print strftime("%c", $0); }' 2>/dev/null; then
  1262. return
  1263. fi
  1264. }
  1265. _normalizeJson() {
  1266. sed "s/\" *: *\([\"{\[]\)/\":\1/g" | sed "s/^ *\([^ ]\)/\1/" | tr -d "\r\n"
  1267. }
  1268. _stat() {
  1269. #Linux
  1270. if stat -c '%U:%G' "$1" 2>/dev/null; then
  1271. return
  1272. fi
  1273. #BSD
  1274. if stat -f '%Su:%Sg' "$1" 2>/dev/null; then
  1275. return
  1276. fi
  1277. return 1 #error, 'stat' not found
  1278. }
  1279. #keyfile
  1280. _calcjwk() {
  1281. keyfile="$1"
  1282. if [ -z "$keyfile" ]; then
  1283. _usage "Usage: _calcjwk keyfile"
  1284. return 1
  1285. fi
  1286. if [ "$JWK_HEADER" ] && [ "$__CACHED_JWK_KEY_FILE" = "$keyfile" ]; then
  1287. _debug2 "Use cached jwk for file: $__CACHED_JWK_KEY_FILE"
  1288. return 0
  1289. fi
  1290. if grep "BEGIN RSA PRIVATE KEY" "$keyfile" >/dev/null 2>&1; then
  1291. _debug "RSA key"
  1292. pub_exp=$(${ACME_OPENSSL_BIN:-openssl} rsa -in "$keyfile" -noout -text | grep "^publicExponent:" | cut -d '(' -f 2 | cut -d 'x' -f 2 | cut -d ')' -f 1)
  1293. if [ "${#pub_exp}" = "5" ]; then
  1294. pub_exp=0$pub_exp
  1295. fi
  1296. _debug3 pub_exp "$pub_exp"
  1297. e=$(echo "$pub_exp" | _h2b | _base64)
  1298. _debug3 e "$e"
  1299. modulus=$(${ACME_OPENSSL_BIN:-openssl} rsa -in "$keyfile" -modulus -noout | cut -d '=' -f 2)
  1300. _debug3 modulus "$modulus"
  1301. n="$(printf "%s" "$modulus" | _h2b | _base64 | _url_replace)"
  1302. _debug3 n "$n"
  1303. jwk='{"e": "'$e'", "kty": "RSA", "n": "'$n'"}'
  1304. _debug3 jwk "$jwk"
  1305. JWK_HEADER='{"alg": "RS256", "jwk": '$jwk'}'
  1306. JWK_HEADERPLACE_PART1='{"nonce": "'
  1307. JWK_HEADERPLACE_PART2='", "alg": "RS256"'
  1308. elif grep "BEGIN EC PRIVATE KEY" "$keyfile" >/dev/null 2>&1; then
  1309. _debug "EC key"
  1310. crv="$(${ACME_OPENSSL_BIN:-openssl} ec -in "$keyfile" -noout -text 2>/dev/null | grep "^NIST CURVE:" | cut -d ":" -f 2 | tr -d " \r\n")"
  1311. _debug3 crv "$crv"
  1312. __ECC_KEY_LEN=$(echo "$crv" | cut -d "-" -f 2)
  1313. if [ "$__ECC_KEY_LEN" = "521" ]; then
  1314. __ECC_KEY_LEN=512
  1315. fi
  1316. _debug3 __ECC_KEY_LEN "$__ECC_KEY_LEN"
  1317. if [ -z "$crv" ]; then
  1318. _debug "Let's try ASN1 OID"
  1319. crv_oid="$(${ACME_OPENSSL_BIN:-openssl} ec -in "$keyfile" -noout -text 2>/dev/null | grep "^ASN1 OID:" | cut -d ":" -f 2 | tr -d " \r\n")"
  1320. _debug3 crv_oid "$crv_oid"
  1321. case "${crv_oid}" in
  1322. "prime256v1")
  1323. crv="P-256"
  1324. __ECC_KEY_LEN=256
  1325. ;;
  1326. "secp384r1")
  1327. crv="P-384"
  1328. __ECC_KEY_LEN=384
  1329. ;;
  1330. "secp521r1")
  1331. crv="P-521"
  1332. __ECC_KEY_LEN=512
  1333. ;;
  1334. *)
  1335. _err "ECC oid : $crv_oid"
  1336. return 1
  1337. ;;
  1338. esac
  1339. _debug3 crv "$crv"
  1340. fi
  1341. pubi="$(${ACME_OPENSSL_BIN:-openssl} ec -in "$keyfile" -noout -text 2>/dev/null | grep -n pub: | cut -d : -f 1)"
  1342. pubi=$(_math "$pubi" + 1)
  1343. _debug3 pubi "$pubi"
  1344. pubj="$(${ACME_OPENSSL_BIN:-openssl} ec -in "$keyfile" -noout -text 2>/dev/null | grep -n "ASN1 OID:" | cut -d : -f 1)"
  1345. pubj=$(_math "$pubj" - 1)
  1346. _debug3 pubj "$pubj"
  1347. pubtext="$(${ACME_OPENSSL_BIN:-openssl} ec -in "$keyfile" -noout -text 2>/dev/null | sed -n "$pubi,${pubj}p" | tr -d " \n\r")"
  1348. _debug3 pubtext "$pubtext"
  1349. xlen="$(printf "%s" "$pubtext" | tr -d ':' | wc -c)"
  1350. xlen=$(_math "$xlen" / 4)
  1351. _debug3 xlen "$xlen"
  1352. xend=$(_math "$xlen" + 1)
  1353. x="$(printf "%s" "$pubtext" | cut -d : -f 2-"$xend")"
  1354. _debug3 x "$x"
  1355. x64="$(printf "%s" "$x" | tr -d : | _h2b | _base64 | _url_replace)"
  1356. _debug3 x64 "$x64"
  1357. xend=$(_math "$xend" + 1)
  1358. y="$(printf "%s" "$pubtext" | cut -d : -f "$xend"-10000)"
  1359. _debug3 y "$y"
  1360. y64="$(printf "%s" "$y" | tr -d : | _h2b | _base64 | _url_replace)"
  1361. _debug3 y64 "$y64"
  1362. jwk='{"crv": "'$crv'", "kty": "EC", "x": "'$x64'", "y": "'$y64'"}'
  1363. _debug3 jwk "$jwk"
  1364. JWK_HEADER='{"alg": "ES'$__ECC_KEY_LEN'", "jwk": '$jwk'}'
  1365. JWK_HEADERPLACE_PART1='{"nonce": "'
  1366. JWK_HEADERPLACE_PART2='", "alg": "ES'$__ECC_KEY_LEN'"'
  1367. else
  1368. _err "Only RSA or EC key is supported. keyfile=$keyfile"
  1369. _debug2 "$(cat "$keyfile")"
  1370. return 1
  1371. fi
  1372. _debug3 JWK_HEADER "$JWK_HEADER"
  1373. __CACHED_JWK_KEY_FILE="$keyfile"
  1374. }
  1375. _time() {
  1376. date -u "+%s"
  1377. }
  1378. _utc_date() {
  1379. date -u "+%Y-%m-%d %H:%M:%S"
  1380. }
  1381. _mktemp() {
  1382. if _exists mktemp; then
  1383. if mktemp 2>/dev/null; then
  1384. return 0
  1385. elif _contains "$(mktemp 2>&1)" "-t prefix" && mktemp -t "$PROJECT_NAME" 2>/dev/null; then
  1386. #for Mac osx
  1387. return 0
  1388. fi
  1389. fi
  1390. if [ -d "/tmp" ]; then
  1391. echo "/tmp/${PROJECT_NAME}wefADf24sf.$(_time).tmp"
  1392. return 0
  1393. elif [ "$LE_TEMP_DIR" ] && mkdir -p "$LE_TEMP_DIR"; then
  1394. echo "/$LE_TEMP_DIR/wefADf24sf.$(_time).tmp"
  1395. return 0
  1396. fi
  1397. _err "Can not create temp file."
  1398. }
  1399. _inithttp() {
  1400. if [ -z "$HTTP_HEADER" ] || ! touch "$HTTP_HEADER"; then
  1401. HTTP_HEADER="$(_mktemp)"
  1402. _debug2 HTTP_HEADER "$HTTP_HEADER"
  1403. fi
  1404. if [ "$__HTTP_INITIALIZED" ]; then
  1405. if [ "$_ACME_CURL$_ACME_WGET" ]; then
  1406. _debug2 "Http already initialized."
  1407. return 0
  1408. fi
  1409. fi
  1410. if [ -z "$_ACME_CURL" ] && _exists "curl"; then
  1411. _ACME_CURL="curl -L --silent --dump-header $HTTP_HEADER "
  1412. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  1413. _CURL_DUMP="$(_mktemp)"
  1414. _ACME_CURL="$_ACME_CURL --trace-ascii $_CURL_DUMP "
  1415. fi
  1416. if [ "$CA_PATH" ]; then
  1417. _ACME_CURL="$_ACME_CURL --capath $CA_PATH "
  1418. elif [ "$CA_BUNDLE" ]; then
  1419. _ACME_CURL="$_ACME_CURL --cacert $CA_BUNDLE "
  1420. fi
  1421. if _contains "$(curl --help 2>&1)" "--globoff"; then
  1422. _ACME_CURL="$_ACME_CURL -g "
  1423. fi
  1424. fi
  1425. if [ -z "$_ACME_WGET" ] && _exists "wget"; then
  1426. _ACME_WGET="wget -q"
  1427. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  1428. _ACME_WGET="$_ACME_WGET -d "
  1429. fi
  1430. if [ "$CA_PATH" ]; then
  1431. _ACME_WGET="$_ACME_WGET --ca-directory=$CA_PATH "
  1432. elif [ "$CA_BUNDLE" ]; then
  1433. _ACME_WGET="$_ACME_WGET --ca-certificate=$CA_BUNDLE "
  1434. fi
  1435. fi
  1436. #from wget 1.14: do not skip body on 404 error
  1437. if [ "$_ACME_WGET" ] && _contains "$($_ACME_WGET --help 2>&1)" "--content-on-error"; then
  1438. _ACME_WGET="$_ACME_WGET --content-on-error "
  1439. fi
  1440. __HTTP_INITIALIZED=1
  1441. }
  1442. # body url [needbase64] [POST|PUT|DELETE] [ContentType]
  1443. _post() {
  1444. body="$1"
  1445. _post_url="$2"
  1446. needbase64="$3"
  1447. httpmethod="$4"
  1448. _postContentType="$5"
  1449. if [ -z "$httpmethod" ]; then
  1450. httpmethod="POST"
  1451. fi
  1452. _debug $httpmethod
  1453. _debug "_post_url" "$_post_url"
  1454. _debug2 "body" "$body"
  1455. _debug2 "_postContentType" "$_postContentType"
  1456. _inithttp
  1457. if [ "$_ACME_CURL" ] && [ "${ACME_USE_WGET:-0}" = "0" ]; then
  1458. _CURL="$_ACME_CURL"
  1459. if [ "$HTTPS_INSECURE" ]; then
  1460. _CURL="$_CURL --insecure "
  1461. fi
  1462. if [ "$httpmethod" = "HEAD" ]; then
  1463. _CURL="$_CURL -I "
  1464. fi
  1465. _debug "_CURL" "$_CURL"
  1466. if [ "$needbase64" ]; then
  1467. if [ "$body" ]; then
  1468. if [ "$_postContentType" ]; then
  1469. response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "Content-Type: $_postContentType" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" --data "$body" "$_post_url" | _base64)"
  1470. else
  1471. response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" --data "$body" "$_post_url" | _base64)"
  1472. fi
  1473. else
  1474. if [ "$_postContentType" ]; then
  1475. response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "Content-Type: $_postContentType" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" "$_post_url" | _base64)"
  1476. else
  1477. response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" "$_post_url" | _base64)"
  1478. fi
  1479. fi
  1480. else
  1481. if [ "$body" ]; then
  1482. if [ "$_postContentType" ]; then
  1483. response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "Content-Type: $_postContentType" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" --data "$body" "$_post_url")"
  1484. else
  1485. response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" --data "$body" "$_post_url")"
  1486. fi
  1487. else
  1488. if [ "$_postContentType" ]; then
  1489. response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "Content-Type: $_postContentType" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" "$_post_url")"
  1490. else
  1491. response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" "$_post_url")"
  1492. fi
  1493. fi
  1494. fi
  1495. _ret="$?"
  1496. if [ "$_ret" != "0" ]; then
  1497. _err "Please refer to https://curl.haxx.se/libcurl/c/libcurl-errors.html for error code: $_ret"
  1498. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  1499. _err "Here is the curl dump log:"
  1500. _err "$(cat "$_CURL_DUMP")"
  1501. fi
  1502. fi
  1503. elif [ "$_ACME_WGET" ]; then
  1504. _WGET="$_ACME_WGET"
  1505. if [ "$HTTPS_INSECURE" ]; then
  1506. _WGET="$_WGET --no-check-certificate "
  1507. fi
  1508. if [ "$httpmethod" = "HEAD" ]; then
  1509. _WGET="$_WGET --read-timeout=3.0 --tries=2 "
  1510. fi
  1511. _debug "_WGET" "$_WGET"
  1512. if [ "$needbase64" ]; then
  1513. if [ "$httpmethod" = "POST" ]; then
  1514. if [ "$_postContentType" ]; then
  1515. response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --header "Content-Type: $_postContentType" --post-data="$body" "$_post_url" 2>"$HTTP_HEADER" | _base64)"
  1516. else
  1517. response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --post-data="$body" "$_post_url" 2>"$HTTP_HEADER" | _base64)"
  1518. fi
  1519. else
  1520. if [ "$_postContentType" ]; then
  1521. response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --header "Content-Type: $_postContentType" --method $httpmethod --body-data="$body" "$_post_url" 2>"$HTTP_HEADER" | _base64)"
  1522. else
  1523. response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --method $httpmethod --body-data="$body" "$_post_url" 2>"$HTTP_HEADER" | _base64)"
  1524. fi
  1525. fi
  1526. else
  1527. if [ "$httpmethod" = "POST" ]; then
  1528. if [ "$_postContentType" ]; then
  1529. response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --header "Content-Type: $_postContentType" --post-data="$body" "$_post_url" 2>"$HTTP_HEADER")"
  1530. else
  1531. response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --post-data="$body" "$_post_url" 2>"$HTTP_HEADER")"
  1532. fi
  1533. elif [ "$httpmethod" = "HEAD" ]; then
  1534. if [ "$_postContentType" ]; then
  1535. response="$($_WGET --spider -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --header "Content-Type: $_postContentType" --post-data="$body" "$_post_url" 2>"$HTTP_HEADER")"
  1536. else
  1537. response="$($_WGET --spider -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --post-data="$body" "$_post_url" 2>"$HTTP_HEADER")"
  1538. fi
  1539. else
  1540. if [ "$_postContentType" ]; then
  1541. response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --header "Content-Type: $_postContentType" --method $httpmethod --body-data="$body" "$_post_url" 2>"$HTTP_HEADER")"
  1542. else
  1543. response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --method $httpmethod --body-data="$body" "$_post_url" 2>"$HTTP_HEADER")"
  1544. fi
  1545. fi
  1546. fi
  1547. _ret="$?"
  1548. if [ "$_ret" = "8" ]; then
  1549. _ret=0
  1550. _debug "wget returns 8, the server returns a 'Bad request' response, lets process the response later."
  1551. fi
  1552. if [ "$_ret" != "0" ]; then
  1553. _err "Please refer to https://www.gnu.org/software/wget/manual/html_node/Exit-Status.html for error code: $_ret"
  1554. fi
  1555. _sed_i "s/^ *//g" "$HTTP_HEADER"
  1556. else
  1557. _ret="$?"
  1558. _err "Neither curl nor wget is found, can not do $httpmethod."
  1559. fi
  1560. _debug "_ret" "$_ret"
  1561. printf "%s" "$response"
  1562. return $_ret
  1563. }
  1564. # url getheader timeout
  1565. _get() {
  1566. _debug GET
  1567. url="$1"
  1568. onlyheader="$2"
  1569. t="$3"
  1570. _debug url "$url"
  1571. _debug "timeout=$t"
  1572. _inithttp
  1573. if [ "$_ACME_CURL" ] && [ "${ACME_USE_WGET:-0}" = "0" ]; then
  1574. _CURL="$_ACME_CURL"
  1575. if [ "$HTTPS_INSECURE" ]; then
  1576. _CURL="$_CURL --insecure "
  1577. fi
  1578. if [ "$t" ]; then
  1579. _CURL="$_CURL --connect-timeout $t"
  1580. fi
  1581. _debug "_CURL" "$_CURL"
  1582. if [ "$onlyheader" ]; then
  1583. $_CURL -I --user-agent "$USER_AGENT" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" "$url"
  1584. else
  1585. $_CURL --user-agent "$USER_AGENT" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" "$url"
  1586. fi
  1587. ret=$?
  1588. if [ "$ret" != "0" ]; then
  1589. _err "Please refer to https://curl.haxx.se/libcurl/c/libcurl-errors.html for error code: $ret"
  1590. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  1591. _err "Here is the curl dump log:"
  1592. _err "$(cat "$_CURL_DUMP")"
  1593. fi
  1594. fi
  1595. elif [ "$_ACME_WGET" ]; then
  1596. _WGET="$_ACME_WGET"
  1597. if [ "$HTTPS_INSECURE" ]; then
  1598. _WGET="$_WGET --no-check-certificate "
  1599. fi
  1600. if [ "$t" ]; then
  1601. _WGET="$_WGET --timeout=$t"
  1602. fi
  1603. _debug "_WGET" "$_WGET"
  1604. if [ "$onlyheader" ]; then
  1605. $_WGET --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" -S -O /dev/null "$url" 2>&1 | sed 's/^[ ]*//g'
  1606. else
  1607. $_WGET --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" -O - "$url"
  1608. fi
  1609. ret=$?
  1610. if [ "$ret" = "8" ]; then
  1611. ret=0
  1612. _debug "wget returns 8, the server returns a 'Bad request' response, lets process the response later."
  1613. fi
  1614. if [ "$ret" != "0" ]; then
  1615. _err "Please refer to https://www.gnu.org/software/wget/manual/html_node/Exit-Status.html for error code: $ret"
  1616. fi
  1617. else
  1618. ret=$?
  1619. _err "Neither curl nor wget is found, can not do GET."
  1620. fi
  1621. _debug "ret" "$ret"
  1622. return $ret
  1623. }
  1624. _head_n() {
  1625. head -n "$1"
  1626. }
  1627. _tail_n() {
  1628. if ! tail -n "$1" 2>/dev/null; then
  1629. #fix for solaris
  1630. tail -"$1"
  1631. fi
  1632. }
  1633. # url payload needbase64 keyfile
  1634. _send_signed_request() {
  1635. url=$1
  1636. payload=$2
  1637. needbase64=$3
  1638. keyfile=$4
  1639. if [ -z "$keyfile" ]; then
  1640. keyfile="$ACCOUNT_KEY_PATH"
  1641. fi
  1642. _debug url "$url"
  1643. _debug payload "$payload"
  1644. if ! _calcjwk "$keyfile"; then
  1645. return 1
  1646. fi
  1647. __request_conent_type="$CONTENT_TYPE_JSON"
  1648. payload64=$(printf "%s" "$payload" | _base64 | _url_replace)
  1649. _debug3 payload64 "$payload64"
  1650. MAX_REQUEST_RETRY_TIMES=20
  1651. _sleep_retry_sec=1
  1652. _request_retry_times=0
  1653. while [ "${_request_retry_times}" -lt "$MAX_REQUEST_RETRY_TIMES" ]; do
  1654. _request_retry_times=$(_math "$_request_retry_times" + 1)
  1655. _debug3 _request_retry_times "$_request_retry_times"
  1656. if [ -z "$_CACHED_NONCE" ]; then
  1657. _headers=""
  1658. if [ "$ACME_NEW_NONCE" ]; then
  1659. _debug2 "Get nonce with HEAD. ACME_NEW_NONCE" "$ACME_NEW_NONCE"
  1660. nonceurl="$ACME_NEW_NONCE"
  1661. if _post "" "$nonceurl" "" "HEAD" "$__request_conent_type" >/dev/null; then
  1662. _headers="$(cat "$HTTP_HEADER")"
  1663. _debug2 _headers "$_headers"
  1664. _CACHED_NONCE="$(echo "$_headers" | grep -i "Replay-Nonce:" | _head_n 1 | tr -d "\r\n " | cut -d ':' -f 2)"
  1665. fi
  1666. fi
  1667. if [ -z "$_CACHED_NONCE" ]; then
  1668. _debug2 "Get nonce with GET. ACME_DIRECTORY" "$ACME_DIRECTORY"
  1669. nonceurl="$ACME_DIRECTORY"
  1670. _headers="$(_get "$nonceurl" "onlyheader")"
  1671. _debug2 _headers "$_headers"
  1672. _CACHED_NONCE="$(echo "$_headers" | grep -i "Replay-Nonce:" | _head_n 1 | tr -d "\r\n " | cut -d ':' -f 2)"
  1673. fi
  1674. if [ -z "$_CACHED_NONCE" ] && [ "$ACME_NEW_NONCE" ]; then
  1675. _debug2 "Get nonce with GET. ACME_NEW_NONCE" "$ACME_NEW_NONCE"
  1676. nonceurl="$ACME_NEW_NONCE"
  1677. _headers="$(_get "$nonceurl" "onlyheader")"
  1678. _debug2 _headers "$_headers"
  1679. _CACHED_NONCE="$(echo "$_headers" | grep -i "Replay-Nonce:" | _head_n 1 | tr -d "\r\n " | cut -d ':' -f 2)"
  1680. fi
  1681. _debug2 _CACHED_NONCE "$_CACHED_NONCE"
  1682. if [ "$?" != "0" ]; then
  1683. _err "Can not connect to $nonceurl to get nonce."
  1684. return 1
  1685. fi
  1686. else
  1687. _debug2 "Use _CACHED_NONCE" "$_CACHED_NONCE"
  1688. fi
  1689. nonce="$_CACHED_NONCE"
  1690. _debug2 nonce "$nonce"
  1691. if [ -z "$nonce" ]; then
  1692. _info "Could not get nonce, let's try again."
  1693. _sleep 2
  1694. continue
  1695. fi
  1696. if [ "$ACME_VERSION" = "2" ]; then
  1697. if [ "$url" = "$ACME_NEW_ACCOUNT" ] || [ "$url" = "$ACME_REVOKE_CERT" ]; then
  1698. protected="$JWK_HEADERPLACE_PART1$nonce\", \"url\": \"${url}$JWK_HEADERPLACE_PART2, \"jwk\": $jwk"'}'
  1699. else
  1700. protected="$JWK_HEADERPLACE_PART1$nonce\", \"url\": \"${url}$JWK_HEADERPLACE_PART2, \"kid\": \"${ACCOUNT_URL}\""'}'
  1701. fi
  1702. else
  1703. protected="$JWK_HEADERPLACE_PART1$nonce\", \"url\": \"${url}$JWK_HEADERPLACE_PART2, \"jwk\": $jwk"'}'
  1704. fi
  1705. _debug3 protected "$protected"
  1706. protected64="$(printf "%s" "$protected" | _base64 | _url_replace)"
  1707. _debug3 protected64 "$protected64"
  1708. if ! _sig_t="$(printf "%s" "$protected64.$payload64" | _sign "$keyfile" "sha256")"; then
  1709. _err "Sign request failed."
  1710. return 1
  1711. fi
  1712. _debug3 _sig_t "$_sig_t"
  1713. sig="$(printf "%s" "$_sig_t" | _url_replace)"
  1714. _debug3 sig "$sig"
  1715. body="{\"protected\": \"$protected64\", \"payload\": \"$payload64\", \"signature\": \"$sig\"}"
  1716. _debug3 body "$body"
  1717. response="$(_post "$body" "$url" "$needbase64" "POST" "$__request_conent_type")"
  1718. _CACHED_NONCE=""
  1719. if [ "$?" != "0" ]; then
  1720. _err "Can not post to $url"
  1721. return 1
  1722. fi
  1723. responseHeaders="$(cat "$HTTP_HEADER")"
  1724. _debug2 responseHeaders "$responseHeaders"
  1725. code="$(grep "^HTTP" "$HTTP_HEADER" | _tail_n 1 | cut -d " " -f 2 | tr -d "\r\n")"
  1726. _debug code "$code"
  1727. _debug2 original "$response"
  1728. if echo "$responseHeaders" | grep -i "Content-Type: application/json" >/dev/null 2>&1; then
  1729. response="$(echo "$response" | _normalizeJson)"
  1730. fi
  1731. _debug2 response "$response"
  1732. _CACHED_NONCE="$(echo "$responseHeaders" | grep -i "Replay-Nonce:" | _head_n 1 | tr -d "\r\n " | cut -d ':' -f 2)"
  1733. if ! _startswith "$code" "2"; then
  1734. _body="$response"
  1735. if [ "$needbase64" ]; then
  1736. _body="$(echo "$_body" | _dbase64 multiline)"
  1737. _debug3 _body "$_body"
  1738. fi
  1739. if _contains "$_body" "JWS has invalid anti-replay nonce" || _contains "$_body" "JWS has an invalid anti-replay nonce"; then
  1740. _info "It seems the CA server is busy now, let's wait and retry. Sleeping $_sleep_retry_sec seconds."
  1741. _CACHED_NONCE=""
  1742. _sleep $_sleep_retry_sec
  1743. continue
  1744. fi
  1745. fi
  1746. break
  1747. done
  1748. }
  1749. #setopt "file" "opt" "=" "value" [";"]
  1750. _setopt() {
  1751. __conf="$1"
  1752. __opt="$2"
  1753. __sep="$3"
  1754. __val="$4"
  1755. __end="$5"
  1756. if [ -z "$__opt" ]; then
  1757. _usage usage: _setopt '"file" "opt" "=" "value" [";"]'
  1758. return
  1759. fi
  1760. if [ ! -f "$__conf" ]; then
  1761. touch "$__conf"
  1762. fi
  1763. if grep -n "^$__opt$__sep" "$__conf" >/dev/null; then
  1764. _debug3 OK
  1765. if _contains "$__val" "&"; then
  1766. __val="$(echo "$__val" | sed 's/&/\\&/g')"
  1767. fi
  1768. text="$(cat "$__conf")"
  1769. printf -- "%s\n" "$text" | sed "s|^$__opt$__sep.*$|$__opt$__sep$__val$__end|" >"$__conf"
  1770. elif grep -n "^#$__opt$__sep" "$__conf" >/dev/null; then
  1771. if _contains "$__val" "&"; then
  1772. __val="$(echo "$__val" | sed 's/&/\\&/g')"
  1773. fi
  1774. text="$(cat "$__conf")"
  1775. printf -- "%s\n" "$text" | sed "s|^#$__opt$__sep.*$|$__opt$__sep$__val$__end|" >"$__conf"
  1776. else
  1777. _debug3 APP
  1778. echo "$__opt$__sep$__val$__end" >>"$__conf"
  1779. fi
  1780. _debug3 "$(grep -n "^$__opt$__sep" "$__conf")"
  1781. }
  1782. #_save_conf file key value base64encode
  1783. #save to conf
  1784. _save_conf() {
  1785. _s_c_f="$1"
  1786. _sdkey="$2"
  1787. _sdvalue="$3"
  1788. _b64encode="$4"
  1789. if [ "$_sdvalue" ] && [ "$_b64encode" ]; then
  1790. _sdvalue="${B64CONF_START}$(printf "%s" "${_sdvalue}" | _base64)${B64CONF_END}"
  1791. fi
  1792. if [ "$_s_c_f" ]; then
  1793. _setopt "$_s_c_f" "$_sdkey" "=" "'$_sdvalue'"
  1794. else
  1795. _err "config file is empty, can not save $_sdkey=$_sdvalue"
  1796. fi
  1797. }
  1798. #_clear_conf file key
  1799. _clear_conf() {
  1800. _c_c_f="$1"
  1801. _sdkey="$2"
  1802. if [ "$_c_c_f" ]; then
  1803. _conf_data="$(cat "$_c_c_f")"
  1804. echo "$_conf_data" | sed "s/^$_sdkey *=.*$//" >"$_c_c_f"
  1805. else
  1806. _err "config file is empty, can not clear"
  1807. fi
  1808. }
  1809. #_read_conf file key
  1810. _read_conf() {
  1811. _r_c_f="$1"
  1812. _sdkey="$2"
  1813. if [ -f "$_r_c_f" ]; then
  1814. _sdv="$(
  1815. eval "$(grep "^$_sdkey *=" "$_r_c_f")"
  1816. eval "printf \"%s\" \"\$$_sdkey\""
  1817. )"
  1818. if _startswith "$_sdv" "${B64CONF_START}" && _endswith "$_sdv" "${B64CONF_END}"; then
  1819. _sdv="$(echo "$_sdv" | sed "s/${B64CONF_START}//" | sed "s/${B64CONF_END}//" | _dbase64)"
  1820. fi
  1821. printf "%s" "$_sdv"
  1822. else
  1823. _debug "config file is empty, can not read $_sdkey"
  1824. fi
  1825. }
  1826. #_savedomainconf key value base64encode
  1827. #save to domain.conf
  1828. _savedomainconf() {
  1829. _save_conf "$DOMAIN_CONF" "$@"
  1830. }
  1831. #_cleardomainconf key
  1832. _cleardomainconf() {
  1833. _clear_conf "$DOMAIN_CONF" "$1"
  1834. }
  1835. #_readdomainconf key
  1836. _readdomainconf() {
  1837. _read_conf "$DOMAIN_CONF" "$1"
  1838. }
  1839. #key value base64encode
  1840. _savedeployconf() {
  1841. _savedomainconf "SAVED_$1" "$2" "$3"
  1842. #remove later
  1843. _cleardomainconf "$1"
  1844. }
  1845. #key
  1846. _getdeployconf() {
  1847. _rac_key="$1"
  1848. _rac_value="$(eval echo \$"$_rac_key")"
  1849. if [ "$_rac_value" ]; then
  1850. if _startswith "$_rac_value" '"' && _endswith "$_rac_value" '"'; then
  1851. _debug2 "trim quotation marks"
  1852. eval "export $_rac_key=$_rac_value"
  1853. fi
  1854. return 0 # do nothing
  1855. fi
  1856. _saved=$(_readdomainconf "SAVED_$_rac_key")
  1857. eval "export $_rac_key=$_saved"
  1858. }
  1859. #_saveaccountconf key value base64encode
  1860. _saveaccountconf() {
  1861. _save_conf "$ACCOUNT_CONF_PATH" "$@"
  1862. }
  1863. #key value base64encode
  1864. _saveaccountconf_mutable() {
  1865. _save_conf "$ACCOUNT_CONF_PATH" "SAVED_$1" "$2" "$3"
  1866. #remove later
  1867. _clearaccountconf "$1"
  1868. }
  1869. #key
  1870. _readaccountconf() {
  1871. _read_conf "$ACCOUNT_CONF_PATH" "$1"
  1872. }
  1873. #key
  1874. _readaccountconf_mutable() {
  1875. _rac_key="$1"
  1876. _readaccountconf "SAVED_$_rac_key"
  1877. }
  1878. #_clearaccountconf key
  1879. _clearaccountconf() {
  1880. _clear_conf "$ACCOUNT_CONF_PATH" "$1"
  1881. }
  1882. #_savecaconf key value
  1883. _savecaconf() {
  1884. _save_conf "$CA_CONF" "$1" "$2"
  1885. }
  1886. #_readcaconf key
  1887. _readcaconf() {
  1888. _read_conf "$CA_CONF" "$1"
  1889. }
  1890. #_clearaccountconf key
  1891. _clearcaconf() {
  1892. _clear_conf "$CA_CONF" "$1"
  1893. }
  1894. # content localaddress
  1895. _startserver() {
  1896. content="$1"
  1897. ncaddr="$2"
  1898. _debug "content" "$content"
  1899. _debug "ncaddr" "$ncaddr"
  1900. _debug "startserver: $$"
  1901. _debug Le_HTTPPort "$Le_HTTPPort"
  1902. _debug Le_Listen_V4 "$Le_Listen_V4"
  1903. _debug Le_Listen_V6 "$Le_Listen_V6"
  1904. _NC="socat"
  1905. if [ "$Le_Listen_V4" ]; then
  1906. _NC="$_NC -4"
  1907. elif [ "$Le_Listen_V6" ]; then
  1908. _NC="$_NC -6"
  1909. fi
  1910. if [ "$DEBUG" ] && [ "$DEBUG" -gt "1" ]; then
  1911. _NC="$_NC -d -d -v"
  1912. fi
  1913. SOCAT_OPTIONS=TCP-LISTEN:$Le_HTTPPort,crlf,reuseaddr,fork
  1914. #Adding bind to local-address
  1915. if [ "$ncaddr" ]; then
  1916. SOCAT_OPTIONS="$SOCAT_OPTIONS,bind=${ncaddr}"
  1917. fi
  1918. _content_len="$(printf "%s" "$content" | wc -c)"
  1919. _debug _content_len "$_content_len"
  1920. _debug "_NC" "$_NC $SOCAT_OPTIONS"
  1921. $_NC $SOCAT_OPTIONS SYSTEM:"sleep 1; \
  1922. echo 'HTTP/1.0 200 OK'; \
  1923. echo 'Content-Length\: $_content_len'; \
  1924. echo ''; \
  1925. printf -- '$content';" &
  1926. serverproc="$!"
  1927. }
  1928. _stopserver() {
  1929. pid="$1"
  1930. _debug "pid" "$pid"
  1931. if [ -z "$pid" ]; then
  1932. return
  1933. fi
  1934. kill $pid
  1935. }
  1936. # sleep sec
  1937. _sleep() {
  1938. _sleep_sec="$1"
  1939. if [ "$__INTERACTIVE" ]; then
  1940. _sleep_c="$_sleep_sec"
  1941. while [ "$_sleep_c" -ge "0" ]; do
  1942. printf "\r \r"
  1943. __green "$_sleep_c"
  1944. _sleep_c="$(_math "$_sleep_c" - 1)"
  1945. sleep 1
  1946. done
  1947. printf "\r"
  1948. else
  1949. sleep "$_sleep_sec"
  1950. fi
  1951. }
  1952. # _starttlsserver san_a san_b port content _ncaddr acmeValidationv1
  1953. _starttlsserver() {
  1954. _info "Starting tls server."
  1955. san_a="$1"
  1956. san_b="$2"
  1957. port="$3"
  1958. content="$4"
  1959. opaddr="$5"
  1960. acmeValidationv1="$6"
  1961. _debug san_a "$san_a"
  1962. _debug san_b "$san_b"
  1963. _debug port "$port"
  1964. _debug acmeValidationv1 "$acmeValidationv1"
  1965. #create key TLS_KEY
  1966. if ! _createkey "2048" "$TLS_KEY"; then
  1967. _err "Create tls validation key error."
  1968. return 1
  1969. fi
  1970. #create csr
  1971. alt="$san_a"
  1972. if [ "$san_b" ]; then
  1973. alt="$alt,$san_b"
  1974. fi
  1975. if ! _createcsr "tls.acme.sh" "$alt" "$TLS_KEY" "$TLS_CSR" "$TLS_CONF" "$acmeValidationv1"; then
  1976. _err "Create tls validation csr error."
  1977. return 1
  1978. fi
  1979. #self signed
  1980. if ! _signcsr "$TLS_KEY" "$TLS_CSR" "$TLS_CONF" "$TLS_CERT"; then
  1981. _err "Create tls validation cert error."
  1982. return 1
  1983. fi
  1984. __S_OPENSSL="${ACME_OPENSSL_BIN:-openssl} s_server -www -cert $TLS_CERT -key $TLS_KEY "
  1985. if [ "$opaddr" ]; then
  1986. __S_OPENSSL="$__S_OPENSSL -accept $opaddr:$port"
  1987. else
  1988. __S_OPENSSL="$__S_OPENSSL -accept $port"
  1989. fi
  1990. _debug Le_Listen_V4 "$Le_Listen_V4"
  1991. _debug Le_Listen_V6 "$Le_Listen_V6"
  1992. if [ "$Le_Listen_V4" ]; then
  1993. __S_OPENSSL="$__S_OPENSSL -4"
  1994. elif [ "$Le_Listen_V6" ]; then
  1995. __S_OPENSSL="$__S_OPENSSL -6"
  1996. fi
  1997. if [ "$acmeValidationv1" ]; then
  1998. __S_OPENSSL="$__S_OPENSSL -alpn acme-tls/1"
  1999. fi
  2000. _debug "$__S_OPENSSL"
  2001. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  2002. $__S_OPENSSL -tlsextdebug &
  2003. else
  2004. $__S_OPENSSL >/dev/null 2>&1 &
  2005. fi
  2006. serverproc="$!"
  2007. sleep 1
  2008. _debug serverproc "$serverproc"
  2009. }
  2010. #file
  2011. _readlink() {
  2012. _rf="$1"
  2013. if ! readlink -f "$_rf" 2>/dev/null; then
  2014. if _startswith "$_rf" "/"; then
  2015. echo "$_rf"
  2016. return 0
  2017. fi
  2018. echo "$(pwd)/$_rf" | _conapath
  2019. fi
  2020. }
  2021. _conapath() {
  2022. sed "s#/\./#/#g"
  2023. }
  2024. __initHome() {
  2025. if [ -z "$_SCRIPT_HOME" ]; then
  2026. if _exists readlink && _exists dirname; then
  2027. _debug "Lets find script dir."
  2028. _debug "_SCRIPT_" "$_SCRIPT_"
  2029. _script="$(_readlink "$_SCRIPT_")"
  2030. _debug "_script" "$_script"
  2031. _script_home="$(dirname "$_script")"
  2032. _debug "_script_home" "$_script_home"
  2033. if [ -d "$_script_home" ]; then
  2034. _SCRIPT_HOME="$_script_home"
  2035. else
  2036. _err "It seems the script home is not correct:$_script_home"
  2037. fi
  2038. fi
  2039. fi
  2040. # if [ -z "$LE_WORKING_DIR" ]; then
  2041. # if [ -f "$DEFAULT_INSTALL_HOME/account.conf" ]; then
  2042. # _debug "It seems that $PROJECT_NAME is already installed in $DEFAULT_INSTALL_HOME"
  2043. # LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
  2044. # else
  2045. # LE_WORKING_DIR="$_SCRIPT_HOME"
  2046. # fi
  2047. # fi
  2048. if [ -z "$LE_WORKING_DIR" ]; then
  2049. _debug "Using default home:$DEFAULT_INSTALL_HOME"
  2050. LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
  2051. fi
  2052. export LE_WORKING_DIR
  2053. if [ -z "$LE_CONFIG_HOME" ]; then
  2054. LE_CONFIG_HOME="$LE_WORKING_DIR"
  2055. fi
  2056. _debug "Using config home:$LE_CONFIG_HOME"
  2057. export LE_CONFIG_HOME
  2058. _DEFAULT_ACCOUNT_CONF_PATH="$LE_CONFIG_HOME/account.conf"
  2059. if [ -z "$ACCOUNT_CONF_PATH" ]; then
  2060. if [ -f "$_DEFAULT_ACCOUNT_CONF_PATH" ]; then
  2061. . "$_DEFAULT_ACCOUNT_CONF_PATH"
  2062. fi
  2063. fi
  2064. if [ -z "$ACCOUNT_CONF_PATH" ]; then
  2065. ACCOUNT_CONF_PATH="$_DEFAULT_ACCOUNT_CONF_PATH"
  2066. fi
  2067. DEFAULT_LOG_FILE="$LE_CONFIG_HOME/$PROJECT_NAME.log"
  2068. DEFAULT_CA_HOME="$LE_CONFIG_HOME/ca"
  2069. if [ -z "$LE_TEMP_DIR" ]; then
  2070. LE_TEMP_DIR="$LE_CONFIG_HOME/tmp"
  2071. fi
  2072. }
  2073. #server
  2074. _initAPI() {
  2075. _api_server="${1:-$ACME_DIRECTORY}"
  2076. _debug "_init api for server: $_api_server"
  2077. if [ -z "$ACME_NEW_ACCOUNT" ]; then
  2078. response=$(_get "$_api_server")
  2079. if [ "$?" != "0" ]; then
  2080. _debug2 "response" "$response"
  2081. _err "Can not init api."
  2082. return 1
  2083. fi
  2084. _debug2 "response" "$response"
  2085. ACME_KEY_CHANGE=$(echo "$response" | _egrep_o 'key-change" *: *"[^"]*"' | cut -d '"' -f 3)
  2086. if [ -z "$ACME_KEY_CHANGE" ]; then
  2087. ACME_KEY_CHANGE=$(echo "$response" | _egrep_o 'keyChange" *: *"[^"]*"' | cut -d '"' -f 3)
  2088. fi
  2089. export ACME_KEY_CHANGE
  2090. ACME_NEW_AUTHZ=$(echo "$response" | _egrep_o 'new-authz" *: *"[^"]*"' | cut -d '"' -f 3)
  2091. if [ -z "$ACME_NEW_AUTHZ" ]; then
  2092. ACME_NEW_AUTHZ=$(echo "$response" | _egrep_o 'newAuthz" *: *"[^"]*"' | cut -d '"' -f 3)
  2093. fi
  2094. export ACME_NEW_AUTHZ
  2095. ACME_NEW_ORDER=$(echo "$response" | _egrep_o 'new-cert" *: *"[^"]*"' | cut -d '"' -f 3)
  2096. ACME_NEW_ORDER_RES="new-cert"
  2097. if [ -z "$ACME_NEW_ORDER" ]; then
  2098. ACME_NEW_ORDER=$(echo "$response" | _egrep_o 'new-order" *: *"[^"]*"' | cut -d '"' -f 3)
  2099. ACME_NEW_ORDER_RES="new-order"
  2100. if [ -z "$ACME_NEW_ORDER" ]; then
  2101. ACME_NEW_ORDER=$(echo "$response" | _egrep_o 'newOrder" *: *"[^"]*"' | cut -d '"' -f 3)
  2102. fi
  2103. fi
  2104. export ACME_NEW_ORDER
  2105. export ACME_NEW_ORDER_RES
  2106. ACME_NEW_ACCOUNT=$(echo "$response" | _egrep_o 'new-reg" *: *"[^"]*"' | cut -d '"' -f 3)
  2107. ACME_NEW_ACCOUNT_RES="new-reg"
  2108. if [ -z "$ACME_NEW_ACCOUNT" ]; then
  2109. ACME_NEW_ACCOUNT=$(echo "$response" | _egrep_o 'new-account" *: *"[^"]*"' | cut -d '"' -f 3)
  2110. ACME_NEW_ACCOUNT_RES="new-account"
  2111. if [ -z "$ACME_NEW_ACCOUNT" ]; then
  2112. ACME_NEW_ACCOUNT=$(echo "$response" | _egrep_o 'newAccount" *: *"[^"]*"' | cut -d '"' -f 3)
  2113. if [ "$ACME_NEW_ACCOUNT" ]; then
  2114. export ACME_VERSION=2
  2115. fi
  2116. fi
  2117. fi
  2118. export ACME_NEW_ACCOUNT
  2119. export ACME_NEW_ACCOUNT_RES
  2120. ACME_REVOKE_CERT=$(echo "$response" | _egrep_o 'revoke-cert" *: *"[^"]*"' | cut -d '"' -f 3)
  2121. if [ -z "$ACME_REVOKE_CERT" ]; then
  2122. ACME_REVOKE_CERT=$(echo "$response" | _egrep_o 'revokeCert" *: *"[^"]*"' | cut -d '"' -f 3)
  2123. fi
  2124. export ACME_REVOKE_CERT
  2125. ACME_NEW_NONCE=$(echo "$response" | _egrep_o 'new-nonce" *: *"[^"]*"' | cut -d '"' -f 3)
  2126. if [ -z "$ACME_NEW_NONCE" ]; then
  2127. ACME_NEW_NONCE=$(echo "$response" | _egrep_o 'newNonce" *: *"[^"]*"' | cut -d '"' -f 3)
  2128. fi
  2129. export ACME_NEW_NONCE
  2130. ACME_AGREEMENT=$(echo "$response" | _egrep_o 'terms-of-service" *: *"[^"]*"' | cut -d '"' -f 3)
  2131. if [ -z "$ACME_AGREEMENT" ]; then
  2132. ACME_AGREEMENT=$(echo "$response" | _egrep_o 'termsOfService" *: *"[^"]*"' | cut -d '"' -f 3)
  2133. fi
  2134. export ACME_AGREEMENT
  2135. _debug "ACME_KEY_CHANGE" "$ACME_KEY_CHANGE"
  2136. _debug "ACME_NEW_AUTHZ" "$ACME_NEW_AUTHZ"
  2137. _debug "ACME_NEW_ORDER" "$ACME_NEW_ORDER"
  2138. _debug "ACME_NEW_ACCOUNT" "$ACME_NEW_ACCOUNT"
  2139. _debug "ACME_REVOKE_CERT" "$ACME_REVOKE_CERT"
  2140. _debug "ACME_AGREEMENT" "$ACME_AGREEMENT"
  2141. _debug "ACME_NEW_NONCE" "$ACME_NEW_NONCE"
  2142. _debug "ACME_VERSION" "$ACME_VERSION"
  2143. fi
  2144. }
  2145. #[domain] [keylength or isEcc flag]
  2146. _initpath() {
  2147. domain="$1"
  2148. _ilength="$2"
  2149. __initHome
  2150. if [ -f "$ACCOUNT_CONF_PATH" ]; then
  2151. . "$ACCOUNT_CONF_PATH"
  2152. fi
  2153. if [ "$ACME_IN_CRON" ]; then
  2154. if [ ! "$_USER_PATH_EXPORTED" ]; then
  2155. _USER_PATH_EXPORTED=1
  2156. export PATH="$USER_PATH:$PATH"
  2157. fi
  2158. fi
  2159. if [ -z "$CA_HOME" ]; then
  2160. CA_HOME="$DEFAULT_CA_HOME"
  2161. fi
  2162. if [ "$ACME_VERSION" = "2" ]; then
  2163. DEFAULT_CA="$LETSENCRYPT_CA_V2"
  2164. DEFAULT_STAGING_CA="$LETSENCRYPT_STAGING_CA_V2"
  2165. fi
  2166. if [ -z "$ACME_DIRECTORY" ]; then
  2167. if [ -z "$STAGE" ]; then
  2168. ACME_DIRECTORY="$DEFAULT_CA"
  2169. else
  2170. ACME_DIRECTORY="$DEFAULT_STAGING_CA"
  2171. _info "Using stage ACME_DIRECTORY: $ACME_DIRECTORY"
  2172. fi
  2173. fi
  2174. _debug ACME_DIRECTORY "$ACME_DIRECTORY"
  2175. _ACME_SERVER_HOST="$(echo "$ACME_DIRECTORY" | cut -d : -f 2 | tr -s / | cut -d / -f 2)"
  2176. _debug2 "_ACME_SERVER_HOST" "$_ACME_SERVER_HOST"
  2177. CA_DIR="$CA_HOME/$_ACME_SERVER_HOST"
  2178. _DEFAULT_CA_CONF="$CA_DIR/ca.conf"
  2179. if [ -z "$CA_CONF" ]; then
  2180. CA_CONF="$_DEFAULT_CA_CONF"
  2181. fi
  2182. _debug3 CA_CONF "$CA_CONF"
  2183. if [ -f "$CA_CONF" ]; then
  2184. . "$CA_CONF"
  2185. fi
  2186. if [ -z "$ACME_DIR" ]; then
  2187. ACME_DIR="/home/.acme"
  2188. fi
  2189. if [ -z "$APACHE_CONF_BACKUP_DIR" ]; then
  2190. APACHE_CONF_BACKUP_DIR="$LE_CONFIG_HOME"
  2191. fi
  2192. if [ -z "$USER_AGENT" ]; then
  2193. USER_AGENT="$DEFAULT_USER_AGENT"
  2194. fi
  2195. if [ -z "$HTTP_HEADER" ]; then
  2196. HTTP_HEADER="$LE_CONFIG_HOME/http.header"
  2197. fi
  2198. _OLD_ACCOUNT_KEY="$LE_WORKING_DIR/account.key"
  2199. _OLD_ACCOUNT_JSON="$LE_WORKING_DIR/account.json"
  2200. _DEFAULT_ACCOUNT_KEY_PATH="$CA_DIR/account.key"
  2201. _DEFAULT_ACCOUNT_JSON_PATH="$CA_DIR/account.json"
  2202. if [ -z "$ACCOUNT_KEY_PATH" ]; then
  2203. ACCOUNT_KEY_PATH="$_DEFAULT_ACCOUNT_KEY_PATH"
  2204. fi
  2205. if [ -z "$ACCOUNT_JSON_PATH" ]; then
  2206. ACCOUNT_JSON_PATH="$_DEFAULT_ACCOUNT_JSON_PATH"
  2207. fi
  2208. _DEFAULT_CERT_HOME="$LE_CONFIG_HOME"
  2209. if [ -z "$CERT_HOME" ]; then
  2210. CERT_HOME="$_DEFAULT_CERT_HOME"
  2211. fi
  2212. if [ -z "$ACME_OPENSSL_BIN" ] || [ ! -f "$ACME_OPENSSL_BIN" ] || [ ! -x "$ACME_OPENSSL_BIN" ]; then
  2213. ACME_OPENSSL_BIN="$DEFAULT_OPENSSL_BIN"
  2214. fi
  2215. if [ -z "$domain" ]; then
  2216. return 0
  2217. fi
  2218. if [ -z "$DOMAIN_PATH" ]; then
  2219. domainhome="$CERT_HOME/$domain"
  2220. domainhomeecc="$CERT_HOME/$domain$ECC_SUFFIX"
  2221. DOMAIN_PATH="$domainhome"
  2222. if _isEccKey "$_ilength"; then
  2223. DOMAIN_PATH="$domainhomeecc"
  2224. else
  2225. if [ ! -d "$domainhome" ] && [ -d "$domainhomeecc" ]; then
  2226. _info "The domain '$domain' seems to have a ECC cert already, please add '$(__red "--ecc")' parameter if you want to use that cert."
  2227. fi
  2228. fi
  2229. _debug DOMAIN_PATH "$DOMAIN_PATH"
  2230. fi
  2231. if [ -z "$DOMAIN_BACKUP_PATH" ]; then
  2232. DOMAIN_BACKUP_PATH="$DOMAIN_PATH/backup"
  2233. fi
  2234. if [ -z "$DOMAIN_CONF" ]; then
  2235. DOMAIN_CONF="$DOMAIN_PATH/$domain.conf"
  2236. fi
  2237. if [ -z "$DOMAIN_SSL_CONF" ]; then
  2238. DOMAIN_SSL_CONF="$DOMAIN_PATH/$domain.csr.conf"
  2239. fi
  2240. if [ -z "$CSR_PATH" ]; then
  2241. CSR_PATH="$DOMAIN_PATH/$domain.csr"
  2242. fi
  2243. if [ -z "$CERT_KEY_PATH" ]; then
  2244. CERT_KEY_PATH="$DOMAIN_PATH/$domain.key"
  2245. fi
  2246. if [ -z "$CERT_PATH" ]; then
  2247. CERT_PATH="$DOMAIN_PATH/$domain.cer"
  2248. fi
  2249. if [ -z "$CA_CERT_PATH" ]; then
  2250. CA_CERT_PATH="$DOMAIN_PATH/ca.cer"
  2251. fi
  2252. if [ -z "$CERT_FULLCHAIN_PATH" ]; then
  2253. CERT_FULLCHAIN_PATH="$DOMAIN_PATH/fullchain.cer"
  2254. fi
  2255. if [ -z "$CERT_PFX_PATH" ]; then
  2256. CERT_PFX_PATH="$DOMAIN_PATH/$domain.pfx"
  2257. fi
  2258. if [ -z "$CERT_PKCS8_PATH" ]; then
  2259. CERT_PKCS8_PATH="$DOMAIN_PATH/$domain.pkcs8"
  2260. fi
  2261. if [ -z "$TLS_CONF" ]; then
  2262. TLS_CONF="$DOMAIN_PATH/tls.validation.conf"
  2263. fi
  2264. if [ -z "$TLS_CERT" ]; then
  2265. TLS_CERT="$DOMAIN_PATH/tls.validation.cert"
  2266. fi
  2267. if [ -z "$TLS_KEY" ]; then
  2268. TLS_KEY="$DOMAIN_PATH/tls.validation.key"
  2269. fi
  2270. if [ -z "$TLS_CSR" ]; then
  2271. TLS_CSR="$DOMAIN_PATH/tls.validation.csr"
  2272. fi
  2273. }
  2274. _exec() {
  2275. if [ -z "$_EXEC_TEMP_ERR" ]; then
  2276. _EXEC_TEMP_ERR="$(_mktemp)"
  2277. fi
  2278. if [ "$_EXEC_TEMP_ERR" ]; then
  2279. eval "$@ 2>>$_EXEC_TEMP_ERR"
  2280. else
  2281. eval "$@"
  2282. fi
  2283. }
  2284. _exec_err() {
  2285. [ "$_EXEC_TEMP_ERR" ] && _err "$(cat "$_EXEC_TEMP_ERR")" && echo "" >"$_EXEC_TEMP_ERR"
  2286. }
  2287. _apachePath() {
  2288. _APACHECTL="apachectl"
  2289. if ! _exists apachectl; then
  2290. if _exists apache2ctl; then
  2291. _APACHECTL="apache2ctl"
  2292. else
  2293. _err "'apachectl not found. It seems that apache is not installed, or you are not root user.'"
  2294. _err "Please use webroot mode to try again."
  2295. return 1
  2296. fi
  2297. fi
  2298. if ! _exec $_APACHECTL -V >/dev/null; then
  2299. _exec_err
  2300. return 1
  2301. fi
  2302. if [ "$APACHE_HTTPD_CONF" ]; then
  2303. _saveaccountconf APACHE_HTTPD_CONF "$APACHE_HTTPD_CONF"
  2304. httpdconf="$APACHE_HTTPD_CONF"
  2305. httpdconfname="$(basename "$httpdconfname")"
  2306. else
  2307. httpdconfname="$($_APACHECTL -V | grep SERVER_CONFIG_FILE= | cut -d = -f 2 | tr -d '"')"
  2308. _debug httpdconfname "$httpdconfname"
  2309. if [ -z "$httpdconfname" ]; then
  2310. _err "Can not read apache config file."
  2311. return 1
  2312. fi
  2313. if _startswith "$httpdconfname" '/'; then
  2314. httpdconf="$httpdconfname"
  2315. httpdconfname="$(basename "$httpdconfname")"
  2316. else
  2317. httpdroot="$($_APACHECTL -V | grep HTTPD_ROOT= | cut -d = -f 2 | tr -d '"')"
  2318. _debug httpdroot "$httpdroot"
  2319. httpdconf="$httpdroot/$httpdconfname"
  2320. httpdconfname="$(basename "$httpdconfname")"
  2321. fi
  2322. fi
  2323. _debug httpdconf "$httpdconf"
  2324. _debug httpdconfname "$httpdconfname"
  2325. if [ ! -f "$httpdconf" ]; then
  2326. _err "Apache Config file not found" "$httpdconf"
  2327. return 1
  2328. fi
  2329. return 0
  2330. }
  2331. _restoreApache() {
  2332. if [ -z "$usingApache" ]; then
  2333. return 0
  2334. fi
  2335. _initpath
  2336. if ! _apachePath; then
  2337. return 1
  2338. fi
  2339. if [ ! -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname" ]; then
  2340. _debug "No config file to restore."
  2341. return 0
  2342. fi
  2343. cat "$APACHE_CONF_BACKUP_DIR/$httpdconfname" >"$httpdconf"
  2344. _debug "Restored: $httpdconf."
  2345. if ! _exec $_APACHECTL -t; then
  2346. _exec_err
  2347. _err "Sorry, restore apache config error, please contact me."
  2348. return 1
  2349. fi
  2350. _debug "Restored successfully."
  2351. rm -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname"
  2352. return 0
  2353. }
  2354. _setApache() {
  2355. _initpath
  2356. if ! _apachePath; then
  2357. return 1
  2358. fi
  2359. #test the conf first
  2360. _info "Checking if there is an error in the apache config file before starting."
  2361. if ! _exec "$_APACHECTL" -t >/dev/null; then
  2362. _exec_err
  2363. _err "The apache config file has error, please fix it first, then try again."
  2364. _err "Don't worry, there is nothing changed to your system."
  2365. return 1
  2366. else
  2367. _info "OK"
  2368. fi
  2369. #backup the conf
  2370. _debug "Backup apache config file" "$httpdconf"
  2371. if ! cp "$httpdconf" "$APACHE_CONF_BACKUP_DIR/"; then
  2372. _err "Can not backup apache config file, so abort. Don't worry, the apache config is not changed."
  2373. _err "This might be a bug of $PROJECT_NAME , please report issue: $PROJECT"
  2374. return 1
  2375. fi
  2376. _info "JFYI, Config file $httpdconf is backuped to $APACHE_CONF_BACKUP_DIR/$httpdconfname"
  2377. _info "In case there is an error that can not be restored automatically, you may try restore it yourself."
  2378. _info "The backup file will be deleted on success, just forget it."
  2379. #add alias
  2380. apacheVer="$($_APACHECTL -V | grep "Server version:" | cut -d : -f 2 | cut -d " " -f 2 | cut -d '/' -f 2)"
  2381. _debug "apacheVer" "$apacheVer"
  2382. apacheMajer="$(echo "$apacheVer" | cut -d . -f 1)"
  2383. apacheMinor="$(echo "$apacheVer" | cut -d . -f 2)"
  2384. if [ "$apacheVer" ] && [ "$apacheMajer$apacheMinor" -ge "24" ]; then
  2385. echo "
  2386. Alias /.well-known/acme-challenge $ACME_DIR
  2387. <Directory $ACME_DIR >
  2388. Require all granted
  2389. </Directory>
  2390. " >>"$httpdconf"
  2391. else
  2392. echo "
  2393. Alias /.well-known/acme-challenge $ACME_DIR
  2394. <Directory $ACME_DIR >
  2395. Order allow,deny
  2396. Allow from all
  2397. </Directory>
  2398. " >>"$httpdconf"
  2399. fi
  2400. _msg="$($_APACHECTL -t 2>&1)"
  2401. if [ "$?" != "0" ]; then
  2402. _err "Sorry, apache config error"
  2403. if _restoreApache; then
  2404. _err "The apache config file is restored."
  2405. else
  2406. _err "Sorry, The apache config file can not be restored, please report bug."
  2407. fi
  2408. return 1
  2409. fi
  2410. if [ ! -d "$ACME_DIR" ]; then
  2411. mkdir -p "$ACME_DIR"
  2412. chmod 755 "$ACME_DIR"
  2413. fi
  2414. if ! _exec "$_APACHECTL" graceful; then
  2415. _exec_err
  2416. _err "$_APACHECTL graceful error, please contact me."
  2417. _restoreApache
  2418. return 1
  2419. fi
  2420. usingApache="1"
  2421. return 0
  2422. }
  2423. #find the real nginx conf file
  2424. #backup
  2425. #set the nginx conf
  2426. #returns the real nginx conf file
  2427. _setNginx() {
  2428. _d="$1"
  2429. _croot="$2"
  2430. _thumbpt="$3"
  2431. FOUND_REAL_NGINX_CONF=""
  2432. FOUND_REAL_NGINX_CONF_LN=""
  2433. BACKUP_NGINX_CONF=""
  2434. _debug _croot "$_croot"
  2435. _start_f="$(echo "$_croot" | cut -d : -f 2)"
  2436. _debug _start_f "$_start_f"
  2437. if [ -z "$_start_f" ]; then
  2438. _debug "find start conf from nginx command"
  2439. if [ -z "$NGINX_CONF" ]; then
  2440. if ! _exists "nginx"; then
  2441. _err "nginx command is not found."
  2442. return 1
  2443. fi
  2444. NGINX_CONF="$(nginx -V 2>&1 | _egrep_o "--conf-path=[^ ]* " | tr -d " ")"
  2445. _debug NGINX_CONF "$NGINX_CONF"
  2446. NGINX_CONF="$(echo "$NGINX_CONF" | cut -d = -f 2)"
  2447. _debug NGINX_CONF "$NGINX_CONF"
  2448. if [ -z "$NGINX_CONF" ]; then
  2449. _err "Can not find nginx conf."
  2450. NGINX_CONF=""
  2451. return 1
  2452. fi
  2453. if [ ! -f "$NGINX_CONF" ]; then
  2454. _err "'$NGINX_CONF' doesn't exist."
  2455. NGINX_CONF=""
  2456. return 1
  2457. fi
  2458. _debug "Found nginx conf file:$NGINX_CONF"
  2459. fi
  2460. _start_f="$NGINX_CONF"
  2461. fi
  2462. _debug "Start detect nginx conf for $_d from:$_start_f"
  2463. if ! _checkConf "$_d" "$_start_f"; then
  2464. _err "Can not find conf file for domain $d"
  2465. return 1
  2466. fi
  2467. _info "Found conf file: $FOUND_REAL_NGINX_CONF"
  2468. _ln=$FOUND_REAL_NGINX_CONF_LN
  2469. _debug "_ln" "$_ln"
  2470. _lnn=$(_math $_ln + 1)
  2471. _debug _lnn "$_lnn"
  2472. _start_tag="$(sed -n "$_lnn,${_lnn}p" "$FOUND_REAL_NGINX_CONF")"
  2473. _debug "_start_tag" "$_start_tag"
  2474. if [ "$_start_tag" = "$NGINX_START" ]; then
  2475. _info "The domain $_d is already configured, skip"
  2476. FOUND_REAL_NGINX_CONF=""
  2477. return 0
  2478. fi
  2479. mkdir -p "$DOMAIN_BACKUP_PATH"
  2480. _backup_conf="$DOMAIN_BACKUP_PATH/$_d.nginx.conf"
  2481. _debug _backup_conf "$_backup_conf"
  2482. BACKUP_NGINX_CONF="$_backup_conf"
  2483. _info "Backup $FOUND_REAL_NGINX_CONF to $_backup_conf"
  2484. if ! cp "$FOUND_REAL_NGINX_CONF" "$_backup_conf"; then
  2485. _err "backup error."
  2486. FOUND_REAL_NGINX_CONF=""
  2487. return 1
  2488. fi
  2489. if ! _exists "nginx"; then
  2490. _err "nginx command is not found."
  2491. return 1
  2492. fi
  2493. _info "Check the nginx conf before setting up."
  2494. if ! _exec "nginx -t" >/dev/null; then
  2495. _exec_err
  2496. return 1
  2497. fi
  2498. _info "OK, Set up nginx config file"
  2499. if ! sed -n "1,${_ln}p" "$_backup_conf" >"$FOUND_REAL_NGINX_CONF"; then
  2500. cat "$_backup_conf" >"$FOUND_REAL_NGINX_CONF"
  2501. _err "write nginx conf error, but don't worry, the file is restored to the original version."
  2502. return 1
  2503. fi
  2504. echo "$NGINX_START
  2505. location ~ \"^/\.well-known/acme-challenge/([-_a-zA-Z0-9]+)\$\" {
  2506. default_type text/plain;
  2507. return 200 \"\$1.$_thumbpt\";
  2508. }
  2509. #NGINX_START
  2510. " >>"$FOUND_REAL_NGINX_CONF"
  2511. if ! sed -n "${_lnn},99999p" "$_backup_conf" >>"$FOUND_REAL_NGINX_CONF"; then
  2512. cat "$_backup_conf" >"$FOUND_REAL_NGINX_CONF"
  2513. _err "write nginx conf error, but don't worry, the file is restored."
  2514. return 1
  2515. fi
  2516. _debug3 "Modified config:$(cat $FOUND_REAL_NGINX_CONF)"
  2517. _info "nginx conf is done, let's check it again."
  2518. if ! _exec "nginx -t" >/dev/null; then
  2519. _exec_err
  2520. _err "It seems that nginx conf was broken, let's restore."
  2521. cat "$_backup_conf" >"$FOUND_REAL_NGINX_CONF"
  2522. return 1
  2523. fi
  2524. _info "Reload nginx"
  2525. if ! _exec "nginx -s reload" >/dev/null; then
  2526. _exec_err
  2527. _err "It seems that nginx reload error, let's restore."
  2528. cat "$_backup_conf" >"$FOUND_REAL_NGINX_CONF"
  2529. return 1
  2530. fi
  2531. return 0
  2532. }
  2533. #d , conf
  2534. _checkConf() {
  2535. _d="$1"
  2536. _c_file="$2"
  2537. _debug "Start _checkConf from:$_c_file"
  2538. if [ ! -f "$2" ] && ! echo "$2" | grep '*$' >/dev/null && echo "$2" | grep '*' >/dev/null; then
  2539. _debug "wildcard"
  2540. for _w_f in $2; do
  2541. if [ -f "$_w_f" ] && _checkConf "$1" "$_w_f"; then
  2542. return 0
  2543. fi
  2544. done
  2545. #not found
  2546. return 1
  2547. elif [ -f "$2" ]; then
  2548. _debug "single"
  2549. if _isRealNginxConf "$1" "$2"; then
  2550. _debug "$2 is found."
  2551. FOUND_REAL_NGINX_CONF="$2"
  2552. return 0
  2553. fi
  2554. if cat "$2" | tr "\t" " " | grep "^ *include *.*;" >/dev/null; then
  2555. _debug "Try include files"
  2556. for included in $(cat "$2" | tr "\t" " " | grep "^ *include *.*;" | sed "s/include //" | tr -d " ;"); do
  2557. _debug "check included $included"
  2558. if _checkConf "$1" "$included"; then
  2559. return 0
  2560. fi
  2561. done
  2562. fi
  2563. return 1
  2564. else
  2565. _debug "$2 not found."
  2566. return 1
  2567. fi
  2568. return 1
  2569. }
  2570. #d , conf
  2571. _isRealNginxConf() {
  2572. _debug "_isRealNginxConf $1 $2"
  2573. if [ -f "$2" ]; then
  2574. for _fln in $(tr "\t" ' ' <"$2" | grep -n "^ *server_name.* $1" | cut -d : -f 1); do
  2575. _debug _fln "$_fln"
  2576. if [ "$_fln" ]; then
  2577. _start=$(tr "\t" ' ' <"$2" | _head_n "$_fln" | grep -n "^ *server *" | grep -v server_name | _tail_n 1)
  2578. _debug "_start" "$_start"
  2579. _start_n=$(echo "$_start" | cut -d : -f 1)
  2580. _start_nn=$(_math $_start_n + 1)
  2581. _debug "_start_n" "$_start_n"
  2582. _debug "_start_nn" "$_start_nn"
  2583. _left="$(sed -n "${_start_nn},99999p" "$2")"
  2584. _debug2 _left "$_left"
  2585. _end="$(echo "$_left" | tr "\t" ' ' | grep -n "^ *server *" | grep -v server_name | _head_n 1)"
  2586. _debug "_end" "$_end"
  2587. if [ "$_end" ]; then
  2588. _end_n=$(echo "$_end" | cut -d : -f 1)
  2589. _debug "_end_n" "$_end_n"
  2590. _seg_n=$(echo "$_left" | sed -n "1,${_end_n}p")
  2591. else
  2592. _seg_n="$_left"
  2593. fi
  2594. _debug "_seg_n" "$_seg_n"
  2595. _skip_ssl=1
  2596. for _listen_i in $(echo "$_seg_n" | tr "\t" ' ' | grep "^ *listen" | tr -d " "); do
  2597. if [ "$_listen_i" ]; then
  2598. if [ "$(echo "$_listen_i" | _egrep_o "listen.*ssl")" ]; then
  2599. _debug2 "$_listen_i is ssl"
  2600. else
  2601. _debug2 "$_listen_i is plain text"
  2602. _skip_ssl=""
  2603. break
  2604. fi
  2605. fi
  2606. done
  2607. if [ "$_skip_ssl" = "1" ]; then
  2608. _debug "ssl on, skip"
  2609. else
  2610. FOUND_REAL_NGINX_CONF_LN=$_fln
  2611. _debug3 "found FOUND_REAL_NGINX_CONF_LN" "$FOUND_REAL_NGINX_CONF_LN"
  2612. return 0
  2613. fi
  2614. fi
  2615. done
  2616. fi
  2617. return 1
  2618. }
  2619. #restore all the nginx conf
  2620. _restoreNginx() {
  2621. if [ -z "$NGINX_RESTORE_VLIST" ]; then
  2622. _debug "No need to restore nginx, skip."
  2623. return
  2624. fi
  2625. _debug "_restoreNginx"
  2626. _debug "NGINX_RESTORE_VLIST" "$NGINX_RESTORE_VLIST"
  2627. for ng_entry in $(echo "$NGINX_RESTORE_VLIST" | tr "$dvsep" ' '); do
  2628. _debug "ng_entry" "$ng_entry"
  2629. _nd=$(echo "$ng_entry" | cut -d "$sep" -f 1)
  2630. _ngconf=$(echo "$ng_entry" | cut -d "$sep" -f 2)
  2631. _ngbackupconf=$(echo "$ng_entry" | cut -d "$sep" -f 3)
  2632. _info "Restoring from $_ngbackupconf to $_ngconf"
  2633. cat "$_ngbackupconf" >"$_ngconf"
  2634. done
  2635. _info "Reload nginx"
  2636. if ! _exec "nginx -s reload" >/dev/null; then
  2637. _exec_err
  2638. _err "It seems that nginx reload error, please report bug."
  2639. return 1
  2640. fi
  2641. return 0
  2642. }
  2643. _clearup() {
  2644. _stopserver "$serverproc"
  2645. serverproc=""
  2646. _restoreApache
  2647. _restoreNginx
  2648. _clearupdns
  2649. if [ -z "$DEBUG" ]; then
  2650. rm -f "$TLS_CONF"
  2651. rm -f "$TLS_CERT"
  2652. rm -f "$TLS_KEY"
  2653. rm -f "$TLS_CSR"
  2654. fi
  2655. }
  2656. _clearupdns() {
  2657. _debug "_clearupdns"
  2658. _debug "dns_entries" "$dns_entries"
  2659. if [ -z "$dns_entries" ]; then
  2660. _debug "skip dns."
  2661. return
  2662. fi
  2663. _info "Removing DNS records."
  2664. for entry in $dns_entries; do
  2665. d=$(_getfield "$entry" 1)
  2666. txtdomain=$(_getfield "$entry" 2)
  2667. aliasDomain=$(_getfield "$entry" 3)
  2668. _currentRoot=$(_getfield "$entry" 4)
  2669. txt=$(_getfield "$entry" 5)
  2670. d_api=$(_getfield "$entry" 6)
  2671. _debug "d" "$d"
  2672. _debug "txtdomain" "$txtdomain"
  2673. _debug "aliasDomain" "$aliasDomain"
  2674. _debug "_currentRoot" "$_currentRoot"
  2675. _debug "txt" "$txt"
  2676. _debug "d_api" "$d_api"
  2677. if [ "$d_api" = "$txt" ]; then
  2678. d_api=""
  2679. fi
  2680. if [ -z "$d_api" ]; then
  2681. _info "Not Found domain api file: $d_api"
  2682. continue
  2683. fi
  2684. if [ "$aliasDomain" ]; then
  2685. txtdomain="$aliasDomain"
  2686. fi
  2687. (
  2688. if ! . "$d_api"; then
  2689. _err "Load file $d_api error. Please check your api file and try again."
  2690. return 1
  2691. fi
  2692. rmcommand="${_currentRoot}_rm"
  2693. if ! _exists "$rmcommand"; then
  2694. _err "It seems that your api file doesn't define $rmcommand"
  2695. return 1
  2696. fi
  2697. _info "Removing txt: $txt for domain: $txtdomain"
  2698. if ! $rmcommand "$txtdomain" "$txt"; then
  2699. _err "Error removing txt for domain:$txtdomain"
  2700. return 1
  2701. fi
  2702. _info "Removed: Success"
  2703. )
  2704. done
  2705. }
  2706. # webroot removelevel tokenfile
  2707. _clearupwebbroot() {
  2708. __webroot="$1"
  2709. if [ -z "$__webroot" ]; then
  2710. _debug "no webroot specified, skip"
  2711. return 0
  2712. fi
  2713. _rmpath=""
  2714. if [ "$2" = '1' ]; then
  2715. _rmpath="$__webroot/.well-known"
  2716. elif [ "$2" = '2' ]; then
  2717. _rmpath="$__webroot/.well-known/acme-challenge"
  2718. elif [ "$2" = '3' ]; then
  2719. _rmpath="$__webroot/.well-known/acme-challenge/$3"
  2720. else
  2721. _debug "Skip for removelevel:$2"
  2722. fi
  2723. if [ "$_rmpath" ]; then
  2724. if [ "$DEBUG" ]; then
  2725. _debug "Debugging, skip removing: $_rmpath"
  2726. else
  2727. rm -rf "$_rmpath"
  2728. fi
  2729. fi
  2730. return 0
  2731. }
  2732. _on_before_issue() {
  2733. _chk_web_roots="$1"
  2734. _chk_main_domain="$2"
  2735. _chk_alt_domains="$3"
  2736. _chk_pre_hook="$4"
  2737. _chk_local_addr="$5"
  2738. _debug _on_before_issue
  2739. _debug _chk_main_domain "$_chk_main_domain"
  2740. _debug _chk_alt_domains "$_chk_alt_domains"
  2741. #run pre hook
  2742. if [ "$_chk_pre_hook" ]; then
  2743. _info "Run pre hook:'$_chk_pre_hook'"
  2744. if ! (
  2745. cd "$DOMAIN_PATH" && eval "$_chk_pre_hook"
  2746. ); then
  2747. _err "Error when run pre hook."
  2748. return 1
  2749. fi
  2750. fi
  2751. if _hasfield "$_chk_web_roots" "$NO_VALUE"; then
  2752. if ! _exists "socat"; then
  2753. _err "Please install socat tools first."
  2754. return 1
  2755. fi
  2756. fi
  2757. _debug Le_LocalAddress "$_chk_local_addr"
  2758. _index=1
  2759. _currentRoot=""
  2760. _addrIndex=1
  2761. _w_index=1
  2762. while true; do
  2763. d="$(echo "$_chk_main_domain,$_chk_alt_domains," | cut -d , -f "$_w_index")"
  2764. _w_index="$(_math "$_w_index" + 1)"
  2765. _debug d "$d"
  2766. if [ -z "$d" ]; then
  2767. break
  2768. fi
  2769. _debug "Check for domain" "$d"
  2770. _currentRoot="$(_getfield "$_chk_web_roots" $_index)"
  2771. _debug "_currentRoot" "$_currentRoot"
  2772. _index=$(_math $_index + 1)
  2773. _checkport=""
  2774. if [ "$_currentRoot" = "$NO_VALUE" ]; then
  2775. _info "Standalone mode."
  2776. if [ -z "$Le_HTTPPort" ]; then
  2777. Le_HTTPPort=80
  2778. _cleardomainconf "Le_HTTPPort"
  2779. else
  2780. _savedomainconf "Le_HTTPPort" "$Le_HTTPPort"
  2781. fi
  2782. _checkport="$Le_HTTPPort"
  2783. elif [ "$_currentRoot" = "$W_ALPN" ]; then
  2784. _info "Standalone alpn mode."
  2785. if [ -z "$Le_TLSPort" ]; then
  2786. Le_TLSPort=443
  2787. else
  2788. _savedomainconf "Le_TLSPort" "$Le_TLSPort"
  2789. fi
  2790. _checkport="$Le_TLSPort"
  2791. fi
  2792. if [ "$_checkport" ]; then
  2793. _debug _checkport "$_checkport"
  2794. _checkaddr="$(_getfield "$_chk_local_addr" $_addrIndex)"
  2795. _debug _checkaddr "$_checkaddr"
  2796. _addrIndex="$(_math $_addrIndex + 1)"
  2797. _netprc="$(_ss "$_checkport" | grep "$_checkport")"
  2798. netprc="$(echo "$_netprc" | grep "$_checkaddr")"
  2799. if [ -z "$netprc" ]; then
  2800. netprc="$(echo "$_netprc" | grep "$LOCAL_ANY_ADDRESS")"
  2801. fi
  2802. if [ "$netprc" ]; then
  2803. _err "$netprc"
  2804. _err "tcp port $_checkport is already used by $(echo "$netprc" | cut -d : -f 4)"
  2805. _err "Please stop it first"
  2806. return 1
  2807. fi
  2808. fi
  2809. done
  2810. if _hasfield "$_chk_web_roots" "apache"; then
  2811. if ! _setApache; then
  2812. _err "set up apache error. Report error to me."
  2813. return 1
  2814. fi
  2815. else
  2816. usingApache=""
  2817. fi
  2818. }
  2819. _on_issue_err() {
  2820. _chk_post_hook="$1"
  2821. _chk_vlist="$2"
  2822. _debug _on_issue_err
  2823. if [ "$LOG_FILE" ]; then
  2824. _err "Please check log file for more details: $LOG_FILE"
  2825. else
  2826. _err "Please add '--debug' or '--log' to check more details."
  2827. _err "See: $_DEBUG_WIKI"
  2828. fi
  2829. #run the post hook
  2830. if [ "$_chk_post_hook" ]; then
  2831. _info "Run post hook:'$_chk_post_hook'"
  2832. if ! (
  2833. cd "$DOMAIN_PATH" && eval "$_chk_post_hook"
  2834. ); then
  2835. _err "Error when run post hook."
  2836. return 1
  2837. fi
  2838. fi
  2839. #trigger the validation to flush the pending authz
  2840. _debug2 "_chk_vlist" "$_chk_vlist"
  2841. if [ "$_chk_vlist" ]; then
  2842. (
  2843. _debug2 "start to deactivate authz"
  2844. ventries=$(echo "$_chk_vlist" | tr "$dvsep" ' ')
  2845. for ventry in $ventries; do
  2846. d=$(echo "$ventry" | cut -d "$sep" -f 1)
  2847. keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
  2848. uri=$(echo "$ventry" | cut -d "$sep" -f 3)
  2849. vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
  2850. _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
  2851. __trigger_validation "$uri" "$keyauthorization"
  2852. done
  2853. )
  2854. fi
  2855. if [ "$IS_RENEW" = "1" ] && _hasfield "$Le_Webroot" "$W_DNS"; then
  2856. _err "$_DNS_MANUAL_ERR"
  2857. fi
  2858. if [ "$DEBUG" ] && [ "$DEBUG" -gt "0" ]; then
  2859. _debug "$(_dlg_versions)"
  2860. fi
  2861. }
  2862. _on_issue_success() {
  2863. _chk_post_hook="$1"
  2864. _chk_renew_hook="$2"
  2865. _debug _on_issue_success
  2866. #run the post hook
  2867. if [ "$_chk_post_hook" ]; then
  2868. _info "Run post hook:'$_chk_post_hook'"
  2869. if ! (
  2870. export CERT_PATH
  2871. export CERT_KEY_PATH
  2872. export CA_CERT_PATH
  2873. export CERT_FULLCHAIN_PATH
  2874. export Le_Domain="$_main_domain"
  2875. cd "$DOMAIN_PATH" && eval "$_chk_post_hook"
  2876. ); then
  2877. _err "Error when run post hook."
  2878. return 1
  2879. fi
  2880. fi
  2881. #run renew hook
  2882. if [ "$IS_RENEW" ] && [ "$_chk_renew_hook" ]; then
  2883. _info "Run renew hook:'$_chk_renew_hook'"
  2884. if ! (
  2885. export CERT_PATH
  2886. export CERT_KEY_PATH
  2887. export CA_CERT_PATH
  2888. export CERT_FULLCHAIN_PATH
  2889. export Le_Domain="$_main_domain"
  2890. cd "$DOMAIN_PATH" && eval "$_chk_renew_hook"
  2891. ); then
  2892. _err "Error when run renew hook."
  2893. return 1
  2894. fi
  2895. fi
  2896. if _hasfield "$Le_Webroot" "$W_DNS"; then
  2897. _err "$_DNS_MANUAL_WARN"
  2898. fi
  2899. }
  2900. registeraccount() {
  2901. _reg_length="$1"
  2902. _initpath
  2903. _regAccount "$_reg_length"
  2904. }
  2905. __calcAccountKeyHash() {
  2906. [ -f "$ACCOUNT_KEY_PATH" ] && _digest sha256 <"$ACCOUNT_KEY_PATH"
  2907. }
  2908. __calc_account_thumbprint() {
  2909. printf "%s" "$jwk" | tr -d ' ' | _digest "sha256" | _url_replace
  2910. }
  2911. #keylength
  2912. _regAccount() {
  2913. _initpath
  2914. _reg_length="$1"
  2915. _debug3 _regAccount "$_regAccount"
  2916. _initAPI
  2917. mkdir -p "$CA_DIR"
  2918. if [ ! -f "$ACCOUNT_KEY_PATH" ] && [ -f "$_OLD_ACCOUNT_KEY" ]; then
  2919. _info "mv $_OLD_ACCOUNT_KEY to $ACCOUNT_KEY_PATH"
  2920. mv "$_OLD_ACCOUNT_KEY" "$ACCOUNT_KEY_PATH"
  2921. fi
  2922. if [ ! -f "$ACCOUNT_JSON_PATH" ] && [ -f "$_OLD_ACCOUNT_JSON" ]; then
  2923. _info "mv $_OLD_ACCOUNT_JSON to $ACCOUNT_JSON_PATH"
  2924. mv "$_OLD_ACCOUNT_JSON" "$ACCOUNT_JSON_PATH"
  2925. fi
  2926. if [ ! -f "$ACCOUNT_KEY_PATH" ]; then
  2927. if ! _create_account_key "$_reg_length"; then
  2928. _err "Create account key error."
  2929. return 1
  2930. fi
  2931. fi
  2932. if ! _calcjwk "$ACCOUNT_KEY_PATH"; then
  2933. return 1
  2934. fi
  2935. if [ "$ACME_VERSION" = "2" ]; then
  2936. regjson='{"termsOfServiceAgreed": true}'
  2937. if [ "$ACCOUNT_EMAIL" ]; then
  2938. regjson='{"contact": ["mailto: '$ACCOUNT_EMAIL'"], "termsOfServiceAgreed": true}'
  2939. fi
  2940. else
  2941. _reg_res="$ACME_NEW_ACCOUNT_RES"
  2942. regjson='{"resource": "'$_reg_res'", "terms-of-service-agreed": true, "agreement": "'$ACME_AGREEMENT'"}'
  2943. if [ "$ACCOUNT_EMAIL" ]; then
  2944. regjson='{"resource": "'$_reg_res'", "contact": ["mailto: '$ACCOUNT_EMAIL'"], "terms-of-service-agreed": true, "agreement": "'$ACME_AGREEMENT'"}'
  2945. fi
  2946. fi
  2947. _info "Registering account"
  2948. if ! _send_signed_request "${ACME_NEW_ACCOUNT}" "$regjson"; then
  2949. _err "Register account Error: $response"
  2950. return 1
  2951. fi
  2952. if [ "$code" = "" ] || [ "$code" = '201' ]; then
  2953. echo "$response" >"$ACCOUNT_JSON_PATH"
  2954. _info "Registered"
  2955. elif [ "$code" = '409' ] || [ "$code" = '200' ]; then
  2956. _info "Already registered"
  2957. else
  2958. _err "Register account Error: $response"
  2959. return 1
  2960. fi
  2961. _debug2 responseHeaders "$responseHeaders"
  2962. _accUri="$(echo "$responseHeaders" | grep -i "^Location:" | _head_n 1 | cut -d ' ' -f 2 | tr -d "\r\n")"
  2963. _debug "_accUri" "$_accUri"
  2964. if [ -z "$_accUri" ]; then
  2965. _err "Can not find account id url."
  2966. _err "$responseHeaders"
  2967. return 1
  2968. fi
  2969. _savecaconf "ACCOUNT_URL" "$_accUri"
  2970. export ACCOUNT_URL="$_accUri"
  2971. CA_KEY_HASH="$(__calcAccountKeyHash)"
  2972. _debug "Calc CA_KEY_HASH" "$CA_KEY_HASH"
  2973. _savecaconf CA_KEY_HASH "$CA_KEY_HASH"
  2974. if [ "$code" = '403' ]; then
  2975. _err "It seems that the account key is already deactivated, please use a new account key."
  2976. return 1
  2977. fi
  2978. ACCOUNT_THUMBPRINT="$(__calc_account_thumbprint)"
  2979. _info "ACCOUNT_THUMBPRINT" "$ACCOUNT_THUMBPRINT"
  2980. }
  2981. #implement updateaccount
  2982. updateaccount() {
  2983. _initpath
  2984. if [ ! -f "$ACCOUNT_KEY_PATH" ] && [ -f "$_OLD_ACCOUNT_KEY" ]; then
  2985. _info "mv $_OLD_ACCOUNT_KEY to $ACCOUNT_KEY_PATH"
  2986. mv "$_OLD_ACCOUNT_KEY" "$ACCOUNT_KEY_PATH"
  2987. fi
  2988. if [ ! -f "$ACCOUNT_JSON_PATH" ] && [ -f "$_OLD_ACCOUNT_JSON" ]; then
  2989. _info "mv $_OLD_ACCOUNT_JSON to $ACCOUNT_JSON_PATH"
  2990. mv "$_OLD_ACCOUNT_JSON" "$ACCOUNT_JSON_PATH"
  2991. fi
  2992. if [ ! -f "$ACCOUNT_KEY_PATH" ]; then
  2993. _err "Account key is not found at: $ACCOUNT_KEY_PATH"
  2994. return 1
  2995. fi
  2996. _accUri=$(_readcaconf "ACCOUNT_URL")
  2997. _debug _accUri "$_accUri"
  2998. if [ -z "$_accUri" ]; then
  2999. _err "The account url is empty, please run '--update-account' first to update the account info first,"
  3000. _err "Then try again."
  3001. return 1
  3002. fi
  3003. if ! _calcjwk "$ACCOUNT_KEY_PATH"; then
  3004. return 1
  3005. fi
  3006. _initAPI
  3007. if [ "$ACME_VERSION" = "2" ]; then
  3008. if [ "$ACCOUNT_EMAIL" ]; then
  3009. updjson='{"contact": ["mailto: '$ACCOUNT_EMAIL'"]}'
  3010. fi
  3011. else
  3012. # ACMEv1: Updates happen the same way a registration is done.
  3013. # https://tools.ietf.org/html/draft-ietf-acme-acme-01#section-6.3
  3014. _regAccount
  3015. return
  3016. fi
  3017. # this part handles ACMEv2 account updates.
  3018. _send_signed_request "$_accUri" "$updjson"
  3019. if [ "$code" = '200' ]; then
  3020. _info "account update success for $_accUri."
  3021. else
  3022. _info "Error. The account was not updated."
  3023. return 1
  3024. fi
  3025. }
  3026. #Implement deactivate account
  3027. deactivateaccount() {
  3028. _initpath
  3029. if [ ! -f "$ACCOUNT_KEY_PATH" ] && [ -f "$_OLD_ACCOUNT_KEY" ]; then
  3030. _info "mv $_OLD_ACCOUNT_KEY to $ACCOUNT_KEY_PATH"
  3031. mv "$_OLD_ACCOUNT_KEY" "$ACCOUNT_KEY_PATH"
  3032. fi
  3033. if [ ! -f "$ACCOUNT_JSON_PATH" ] && [ -f "$_OLD_ACCOUNT_JSON" ]; then
  3034. _info "mv $_OLD_ACCOUNT_JSON to $ACCOUNT_JSON_PATH"
  3035. mv "$_OLD_ACCOUNT_JSON" "$ACCOUNT_JSON_PATH"
  3036. fi
  3037. if [ ! -f "$ACCOUNT_KEY_PATH" ]; then
  3038. _err "Account key is not found at: $ACCOUNT_KEY_PATH"
  3039. return 1
  3040. fi
  3041. _accUri=$(_readcaconf "ACCOUNT_URL")
  3042. _debug _accUri "$_accUri"
  3043. if [ -z "$_accUri" ]; then
  3044. _err "The account url is empty, please run '--update-account' first to update the account info first,"
  3045. _err "Then try again."
  3046. return 1
  3047. fi
  3048. if ! _calcjwk "$ACCOUNT_KEY_PATH"; then
  3049. return 1
  3050. fi
  3051. _initAPI
  3052. if [ "$ACME_VERSION" = "2" ]; then
  3053. _djson="{\"status\":\"deactivated\"}"
  3054. else
  3055. _djson="{\"resource\": \"reg\", \"status\":\"deactivated\"}"
  3056. fi
  3057. if _send_signed_request "$_accUri" "$_djson" && _contains "$response" '"deactivated"'; then
  3058. _info "Deactivate account success for $_accUri."
  3059. _accid=$(echo "$response" | _egrep_o "\"id\" *: *[^,]*," | cut -d : -f 2 | tr -d ' ,')
  3060. elif [ "$code" = "403" ]; then
  3061. _info "The account is already deactivated."
  3062. _accid=$(_getfield "$_accUri" "999" "/")
  3063. else
  3064. _err "Deactivate: account failed for $_accUri."
  3065. return 1
  3066. fi
  3067. _debug "Account id: $_accid"
  3068. if [ "$_accid" ]; then
  3069. _deactivated_account_path="$CA_DIR/deactivated/$_accid"
  3070. _debug _deactivated_account_path "$_deactivated_account_path"
  3071. if mkdir -p "$_deactivated_account_path"; then
  3072. _info "Moving deactivated account info to $_deactivated_account_path/"
  3073. mv "$CA_CONF" "$_deactivated_account_path/"
  3074. mv "$ACCOUNT_JSON_PATH" "$_deactivated_account_path/"
  3075. mv "$ACCOUNT_KEY_PATH" "$_deactivated_account_path/"
  3076. else
  3077. _err "Can not create dir: $_deactivated_account_path, try to remove the deactivated account key."
  3078. rm -f "$CA_CONF"
  3079. rm -f "$ACCOUNT_JSON_PATH"
  3080. rm -f "$ACCOUNT_KEY_PATH"
  3081. fi
  3082. fi
  3083. }
  3084. # domain folder file
  3085. _findHook() {
  3086. _hookdomain="$1"
  3087. _hookcat="$2"
  3088. _hookname="$3"
  3089. if [ -f "$_SCRIPT_HOME/$_hookcat/$_hookname" ]; then
  3090. d_api="$_SCRIPT_HOME/$_hookcat/$_hookname"
  3091. elif [ -f "$_SCRIPT_HOME/$_hookcat/$_hookname.sh" ]; then
  3092. d_api="$_SCRIPT_HOME/$_hookcat/$_hookname.sh"
  3093. elif [ "$_hookdomain" ] && [ -f "$LE_WORKING_DIR/$_hookdomain/$_hookname" ]; then
  3094. d_api="$LE_WORKING_DIR/$_hookdomain/$_hookname"
  3095. elif [ "$_hookdomain" ] && [ -f "$LE_WORKING_DIR/$_hookdomain/$_hookname.sh" ]; then
  3096. d_api="$LE_WORKING_DIR/$_hookdomain/$_hookname.sh"
  3097. elif [ -f "$LE_WORKING_DIR/$_hookname" ]; then
  3098. d_api="$LE_WORKING_DIR/$_hookname"
  3099. elif [ -f "$LE_WORKING_DIR/$_hookname.sh" ]; then
  3100. d_api="$LE_WORKING_DIR/$_hookname.sh"
  3101. elif [ -f "$LE_WORKING_DIR/$_hookcat/$_hookname" ]; then
  3102. d_api="$LE_WORKING_DIR/$_hookcat/$_hookname"
  3103. elif [ -f "$LE_WORKING_DIR/$_hookcat/$_hookname.sh" ]; then
  3104. d_api="$LE_WORKING_DIR/$_hookcat/$_hookname.sh"
  3105. fi
  3106. printf "%s" "$d_api"
  3107. }
  3108. #domain
  3109. __get_domain_new_authz() {
  3110. _gdnd="$1"
  3111. _info "Getting new-authz for domain" "$_gdnd"
  3112. _initAPI
  3113. _Max_new_authz_retry_times=5
  3114. _authz_i=0
  3115. while [ "$_authz_i" -lt "$_Max_new_authz_retry_times" ]; do
  3116. _debug "Try new-authz for the $_authz_i time."
  3117. if ! _send_signed_request "${ACME_NEW_AUTHZ}" "{\"resource\": \"new-authz\", \"identifier\": {\"type\": \"dns\", \"value\": \"$(_idn "$_gdnd")\"}}"; then
  3118. _err "Can not get domain new authz."
  3119. return 1
  3120. fi
  3121. if _contains "$response" "No registration exists matching provided key"; then
  3122. _err "It seems there is an error, but it's recovered now, please try again."
  3123. _err "If you see this message for a second time, please report bug: $(__green "$PROJECT")"
  3124. _clearcaconf "CA_KEY_HASH"
  3125. break
  3126. fi
  3127. if ! _contains "$response" "An error occurred while processing your request"; then
  3128. _info "The new-authz request is ok."
  3129. break
  3130. fi
  3131. _authz_i="$(_math "$_authz_i" + 1)"
  3132. _info "The server is busy, Sleep $_authz_i to retry."
  3133. _sleep "$_authz_i"
  3134. done
  3135. if [ "$_authz_i" = "$_Max_new_authz_retry_times" ]; then
  3136. _err "new-authz retry reach the max $_Max_new_authz_retry_times times."
  3137. fi
  3138. if [ "$code" ] && [ "$code" != '201' ]; then
  3139. _err "new-authz error: $response"
  3140. return 1
  3141. fi
  3142. }
  3143. #uri keyAuthorization
  3144. __trigger_validation() {
  3145. _debug2 "Trigger domain validation."
  3146. _t_url="$1"
  3147. _debug2 _t_url "$_t_url"
  3148. _t_key_authz="$2"
  3149. _debug2 _t_key_authz "$_t_key_authz"
  3150. _t_vtype="$3"
  3151. _debug2 _t_vtype "$_t_vtype"
  3152. if [ "$ACME_VERSION" = "2" ]; then
  3153. _send_signed_request "$_t_url" "{}"
  3154. else
  3155. _send_signed_request "$_t_url" "{\"resource\": \"challenge\", \"type\": \"$_t_vtype\", \"keyAuthorization\": \"$_t_key_authz\"}"
  3156. fi
  3157. }
  3158. #endpoint domain type
  3159. _ns_lookup() {
  3160. _ns_ep="$1"
  3161. _ns_domain="$2"
  3162. _ns_type="$3"
  3163. _debug2 "_ns_ep" "$_ns_ep"
  3164. _debug2 "_ns_domain" "$_ns_domain"
  3165. _debug2 "_ns_type" "$_ns_type"
  3166. response="$(_H1="accept: application/dns-json" _get "$_ns_ep?name=$_ns_domain&type=$_ns_type")"
  3167. _ret=$?
  3168. _debug2 "response" "$response"
  3169. if [ "$_ret" != "0" ]; then
  3170. return $_ret
  3171. fi
  3172. _answers="$(echo "$response" | tr '{}' '<>' | _egrep_o '"Answer":\[[^]]*]' | tr '<>' '\n\n')"
  3173. _debug2 "_answers" "$_answers"
  3174. echo "$_answers"
  3175. }
  3176. #domain, type
  3177. _ns_lookup_cf() {
  3178. _cf_ld="$1"
  3179. _cf_ld_type="$2"
  3180. _cf_ep="https://cloudflare-dns.com/dns-query"
  3181. _ns_lookup "$_cf_ep" "$_cf_ld" "$_cf_ld_type"
  3182. }
  3183. #domain, type
  3184. _ns_purge_cf() {
  3185. _cf_d="$1"
  3186. _cf_d_type="$2"
  3187. _debug "Cloudflare purge $_cf_d_type record for domain $_cf_d"
  3188. _cf_purl="https://cloudflare-dns.com/api/v1/purge?domain=$_cf_d&type=$_cf_d_type"
  3189. response="$(_post "" "$_cf_purl")"
  3190. _debug2 response "$response"
  3191. }
  3192. #txtdomain, alias, txt
  3193. __check_txt() {
  3194. _c_txtdomain="$1"
  3195. _c_aliasdomain="$2"
  3196. _c_txt="$3"
  3197. _debug "_c_txtdomain" "$_c_txtdomain"
  3198. _debug "_c_aliasdomain" "$_c_aliasdomain"
  3199. _debug "_c_txt" "$_c_txt"
  3200. _answers="$(_ns_lookup_cf "$_c_aliasdomain" TXT)"
  3201. _contains "$_answers" "$_c_txt"
  3202. }
  3203. #txtdomain
  3204. __purge_txt() {
  3205. _p_txtdomain="$1"
  3206. _debug _p_txtdomain "$_p_txtdomain"
  3207. _ns_purge_cf "$_p_txtdomain" "TXT"
  3208. }
  3209. #wait and check each dns entries
  3210. _check_dns_entries() {
  3211. _success_txt=","
  3212. _end_time="$(_time)"
  3213. _end_time="$(_math "$_end_time" + 1200)" #let's check no more than 20 minutes.
  3214. while [ "$(_time)" -le "$_end_time" ]; do
  3215. _left=""
  3216. for entry in $dns_entries; do
  3217. d=$(_getfield "$entry" 1)
  3218. txtdomain=$(_getfield "$entry" 2)
  3219. txtdomain=$(_idn "$txtdomain")
  3220. aliasDomain=$(_getfield "$entry" 3)
  3221. aliasDomain=$(_idn "$aliasDomain")
  3222. txt=$(_getfield "$entry" 5)
  3223. d_api=$(_getfield "$entry" 6)
  3224. _debug "d" "$d"
  3225. _debug "txtdomain" "$txtdomain"
  3226. _debug "aliasDomain" "$aliasDomain"
  3227. _debug "txt" "$txt"
  3228. _debug "d_api" "$d_api"
  3229. _info "Checking $d for $aliasDomain"
  3230. if _contains "$_success_txt" ",$txt,"; then
  3231. _info "Already success, continue next one."
  3232. continue
  3233. fi
  3234. if __check_txt "$txtdomain" "$aliasDomain" "$txt"; then
  3235. _info "Domain $d '$aliasDomain' success."
  3236. _success_txt="$_success_txt,$txt,"
  3237. continue
  3238. fi
  3239. _left=1
  3240. _info "Not valid yet, let's wait 10 seconds and check next one."
  3241. __purge_txt "$txtdomain"
  3242. if [ "$txtdomain" != "$aliasDomain" ]; then
  3243. __purge_txt "$aliasDomain"
  3244. fi
  3245. _sleep 10
  3246. done
  3247. if [ "$_left" ]; then
  3248. _info "Let's wait 10 seconds and check again".
  3249. _sleep 10
  3250. else
  3251. _info "All success, let's return"
  3252. break
  3253. fi
  3254. done
  3255. }
  3256. #webroot, domain domainlist keylength
  3257. issue() {
  3258. if [ -z "$2" ]; then
  3259. _usage "Usage: $PROJECT_ENTRY --issue -d a.com -w /path/to/webroot/a.com/ "
  3260. return 1
  3261. fi
  3262. if [ -z "$1" ]; then
  3263. _usage "Please specify at least one validation method: '--webroot', '--standalone', '--apache', '--nginx' or '--dns' etc."
  3264. return 1
  3265. fi
  3266. _web_roots="$1"
  3267. _main_domain="$2"
  3268. _alt_domains="$3"
  3269. if _contains "$_main_domain" ","; then
  3270. _main_domain=$(echo "$2,$3" | cut -d , -f 1)
  3271. _alt_domains=$(echo "$2,$3" | cut -d , -f 2- | sed "s/,${NO_VALUE}$//")
  3272. fi
  3273. _debug _main_domain "$_main_domain"
  3274. _debug _alt_domains "$_alt_domains"
  3275. _key_length="$4"
  3276. _real_cert="$5"
  3277. _real_key="$6"
  3278. _real_ca="$7"
  3279. _reload_cmd="$8"
  3280. _real_fullchain="$9"
  3281. _pre_hook="${10}"
  3282. _post_hook="${11}"
  3283. _renew_hook="${12}"
  3284. _local_addr="${13}"
  3285. _challenge_alias="${14}"
  3286. #remove these later.
  3287. if [ "$_web_roots" = "dns-cf" ]; then
  3288. _web_roots="dns_cf"
  3289. fi
  3290. if [ "$_web_roots" = "dns-dp" ]; then
  3291. _web_roots="dns_dp"
  3292. fi
  3293. if [ "$_web_roots" = "dns-cx" ]; then
  3294. _web_roots="dns_cx"
  3295. fi
  3296. if [ ! "$IS_RENEW" ]; then
  3297. _initpath "$_main_domain" "$_key_length"
  3298. mkdir -p "$DOMAIN_PATH"
  3299. fi
  3300. if _hasfield "$_web_roots" "$W_DNS" && [ -z "$FORCE_DNS_MANUAL" ]; then
  3301. _err "$_DNS_MANUAL_ERROR"
  3302. return 1
  3303. fi
  3304. _debug "Using ACME_DIRECTORY: $ACME_DIRECTORY"
  3305. _initAPI
  3306. if [ -f "$DOMAIN_CONF" ]; then
  3307. Le_NextRenewTime=$(_readdomainconf Le_NextRenewTime)
  3308. _debug Le_NextRenewTime "$Le_NextRenewTime"
  3309. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(_time)" -lt "$Le_NextRenewTime" ]; then
  3310. _saved_domain=$(_readdomainconf Le_Domain)
  3311. _debug _saved_domain "$_saved_domain"
  3312. _saved_alt=$(_readdomainconf Le_Alt)
  3313. _debug _saved_alt "$_saved_alt"
  3314. if [ "$_saved_domain,$_saved_alt" = "$_main_domain,$_alt_domains" ]; then
  3315. _info "Domains not changed."
  3316. _info "Skip, Next renewal time is: $(__green "$(_readdomainconf Le_NextRenewTimeStr)")"
  3317. _info "Add '$(__red '--force')' to force to renew."
  3318. return $RENEW_SKIP
  3319. else
  3320. _info "Domains have changed."
  3321. fi
  3322. fi
  3323. fi
  3324. _savedomainconf "Le_Domain" "$_main_domain"
  3325. _savedomainconf "Le_Alt" "$_alt_domains"
  3326. _savedomainconf "Le_Webroot" "$_web_roots"
  3327. _savedomainconf "Le_PreHook" "$_pre_hook" "base64"
  3328. _savedomainconf "Le_PostHook" "$_post_hook" "base64"
  3329. _savedomainconf "Le_RenewHook" "$_renew_hook" "base64"
  3330. if [ "$_local_addr" ]; then
  3331. _savedomainconf "Le_LocalAddress" "$_local_addr"
  3332. else
  3333. _cleardomainconf "Le_LocalAddress"
  3334. fi
  3335. if [ "$_challenge_alias" ]; then
  3336. _savedomainconf "Le_ChallengeAlias" "$_challenge_alias"
  3337. else
  3338. _cleardomainconf "Le_ChallengeAlias"
  3339. fi
  3340. if [ "$ACME_DIRECTORY" != "$DEFAULT_CA" ]; then
  3341. Le_API="$ACME_DIRECTORY"
  3342. _savedomainconf "Le_API" "$Le_API"
  3343. else
  3344. _cleardomainconf Le_API
  3345. fi
  3346. if [ "$_alt_domains" = "$NO_VALUE" ]; then
  3347. _alt_domains=""
  3348. fi
  3349. if [ "$_key_length" = "$NO_VALUE" ]; then
  3350. _key_length=""
  3351. fi
  3352. if ! _on_before_issue "$_web_roots" "$_main_domain" "$_alt_domains" "$_pre_hook" "$_local_addr"; then
  3353. _err "_on_before_issue."
  3354. return 1
  3355. fi
  3356. _saved_account_key_hash="$(_readcaconf "CA_KEY_HASH")"
  3357. _debug2 _saved_account_key_hash "$_saved_account_key_hash"
  3358. if [ -z "$ACCOUNT_URL" ] || [ -z "$_saved_account_key_hash" ] || [ "$_saved_account_key_hash" != "$(__calcAccountKeyHash)" ]; then
  3359. if ! _regAccount "$_accountkeylength"; then
  3360. _on_issue_err "$_post_hook"
  3361. return 1
  3362. fi
  3363. else
  3364. _debug "_saved_account_key_hash is not changed, skip register account."
  3365. fi
  3366. if [ -f "$CSR_PATH" ] && [ ! -f "$CERT_KEY_PATH" ]; then
  3367. _info "Signing from existing CSR."
  3368. else
  3369. _key=$(_readdomainconf Le_Keylength)
  3370. _debug "Read key length:$_key"
  3371. if [ ! -f "$CERT_KEY_PATH" ] || [ "$_key_length" != "$_key" ] || [ "$Le_ForceNewDomainKey" = "1" ]; then
  3372. if ! createDomainKey "$_main_domain" "$_key_length"; then
  3373. _err "Create domain key error."
  3374. _clearup
  3375. _on_issue_err "$_post_hook"
  3376. return 1
  3377. fi
  3378. fi
  3379. if ! _createcsr "$_main_domain" "$_alt_domains" "$CERT_KEY_PATH" "$CSR_PATH" "$DOMAIN_SSL_CONF"; then
  3380. _err "Create CSR error."
  3381. _clearup
  3382. _on_issue_err "$_post_hook"
  3383. return 1
  3384. fi
  3385. fi
  3386. _savedomainconf "Le_Keylength" "$_key_length"
  3387. vlist="$Le_Vlist"
  3388. _cleardomainconf "Le_Vlist"
  3389. _info "Getting domain auth token for each domain"
  3390. sep='#'
  3391. dvsep=','
  3392. if [ -z "$vlist" ]; then
  3393. if [ "$ACME_VERSION" = "2" ]; then
  3394. #make new order request
  3395. _identifiers="{\"type\":\"dns\",\"value\":\"$(_idn "$_main_domain")\"}"
  3396. _w_index=1
  3397. while true; do
  3398. d="$(echo "$_alt_domains," | cut -d , -f "$_w_index")"
  3399. _w_index="$(_math "$_w_index" + 1)"
  3400. _debug d "$d"
  3401. if [ -z "$d" ]; then
  3402. break
  3403. fi
  3404. _identifiers="$_identifiers,{\"type\":\"dns\",\"value\":\"$(_idn "$d")\"}"
  3405. done
  3406. _debug2 _identifiers "$_identifiers"
  3407. if ! _send_signed_request "$ACME_NEW_ORDER" "{\"identifiers\": [$_identifiers]}"; then
  3408. _err "Create new order error."
  3409. _clearup
  3410. _on_issue_err "$_post_hook"
  3411. return 1
  3412. fi
  3413. Le_LinkOrder="$(echo "$responseHeaders" | grep -i '^Location.*$' | _tail_n 1 | tr -d "\r\n" | cut -d " " -f 2)"
  3414. _debug Le_LinkOrder "$Le_LinkOrder"
  3415. Le_OrderFinalize="$(echo "$response" | _egrep_o '"finalize" *: *"[^"]*"' | cut -d '"' -f 4)"
  3416. _debug Le_OrderFinalize "$Le_OrderFinalize"
  3417. if [ -z "$Le_OrderFinalize" ]; then
  3418. _err "Create new order error. Le_OrderFinalize not found. $response"
  3419. _clearup
  3420. _on_issue_err "$_post_hook"
  3421. return 1
  3422. fi
  3423. #for dns manual mode
  3424. _savedomainconf "Le_OrderFinalize" "$Le_OrderFinalize"
  3425. _authorizations_seg="$(echo "$response" | _egrep_o '"authorizations" *: *\[[^\]*\]' | cut -d '[' -f 2 | tr -d ']' | tr -d '"')"
  3426. _debug2 _authorizations_seg "$_authorizations_seg"
  3427. if [ -z "$_authorizations_seg" ]; then
  3428. _err "_authorizations_seg not found."
  3429. _clearup
  3430. _on_issue_err "$_post_hook"
  3431. return 1
  3432. fi
  3433. #domain and authz map
  3434. _authorizations_map=""
  3435. for _authz_url in $(echo "$_authorizations_seg" | tr ',' ' '); do
  3436. _debug2 "_authz_url" "$_authz_url"
  3437. if ! _send_signed_request "$_authz_url"; then
  3438. _err "get to authz error."
  3439. _err "_authorizations_seg" "$_authorizations_seg"
  3440. _err "_authz_url" "$_authz_url"
  3441. _clearup
  3442. _on_issue_err "$_post_hook"
  3443. return 1
  3444. fi
  3445. response="$(echo "$response" | _normalizeJson)"
  3446. _debug2 response "$response"
  3447. _d="$(echo "$response" | _egrep_o '"value" *: *"[^"]*"' | cut -d : -f 2 | tr -d ' "')"
  3448. if _contains "$response" "\"wildcard\" *: *true"; then
  3449. _d="*.$_d"
  3450. fi
  3451. _debug2 _d "$_d"
  3452. _authorizations_map="$_d,$response
  3453. $_authorizations_map"
  3454. done
  3455. _debug2 _authorizations_map "$_authorizations_map"
  3456. fi
  3457. _index=0
  3458. _currentRoot=""
  3459. _w_index=1
  3460. while true; do
  3461. d="$(echo "$_main_domain,$_alt_domains," | cut -d , -f "$_w_index")"
  3462. _w_index="$(_math "$_w_index" + 1)"
  3463. _debug d "$d"
  3464. if [ -z "$d" ]; then
  3465. break
  3466. fi
  3467. _info "Getting webroot for domain" "$d"
  3468. _index=$(_math $_index + 1)
  3469. _w="$(echo $_web_roots | cut -d , -f $_index)"
  3470. _debug _w "$_w"
  3471. if [ "$_w" ]; then
  3472. _currentRoot="$_w"
  3473. fi
  3474. _debug "_currentRoot" "$_currentRoot"
  3475. vtype="$VTYPE_HTTP"
  3476. #todo, v2 wildcard force to use dns
  3477. if _startswith "$_currentRoot" "$W_DNS"; then
  3478. vtype="$VTYPE_DNS"
  3479. fi
  3480. if [ "$_currentRoot" = "$W_ALPN" ]; then
  3481. vtype="$VTYPE_ALPN"
  3482. fi
  3483. if [ "$ACME_VERSION" = "2" ]; then
  3484. response="$(echo "$_authorizations_map" | grep "^$(_idn "$d")," | sed "s/$d,//")"
  3485. _debug2 "response" "$response"
  3486. if [ -z "$response" ]; then
  3487. _err "get to authz error."
  3488. _err "_authorizations_map" "$_authorizations_map"
  3489. _clearup
  3490. _on_issue_err "$_post_hook"
  3491. return 1
  3492. fi
  3493. else
  3494. if ! __get_domain_new_authz "$d"; then
  3495. _clearup
  3496. _on_issue_err "$_post_hook"
  3497. return 1
  3498. fi
  3499. fi
  3500. if [ -z "$thumbprint" ]; then
  3501. thumbprint="$(__calc_account_thumbprint)"
  3502. fi
  3503. entry="$(echo "$response" | _egrep_o '[^\{]*"type":"'$vtype'"[^\}]*')"
  3504. _debug entry "$entry"
  3505. if [ -z "$entry" ]; then
  3506. _err "Error, can not get domain token entry $d"
  3507. _supported_vtypes="$(echo "$response" | _egrep_o "\"challenges\":\[[^]]*]" | tr '{' "\n" | grep type | cut -d '"' -f 4 | tr "\n" ' ')"
  3508. if [ "$_supported_vtypes" ]; then
  3509. _err "The supported validation types are: $_supported_vtypes, but you specified: $vtype"
  3510. fi
  3511. _clearup
  3512. _on_issue_err "$_post_hook"
  3513. return 1
  3514. fi
  3515. token="$(echo "$entry" | _egrep_o '"token":"[^"]*' | cut -d : -f 2 | tr -d '"')"
  3516. _debug token "$token"
  3517. if [ -z "$token" ]; then
  3518. _err "Error, can not get domain token $entry"
  3519. _clearup
  3520. _on_issue_err "$_post_hook"
  3521. return 1
  3522. fi
  3523. if [ "$ACME_VERSION" = "2" ]; then
  3524. uri="$(echo "$entry" | _egrep_o '"url":"[^"]*' | cut -d '"' -f 4 | _head_n 1)"
  3525. else
  3526. uri="$(echo "$entry" | _egrep_o '"uri":"[^"]*' | cut -d '"' -f 4)"
  3527. fi
  3528. _debug uri "$uri"
  3529. if [ -z "$uri" ]; then
  3530. _err "Error, can not get domain uri. $entry"
  3531. _clearup
  3532. _on_issue_err "$_post_hook"
  3533. return 1
  3534. fi
  3535. keyauthorization="$token.$thumbprint"
  3536. _debug keyauthorization "$keyauthorization"
  3537. if printf "%s" "$response" | grep '"status":"valid"' >/dev/null 2>&1; then
  3538. _debug "$d is already verified."
  3539. keyauthorization="$STATE_VERIFIED"
  3540. _debug keyauthorization "$keyauthorization"
  3541. fi
  3542. dvlist="$d$sep$keyauthorization$sep$uri$sep$vtype$sep$_currentRoot"
  3543. _debug dvlist "$dvlist"
  3544. vlist="$vlist$dvlist$dvsep"
  3545. done
  3546. _debug vlist "$vlist"
  3547. #add entry
  3548. dns_entries=""
  3549. dnsadded=""
  3550. ventries=$(echo "$vlist" | tr "$dvsep" ' ')
  3551. _alias_index=1
  3552. for ventry in $ventries; do
  3553. d=$(echo "$ventry" | cut -d "$sep" -f 1)
  3554. keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
  3555. vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
  3556. _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
  3557. _debug d "$d"
  3558. if [ "$keyauthorization" = "$STATE_VERIFIED" ]; then
  3559. _debug "$d is already verified, skip $vtype."
  3560. _alias_index="$(_math "$_alias_index" + 1)"
  3561. continue
  3562. fi
  3563. if [ "$vtype" = "$VTYPE_DNS" ]; then
  3564. dnsadded='0'
  3565. _dns_root_d="$d"
  3566. if _startswith "$_dns_root_d" "*."; then
  3567. _dns_root_d="$(echo "$_dns_root_d" | sed 's/*.//')"
  3568. fi
  3569. _d_alias="$(_getfield "$_challenge_alias" "$_alias_index")"
  3570. _alias_index="$(_math "$_alias_index" + 1)"
  3571. _debug "_d_alias" "$_d_alias"
  3572. if [ "$_d_alias" ]; then
  3573. if _startswith "$_d_alias" "$DNS_ALIAS_PREFIX"; then
  3574. txtdomain="$(echo "$_d_alias" | sed "s/$DNS_ALIAS_PREFIX//")"
  3575. else
  3576. txtdomain="_acme-challenge.$_d_alias"
  3577. fi
  3578. dns_entry="${_dns_root_d}${dvsep}_acme-challenge.$_dns_root_d$dvsep$txtdomain$dvsep$_currentRoot"
  3579. else
  3580. txtdomain="_acme-challenge.$_dns_root_d"
  3581. dns_entry="${_dns_root_d}${dvsep}_acme-challenge.$_dns_root_d$dvsep$dvsep$_currentRoot"
  3582. fi
  3583. _debug txtdomain "$txtdomain"
  3584. txt="$(printf "%s" "$keyauthorization" | _digest "sha256" | _url_replace)"
  3585. _debug txt "$txt"
  3586. d_api="$(_findHook "$_dns_root_d" $_SUB_FOLDER_DNSAPI "$_currentRoot")"
  3587. _debug d_api "$d_api"
  3588. dns_entry="$dns_entry$dvsep$txt${dvsep}$d_api"
  3589. _debug2 dns_entry "$dns_entry"
  3590. if [ "$d_api" ]; then
  3591. _debug "Found domain api file: $d_api"
  3592. else
  3593. if [ "$_currentRoot" != "$W_DNS" ]; then
  3594. _err "Can not find dns api hook for: $_currentRoot"
  3595. _info "You need to add the txt record manually."
  3596. fi
  3597. _info "$(__red "Add the following TXT record:")"
  3598. _info "$(__red "Domain: '$(__green "$txtdomain")'")"
  3599. _info "$(__red "TXT value: '$(__green "$txt")'")"
  3600. _info "$(__red "Please be aware that you prepend _acme-challenge. before your domain")"
  3601. _info "$(__red "so the resulting subdomain will be: $txtdomain")"
  3602. continue
  3603. fi
  3604. (
  3605. if ! . "$d_api"; then
  3606. _err "Load file $d_api error. Please check your api file and try again."
  3607. return 1
  3608. fi
  3609. addcommand="${_currentRoot}_add"
  3610. if ! _exists "$addcommand"; then
  3611. _err "It seems that your api file is not correct, it must have a function named: $addcommand"
  3612. return 1
  3613. fi
  3614. _info "Adding txt value: $txt for domain: $txtdomain"
  3615. if ! $addcommand "$txtdomain" "$txt"; then
  3616. _err "Error add txt for domain:$txtdomain"
  3617. return 1
  3618. fi
  3619. _info "The txt record is added: Success."
  3620. )
  3621. if [ "$?" != "0" ]; then
  3622. _on_issue_err "$_post_hook" "$vlist"
  3623. _clearup
  3624. return 1
  3625. fi
  3626. dns_entries="$dns_entries$dns_entry
  3627. "
  3628. _debug2 "$dns_entries"
  3629. dnsadded='1'
  3630. fi
  3631. done
  3632. if [ "$dnsadded" = '0' ]; then
  3633. _savedomainconf "Le_Vlist" "$vlist"
  3634. _debug "Dns record not added yet, so, save to $DOMAIN_CONF and exit."
  3635. _err "Please add the TXT records to the domains, and re-run with --renew."
  3636. _on_issue_err "$_post_hook"
  3637. _clearup
  3638. return 1
  3639. fi
  3640. fi
  3641. if [ "$dns_entries" ]; then
  3642. if [ -z "$Le_DNSSleep" ]; then
  3643. _info "Let's check each dns records now. Sleep 20 seconds first."
  3644. _sleep 20
  3645. if ! _check_dns_entries; then
  3646. _err "check dns error."
  3647. _on_issue_err "$_post_hook"
  3648. _clearup
  3649. return 1
  3650. fi
  3651. else
  3652. _savedomainconf "Le_DNSSleep" "$Le_DNSSleep"
  3653. _info "Sleep $(__green $Le_DNSSleep) seconds for the txt records to take effect"
  3654. _sleep "$Le_DNSSleep"
  3655. fi
  3656. fi
  3657. NGINX_RESTORE_VLIST=""
  3658. _debug "ok, let's start to verify"
  3659. _ncIndex=1
  3660. ventries=$(echo "$vlist" | tr "$dvsep" ' ')
  3661. for ventry in $ventries; do
  3662. d=$(echo "$ventry" | cut -d "$sep" -f 1)
  3663. keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
  3664. uri=$(echo "$ventry" | cut -d "$sep" -f 3)
  3665. vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
  3666. _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
  3667. if [ "$keyauthorization" = "$STATE_VERIFIED" ]; then
  3668. _info "$d is already verified, skip $vtype."
  3669. continue
  3670. fi
  3671. _info "Verifying: $d"
  3672. _debug "d" "$d"
  3673. _debug "keyauthorization" "$keyauthorization"
  3674. _debug "uri" "$uri"
  3675. removelevel=""
  3676. token="$(printf "%s" "$keyauthorization" | cut -d '.' -f 1)"
  3677. _debug "_currentRoot" "$_currentRoot"
  3678. if [ "$vtype" = "$VTYPE_HTTP" ]; then
  3679. if [ "$_currentRoot" = "$NO_VALUE" ]; then
  3680. _info "Standalone mode server"
  3681. _ncaddr="$(_getfield "$_local_addr" "$_ncIndex")"
  3682. _ncIndex="$(_math $_ncIndex + 1)"
  3683. _startserver "$keyauthorization" "$_ncaddr"
  3684. if [ "$?" != "0" ]; then
  3685. _clearup
  3686. _on_issue_err "$_post_hook" "$vlist"
  3687. return 1
  3688. fi
  3689. sleep 1
  3690. _debug serverproc "$serverproc"
  3691. elif [ "$_currentRoot" = "$MODE_STATELESS" ]; then
  3692. _info "Stateless mode for domain:$d"
  3693. _sleep 1
  3694. elif _startswith "$_currentRoot" "$NGINX"; then
  3695. _info "Nginx mode for domain:$d"
  3696. #set up nginx server
  3697. FOUND_REAL_NGINX_CONF=""
  3698. BACKUP_NGINX_CONF=""
  3699. if ! _setNginx "$d" "$_currentRoot" "$thumbprint"; then
  3700. _clearup
  3701. _on_issue_err "$_post_hook" "$vlist"
  3702. return 1
  3703. fi
  3704. if [ "$FOUND_REAL_NGINX_CONF" ]; then
  3705. _realConf="$FOUND_REAL_NGINX_CONF"
  3706. _backup="$BACKUP_NGINX_CONF"
  3707. _debug _realConf "$_realConf"
  3708. NGINX_RESTORE_VLIST="$d$sep$_realConf$sep$_backup$dvsep$NGINX_RESTORE_VLIST"
  3709. fi
  3710. _sleep 1
  3711. else
  3712. if [ "$_currentRoot" = "apache" ]; then
  3713. wellknown_path="$ACME_DIR"
  3714. else
  3715. wellknown_path="$_currentRoot/.well-known/acme-challenge"
  3716. if [ ! -d "$_currentRoot/.well-known" ]; then
  3717. removelevel='1'
  3718. elif [ ! -d "$_currentRoot/.well-known/acme-challenge" ]; then
  3719. removelevel='2'
  3720. else
  3721. removelevel='3'
  3722. fi
  3723. fi
  3724. _debug wellknown_path "$wellknown_path"
  3725. _debug "writing token:$token to $wellknown_path/$token"
  3726. mkdir -p "$wellknown_path"
  3727. if ! printf "%s" "$keyauthorization" >"$wellknown_path/$token"; then
  3728. _err "$d:Can not write token to file : $wellknown_path/$token"
  3729. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3730. _clearup
  3731. _on_issue_err "$_post_hook" "$vlist"
  3732. return 1
  3733. fi
  3734. if [ ! "$usingApache" ]; then
  3735. if webroot_owner=$(_stat "$_currentRoot"); then
  3736. _debug "Changing owner/group of .well-known to $webroot_owner"
  3737. if ! _exec "chown -R \"$webroot_owner\" \"$_currentRoot/.well-known\""; then
  3738. _debug "$(cat "$_EXEC_TEMP_ERR")"
  3739. _exec_err >/dev/null 2>&1
  3740. fi
  3741. else
  3742. _debug "not changing owner/group of webroot"
  3743. fi
  3744. fi
  3745. fi
  3746. elif [ "$vtype" = "$VTYPE_ALPN" ]; then
  3747. acmevalidationv1="$(printf "%s" "$keyauthorization" | _digest "sha256" "hex")"
  3748. _debug acmevalidationv1 "$acmevalidationv1"
  3749. if ! _starttlsserver "$d" "" "$Le_TLSPort" "$keyauthorization" "$_ncaddr" "$acmevalidationv1"; then
  3750. _err "Start tls server error."
  3751. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3752. _clearup
  3753. _on_issue_err "$_post_hook" "$vlist"
  3754. return 1
  3755. fi
  3756. fi
  3757. if ! __trigger_validation "$uri" "$keyauthorization" "$vtype"; then
  3758. _err "$d:Can not get challenge: $response"
  3759. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3760. _clearup
  3761. _on_issue_err "$_post_hook" "$vlist"
  3762. return 1
  3763. fi
  3764. if [ "$code" ] && [ "$code" != '202' ]; then
  3765. if [ "$code" = '200' ]; then
  3766. _debug "trigger validation code: $code"
  3767. else
  3768. _err "$d:Challenge error: $response"
  3769. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3770. _clearup
  3771. _on_issue_err "$_post_hook" "$vlist"
  3772. return 1
  3773. fi
  3774. fi
  3775. waittimes=0
  3776. if [ -z "$MAX_RETRY_TIMES" ]; then
  3777. MAX_RETRY_TIMES=30
  3778. fi
  3779. while true; do
  3780. waittimes=$(_math "$waittimes" + 1)
  3781. if [ "$waittimes" -ge "$MAX_RETRY_TIMES" ]; then
  3782. _err "$d:Timeout"
  3783. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3784. _clearup
  3785. _on_issue_err "$_post_hook" "$vlist"
  3786. return 1
  3787. fi
  3788. _debug "sleep 2 secs to verify"
  3789. sleep 2
  3790. _debug "checking"
  3791. if [ "$ACME_VERSION" = "2" ]; then
  3792. _send_signed_request "$uri"
  3793. else
  3794. response="$(_get "$uri")"
  3795. fi
  3796. if [ "$?" != "0" ]; then
  3797. _err "$d:Verify error:$response"
  3798. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3799. _clearup
  3800. _on_issue_err "$_post_hook" "$vlist"
  3801. return 1
  3802. fi
  3803. _debug2 original "$response"
  3804. response="$(echo "$response" | _normalizeJson)"
  3805. _debug2 response "$response"
  3806. status=$(echo "$response" | _egrep_o '"status":"[^"]*' | cut -d : -f 2 | tr -d '"')
  3807. if [ "$status" = "valid" ]; then
  3808. _info "$(__green Success)"
  3809. _stopserver "$serverproc"
  3810. serverproc=""
  3811. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3812. break
  3813. fi
  3814. if [ "$status" = "invalid" ]; then
  3815. error="$(echo "$response" | _egrep_o '"error":\{[^\}]*')"
  3816. _debug2 error "$error"
  3817. errordetail="$(echo "$error" | _egrep_o '"detail": *"[^"]*' | cut -d '"' -f 4)"
  3818. _debug2 errordetail "$errordetail"
  3819. if [ "$errordetail" ]; then
  3820. _err "$d:Verify error:$errordetail"
  3821. else
  3822. _err "$d:Verify error:$error"
  3823. fi
  3824. if [ "$DEBUG" ]; then
  3825. if [ "$vtype" = "$VTYPE_HTTP" ]; then
  3826. _debug "Debug: get token url."
  3827. _get "http://$d/.well-known/acme-challenge/$token" "" 1
  3828. fi
  3829. fi
  3830. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3831. _clearup
  3832. _on_issue_err "$_post_hook" "$vlist"
  3833. return 1
  3834. fi
  3835. if [ "$status" = "pending" ]; then
  3836. _info "Pending"
  3837. elif [ "$status" = "processing" ]; then
  3838. _info "Processing"
  3839. else
  3840. _err "$d:Verify error:$response"
  3841. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3842. _clearup
  3843. _on_issue_err "$_post_hook" "$vlist"
  3844. return 1
  3845. fi
  3846. done
  3847. done
  3848. _clearup
  3849. _info "Verify finished, start to sign."
  3850. der="$(_getfile "${CSR_PATH}" "${BEGIN_CSR}" "${END_CSR}" | tr -d "\r\n" | _url_replace)"
  3851. if [ "$ACME_VERSION" = "2" ]; then
  3852. _info "Lets finalize the order, Le_OrderFinalize: $Le_OrderFinalize"
  3853. if ! _send_signed_request "${Le_OrderFinalize}" "{\"csr\": \"$der\"}"; then
  3854. _err "Sign failed."
  3855. _on_issue_err "$_post_hook"
  3856. return 1
  3857. fi
  3858. if [ "$code" != "200" ]; then
  3859. _err "Sign failed, finalize code is not 200."
  3860. _err "$response"
  3861. _on_issue_err "$_post_hook"
  3862. return 1
  3863. fi
  3864. if [ -z "$Le_LinkOrder" ]; then
  3865. Le_LinkOrder="$(echo "$responseHeaders" | grep -i '^Location.*$' | _tail_n 1 | tr -d "\r\n" | cut -d " " -f 2)"
  3866. fi
  3867. _savedomainconf "Le_LinkOrder" "$Le_LinkOrder"
  3868. _link_cert_retry=0
  3869. _MAX_CERT_RETRY=5
  3870. while [ "$_link_cert_retry" -lt "$_MAX_CERT_RETRY" ]; do
  3871. if _contains "$response" "\"status\":\"valid\""; then
  3872. _debug "Order status is valid."
  3873. Le_LinkCert="$(echo "$response" | _egrep_o '"certificate" *: *"[^"]*"' | cut -d '"' -f 4)"
  3874. _debug Le_LinkCert "$Le_LinkCert"
  3875. if [ -z "$Le_LinkCert" ]; then
  3876. _err "Sign error, can not find Le_LinkCert"
  3877. _err "$response"
  3878. _on_issue_err "$_post_hook"
  3879. return 1
  3880. fi
  3881. break
  3882. elif _contains "$response" "\"processing\""; then
  3883. _info "Order status is processing, lets sleep and retry."
  3884. _sleep 2
  3885. else
  3886. _err "Sign error, wrong status"
  3887. _err "$response"
  3888. _on_issue_err "$_post_hook"
  3889. return 1
  3890. fi
  3891. #the order is processing, so we are going to poll order status
  3892. if [ -z "$Le_LinkOrder" ]; then
  3893. _err "Sign error, can not get order link location header"
  3894. _err "responseHeaders" "$responseHeaders"
  3895. _on_issue_err "$_post_hook"
  3896. return 1
  3897. fi
  3898. _info "Polling order status: $Le_LinkOrder"
  3899. if ! _send_signed_request "$Le_LinkOrder"; then
  3900. _err "Sign failed, can not post to Le_LinkOrder cert:$Le_LinkOrder."
  3901. _err "$response"
  3902. _on_issue_err "$_post_hook"
  3903. return 1
  3904. fi
  3905. _link_cert_retry="$(_math $_link_cert_retry + 1)"
  3906. done
  3907. if [ -z "$Le_LinkCert" ]; then
  3908. _err "Sign failed, can not get Le_LinkCert, retry time limit."
  3909. _err "$response"
  3910. _on_issue_err "$_post_hook"
  3911. return 1
  3912. fi
  3913. _info "Download cert, Le_LinkCert: $Le_LinkCert"
  3914. if ! _send_signed_request "$Le_LinkCert"; then
  3915. _err "Sign failed, can not download cert:$Le_LinkCert."
  3916. _err "$response"
  3917. _on_issue_err "$_post_hook"
  3918. return 1
  3919. fi
  3920. echo "$response" >"$CERT_PATH"
  3921. if [ "$(grep -- "$BEGIN_CERT" "$CERT_PATH" | wc -l)" -gt "1" ]; then
  3922. _debug "Found cert chain"
  3923. cat "$CERT_PATH" >"$CERT_FULLCHAIN_PATH"
  3924. _end_n="$(grep -n -- "$END_CERT" "$CERT_FULLCHAIN_PATH" | _head_n 1 | cut -d : -f 1)"
  3925. _debug _end_n "$_end_n"
  3926. sed -n "1,${_end_n}p" "$CERT_FULLCHAIN_PATH" >"$CERT_PATH"
  3927. _end_n="$(_math $_end_n + 1)"
  3928. sed -n "${_end_n},9999p" "$CERT_FULLCHAIN_PATH" >"$CA_CERT_PATH"
  3929. fi
  3930. else
  3931. if ! _send_signed_request "${ACME_NEW_ORDER}" "{\"resource\": \"$ACME_NEW_ORDER_RES\", \"csr\": \"$der\"}" "needbase64"; then
  3932. _err "Sign failed. $response"
  3933. _on_issue_err "$_post_hook"
  3934. return 1
  3935. fi
  3936. _rcert="$response"
  3937. Le_LinkCert="$(grep -i '^Location.*$' "$HTTP_HEADER" | _tail_n 1 | tr -d "\r\n" | cut -d " " -f 2)"
  3938. echo "$BEGIN_CERT" >"$CERT_PATH"
  3939. #if ! _get "$Le_LinkCert" | _base64 "multiline" >> "$CERT_PATH" ; then
  3940. # _debug "Get cert failed. Let's try last response."
  3941. # printf -- "%s" "$_rcert" | _dbase64 "multiline" | _base64 "multiline" >> "$CERT_PATH"
  3942. #fi
  3943. if ! printf -- "%s" "$_rcert" | _dbase64 "multiline" | _base64 "multiline" >>"$CERT_PATH"; then
  3944. _debug "Try cert link."
  3945. _get "$Le_LinkCert" | _base64 "multiline" >>"$CERT_PATH"
  3946. fi
  3947. echo "$END_CERT" >>"$CERT_PATH"
  3948. fi
  3949. _debug "Le_LinkCert" "$Le_LinkCert"
  3950. _savedomainconf "Le_LinkCert" "$Le_LinkCert"
  3951. if [ -z "$Le_LinkCert" ] || ! _checkcert "$CERT_PATH"; then
  3952. response="$(echo "$response" | _dbase64 "multiline" | tr -d '\0' | _normalizeJson)"
  3953. _err "Sign failed: $(echo "$response" | _egrep_o '"detail":"[^"]*"')"
  3954. _on_issue_err "$_post_hook"
  3955. return 1
  3956. fi
  3957. if [ "$Le_LinkCert" ]; then
  3958. _info "$(__green "Cert success.")"
  3959. cat "$CERT_PATH"
  3960. _info "Your cert is in $(__green " $CERT_PATH ")"
  3961. if [ -f "$CERT_KEY_PATH" ]; then
  3962. _info "Your cert key is in $(__green " $CERT_KEY_PATH ")"
  3963. fi
  3964. if [ ! "$USER_PATH" ] || [ ! "$ACME_IN_CRON" ]; then
  3965. USER_PATH="$PATH"
  3966. _saveaccountconf "USER_PATH" "$USER_PATH"
  3967. fi
  3968. fi
  3969. if [ "$ACME_VERSION" = "2" ]; then
  3970. _debug "v2 chain."
  3971. else
  3972. cp "$CERT_PATH" "$CERT_FULLCHAIN_PATH"
  3973. Le_LinkIssuer=$(grep -i '^Link' "$HTTP_HEADER" | _head_n 1 | cut -d " " -f 2 | cut -d ';' -f 1 | tr -d '<>')
  3974. if [ "$Le_LinkIssuer" ]; then
  3975. if ! _contains "$Le_LinkIssuer" ":"; then
  3976. _info "$(__red "Relative issuer link found.")"
  3977. Le_LinkIssuer="$_ACME_SERVER_HOST$Le_LinkIssuer"
  3978. fi
  3979. _debug Le_LinkIssuer "$Le_LinkIssuer"
  3980. _savedomainconf "Le_LinkIssuer" "$Le_LinkIssuer"
  3981. _link_issuer_retry=0
  3982. _MAX_ISSUER_RETRY=5
  3983. while [ "$_link_issuer_retry" -lt "$_MAX_ISSUER_RETRY" ]; do
  3984. _debug _link_issuer_retry "$_link_issuer_retry"
  3985. if [ "$ACME_VERSION" = "2" ]; then
  3986. if _send_signed_request "$Le_LinkIssuer"; then
  3987. echo "$response" >"$CA_CERT_PATH"
  3988. break
  3989. fi
  3990. else
  3991. if _get "$Le_LinkIssuer" >"$CA_CERT_PATH.der"; then
  3992. echo "$BEGIN_CERT" >"$CA_CERT_PATH"
  3993. _base64 "multiline" <"$CA_CERT_PATH.der" >>"$CA_CERT_PATH"
  3994. echo "$END_CERT" >>"$CA_CERT_PATH"
  3995. if ! _checkcert "$CA_CERT_PATH"; then
  3996. _err "Can not get the ca cert."
  3997. break
  3998. fi
  3999. cat "$CA_CERT_PATH" >>"$CERT_FULLCHAIN_PATH"
  4000. rm -f "$CA_CERT_PATH.der"
  4001. break
  4002. fi
  4003. fi
  4004. _link_issuer_retry=$(_math $_link_issuer_retry + 1)
  4005. _sleep "$_link_issuer_retry"
  4006. done
  4007. if [ "$_link_issuer_retry" = "$_MAX_ISSUER_RETRY" ]; then
  4008. _err "Max retry for issuer ca cert is reached."
  4009. fi
  4010. else
  4011. _debug "No Le_LinkIssuer header found."
  4012. fi
  4013. fi
  4014. [ -f "$CA_CERT_PATH" ] && _info "The intermediate CA cert is in $(__green " $CA_CERT_PATH ")"
  4015. [ -f "$CERT_FULLCHAIN_PATH" ] && _info "And the full chain certs is there: $(__green " $CERT_FULLCHAIN_PATH ")"
  4016. Le_CertCreateTime=$(_time)
  4017. _savedomainconf "Le_CertCreateTime" "$Le_CertCreateTime"
  4018. Le_CertCreateTimeStr=$(date -u)
  4019. _savedomainconf "Le_CertCreateTimeStr" "$Le_CertCreateTimeStr"
  4020. if [ -z "$Le_RenewalDays" ] || [ "$Le_RenewalDays" -lt "0" ]; then
  4021. Le_RenewalDays="$DEFAULT_RENEW"
  4022. else
  4023. _savedomainconf "Le_RenewalDays" "$Le_RenewalDays"
  4024. fi
  4025. if [ "$CA_BUNDLE" ]; then
  4026. _saveaccountconf CA_BUNDLE "$CA_BUNDLE"
  4027. else
  4028. _clearaccountconf "CA_BUNDLE"
  4029. fi
  4030. if [ "$CA_PATH" ]; then
  4031. _saveaccountconf CA_PATH "$CA_PATH"
  4032. else
  4033. _clearaccountconf "CA_PATH"
  4034. fi
  4035. if [ "$HTTPS_INSECURE" ]; then
  4036. _saveaccountconf HTTPS_INSECURE "$HTTPS_INSECURE"
  4037. else
  4038. _clearaccountconf "HTTPS_INSECURE"
  4039. fi
  4040. if [ "$Le_Listen_V4" ]; then
  4041. _savedomainconf "Le_Listen_V4" "$Le_Listen_V4"
  4042. _cleardomainconf Le_Listen_V6
  4043. elif [ "$Le_Listen_V6" ]; then
  4044. _savedomainconf "Le_Listen_V6" "$Le_Listen_V6"
  4045. _cleardomainconf Le_Listen_V4
  4046. fi
  4047. if [ "$Le_ForceNewDomainKey" = "1" ]; then
  4048. _savedomainconf "Le_ForceNewDomainKey" "$Le_ForceNewDomainKey"
  4049. else
  4050. _cleardomainconf Le_ForceNewDomainKey
  4051. fi
  4052. Le_NextRenewTime=$(_math "$Le_CertCreateTime" + "$Le_RenewalDays" \* 24 \* 60 \* 60)
  4053. Le_NextRenewTimeStr=$(_time2str "$Le_NextRenewTime")
  4054. _savedomainconf "Le_NextRenewTimeStr" "$Le_NextRenewTimeStr"
  4055. Le_NextRenewTime=$(_math "$Le_NextRenewTime" - 86400)
  4056. _savedomainconf "Le_NextRenewTime" "$Le_NextRenewTime"
  4057. if [ "$_real_cert$_real_key$_real_ca$_reload_cmd$_real_fullchain" ]; then
  4058. _savedomainconf "Le_RealCertPath" "$_real_cert"
  4059. _savedomainconf "Le_RealCACertPath" "$_real_ca"
  4060. _savedomainconf "Le_RealKeyPath" "$_real_key"
  4061. _savedomainconf "Le_ReloadCmd" "$_reload_cmd" "base64"
  4062. _savedomainconf "Le_RealFullChainPath" "$_real_fullchain"
  4063. if ! _installcert "$_main_domain" "$_real_cert" "$_real_key" "$_real_ca" "$_real_fullchain" "$_reload_cmd"; then
  4064. return 1
  4065. fi
  4066. fi
  4067. if ! _on_issue_success "$_post_hook" "$_renew_hook"; then
  4068. _err "Call hook error."
  4069. return 1
  4070. fi
  4071. }
  4072. #domain [isEcc]
  4073. renew() {
  4074. Le_Domain="$1"
  4075. if [ -z "$Le_Domain" ]; then
  4076. _usage "Usage: $PROJECT_ENTRY --renew -d domain.com [--ecc]"
  4077. return 1
  4078. fi
  4079. _isEcc="$2"
  4080. _initpath "$Le_Domain" "$_isEcc"
  4081. _info "$(__green "Renew: '$Le_Domain'")"
  4082. if [ ! -f "$DOMAIN_CONF" ]; then
  4083. _info "'$Le_Domain' is not a issued domain, skip."
  4084. return $RENEW_SKIP
  4085. fi
  4086. if [ "$Le_RenewalDays" ]; then
  4087. _savedomainconf Le_RenewalDays "$Le_RenewalDays"
  4088. fi
  4089. . "$DOMAIN_CONF"
  4090. _debug Le_API "$Le_API"
  4091. if [ "$Le_API" = "$LETSENCRYPT_CA_V1" ]; then
  4092. _cleardomainconf Le_API
  4093. Le_API="$DEFAULT_CA"
  4094. fi
  4095. if [ "$Le_API" = "$LETSENCRYPT_STAGING_CA_V1" ]; then
  4096. _cleardomainconf Le_API
  4097. Le_API="$DEFAULT_STAGING_CA"
  4098. fi
  4099. if [ "$Le_API" ]; then
  4100. if [ "$_OLD_CA_HOST" = "$Le_API" ]; then
  4101. export Le_API="$DEFAULT_CA"
  4102. _savedomainconf Le_API "$Le_API"
  4103. fi
  4104. if [ "$_OLD_STAGE_CA_HOST" = "$Le_API" ]; then
  4105. export Le_API="$DEFAULT_STAGING_CA"
  4106. _savedomainconf Le_API "$Le_API"
  4107. fi
  4108. export ACME_DIRECTORY="$Le_API"
  4109. #reload ca configs
  4110. ACCOUNT_KEY_PATH=""
  4111. ACCOUNT_JSON_PATH=""
  4112. CA_CONF=""
  4113. _debug3 "initpath again."
  4114. _initpath "$Le_Domain" "$_isEcc"
  4115. fi
  4116. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(_time)" -lt "$Le_NextRenewTime" ]; then
  4117. _info "Skip, Next renewal time is: $(__green "$Le_NextRenewTimeStr")"
  4118. _info "Add '$(__red '--force')' to force to renew."
  4119. return "$RENEW_SKIP"
  4120. fi
  4121. if [ "$ACME_IN_CRON" = "1" ] && [ -z "$Le_CertCreateTime" ]; then
  4122. _info "Skip invalid cert for: $Le_Domain"
  4123. return $RENEW_SKIP
  4124. fi
  4125. IS_RENEW="1"
  4126. Le_ReloadCmd="$(_readdomainconf Le_ReloadCmd)"
  4127. Le_PreHook="$(_readdomainconf Le_PreHook)"
  4128. Le_PostHook="$(_readdomainconf Le_PostHook)"
  4129. Le_RenewHook="$(_readdomainconf Le_RenewHook)"
  4130. issue "$Le_Webroot" "$Le_Domain" "$Le_Alt" "$Le_Keylength" "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd" "$Le_RealFullChainPath" "$Le_PreHook" "$Le_PostHook" "$Le_RenewHook" "$Le_LocalAddress" "$Le_ChallengeAlias"
  4131. res="$?"
  4132. if [ "$res" != "0" ]; then
  4133. return "$res"
  4134. fi
  4135. if [ "$Le_DeployHook" ]; then
  4136. _deploy "$Le_Domain" "$Le_DeployHook"
  4137. res="$?"
  4138. fi
  4139. IS_RENEW=""
  4140. return "$res"
  4141. }
  4142. #renewAll [stopRenewOnError]
  4143. renewAll() {
  4144. _initpath
  4145. _stopRenewOnError="$1"
  4146. _debug "_stopRenewOnError" "$_stopRenewOnError"
  4147. _ret="0"
  4148. _success_msg=""
  4149. _error_msg=""
  4150. _skipped_msg=""
  4151. _error_level=$NOTIFY_LEVEL_SKIP
  4152. _notify_code=$RENEW_SKIP
  4153. _set_level=${NOTIFY_LEVEL:-$NOTIFY_LEVEL_DEFAULT}
  4154. _debug "_set_level" "$_set_level"
  4155. for di in "${CERT_HOME}"/*.*/; do
  4156. _debug di "$di"
  4157. if ! [ -d "$di" ]; then
  4158. _debug "Not directory, skip: $di"
  4159. continue
  4160. fi
  4161. d=$(basename "$di")
  4162. _debug d "$d"
  4163. (
  4164. if _endswith "$d" "$ECC_SUFFIX"; then
  4165. _isEcc=$(echo "$d" | cut -d "$ECC_SEP" -f 2)
  4166. d=$(echo "$d" | cut -d "$ECC_SEP" -f 1)
  4167. fi
  4168. renew "$d" "$_isEcc"
  4169. )
  4170. rc="$?"
  4171. _debug "Return code: $rc"
  4172. if [ "$rc" = "0" ]; then
  4173. if [ $_error_level -gt $NOTIFY_LEVEL_RENEW ]; then
  4174. _error_level="$NOTIFY_LEVEL_RENEW"
  4175. _notify_code=0
  4176. fi
  4177. if [ "$ACME_IN_CRON" ]; then
  4178. if [ $_set_level -ge $NOTIFY_LEVEL_RENEW ]; then
  4179. if [ "$NOTIFY_MODE" = "$NOTIFY_MODE_CERT" ]; then
  4180. _send_notify "Renew $d success" "Good, the cert is renewed." "$NOTIFY_HOOK" 0
  4181. fi
  4182. fi
  4183. fi
  4184. _success_msg="${_success_msg} $d
  4185. "
  4186. elif [ "$rc" = "$RENEW_SKIP" ]; then
  4187. if [ $_error_level -gt $NOTIFY_LEVEL_SKIP ]; then
  4188. _error_level="$NOTIFY_LEVEL_SKIP"
  4189. _notify_code=$RENEW_SKIP
  4190. fi
  4191. if [ "$ACME_IN_CRON" ]; then
  4192. if [ $_set_level -ge $NOTIFY_LEVEL_SKIP ]; then
  4193. if [ "$NOTIFY_MODE" = "$NOTIFY_MODE_CERT" ]; then
  4194. _send_notify "Renew $d skipped" "Good, the cert is skipped." "$NOTIFY_HOOK" "$RENEW_SKIP"
  4195. fi
  4196. fi
  4197. fi
  4198. _info "Skipped $d"
  4199. _skipped_msg="${_skipped_msg} $d
  4200. "
  4201. else
  4202. if [ $_error_level -gt $NOTIFY_LEVEL_ERROR ]; then
  4203. _error_level="$NOTIFY_LEVEL_ERROR"
  4204. _notify_code=1
  4205. fi
  4206. if [ "$ACME_IN_CRON" ]; then
  4207. if [ $_set_level -ge $NOTIFY_LEVEL_ERROR ]; then
  4208. if [ "$NOTIFY_MODE" = "$NOTIFY_MODE_CERT" ]; then
  4209. _send_notify "Renew $d error" "There is an error." "$NOTIFY_HOOK" 1
  4210. fi
  4211. fi
  4212. fi
  4213. _error_msg="${_error_msg} $d
  4214. "
  4215. if [ "$_stopRenewOnError" ]; then
  4216. _err "Error renew $d, stop now."
  4217. _ret="$rc"
  4218. break
  4219. else
  4220. _ret="$rc"
  4221. _err "Error renew $d."
  4222. fi
  4223. fi
  4224. done
  4225. _debug _error_level "$_error_level"
  4226. _debug _set_level "$_set_level"
  4227. if [ "$ACME_IN_CRON" ] && [ $_error_level -le $_set_level ]; then
  4228. if [ -z "$NOTIFY_MODE" ] || [ "$NOTIFY_MODE" = "$NOTIFY_MODE_BULK" ]; then
  4229. _msg_subject="Renew"
  4230. if [ "$_error_msg" ]; then
  4231. _msg_subject="${_msg_subject} Error"
  4232. _msg_data="Error certs:
  4233. ${_error_msg}
  4234. "
  4235. fi
  4236. if [ "$_success_msg" ]; then
  4237. _msg_subject="${_msg_subject} Success"
  4238. _msg_data="${_msg_data}Success certs:
  4239. ${_success_msg}
  4240. "
  4241. fi
  4242. if [ "$_skipped_msg" ]; then
  4243. _msg_subject="${_msg_subject} Skipped"
  4244. _msg_data="${_msg_data}Skipped certs:
  4245. ${_skipped_msg}
  4246. "
  4247. fi
  4248. _send_notify "$_msg_subject" "$_msg_data" "$NOTIFY_HOOK" "$_notify_code"
  4249. fi
  4250. fi
  4251. return "$_ret"
  4252. }
  4253. #csr webroot
  4254. signcsr() {
  4255. _csrfile="$1"
  4256. _csrW="$2"
  4257. if [ -z "$_csrfile" ] || [ -z "$_csrW" ]; then
  4258. _usage "Usage: $PROJECT_ENTRY --signcsr --csr mycsr.csr -w /path/to/webroot/a.com/ "
  4259. return 1
  4260. fi
  4261. _real_cert="$3"
  4262. _real_key="$4"
  4263. _real_ca="$5"
  4264. _reload_cmd="$6"
  4265. _real_fullchain="$7"
  4266. _pre_hook="${8}"
  4267. _post_hook="${9}"
  4268. _renew_hook="${10}"
  4269. _local_addr="${11}"
  4270. _challenge_alias="${12}"
  4271. _csrsubj=$(_readSubjectFromCSR "$_csrfile")
  4272. if [ "$?" != "0" ]; then
  4273. _err "Can not read subject from csr: $_csrfile"
  4274. return 1
  4275. fi
  4276. _debug _csrsubj "$_csrsubj"
  4277. if _contains "$_csrsubj" ' ' || ! _contains "$_csrsubj" '.'; then
  4278. _info "It seems that the subject: $_csrsubj is not a valid domain name. Drop it."
  4279. _csrsubj=""
  4280. fi
  4281. _csrdomainlist=$(_readSubjectAltNamesFromCSR "$_csrfile")
  4282. if [ "$?" != "0" ]; then
  4283. _err "Can not read domain list from csr: $_csrfile"
  4284. return 1
  4285. fi
  4286. _debug "_csrdomainlist" "$_csrdomainlist"
  4287. if [ -z "$_csrsubj" ]; then
  4288. _csrsubj="$(_getfield "$_csrdomainlist" 1)"
  4289. _debug _csrsubj "$_csrsubj"
  4290. _csrdomainlist="$(echo "$_csrdomainlist" | cut -d , -f 2-)"
  4291. _debug "_csrdomainlist" "$_csrdomainlist"
  4292. fi
  4293. if [ -z "$_csrsubj" ]; then
  4294. _err "Can not read subject from csr: $_csrfile"
  4295. return 1
  4296. fi
  4297. _csrkeylength=$(_readKeyLengthFromCSR "$_csrfile")
  4298. if [ "$?" != "0" ] || [ -z "$_csrkeylength" ]; then
  4299. _err "Can not read key length from csr: $_csrfile"
  4300. return 1
  4301. fi
  4302. if [ -z "$ACME_VERSION" ] && _contains "$_csrsubj,$_csrdomainlist" "*."; then
  4303. export ACME_VERSION=2
  4304. fi
  4305. _initpath "$_csrsubj" "$_csrkeylength"
  4306. mkdir -p "$DOMAIN_PATH"
  4307. _info "Copy csr to: $CSR_PATH"
  4308. cp "$_csrfile" "$CSR_PATH"
  4309. issue "$_csrW" "$_csrsubj" "$_csrdomainlist" "$_csrkeylength" "$_real_cert" "$_real_key" "$_real_ca" "$_reload_cmd" "$_real_fullchain" "$_pre_hook" "$_post_hook" "$_renew_hook" "$_local_addr" "$_challenge_alias"
  4310. }
  4311. showcsr() {
  4312. _csrfile="$1"
  4313. _csrd="$2"
  4314. if [ -z "$_csrfile" ] && [ -z "$_csrd" ]; then
  4315. _usage "Usage: $PROJECT_ENTRY --showcsr --csr mycsr.csr"
  4316. return 1
  4317. fi
  4318. _initpath
  4319. _csrsubj=$(_readSubjectFromCSR "$_csrfile")
  4320. if [ "$?" != "0" ] || [ -z "$_csrsubj" ]; then
  4321. _err "Can not read subject from csr: $_csrfile"
  4322. return 1
  4323. fi
  4324. _info "Subject=$_csrsubj"
  4325. _csrdomainlist=$(_readSubjectAltNamesFromCSR "$_csrfile")
  4326. if [ "$?" != "0" ]; then
  4327. _err "Can not read domain list from csr: $_csrfile"
  4328. return 1
  4329. fi
  4330. _debug "_csrdomainlist" "$_csrdomainlist"
  4331. _info "SubjectAltNames=$_csrdomainlist"
  4332. _csrkeylength=$(_readKeyLengthFromCSR "$_csrfile")
  4333. if [ "$?" != "0" ] || [ -z "$_csrkeylength" ]; then
  4334. _err "Can not read key length from csr: $_csrfile"
  4335. return 1
  4336. fi
  4337. _info "KeyLength=$_csrkeylength"
  4338. }
  4339. list() {
  4340. _raw="$1"
  4341. _initpath
  4342. _sep="|"
  4343. if [ "$_raw" ]; then
  4344. printf "%s\n" "Main_Domain${_sep}KeyLength${_sep}SAN_Domains${_sep}Created${_sep}Renew"
  4345. for di in "${CERT_HOME}"/*.*/; do
  4346. d=$(basename "$di")
  4347. _debug d "$d"
  4348. (
  4349. if _endswith "$d" "$ECC_SUFFIX"; then
  4350. _isEcc="ecc"
  4351. d=$(echo "$d" | cut -d "$ECC_SEP" -f 1)
  4352. fi
  4353. DOMAIN_CONF="$di/$d.conf"
  4354. if [ -f "$DOMAIN_CONF" ]; then
  4355. . "$DOMAIN_CONF"
  4356. printf "%s\n" "$Le_Domain${_sep}\"$Le_Keylength\"${_sep}$Le_Alt${_sep}$Le_CertCreateTimeStr${_sep}$Le_NextRenewTimeStr"
  4357. fi
  4358. )
  4359. done
  4360. else
  4361. if _exists column; then
  4362. list "raw" | column -t -s "$_sep"
  4363. else
  4364. list "raw" | tr "$_sep" '\t'
  4365. fi
  4366. fi
  4367. }
  4368. _deploy() {
  4369. _d="$1"
  4370. _hooks="$2"
  4371. for _d_api in $(echo "$_hooks" | tr ',' " "); do
  4372. _deployApi="$(_findHook "$_d" $_SUB_FOLDER_DEPLOY "$_d_api")"
  4373. if [ -z "$_deployApi" ]; then
  4374. _err "The deploy hook $_d_api is not found."
  4375. return 1
  4376. fi
  4377. _debug _deployApi "$_deployApi"
  4378. if ! (
  4379. if ! . "$_deployApi"; then
  4380. _err "Load file $_deployApi error. Please check your api file and try again."
  4381. return 1
  4382. fi
  4383. d_command="${_d_api}_deploy"
  4384. if ! _exists "$d_command"; then
  4385. _err "It seems that your api file is not correct, it must have a function named: $d_command"
  4386. return 1
  4387. fi
  4388. if ! $d_command "$_d" "$CERT_KEY_PATH" "$CERT_PATH" "$CA_CERT_PATH" "$CERT_FULLCHAIN_PATH"; then
  4389. _err "Error deploy for domain:$_d"
  4390. return 1
  4391. fi
  4392. ); then
  4393. _err "Deploy error."
  4394. return 1
  4395. else
  4396. _info "$(__green Success)"
  4397. fi
  4398. done
  4399. }
  4400. #domain hooks
  4401. deploy() {
  4402. _d="$1"
  4403. _hooks="$2"
  4404. _isEcc="$3"
  4405. if [ -z "$_hooks" ]; then
  4406. _usage "Usage: $PROJECT_ENTRY --deploy -d domain.com --deploy-hook cpanel [--ecc] "
  4407. return 1
  4408. fi
  4409. _initpath "$_d" "$_isEcc"
  4410. if [ ! -d "$DOMAIN_PATH" ]; then
  4411. _err "The domain '$_d' is not a cert name. You must use the cert name to specify the cert to install."
  4412. _err "Can not find path:'$DOMAIN_PATH'"
  4413. return 1
  4414. fi
  4415. . "$DOMAIN_CONF"
  4416. _savedomainconf Le_DeployHook "$_hooks"
  4417. _deploy "$_d" "$_hooks"
  4418. }
  4419. installcert() {
  4420. _main_domain="$1"
  4421. if [ -z "$_main_domain" ]; then
  4422. _usage "Usage: $PROJECT_ENTRY --installcert -d domain.com [--ecc] [--cert-file cert-file-path] [--key-file key-file-path] [--ca-file ca-cert-file-path] [ --reloadCmd reloadCmd] [--fullchain-file fullchain-path]"
  4423. return 1
  4424. fi
  4425. _real_cert="$2"
  4426. _real_key="$3"
  4427. _real_ca="$4"
  4428. _reload_cmd="$5"
  4429. _real_fullchain="$6"
  4430. _isEcc="$7"
  4431. _initpath "$_main_domain" "$_isEcc"
  4432. if [ ! -d "$DOMAIN_PATH" ]; then
  4433. _err "The domain '$_main_domain' is not a cert name. You must use the cert name to specify the cert to install."
  4434. _err "Can not find path:'$DOMAIN_PATH'"
  4435. return 1
  4436. fi
  4437. _savedomainconf "Le_RealCertPath" "$_real_cert"
  4438. _savedomainconf "Le_RealCACertPath" "$_real_ca"
  4439. _savedomainconf "Le_RealKeyPath" "$_real_key"
  4440. _savedomainconf "Le_ReloadCmd" "$_reload_cmd" "base64"
  4441. _savedomainconf "Le_RealFullChainPath" "$_real_fullchain"
  4442. _installcert "$_main_domain" "$_real_cert" "$_real_key" "$_real_ca" "$_real_fullchain" "$_reload_cmd"
  4443. }
  4444. #domain cert key ca fullchain reloadcmd backup-prefix
  4445. _installcert() {
  4446. _main_domain="$1"
  4447. _real_cert="$2"
  4448. _real_key="$3"
  4449. _real_ca="$4"
  4450. _real_fullchain="$5"
  4451. _reload_cmd="$6"
  4452. _backup_prefix="$7"
  4453. if [ "$_real_cert" = "$NO_VALUE" ]; then
  4454. _real_cert=""
  4455. fi
  4456. if [ "$_real_key" = "$NO_VALUE" ]; then
  4457. _real_key=""
  4458. fi
  4459. if [ "$_real_ca" = "$NO_VALUE" ]; then
  4460. _real_ca=""
  4461. fi
  4462. if [ "$_reload_cmd" = "$NO_VALUE" ]; then
  4463. _reload_cmd=""
  4464. fi
  4465. if [ "$_real_fullchain" = "$NO_VALUE" ]; then
  4466. _real_fullchain=""
  4467. fi
  4468. _backup_path="$DOMAIN_BACKUP_PATH/$_backup_prefix"
  4469. mkdir -p "$_backup_path"
  4470. if [ "$_real_cert" ]; then
  4471. _info "Installing cert to:$_real_cert"
  4472. if [ -f "$_real_cert" ] && [ ! "$IS_RENEW" ]; then
  4473. cp "$_real_cert" "$_backup_path/cert.bak"
  4474. fi
  4475. cat "$CERT_PATH" >"$_real_cert" || return 1
  4476. fi
  4477. if [ "$_real_ca" ]; then
  4478. _info "Installing CA to:$_real_ca"
  4479. if [ "$_real_ca" = "$_real_cert" ]; then
  4480. echo "" >>"$_real_ca"
  4481. cat "$CA_CERT_PATH" >>"$_real_ca" || return 1
  4482. else
  4483. if [ -f "$_real_ca" ] && [ ! "$IS_RENEW" ]; then
  4484. cp "$_real_ca" "$_backup_path/ca.bak"
  4485. fi
  4486. cat "$CA_CERT_PATH" >"$_real_ca" || return 1
  4487. fi
  4488. fi
  4489. if [ "$_real_key" ]; then
  4490. _info "Installing key to:$_real_key"
  4491. if [ -f "$_real_key" ] && [ ! "$IS_RENEW" ]; then
  4492. cp "$_real_key" "$_backup_path/key.bak"
  4493. fi
  4494. if [ -f "$_real_key" ]; then
  4495. cat "$CERT_KEY_PATH" >"$_real_key" || return 1
  4496. else
  4497. cat "$CERT_KEY_PATH" >"$_real_key" || return 1
  4498. chmod 600 "$_real_key"
  4499. fi
  4500. fi
  4501. if [ "$_real_fullchain" ]; then
  4502. _info "Installing full chain to:$_real_fullchain"
  4503. if [ -f "$_real_fullchain" ] && [ ! "$IS_RENEW" ]; then
  4504. cp "$_real_fullchain" "$_backup_path/fullchain.bak"
  4505. fi
  4506. cat "$CERT_FULLCHAIN_PATH" >"$_real_fullchain" || return 1
  4507. fi
  4508. if [ "$_reload_cmd" ]; then
  4509. _info "Run reload cmd: $_reload_cmd"
  4510. if (
  4511. export CERT_PATH
  4512. export CERT_KEY_PATH
  4513. export CA_CERT_PATH
  4514. export CERT_FULLCHAIN_PATH
  4515. export Le_Domain="$_main_domain"
  4516. cd "$DOMAIN_PATH" && eval "$_reload_cmd"
  4517. ); then
  4518. _info "$(__green "Reload success")"
  4519. else
  4520. _err "Reload error for :$Le_Domain"
  4521. fi
  4522. fi
  4523. }
  4524. __read_password() {
  4525. unset _pp
  4526. prompt="Enter Password:"
  4527. while IFS= read -p "$prompt" -r -s -n 1 char; do
  4528. if [ "$char" = $'\0' ]; then
  4529. break
  4530. fi
  4531. prompt='*'
  4532. _pp="$_pp$char"
  4533. done
  4534. echo "$_pp"
  4535. }
  4536. _install_win_taskscheduler() {
  4537. _lesh="$1"
  4538. _centry="$2"
  4539. _randomminute="$3"
  4540. if ! _exists cygpath; then
  4541. _err "cygpath not found"
  4542. return 1
  4543. fi
  4544. if ! _exists schtasks; then
  4545. _err "schtasks.exe is not found, are you on Windows?"
  4546. return 1
  4547. fi
  4548. _winbash="$(cygpath -w $(which bash))"
  4549. _debug _winbash "$_winbash"
  4550. if [ -z "$_winbash" ]; then
  4551. _err "can not find bash path"
  4552. return 1
  4553. fi
  4554. _myname="$(whoami)"
  4555. _debug "_myname" "$_myname"
  4556. if [ -z "$_myname" ]; then
  4557. _err "can not find my user name"
  4558. return 1
  4559. fi
  4560. _debug "_lesh" "$_lesh"
  4561. _info "To install scheduler task in your Windows account, you must input your windows password."
  4562. _info "$PROJECT_NAME doesn't save your password."
  4563. _info "Please input your Windows password for: $(__green "$_myname")"
  4564. _password="$(__read_password)"
  4565. #SCHTASKS.exe '/create' '/SC' 'DAILY' '/TN' "$_WINDOWS_SCHEDULER_NAME" '/F' '/ST' "00:$_randomminute" '/RU' "$_myname" '/RP' "$_password" '/TR' "$_winbash -l -c '$_lesh --cron --home \"$LE_WORKING_DIR\" $_centry'" >/dev/null
  4566. echo SCHTASKS.exe '/create' '/SC' 'DAILY' '/TN' "$_WINDOWS_SCHEDULER_NAME" '/F' '/ST' "00:$_randomminute" '/RU' "$_myname" '/RP' "$_password" '/TR' "\"$_winbash -l -c '$_lesh --cron --home \"$LE_WORKING_DIR\" $_centry'\"" | cmd.exe >/dev/null
  4567. echo
  4568. }
  4569. _uninstall_win_taskscheduler() {
  4570. if ! _exists schtasks; then
  4571. _err "schtasks.exe is not found, are you on Windows?"
  4572. return 1
  4573. fi
  4574. if ! echo SCHTASKS /query /tn "$_WINDOWS_SCHEDULER_NAME" | cmd.exe >/dev/null; then
  4575. _debug "scheduler $_WINDOWS_SCHEDULER_NAME is not found."
  4576. else
  4577. _info "Removing $_WINDOWS_SCHEDULER_NAME"
  4578. echo SCHTASKS /delete /f /tn "$_WINDOWS_SCHEDULER_NAME" | cmd.exe >/dev/null
  4579. fi
  4580. }
  4581. #confighome
  4582. installcronjob() {
  4583. _c_home="$1"
  4584. _initpath
  4585. _CRONTAB="crontab"
  4586. if [ -f "$LE_WORKING_DIR/$PROJECT_ENTRY" ]; then
  4587. lesh="\"$LE_WORKING_DIR\"/$PROJECT_ENTRY"
  4588. else
  4589. _err "Can not install cronjob, $PROJECT_ENTRY not found."
  4590. return 1
  4591. fi
  4592. if [ "$_c_home" ]; then
  4593. _c_entry="--config-home \"$_c_home\" "
  4594. fi
  4595. _t=$(_time)
  4596. random_minute=$(_math $_t % 60)
  4597. if ! _exists "$_CRONTAB" && _exists "fcrontab"; then
  4598. _CRONTAB="fcrontab"
  4599. fi
  4600. if ! _exists "$_CRONTAB"; then
  4601. if _exists cygpath && _exists schtasks.exe; then
  4602. _info "It seems you are on Windows, let's install Windows scheduler task."
  4603. if _install_win_taskscheduler "$lesh" "$_c_entry" "$random_minute"; then
  4604. _info "Install Windows scheduler task success."
  4605. return 0
  4606. else
  4607. _err "Install Windows scheduler task failed."
  4608. return 1
  4609. fi
  4610. fi
  4611. _err "crontab/fcrontab doesn't exist, so, we can not install cron jobs."
  4612. _err "All your certs will not be renewed automatically."
  4613. _err "You must add your own cron job to call '$PROJECT_ENTRY --cron' everyday."
  4614. return 1
  4615. fi
  4616. _info "Installing cron job"
  4617. if ! $_CRONTAB -l | grep "$PROJECT_ENTRY --cron"; then
  4618. if _exists uname && uname -a | grep SunOS >/dev/null; then
  4619. $_CRONTAB -l | {
  4620. cat
  4621. echo "$random_minute 0 * * * $lesh --cron --home \"$LE_WORKING_DIR\" $_c_entry> /dev/null"
  4622. } | $_CRONTAB --
  4623. else
  4624. $_CRONTAB -l | {
  4625. cat
  4626. echo "$random_minute 0 * * * $lesh --cron --home \"$LE_WORKING_DIR\" $_c_entry> /dev/null"
  4627. } | $_CRONTAB -
  4628. fi
  4629. fi
  4630. if [ "$?" != "0" ]; then
  4631. _err "Install cron job failed. You need to manually renew your certs."
  4632. _err "Or you can add cronjob by yourself:"
  4633. _err "$lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"
  4634. return 1
  4635. fi
  4636. }
  4637. uninstallcronjob() {
  4638. _CRONTAB="crontab"
  4639. if ! _exists "$_CRONTAB" && _exists "fcrontab"; then
  4640. _CRONTAB="fcrontab"
  4641. fi
  4642. if ! _exists "$_CRONTAB"; then
  4643. if _exists cygpath && _exists schtasks.exe; then
  4644. _info "It seems you are on Windows, let's uninstall Windows scheduler task."
  4645. if _uninstall_win_taskscheduler; then
  4646. _info "Uninstall Windows scheduler task success."
  4647. return 0
  4648. else
  4649. _err "Uninstall Windows scheduler task failed."
  4650. return 1
  4651. fi
  4652. fi
  4653. return
  4654. fi
  4655. _info "Removing cron job"
  4656. cr="$($_CRONTAB -l | grep "$PROJECT_ENTRY --cron")"
  4657. if [ "$cr" ]; then
  4658. if _exists uname && uname -a | grep solaris >/dev/null; then
  4659. $_CRONTAB -l | sed "/$PROJECT_ENTRY --cron/d" | $_CRONTAB --
  4660. else
  4661. $_CRONTAB -l | sed "/$PROJECT_ENTRY --cron/d" | $_CRONTAB -
  4662. fi
  4663. LE_WORKING_DIR="$(echo "$cr" | cut -d ' ' -f 9 | tr -d '"')"
  4664. _info LE_WORKING_DIR "$LE_WORKING_DIR"
  4665. if _contains "$cr" "--config-home"; then
  4666. LE_CONFIG_HOME="$(echo "$cr" | cut -d ' ' -f 11 | tr -d '"')"
  4667. _debug LE_CONFIG_HOME "$LE_CONFIG_HOME"
  4668. fi
  4669. fi
  4670. _initpath
  4671. }
  4672. revoke() {
  4673. Le_Domain="$1"
  4674. if [ -z "$Le_Domain" ]; then
  4675. _usage "Usage: $PROJECT_ENTRY --revoke -d domain.com [--ecc]"
  4676. return 1
  4677. fi
  4678. _isEcc="$2"
  4679. _initpath "$Le_Domain" "$_isEcc"
  4680. if [ ! -f "$DOMAIN_CONF" ]; then
  4681. _err "$Le_Domain is not a issued domain, skip."
  4682. return 1
  4683. fi
  4684. if [ ! -f "$CERT_PATH" ]; then
  4685. _err "Cert for $Le_Domain $CERT_PATH is not found, skip."
  4686. return 1
  4687. fi
  4688. cert="$(_getfile "${CERT_PATH}" "${BEGIN_CERT}" "${END_CERT}" | tr -d "\r\n" | _url_replace)"
  4689. if [ -z "$cert" ]; then
  4690. _err "Cert for $Le_Domain is empty found, skip."
  4691. return 1
  4692. fi
  4693. _initAPI
  4694. if [ "$ACME_VERSION" = "2" ]; then
  4695. data="{\"certificate\": \"$cert\"}"
  4696. else
  4697. data="{\"resource\": \"revoke-cert\", \"certificate\": \"$cert\"}"
  4698. fi
  4699. uri="${ACME_REVOKE_CERT}"
  4700. if [ -f "$CERT_KEY_PATH" ]; then
  4701. _info "Try domain key first."
  4702. if _send_signed_request "$uri" "$data" "" "$CERT_KEY_PATH"; then
  4703. if [ -z "$response" ]; then
  4704. _info "Revoke success."
  4705. rm -f "$CERT_PATH"
  4706. return 0
  4707. else
  4708. _err "Revoke error by domain key."
  4709. _err "$response"
  4710. fi
  4711. fi
  4712. else
  4713. _info "Domain key file doesn't exists."
  4714. fi
  4715. _info "Try account key."
  4716. if _send_signed_request "$uri" "$data" "" "$ACCOUNT_KEY_PATH"; then
  4717. if [ -z "$response" ]; then
  4718. _info "Revoke success."
  4719. rm -f "$CERT_PATH"
  4720. return 0
  4721. else
  4722. _err "Revoke error."
  4723. _debug "$response"
  4724. fi
  4725. fi
  4726. return 1
  4727. }
  4728. #domain ecc
  4729. remove() {
  4730. Le_Domain="$1"
  4731. if [ -z "$Le_Domain" ]; then
  4732. _usage "Usage: $PROJECT_ENTRY --remove -d domain.com [--ecc]"
  4733. return 1
  4734. fi
  4735. _isEcc="$2"
  4736. _initpath "$Le_Domain" "$_isEcc"
  4737. _removed_conf="$DOMAIN_CONF.removed"
  4738. if [ ! -f "$DOMAIN_CONF" ]; then
  4739. if [ -f "$_removed_conf" ]; then
  4740. _err "$Le_Domain is already removed, You can remove the folder by yourself: $DOMAIN_PATH"
  4741. else
  4742. _err "$Le_Domain is not a issued domain, skip."
  4743. fi
  4744. return 1
  4745. fi
  4746. if mv "$DOMAIN_CONF" "$_removed_conf"; then
  4747. _info "$Le_Domain is removed, the key and cert files are in $(__green $DOMAIN_PATH)"
  4748. _info "You can remove them by yourself."
  4749. return 0
  4750. else
  4751. _err "Remove $Le_Domain failed."
  4752. return 1
  4753. fi
  4754. }
  4755. #domain vtype
  4756. _deactivate() {
  4757. _d_domain="$1"
  4758. _d_type="$2"
  4759. _initpath
  4760. if [ "$ACME_VERSION" = "2" ]; then
  4761. _identifiers="{\"type\":\"dns\",\"value\":\"$_d_domain\"}"
  4762. if ! _send_signed_request "$ACME_NEW_ORDER" "{\"identifiers\": [$_identifiers]}"; then
  4763. _err "Can not get domain new order."
  4764. return 1
  4765. fi
  4766. _authorizations_seg="$(echo "$response" | _egrep_o '"authorizations" *: *\[[^\]*\]' | cut -d '[' -f 2 | tr -d ']' | tr -d '"')"
  4767. _debug2 _authorizations_seg "$_authorizations_seg"
  4768. if [ -z "$_authorizations_seg" ]; then
  4769. _err "_authorizations_seg not found."
  4770. _clearup
  4771. _on_issue_err "$_post_hook"
  4772. return 1
  4773. fi
  4774. authzUri="$_authorizations_seg"
  4775. _debug2 "authzUri" "$authzUri"
  4776. if ! _send_signed_request "$authzUri"; then
  4777. _err "get to authz error."
  4778. _err "_authorizations_seg" "$_authorizations_seg"
  4779. _err "authzUri" "$authzUri"
  4780. _clearup
  4781. _on_issue_err "$_post_hook"
  4782. return 1
  4783. fi
  4784. response="$(echo "$response" | _normalizeJson)"
  4785. _debug2 response "$response"
  4786. _URL_NAME="url"
  4787. else
  4788. if ! __get_domain_new_authz "$_d_domain"; then
  4789. _err "Can not get domain new authz token."
  4790. return 1
  4791. fi
  4792. authzUri="$(echo "$responseHeaders" | grep "^Location:" | _head_n 1 | cut -d ' ' -f 2 | tr -d "\r\n")"
  4793. _debug "authzUri" "$authzUri"
  4794. if [ "$code" ] && [ ! "$code" = '201' ]; then
  4795. _err "new-authz error: $response"
  4796. return 1
  4797. fi
  4798. _URL_NAME="uri"
  4799. fi
  4800. entries="$(echo "$response" | _egrep_o "{ *\"type\":\"[^\"]*\", *\"status\": *\"valid\", *\"$_URL_NAME\"[^}]*")"
  4801. if [ -z "$entries" ]; then
  4802. _info "No valid entries found."
  4803. if [ -z "$thumbprint" ]; then
  4804. thumbprint="$(__calc_account_thumbprint)"
  4805. fi
  4806. _debug "Trigger validation."
  4807. vtype="$VTYPE_DNS"
  4808. entry="$(echo "$response" | _egrep_o '[^\{]*"type":"'$vtype'"[^\}]*')"
  4809. _debug entry "$entry"
  4810. if [ -z "$entry" ]; then
  4811. _err "Error, can not get domain token $d"
  4812. return 1
  4813. fi
  4814. token="$(echo "$entry" | _egrep_o '"token":"[^"]*' | cut -d : -f 2 | tr -d '"')"
  4815. _debug token "$token"
  4816. uri="$(echo "$entry" | _egrep_o "\"$_URL_NAME\":\"[^\"]*" | cut -d : -f 2,3 | tr -d '"')"
  4817. _debug uri "$uri"
  4818. keyauthorization="$token.$thumbprint"
  4819. _debug keyauthorization "$keyauthorization"
  4820. __trigger_validation "$uri" "$keyauthorization"
  4821. fi
  4822. _d_i=0
  4823. _d_max_retry=$(echo "$entries" | wc -l)
  4824. while [ "$_d_i" -lt "$_d_max_retry" ]; do
  4825. _info "Deactivate: $_d_domain"
  4826. _d_i="$(_math $_d_i + 1)"
  4827. entry="$(echo "$entries" | sed -n "${_d_i}p")"
  4828. _debug entry "$entry"
  4829. if [ -z "$entry" ]; then
  4830. _info "No more valid entry found."
  4831. break
  4832. fi
  4833. _vtype="$(echo "$entry" | _egrep_o '"type": *"[^"]*"' | cut -d : -f 2 | tr -d '"')"
  4834. _debug _vtype "$_vtype"
  4835. _info "Found $_vtype"
  4836. uri="$(echo "$entry" | _egrep_o "\"$_URL_NAME\":\"[^\"]*" | cut -d : -f 2,3 | tr -d '"')"
  4837. _debug uri "$uri"
  4838. if [ "$_d_type" ] && [ "$_d_type" != "$_vtype" ]; then
  4839. _info "Skip $_vtype"
  4840. continue
  4841. fi
  4842. _info "Deactivate: $_vtype"
  4843. if [ "$ACME_VERSION" = "2" ]; then
  4844. _djson="{\"status\":\"deactivated\"}"
  4845. else
  4846. _djson="{\"resource\": \"authz\", \"status\":\"deactivated\"}"
  4847. fi
  4848. if _send_signed_request "$authzUri" "$_djson" && _contains "$response" '"deactivated"'; then
  4849. _info "Deactivate: $_vtype success."
  4850. else
  4851. _err "Can not deactivate $_vtype."
  4852. break
  4853. fi
  4854. done
  4855. _debug "$_d_i"
  4856. if [ "$_d_i" -eq "$_d_max_retry" ]; then
  4857. _info "Deactivated success!"
  4858. else
  4859. _err "Deactivate failed."
  4860. fi
  4861. }
  4862. deactivate() {
  4863. _d_domain_list="$1"
  4864. _d_type="$2"
  4865. _initpath
  4866. _initAPI
  4867. _debug _d_domain_list "$_d_domain_list"
  4868. if [ -z "$(echo $_d_domain_list | cut -d , -f 1)" ]; then
  4869. _usage "Usage: $PROJECT_ENTRY --deactivate -d domain.com [-d domain.com]"
  4870. return 1
  4871. fi
  4872. for _d_dm in $(echo "$_d_domain_list" | tr ',' ' '); do
  4873. if [ -z "$_d_dm" ] || [ "$_d_dm" = "$NO_VALUE" ]; then
  4874. continue
  4875. fi
  4876. if ! _deactivate "$_d_dm" "$_d_type"; then
  4877. return 1
  4878. fi
  4879. done
  4880. }
  4881. # Detect profile file if not specified as environment variable
  4882. _detect_profile() {
  4883. if [ -n "$PROFILE" -a -f "$PROFILE" ]; then
  4884. echo "$PROFILE"
  4885. return
  4886. fi
  4887. DETECTED_PROFILE=''
  4888. SHELLTYPE="$(basename "/$SHELL")"
  4889. if [ "$SHELLTYPE" = "bash" ]; then
  4890. if [ -f "$HOME/.bashrc" ]; then
  4891. DETECTED_PROFILE="$HOME/.bashrc"
  4892. elif [ -f "$HOME/.bash_profile" ]; then
  4893. DETECTED_PROFILE="$HOME/.bash_profile"
  4894. fi
  4895. elif [ "$SHELLTYPE" = "zsh" ]; then
  4896. DETECTED_PROFILE="$HOME/.zshrc"
  4897. fi
  4898. if [ -z "$DETECTED_PROFILE" ]; then
  4899. if [ -f "$HOME/.profile" ]; then
  4900. DETECTED_PROFILE="$HOME/.profile"
  4901. elif [ -f "$HOME/.bashrc" ]; then
  4902. DETECTED_PROFILE="$HOME/.bashrc"
  4903. elif [ -f "$HOME/.bash_profile" ]; then
  4904. DETECTED_PROFILE="$HOME/.bash_profile"
  4905. elif [ -f "$HOME/.zshrc" ]; then
  4906. DETECTED_PROFILE="$HOME/.zshrc"
  4907. fi
  4908. fi
  4909. echo "$DETECTED_PROFILE"
  4910. }
  4911. _initconf() {
  4912. _initpath
  4913. if [ ! -f "$ACCOUNT_CONF_PATH" ]; then
  4914. echo "
  4915. #LOG_FILE=\"$DEFAULT_LOG_FILE\"
  4916. #LOG_LEVEL=1
  4917. #AUTO_UPGRADE=\"1\"
  4918. #NO_TIMESTAMP=1
  4919. " >"$ACCOUNT_CONF_PATH"
  4920. fi
  4921. }
  4922. # nocron
  4923. _precheck() {
  4924. _nocron="$1"
  4925. if ! _exists "curl" && ! _exists "wget"; then
  4926. _err "Please install curl or wget first, we need to access http resources."
  4927. return 1
  4928. fi
  4929. if [ -z "$_nocron" ]; then
  4930. if ! _exists "crontab" && ! _exists "fcrontab"; then
  4931. if _exists cygpath && _exists schtasks.exe; then
  4932. _info "It seems you are on Windows, we will install Windows scheduler task."
  4933. else
  4934. _err "It is recommended to install crontab first. try to install 'cron, crontab, crontabs or vixie-cron'."
  4935. _err "We need to set cron job to renew the certs automatically."
  4936. _err "Otherwise, your certs will not be able to be renewed automatically."
  4937. if [ -z "$FORCE" ]; then
  4938. _err "Please add '--force' and try install again to go without crontab."
  4939. _err "./$PROJECT_ENTRY --install --force"
  4940. return 1
  4941. fi
  4942. fi
  4943. fi
  4944. fi
  4945. if ! _exists "${ACME_OPENSSL_BIN:-openssl}"; then
  4946. _err "Please install openssl first. ACME_OPENSSL_BIN=$ACME_OPENSSL_BIN"
  4947. _err "We need openssl to generate keys."
  4948. return 1
  4949. fi
  4950. if ! _exists "socat"; then
  4951. _err "It is recommended to install socat first."
  4952. _err "We use socat for standalone server if you use standalone mode."
  4953. _err "If you don't use standalone mode, just ignore this warning."
  4954. fi
  4955. return 0
  4956. }
  4957. _setShebang() {
  4958. _file="$1"
  4959. _shebang="$2"
  4960. if [ -z "$_shebang" ]; then
  4961. _usage "Usage: file shebang"
  4962. return 1
  4963. fi
  4964. cp "$_file" "$_file.tmp"
  4965. echo "$_shebang" >"$_file"
  4966. sed -n 2,99999p "$_file.tmp" >>"$_file"
  4967. rm -f "$_file.tmp"
  4968. }
  4969. #confighome
  4970. _installalias() {
  4971. _c_home="$1"
  4972. _initpath
  4973. _envfile="$LE_WORKING_DIR/$PROJECT_ENTRY.env"
  4974. if [ "$_upgrading" ] && [ "$_upgrading" = "1" ]; then
  4975. echo "$(cat "$_envfile")" | sed "s|^LE_WORKING_DIR.*$||" >"$_envfile"
  4976. echo "$(cat "$_envfile")" | sed "s|^alias le.*$||" >"$_envfile"
  4977. echo "$(cat "$_envfile")" | sed "s|^alias le.sh.*$||" >"$_envfile"
  4978. fi
  4979. if [ "$_c_home" ]; then
  4980. _c_entry=" --config-home '$_c_home'"
  4981. fi
  4982. _setopt "$_envfile" "export LE_WORKING_DIR" "=" "\"$LE_WORKING_DIR\""
  4983. if [ "$_c_home" ]; then
  4984. _setopt "$_envfile" "export LE_CONFIG_HOME" "=" "\"$LE_CONFIG_HOME\""
  4985. else
  4986. _sed_i "/^export LE_CONFIG_HOME/d" "$_envfile"
  4987. fi
  4988. _setopt "$_envfile" "alias $PROJECT_ENTRY" "=" "\"$LE_WORKING_DIR/$PROJECT_ENTRY$_c_entry\""
  4989. _profile="$(_detect_profile)"
  4990. if [ "$_profile" ]; then
  4991. _debug "Found profile: $_profile"
  4992. _info "Installing alias to '$_profile'"
  4993. _setopt "$_profile" ". \"$_envfile\""
  4994. _info "OK, Close and reopen your terminal to start using $PROJECT_NAME"
  4995. else
  4996. _info "No profile is found, you will need to go into $LE_WORKING_DIR to use $PROJECT_NAME"
  4997. fi
  4998. #for csh
  4999. _cshfile="$LE_WORKING_DIR/$PROJECT_ENTRY.csh"
  5000. _csh_profile="$HOME/.cshrc"
  5001. if [ -f "$_csh_profile" ]; then
  5002. _info "Installing alias to '$_csh_profile'"
  5003. _setopt "$_cshfile" "setenv LE_WORKING_DIR" " " "\"$LE_WORKING_DIR\""
  5004. if [ "$_c_home" ]; then
  5005. _setopt "$_cshfile" "setenv LE_CONFIG_HOME" " " "\"$LE_CONFIG_HOME\""
  5006. else
  5007. _sed_i "/^setenv LE_CONFIG_HOME/d" "$_cshfile"
  5008. fi
  5009. _setopt "$_cshfile" "alias $PROJECT_ENTRY" " " "\"$LE_WORKING_DIR/$PROJECT_ENTRY$_c_entry\""
  5010. _setopt "$_csh_profile" "source \"$_cshfile\""
  5011. fi
  5012. #for tcsh
  5013. _tcsh_profile="$HOME/.tcshrc"
  5014. if [ -f "$_tcsh_profile" ]; then
  5015. _info "Installing alias to '$_tcsh_profile'"
  5016. _setopt "$_cshfile" "setenv LE_WORKING_DIR" " " "\"$LE_WORKING_DIR\""
  5017. if [ "$_c_home" ]; then
  5018. _setopt "$_cshfile" "setenv LE_CONFIG_HOME" " " "\"$LE_CONFIG_HOME\""
  5019. fi
  5020. _setopt "$_cshfile" "alias $PROJECT_ENTRY" " " "\"$LE_WORKING_DIR/$PROJECT_ENTRY$_c_entry\""
  5021. _setopt "$_tcsh_profile" "source \"$_cshfile\""
  5022. fi
  5023. }
  5024. # nocron confighome noprofile
  5025. install() {
  5026. if [ -z "$LE_WORKING_DIR" ]; then
  5027. LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
  5028. fi
  5029. _nocron="$1"
  5030. _c_home="$2"
  5031. _noprofile="$3"
  5032. if ! _initpath; then
  5033. _err "Install failed."
  5034. return 1
  5035. fi
  5036. if [ "$_nocron" ]; then
  5037. _debug "Skip install cron job"
  5038. fi
  5039. if [ "$ACME_IN_CRON" != "1" ]; then
  5040. if ! _precheck "$_nocron"; then
  5041. _err "Pre-check failed, can not install."
  5042. return 1
  5043. fi
  5044. fi
  5045. if [ -z "$_c_home" ] && [ "$LE_CONFIG_HOME" != "$LE_WORKING_DIR" ]; then
  5046. _info "Using config home: $LE_CONFIG_HOME"
  5047. _c_home="$LE_CONFIG_HOME"
  5048. fi
  5049. #convert from le
  5050. if [ -d "$HOME/.le" ]; then
  5051. for envfile in "le.env" "le.sh.env"; do
  5052. if [ -f "$HOME/.le/$envfile" ]; then
  5053. if grep "le.sh" "$HOME/.le/$envfile" >/dev/null; then
  5054. _upgrading="1"
  5055. _info "You are upgrading from le.sh"
  5056. _info "Renaming \"$HOME/.le\" to $LE_WORKING_DIR"
  5057. mv "$HOME/.le" "$LE_WORKING_DIR"
  5058. mv "$LE_WORKING_DIR/$envfile" "$LE_WORKING_DIR/$PROJECT_ENTRY.env"
  5059. break
  5060. fi
  5061. fi
  5062. done
  5063. fi
  5064. _info "Installing to $LE_WORKING_DIR"
  5065. if [ ! -d "$LE_WORKING_DIR" ]; then
  5066. if ! mkdir -p "$LE_WORKING_DIR"; then
  5067. _err "Can not create working dir: $LE_WORKING_DIR"
  5068. return 1
  5069. fi
  5070. chmod 700 "$LE_WORKING_DIR"
  5071. fi
  5072. if [ ! -d "$LE_CONFIG_HOME" ]; then
  5073. if ! mkdir -p "$LE_CONFIG_HOME"; then
  5074. _err "Can not create config dir: $LE_CONFIG_HOME"
  5075. return 1
  5076. fi
  5077. chmod 700 "$LE_CONFIG_HOME"
  5078. fi
  5079. cp "$PROJECT_ENTRY" "$LE_WORKING_DIR/" && chmod +x "$LE_WORKING_DIR/$PROJECT_ENTRY"
  5080. if [ "$?" != "0" ]; then
  5081. _err "Install failed, can not copy $PROJECT_ENTRY"
  5082. return 1
  5083. fi
  5084. _info "Installed to $LE_WORKING_DIR/$PROJECT_ENTRY"
  5085. if [ "$ACME_IN_CRON" != "1" ] && [ -z "$_noprofile" ]; then
  5086. _installalias "$_c_home"
  5087. fi
  5088. for subf in $_SUB_FOLDERS; do
  5089. if [ -d "$subf" ]; then
  5090. mkdir -p "$LE_WORKING_DIR/$subf"
  5091. cp "$subf"/* "$LE_WORKING_DIR"/"$subf"/
  5092. fi
  5093. done
  5094. if [ ! -f "$ACCOUNT_CONF_PATH" ]; then
  5095. _initconf
  5096. fi
  5097. if [ "$_DEFAULT_ACCOUNT_CONF_PATH" != "$ACCOUNT_CONF_PATH" ]; then
  5098. _setopt "$_DEFAULT_ACCOUNT_CONF_PATH" "ACCOUNT_CONF_PATH" "=" "\"$ACCOUNT_CONF_PATH\""
  5099. fi
  5100. if [ "$_DEFAULT_CERT_HOME" != "$CERT_HOME" ]; then
  5101. _saveaccountconf "CERT_HOME" "$CERT_HOME"
  5102. fi
  5103. if [ "$_DEFAULT_ACCOUNT_KEY_PATH" != "$ACCOUNT_KEY_PATH" ]; then
  5104. _saveaccountconf "ACCOUNT_KEY_PATH" "$ACCOUNT_KEY_PATH"
  5105. fi
  5106. if [ -z "$_nocron" ]; then
  5107. installcronjob "$_c_home"
  5108. fi
  5109. if [ -z "$NO_DETECT_SH" ]; then
  5110. #Modify shebang
  5111. if _exists bash; then
  5112. _bash_path="$(bash -c "command -v bash 2>/dev/null")"
  5113. if [ -z "$_bash_path" ]; then
  5114. _bash_path="$(bash -c 'echo $SHELL')"
  5115. fi
  5116. fi
  5117. if [ "$_bash_path" ]; then
  5118. _info "Good, bash is found, so change the shebang to use bash as preferred."
  5119. _shebang='#!'"$_bash_path"
  5120. _setShebang "$LE_WORKING_DIR/$PROJECT_ENTRY" "$_shebang"
  5121. for subf in $_SUB_FOLDERS; do
  5122. if [ -d "$LE_WORKING_DIR/$subf" ]; then
  5123. for _apifile in "$LE_WORKING_DIR/$subf/"*.sh; do
  5124. _setShebang "$_apifile" "$_shebang"
  5125. done
  5126. fi
  5127. done
  5128. fi
  5129. fi
  5130. _info OK
  5131. }
  5132. # nocron
  5133. uninstall() {
  5134. _nocron="$1"
  5135. if [ -z "$_nocron" ]; then
  5136. uninstallcronjob
  5137. fi
  5138. _initpath
  5139. _uninstallalias
  5140. rm -f "$LE_WORKING_DIR/$PROJECT_ENTRY"
  5141. _info "The keys and certs are in \"$(__green "$LE_CONFIG_HOME")\", you can remove them by yourself."
  5142. }
  5143. _uninstallalias() {
  5144. _initpath
  5145. _profile="$(_detect_profile)"
  5146. if [ "$_profile" ]; then
  5147. _info "Uninstalling alias from: '$_profile'"
  5148. text="$(cat "$_profile")"
  5149. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.env\"$||" >"$_profile"
  5150. fi
  5151. _csh_profile="$HOME/.cshrc"
  5152. if [ -f "$_csh_profile" ]; then
  5153. _info "Uninstalling alias from: '$_csh_profile'"
  5154. text="$(cat "$_csh_profile")"
  5155. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.csh\"$||" >"$_csh_profile"
  5156. fi
  5157. _tcsh_profile="$HOME/.tcshrc"
  5158. if [ -f "$_tcsh_profile" ]; then
  5159. _info "Uninstalling alias from: '$_csh_profile'"
  5160. text="$(cat "$_tcsh_profile")"
  5161. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.csh\"$||" >"$_tcsh_profile"
  5162. fi
  5163. }
  5164. cron() {
  5165. export ACME_IN_CRON=1
  5166. _initpath
  5167. _info "$(__green "===Starting cron===")"
  5168. if [ "$AUTO_UPGRADE" = "1" ]; then
  5169. export LE_WORKING_DIR
  5170. (
  5171. if ! upgrade; then
  5172. _err "Cron:Upgrade failed!"
  5173. return 1
  5174. fi
  5175. )
  5176. . "$LE_WORKING_DIR/$PROJECT_ENTRY" >/dev/null
  5177. if [ -t 1 ]; then
  5178. __INTERACTIVE="1"
  5179. fi
  5180. _info "Auto upgraded to: $VER"
  5181. fi
  5182. renewAll
  5183. _ret="$?"
  5184. ACME_IN_CRON=""
  5185. _info "$(__green "===End cron===")"
  5186. exit $_ret
  5187. }
  5188. version() {
  5189. echo "$PROJECT"
  5190. echo "v$VER"
  5191. }
  5192. # subject content hooks code
  5193. _send_notify() {
  5194. _nsubject="$1"
  5195. _ncontent="$2"
  5196. _nhooks="$3"
  5197. _nerror="$4"
  5198. if [ "$NOTIFY_LEVEL" = "$NOTIFY_LEVEL_DISABLE" ]; then
  5199. _debug "The NOTIFY_LEVEL is $NOTIFY_LEVEL, disabled, just return."
  5200. return 0
  5201. fi
  5202. if [ -z "$_nhooks" ]; then
  5203. _debug "The NOTIFY_HOOK is empty, just return."
  5204. return 0
  5205. fi
  5206. _send_err=0
  5207. for _n_hook in $(echo "$_nhooks" | tr ',' " "); do
  5208. _n_hook_file="$(_findHook "" $_SUB_FOLDER_NOTIFY "$_n_hook")"
  5209. _info "Sending via: $_n_hook"
  5210. _debug "Found $_n_hook_file for $_n_hook"
  5211. if [ -z "$_n_hook_file" ]; then
  5212. _err "Can not find the hook file for $_n_hook"
  5213. continue
  5214. fi
  5215. if ! (
  5216. if ! . "$_n_hook_file"; then
  5217. _err "Load file $_n_hook_file error. Please check your api file and try again."
  5218. return 1
  5219. fi
  5220. d_command="${_n_hook}_send"
  5221. if ! _exists "$d_command"; then
  5222. _err "It seems that your api file is not correct, it must have a function named: $d_command"
  5223. return 1
  5224. fi
  5225. if ! $d_command "$_nsubject" "$_ncontent" "$_nerror"; then
  5226. _err "Error send message by $d_command"
  5227. return 1
  5228. fi
  5229. return 0
  5230. ); then
  5231. _err "Set $_n_hook_file error."
  5232. _send_err=1
  5233. else
  5234. _info "$_n_hook $(__green Success)"
  5235. fi
  5236. done
  5237. return $_send_err
  5238. }
  5239. # hook
  5240. _set_notify_hook() {
  5241. _nhooks="$1"
  5242. _test_subject="Hello, this is notification from $PROJECT_NAME"
  5243. _test_content="If you receive this message, your notification works."
  5244. _send_notify "$_test_subject" "$_test_content" "$_nhooks" 0
  5245. }
  5246. #[hook] [level] [mode]
  5247. setnotify() {
  5248. _nhook="$1"
  5249. _nlevel="$2"
  5250. _nmode="$3"
  5251. _initpath
  5252. if [ -z "$_nhook$_nlevel$_nmode" ]; then
  5253. _usage "Usage: $PROJECT_ENTRY --set-notify [--notify-hook mailgun] [--notify-level $NOTIFY_LEVEL_DEFAULT] [--notify-mode $NOTIFY_MODE_DEFAULT]"
  5254. _usage "$_NOTIFY_WIKI"
  5255. return 1
  5256. fi
  5257. if [ "$_nlevel" ]; then
  5258. _info "Set notify level to: $_nlevel"
  5259. export "NOTIFY_LEVEL=$_nlevel"
  5260. _saveaccountconf "NOTIFY_LEVEL" "$NOTIFY_LEVEL"
  5261. fi
  5262. if [ "$_nmode" ]; then
  5263. _info "Set notify mode to: $_nmode"
  5264. export "NOTIFY_MODE=$_nmode"
  5265. _saveaccountconf "NOTIFY_MODE" "$NOTIFY_MODE"
  5266. fi
  5267. if [ "$_nhook" ]; then
  5268. _info "Set notify hook to: $_nhook"
  5269. if [ "$_nhook" = "$NO_VALUE" ]; then
  5270. _info "Clear notify hook"
  5271. _clearaccountconf "NOTIFY_HOOK"
  5272. else
  5273. if _set_notify_hook "$_nhook"; then
  5274. export NOTIFY_HOOK="$_nhook"
  5275. _saveaccountconf "NOTIFY_HOOK" "$NOTIFY_HOOK"
  5276. return 0
  5277. else
  5278. _err "Can not set notify hook to: $_nhook"
  5279. return 1
  5280. fi
  5281. fi
  5282. fi
  5283. }
  5284. showhelp() {
  5285. _initpath
  5286. version
  5287. echo "Usage: $PROJECT_ENTRY command ...[parameters]....
  5288. Commands:
  5289. --help, -h Show this help message.
  5290. --version, -v Show version info.
  5291. --install Install $PROJECT_NAME to your system.
  5292. --uninstall Uninstall $PROJECT_NAME, and uninstall the cron job.
  5293. --upgrade Upgrade $PROJECT_NAME to the latest code from $PROJECT.
  5294. --issue Issue a cert.
  5295. --signcsr Issue a cert from an existing csr.
  5296. --deploy Deploy the cert to your server.
  5297. --install-cert Install the issued cert to apache/nginx or any other server.
  5298. --renew, -r Renew a cert.
  5299. --renew-all Renew all the certs.
  5300. --revoke Revoke a cert.
  5301. --remove Remove the cert from list of certs known to $PROJECT_NAME.
  5302. --list List all the certs.
  5303. --showcsr Show the content of a csr.
  5304. --install-cronjob Install the cron job to renew certs, you don't need to call this. The 'install' command can automatically install the cron job.
  5305. --uninstall-cronjob Uninstall the cron job. The 'uninstall' command can do this automatically.
  5306. --cron Run cron job to renew all the certs.
  5307. --toPkcs Export the certificate and key to a pfx file.
  5308. --toPkcs8 Convert to pkcs8 format.
  5309. --update-account Update account info.
  5310. --register-account Register account key.
  5311. --deactivate-account Deactivate the account.
  5312. --create-account-key Create an account private key, professional use.
  5313. --create-domain-key Create an domain private key, professional use.
  5314. --createCSR, -ccsr Create CSR , professional use.
  5315. --deactivate Deactivate the domain authz, professional use.
  5316. --set-notify Set the cron notification hook, level or mode.
  5317. Parameters:
  5318. --domain, -d domain.tld Specifies a domain, used to issue, renew or revoke etc.
  5319. --challenge-alias domain.tld The challenge domain alias for DNS alias mode: $_DNS_ALIAS_WIKI
  5320. --domain-alias domain.tld The domain alias for DNS alias mode: $_DNS_ALIAS_WIKI
  5321. --force, -f Used to force to install or force to renew a cert immediately.
  5322. --staging, --test Use staging server, just for test.
  5323. --debug Output debug info.
  5324. --output-insecure Output all the sensitive messages. By default all the credentials/sensitive messages are hidden from the output/debug/log for secure.
  5325. --webroot, -w /path/to/webroot Specifies the web root folder for web root mode.
  5326. --standalone Use standalone mode.
  5327. --alpn Use standalone alpn mode.
  5328. --stateless Use stateless mode, see: $_STATELESS_WIKI
  5329. --apache Use apache mode.
  5330. --dns [dns_cf|dns_dp|dns_cx|/path/to/api/file] Use dns mode or dns api.
  5331. --dnssleep [$DEFAULT_DNS_SLEEP] The time in seconds to wait for all the txt records to take effect in dns api mode. Default $DEFAULT_DNS_SLEEP seconds.
  5332. --keylength, -k [2048] Specifies the domain key length: 2048, 3072, 4096, 8192 or ec-256, ec-384.
  5333. --accountkeylength, -ak [2048] Specifies the account key length.
  5334. --log [/path/to/logfile] Specifies the log file. The default is: \"$DEFAULT_LOG_FILE\" if you don't give a file path here.
  5335. --log-level 1|2 Specifies the log level, default is 1.
  5336. --syslog [0|3|6|7] Syslog level, 0: disable syslog, 3: error, 6: info, 7: debug.
  5337. These parameters are to install the cert to nginx/apache or any other server after issue/renew a cert:
  5338. --cert-file After issue/renew, the cert will be copied to this path.
  5339. --key-file After issue/renew, the key will be copied to this path.
  5340. --ca-file After issue/renew, the intermediate cert will be copied to this path.
  5341. --fullchain-file After issue/renew, the fullchain cert will be copied to this path.
  5342. --reloadcmd \"service nginx reload\" After issue/renew, it's used to reload the server.
  5343. --server SERVER ACME Directory Resource URI. (default: https://acme-v01.api.letsencrypt.org/directory)
  5344. --accountconf Specifies a customized account config file.
  5345. --home Specifies the home dir for $PROJECT_NAME.
  5346. --cert-home Specifies the home dir to save all the certs, only valid for '--install' command.
  5347. --config-home Specifies the home dir to save all the configurations.
  5348. --useragent Specifies the user agent string. it will be saved for future use too.
  5349. --accountemail Specifies the account email, only valid for the '--install' and '--update-account' command.
  5350. --accountkey Specifies the account key path, only valid for the '--install' command.
  5351. --days Specifies the days to renew the cert when using '--issue' command. The default value is $DEFAULT_RENEW days.
  5352. --httpport Specifies the standalone listening port. Only valid if the server is behind a reverse proxy or load balancer.
  5353. --tlsport Specifies the standalone tls listening port. Only valid if the server is behind a reverse proxy or load balancer.
  5354. --local-address Specifies the standalone/tls server listening address, in case you have multiple ip addresses.
  5355. --listraw Only used for '--list' command, list the certs in raw format.
  5356. --stopRenewOnError, -se Only valid for '--renew-all' command. Stop if one cert has error in renewal.
  5357. --insecure Do not check the server certificate, in some devices, the api server's certificate may not be trusted.
  5358. --ca-bundle Specifies the path to the CA certificate bundle to verify api server's certificate.
  5359. --ca-path Specifies directory containing CA certificates in PEM format, used by wget or curl.
  5360. --nocron Only valid for '--install' command, which means: do not install the default cron job. In this case, the certs will not be renewed automatically.
  5361. --noprofile Only valid for '--install' command, which means: do not install aliases to user profile.
  5362. --no-color Do not output color text.
  5363. --force-color Force output of color text. Useful for non-interactive use with the aha tool for HTML E-Mails.
  5364. --ecc Specifies to use the ECC cert. Valid for '--install-cert', '--renew', '--revoke', '--toPkcs' and '--createCSR'
  5365. --csr Specifies the input csr.
  5366. --pre-hook Command to be run before obtaining any certificates.
  5367. --post-hook Command to be run after attempting to obtain/renew certificates. No matter the obtain/renew is success or failed.
  5368. --renew-hook Command to be run once for each successfully renewed certificate.
  5369. --deploy-hook The hook file to deploy cert
  5370. --ocsp-must-staple, --ocsp Generate ocsp must Staple extension.
  5371. --always-force-new-domain-key Generate new domain key when renewal. Otherwise, the domain key is not changed by default.
  5372. --auto-upgrade [0|1] Valid for '--upgrade' command, indicating whether to upgrade automatically in future.
  5373. --listen-v4 Force standalone/tls server to listen at ipv4.
  5374. --listen-v6 Force standalone/tls server to listen at ipv6.
  5375. --openssl-bin Specifies a custom openssl bin location.
  5376. --use-wget Force to use wget, if you have both curl and wget installed.
  5377. --yes-I-know-dns-manual-mode-enough-go-ahead-please Force to use dns manual mode: $_DNS_MANUAL_WIKI
  5378. --branch, -b Only valid for '--upgrade' command, specifies the branch name to upgrade to.
  5379. --notify-level 0|1|2|3 Set the notification level: Default value is $NOTIFY_LEVEL_DEFAULT.
  5380. 0: disabled, no notification will be sent.
  5381. 1: send notifications only when there is an error.
  5382. 2: send notifications when a cert is successfully renewed, or there is an error.
  5383. 3: send notifications when a cert is skipped, renewed, or error.
  5384. --notify-mode 0|1 Set notification mode. Default value is $NOTIFY_MODE_DEFAULT.
  5385. 0: Bulk mode. Send all the domain's notifications in one message(mail).
  5386. 1: Cert mode. Send a message for every single cert.
  5387. --notify-hook [hookname] Set the notify hook
  5388. "
  5389. }
  5390. # nocron noprofile
  5391. _installOnline() {
  5392. _info "Installing from online archive."
  5393. _nocron="$1"
  5394. _noprofile="$2"
  5395. if [ ! "$BRANCH" ]; then
  5396. BRANCH="master"
  5397. fi
  5398. target="$PROJECT/archive/$BRANCH.tar.gz"
  5399. _info "Downloading $target"
  5400. localname="$BRANCH.tar.gz"
  5401. if ! _get "$target" >$localname; then
  5402. _err "Download error."
  5403. return 1
  5404. fi
  5405. (
  5406. _info "Extracting $localname"
  5407. if ! (tar xzf $localname || gtar xzf $localname); then
  5408. _err "Extraction error."
  5409. exit 1
  5410. fi
  5411. cd "$PROJECT_NAME-$BRANCH"
  5412. chmod +x $PROJECT_ENTRY
  5413. if ./$PROJECT_ENTRY install "$_nocron" "" "$_noprofile"; then
  5414. _info "Install success!"
  5415. fi
  5416. cd ..
  5417. rm -rf "$PROJECT_NAME-$BRANCH"
  5418. rm -f "$localname"
  5419. )
  5420. }
  5421. upgrade() {
  5422. if (
  5423. _initpath
  5424. export LE_WORKING_DIR
  5425. cd "$LE_WORKING_DIR"
  5426. _installOnline "nocron" "noprofile"
  5427. ); then
  5428. _info "Upgrade success!"
  5429. exit 0
  5430. else
  5431. _err "Upgrade failed!"
  5432. exit 1
  5433. fi
  5434. }
  5435. _processAccountConf() {
  5436. if [ "$_useragent" ]; then
  5437. _saveaccountconf "USER_AGENT" "$_useragent"
  5438. elif [ "$USER_AGENT" ] && [ "$USER_AGENT" != "$DEFAULT_USER_AGENT" ]; then
  5439. _saveaccountconf "USER_AGENT" "$USER_AGENT"
  5440. fi
  5441. if [ "$_accountemail" ]; then
  5442. _saveaccountconf "ACCOUNT_EMAIL" "$_accountemail"
  5443. elif [ "$ACCOUNT_EMAIL" ] && [ "$ACCOUNT_EMAIL" != "$DEFAULT_ACCOUNT_EMAIL" ]; then
  5444. _saveaccountconf "ACCOUNT_EMAIL" "$ACCOUNT_EMAIL"
  5445. fi
  5446. if [ "$_openssl_bin" ]; then
  5447. _saveaccountconf "ACME_OPENSSL_BIN" "$_openssl_bin"
  5448. elif [ "$ACME_OPENSSL_BIN" ] && [ "$ACME_OPENSSL_BIN" != "$DEFAULT_OPENSSL_BIN" ]; then
  5449. _saveaccountconf "ACME_OPENSSL_BIN" "$ACME_OPENSSL_BIN"
  5450. fi
  5451. if [ "$_auto_upgrade" ]; then
  5452. _saveaccountconf "AUTO_UPGRADE" "$_auto_upgrade"
  5453. elif [ "$AUTO_UPGRADE" ]; then
  5454. _saveaccountconf "AUTO_UPGRADE" "$AUTO_UPGRADE"
  5455. fi
  5456. if [ "$_use_wget" ]; then
  5457. _saveaccountconf "ACME_USE_WGET" "$_use_wget"
  5458. elif [ "$ACME_USE_WGET" ]; then
  5459. _saveaccountconf "ACME_USE_WGET" "$ACME_USE_WGET"
  5460. fi
  5461. }
  5462. _checkSudo() {
  5463. if [ "$SUDO_GID" ] && [ "$SUDO_COMMAND" ] && [ "$SUDO_USER" ] && [ "$SUDO_UID" ]; then
  5464. if [ "$SUDO_USER" = "root" ] && [ "$SUDO_UID" = "0" ]; then
  5465. #it's root using sudo, no matter it's using sudo or not, just fine
  5466. return 0
  5467. fi
  5468. if [ "$SUDO_COMMAND" = "/bin/su" ] || [ "$SUDO_COMMAND" = "/bin/bash" ]; then
  5469. #it's a normal user doing "sudo su", or `sudo -i` or `sudo -s`
  5470. #fine
  5471. return 0
  5472. fi
  5473. #otherwise
  5474. return 1
  5475. fi
  5476. return 0
  5477. }
  5478. _process() {
  5479. _CMD=""
  5480. _domain=""
  5481. _altdomains="$NO_VALUE"
  5482. _webroot=""
  5483. _challenge_alias=""
  5484. _keylength=""
  5485. _accountkeylength=""
  5486. _cert_file=""
  5487. _key_file=""
  5488. _ca_file=""
  5489. _fullchain_file=""
  5490. _reloadcmd=""
  5491. _password=""
  5492. _accountconf=""
  5493. _useragent=""
  5494. _accountemail=""
  5495. _accountkey=""
  5496. _certhome=""
  5497. _confighome=""
  5498. _httpport=""
  5499. _tlsport=""
  5500. _dnssleep=""
  5501. _listraw=""
  5502. _stopRenewOnError=""
  5503. #_insecure=""
  5504. _ca_bundle=""
  5505. _ca_path=""
  5506. _nocron=""
  5507. _noprofile=""
  5508. _ecc=""
  5509. _csr=""
  5510. _pre_hook=""
  5511. _post_hook=""
  5512. _renew_hook=""
  5513. _deploy_hook=""
  5514. _logfile=""
  5515. _log=""
  5516. _local_address=""
  5517. _log_level=""
  5518. _auto_upgrade=""
  5519. _listen_v4=""
  5520. _listen_v6=""
  5521. _openssl_bin=""
  5522. _syslog=""
  5523. _use_wget=""
  5524. _server=""
  5525. _notify_hook=""
  5526. _notify_level=""
  5527. _notify_mode=""
  5528. while [ ${#} -gt 0 ]; do
  5529. case "${1}" in
  5530. --help | -h)
  5531. showhelp
  5532. return
  5533. ;;
  5534. --version | -v)
  5535. version
  5536. return
  5537. ;;
  5538. --install)
  5539. _CMD="install"
  5540. ;;
  5541. --uninstall)
  5542. _CMD="uninstall"
  5543. ;;
  5544. --upgrade)
  5545. _CMD="upgrade"
  5546. ;;
  5547. --issue)
  5548. _CMD="issue"
  5549. ;;
  5550. --deploy)
  5551. _CMD="deploy"
  5552. ;;
  5553. --signcsr)
  5554. _CMD="signcsr"
  5555. ;;
  5556. --showcsr)
  5557. _CMD="showcsr"
  5558. ;;
  5559. --installcert | -i | --install-cert)
  5560. _CMD="installcert"
  5561. ;;
  5562. --renew | -r)
  5563. _CMD="renew"
  5564. ;;
  5565. --renewAll | --renewall | --renew-all)
  5566. _CMD="renewAll"
  5567. ;;
  5568. --revoke)
  5569. _CMD="revoke"
  5570. ;;
  5571. --remove)
  5572. _CMD="remove"
  5573. ;;
  5574. --list)
  5575. _CMD="list"
  5576. ;;
  5577. --installcronjob | --install-cronjob)
  5578. _CMD="installcronjob"
  5579. ;;
  5580. --uninstallcronjob | --uninstall-cronjob)
  5581. _CMD="uninstallcronjob"
  5582. ;;
  5583. --cron)
  5584. _CMD="cron"
  5585. ;;
  5586. --toPkcs)
  5587. _CMD="toPkcs"
  5588. ;;
  5589. --toPkcs8)
  5590. _CMD="toPkcs8"
  5591. ;;
  5592. --createAccountKey | --createaccountkey | -cak | --create-account-key)
  5593. _CMD="createAccountKey"
  5594. ;;
  5595. --createDomainKey | --createdomainkey | -cdk | --create-domain-key)
  5596. _CMD="createDomainKey"
  5597. ;;
  5598. --createCSR | --createcsr | -ccr)
  5599. _CMD="createCSR"
  5600. ;;
  5601. --deactivate)
  5602. _CMD="deactivate"
  5603. ;;
  5604. --updateaccount | --update-account)
  5605. _CMD="updateaccount"
  5606. ;;
  5607. --registeraccount | --register-account)
  5608. _CMD="registeraccount"
  5609. ;;
  5610. --deactivate-account)
  5611. _CMD="deactivateaccount"
  5612. ;;
  5613. --set-notify)
  5614. _CMD="setnotify"
  5615. ;;
  5616. --domain | -d)
  5617. _dvalue="$2"
  5618. if [ "$_dvalue" ]; then
  5619. if _startswith "$_dvalue" "-"; then
  5620. _err "'$_dvalue' is not a valid domain for parameter '$1'"
  5621. return 1
  5622. fi
  5623. if _is_idn "$_dvalue" && ! _exists idn; then
  5624. _err "It seems that $_dvalue is an IDN( Internationalized Domain Names), please install 'idn' command first."
  5625. return 1
  5626. fi
  5627. if _startswith "$_dvalue" "*."; then
  5628. _debug "Wildcard domain"
  5629. export ACME_VERSION=2
  5630. fi
  5631. if [ -z "$_domain" ]; then
  5632. _domain="$_dvalue"
  5633. else
  5634. if [ "$_altdomains" = "$NO_VALUE" ]; then
  5635. _altdomains="$_dvalue"
  5636. else
  5637. _altdomains="$_altdomains,$_dvalue"
  5638. fi
  5639. fi
  5640. fi
  5641. shift
  5642. ;;
  5643. --force | -f)
  5644. FORCE="1"
  5645. ;;
  5646. --staging | --test)
  5647. STAGE="1"
  5648. ;;
  5649. --server)
  5650. ACME_DIRECTORY="$2"
  5651. _server="$ACME_DIRECTORY"
  5652. export ACME_DIRECTORY
  5653. shift
  5654. ;;
  5655. --debug)
  5656. if [ -z "$2" ] || _startswith "$2" "-"; then
  5657. DEBUG="$DEBUG_LEVEL_DEFAULT"
  5658. else
  5659. DEBUG="$2"
  5660. shift
  5661. fi
  5662. ;;
  5663. --output-insecure)
  5664. export OUTPUT_INSECURE=1
  5665. ;;
  5666. --webroot | -w)
  5667. wvalue="$2"
  5668. if [ -z "$_webroot" ]; then
  5669. _webroot="$wvalue"
  5670. else
  5671. _webroot="$_webroot,$wvalue"
  5672. fi
  5673. shift
  5674. ;;
  5675. --challenge-alias)
  5676. cvalue="$2"
  5677. _challenge_alias="$_challenge_alias$cvalue,"
  5678. shift
  5679. ;;
  5680. --domain-alias)
  5681. cvalue="$DNS_ALIAS_PREFIX$2"
  5682. _challenge_alias="$_challenge_alias$cvalue,"
  5683. shift
  5684. ;;
  5685. --standalone)
  5686. wvalue="$NO_VALUE"
  5687. if [ -z "$_webroot" ]; then
  5688. _webroot="$wvalue"
  5689. else
  5690. _webroot="$_webroot,$wvalue"
  5691. fi
  5692. ;;
  5693. --alpn)
  5694. wvalue="$W_ALPN"
  5695. if [ -z "$_webroot" ]; then
  5696. _webroot="$wvalue"
  5697. else
  5698. _webroot="$_webroot,$wvalue"
  5699. fi
  5700. ;;
  5701. --stateless)
  5702. wvalue="$MODE_STATELESS"
  5703. if [ -z "$_webroot" ]; then
  5704. _webroot="$wvalue"
  5705. else
  5706. _webroot="$_webroot,$wvalue"
  5707. fi
  5708. ;;
  5709. --local-address)
  5710. lvalue="$2"
  5711. _local_address="$_local_address$lvalue,"
  5712. shift
  5713. ;;
  5714. --apache)
  5715. wvalue="apache"
  5716. if [ -z "$_webroot" ]; then
  5717. _webroot="$wvalue"
  5718. else
  5719. _webroot="$_webroot,$wvalue"
  5720. fi
  5721. ;;
  5722. --nginx)
  5723. wvalue="$NGINX"
  5724. if [ "$2" ] && ! _startswith "$2" "-"; then
  5725. wvalue="$NGINX$2"
  5726. shift
  5727. fi
  5728. if [ -z "$_webroot" ]; then
  5729. _webroot="$wvalue"
  5730. else
  5731. _webroot="$_webroot,$wvalue"
  5732. fi
  5733. ;;
  5734. --dns)
  5735. wvalue="$W_DNS"
  5736. if [ "$2" ] && ! _startswith "$2" "-"; then
  5737. wvalue="$2"
  5738. shift
  5739. fi
  5740. if [ -z "$_webroot" ]; then
  5741. _webroot="$wvalue"
  5742. else
  5743. _webroot="$_webroot,$wvalue"
  5744. fi
  5745. ;;
  5746. --dnssleep)
  5747. _dnssleep="$2"
  5748. Le_DNSSleep="$_dnssleep"
  5749. shift
  5750. ;;
  5751. --keylength | -k)
  5752. _keylength="$2"
  5753. shift
  5754. ;;
  5755. --accountkeylength | -ak)
  5756. _accountkeylength="$2"
  5757. shift
  5758. ;;
  5759. --cert-file | --certpath)
  5760. _cert_file="$2"
  5761. shift
  5762. ;;
  5763. --key-file | --keypath)
  5764. _key_file="$2"
  5765. shift
  5766. ;;
  5767. --ca-file | --capath)
  5768. _ca_file="$2"
  5769. shift
  5770. ;;
  5771. --fullchain-file | --fullchainpath)
  5772. _fullchain_file="$2"
  5773. shift
  5774. ;;
  5775. --reloadcmd | --reloadCmd)
  5776. _reloadcmd="$2"
  5777. shift
  5778. ;;
  5779. --password)
  5780. _password="$2"
  5781. shift
  5782. ;;
  5783. --accountconf)
  5784. _accountconf="$2"
  5785. ACCOUNT_CONF_PATH="$_accountconf"
  5786. shift
  5787. ;;
  5788. --home)
  5789. LE_WORKING_DIR="$2"
  5790. shift
  5791. ;;
  5792. --certhome | --cert-home)
  5793. _certhome="$2"
  5794. CERT_HOME="$_certhome"
  5795. shift
  5796. ;;
  5797. --config-home)
  5798. _confighome="$2"
  5799. LE_CONFIG_HOME="$_confighome"
  5800. shift
  5801. ;;
  5802. --useragent)
  5803. _useragent="$2"
  5804. USER_AGENT="$_useragent"
  5805. shift
  5806. ;;
  5807. --accountemail)
  5808. _accountemail="$2"
  5809. ACCOUNT_EMAIL="$_accountemail"
  5810. shift
  5811. ;;
  5812. --accountkey)
  5813. _accountkey="$2"
  5814. ACCOUNT_KEY_PATH="$_accountkey"
  5815. shift
  5816. ;;
  5817. --days)
  5818. _days="$2"
  5819. Le_RenewalDays="$_days"
  5820. shift
  5821. ;;
  5822. --httpport)
  5823. _httpport="$2"
  5824. Le_HTTPPort="$_httpport"
  5825. shift
  5826. ;;
  5827. --tlsport)
  5828. _tlsport="$2"
  5829. Le_TLSPort="$_tlsport"
  5830. shift
  5831. ;;
  5832. --listraw)
  5833. _listraw="raw"
  5834. ;;
  5835. --stopRenewOnError | --stoprenewonerror | -se)
  5836. _stopRenewOnError="1"
  5837. ;;
  5838. --insecure)
  5839. #_insecure="1"
  5840. HTTPS_INSECURE="1"
  5841. ;;
  5842. --ca-bundle)
  5843. _ca_bundle="$(_readlink "$2")"
  5844. CA_BUNDLE="$_ca_bundle"
  5845. shift
  5846. ;;
  5847. --ca-path)
  5848. _ca_path="$2"
  5849. CA_PATH="$_ca_path"
  5850. shift
  5851. ;;
  5852. --nocron)
  5853. _nocron="1"
  5854. ;;
  5855. --noprofile)
  5856. _noprofile="1"
  5857. ;;
  5858. --no-color)
  5859. export ACME_NO_COLOR=1
  5860. ;;
  5861. --force-color)
  5862. export ACME_FORCE_COLOR=1
  5863. ;;
  5864. --ecc)
  5865. _ecc="isEcc"
  5866. ;;
  5867. --csr)
  5868. _csr="$2"
  5869. shift
  5870. ;;
  5871. --pre-hook)
  5872. _pre_hook="$2"
  5873. shift
  5874. ;;
  5875. --post-hook)
  5876. _post_hook="$2"
  5877. shift
  5878. ;;
  5879. --renew-hook)
  5880. _renew_hook="$2"
  5881. shift
  5882. ;;
  5883. --deploy-hook)
  5884. if [ -z "$2" ] || _startswith "$2" "-"; then
  5885. _usage "Please specify a value for '--deploy-hook'"
  5886. return 1
  5887. fi
  5888. _deploy_hook="$_deploy_hook$2,"
  5889. shift
  5890. ;;
  5891. --ocsp-must-staple | --ocsp)
  5892. Le_OCSP_Staple="1"
  5893. ;;
  5894. --always-force-new-domain-key)
  5895. if [ -z "$2" ] || _startswith "$2" "-"; then
  5896. Le_ForceNewDomainKey=1
  5897. else
  5898. Le_ForceNewDomainKey="$2"
  5899. shift
  5900. fi
  5901. ;;
  5902. --yes-I-know-dns-manual-mode-enough-go-ahead-please)
  5903. export FORCE_DNS_MANUAL=1
  5904. ;;
  5905. --log | --logfile)
  5906. _log="1"
  5907. _logfile="$2"
  5908. if _startswith "$_logfile" '-'; then
  5909. _logfile=""
  5910. else
  5911. shift
  5912. fi
  5913. LOG_FILE="$_logfile"
  5914. if [ -z "$LOG_LEVEL" ]; then
  5915. LOG_LEVEL="$DEFAULT_LOG_LEVEL"
  5916. fi
  5917. ;;
  5918. --log-level)
  5919. _log_level="$2"
  5920. LOG_LEVEL="$_log_level"
  5921. shift
  5922. ;;
  5923. --syslog)
  5924. if ! _startswith "$2" '-'; then
  5925. _syslog="$2"
  5926. shift
  5927. fi
  5928. if [ -z "$_syslog" ]; then
  5929. _syslog="$SYSLOG_LEVEL_DEFAULT"
  5930. fi
  5931. ;;
  5932. --auto-upgrade)
  5933. _auto_upgrade="$2"
  5934. if [ -z "$_auto_upgrade" ] || _startswith "$_auto_upgrade" '-'; then
  5935. _auto_upgrade="1"
  5936. else
  5937. shift
  5938. fi
  5939. AUTO_UPGRADE="$_auto_upgrade"
  5940. ;;
  5941. --listen-v4)
  5942. _listen_v4="1"
  5943. Le_Listen_V4="$_listen_v4"
  5944. ;;
  5945. --listen-v6)
  5946. _listen_v6="1"
  5947. Le_Listen_V6="$_listen_v6"
  5948. ;;
  5949. --openssl-bin)
  5950. _openssl_bin="$2"
  5951. ACME_OPENSSL_BIN="$_openssl_bin"
  5952. shift
  5953. ;;
  5954. --use-wget)
  5955. _use_wget="1"
  5956. ACME_USE_WGET="1"
  5957. ;;
  5958. --branch | -b)
  5959. export BRANCH="$2"
  5960. shift
  5961. ;;
  5962. --notify-hook)
  5963. _nhook="$2"
  5964. if _startswith "$_nhook" "-"; then
  5965. _err "'$_nhook' is not a hook name for '$1'"
  5966. return 1
  5967. fi
  5968. if [ "$_notify_hook" ]; then
  5969. _notify_hook="$_notify_hook,$_nhook"
  5970. else
  5971. _notify_hook="$_nhook"
  5972. fi
  5973. shift
  5974. ;;
  5975. --notify-level)
  5976. _nlevel="$2"
  5977. if _startswith "$_nlevel" "-"; then
  5978. _err "'$_nlevel' is not a integer for '$1'"
  5979. return 1
  5980. fi
  5981. _notify_level="$_nlevel"
  5982. shift
  5983. ;;
  5984. --notify-mode)
  5985. _nmode="$2"
  5986. if _startswith "$_nmode" "-"; then
  5987. _err "'$_nmode' is not a integer for '$1'"
  5988. return 1
  5989. fi
  5990. _notify_mode="$_nmode"
  5991. shift
  5992. ;;
  5993. *)
  5994. _err "Unknown parameter : $1"
  5995. return 1
  5996. ;;
  5997. esac
  5998. shift 1
  5999. done
  6000. if [ "${_CMD}" != "install" ]; then
  6001. if [ "$__INTERACTIVE" ] && ! _checkSudo; then
  6002. if [ -z "$FORCE" ]; then
  6003. #Use "echo" here, instead of _info. it's too early
  6004. echo "It seems that you are using sudo, please read this link first:"
  6005. echo "$_SUDO_WIKI"
  6006. return 1
  6007. fi
  6008. fi
  6009. __initHome
  6010. if [ "$_log" ]; then
  6011. if [ -z "$_logfile" ]; then
  6012. _logfile="$DEFAULT_LOG_FILE"
  6013. fi
  6014. fi
  6015. if [ "$_logfile" ]; then
  6016. _saveaccountconf "LOG_FILE" "$_logfile"
  6017. LOG_FILE="$_logfile"
  6018. fi
  6019. if [ "$_log_level" ]; then
  6020. _saveaccountconf "LOG_LEVEL" "$_log_level"
  6021. LOG_LEVEL="$_log_level"
  6022. fi
  6023. if [ "$_syslog" ]; then
  6024. if _exists logger; then
  6025. if [ "$_syslog" = "0" ]; then
  6026. _clearaccountconf "SYS_LOG"
  6027. else
  6028. _saveaccountconf "SYS_LOG" "$_syslog"
  6029. fi
  6030. SYS_LOG="$_syslog"
  6031. else
  6032. _err "The 'logger' command is not found, can not enable syslog."
  6033. _clearaccountconf "SYS_LOG"
  6034. SYS_LOG=""
  6035. fi
  6036. fi
  6037. _processAccountConf
  6038. fi
  6039. _debug2 LE_WORKING_DIR "$LE_WORKING_DIR"
  6040. if [ "$DEBUG" ]; then
  6041. version
  6042. if [ "$_server" ]; then
  6043. _debug "Using server: $_server"
  6044. fi
  6045. fi
  6046. _debug "Running cmd: ${_CMD}"
  6047. case "${_CMD}" in
  6048. install) install "$_nocron" "$_confighome" "$_noprofile" ;;
  6049. uninstall) uninstall "$_nocron" ;;
  6050. upgrade) upgrade ;;
  6051. issue)
  6052. issue "$_webroot" "$_domain" "$_altdomains" "$_keylength" "$_cert_file" "$_key_file" "$_ca_file" "$_reloadcmd" "$_fullchain_file" "$_pre_hook" "$_post_hook" "$_renew_hook" "$_local_address" "$_challenge_alias"
  6053. ;;
  6054. deploy)
  6055. deploy "$_domain" "$_deploy_hook" "$_ecc"
  6056. ;;
  6057. signcsr)
  6058. signcsr "$_csr" "$_webroot" "$_cert_file" "$_key_file" "$_ca_file" "$_reloadcmd" "$_fullchain_file" "$_pre_hook" "$_post_hook" "$_renew_hook" "$_local_address" "$_challenge_alias"
  6059. ;;
  6060. showcsr)
  6061. showcsr "$_csr" "$_domain"
  6062. ;;
  6063. installcert)
  6064. installcert "$_domain" "$_cert_file" "$_key_file" "$_ca_file" "$_reloadcmd" "$_fullchain_file" "$_ecc"
  6065. ;;
  6066. renew)
  6067. renew "$_domain" "$_ecc"
  6068. ;;
  6069. renewAll)
  6070. renewAll "$_stopRenewOnError"
  6071. ;;
  6072. revoke)
  6073. revoke "$_domain" "$_ecc"
  6074. ;;
  6075. remove)
  6076. remove "$_domain" "$_ecc"
  6077. ;;
  6078. deactivate)
  6079. deactivate "$_domain,$_altdomains"
  6080. ;;
  6081. registeraccount)
  6082. registeraccount "$_accountkeylength"
  6083. ;;
  6084. updateaccount)
  6085. updateaccount
  6086. ;;
  6087. deactivateaccount)
  6088. deactivateaccount
  6089. ;;
  6090. list)
  6091. list "$_listraw"
  6092. ;;
  6093. installcronjob) installcronjob "$_confighome" ;;
  6094. uninstallcronjob) uninstallcronjob ;;
  6095. cron) cron ;;
  6096. toPkcs)
  6097. toPkcs "$_domain" "$_password" "$_ecc"
  6098. ;;
  6099. toPkcs8)
  6100. toPkcs8 "$_domain" "$_ecc"
  6101. ;;
  6102. createAccountKey)
  6103. createAccountKey "$_accountkeylength"
  6104. ;;
  6105. createDomainKey)
  6106. createDomainKey "$_domain" "$_keylength"
  6107. ;;
  6108. createCSR)
  6109. createCSR "$_domain" "$_altdomains" "$_ecc"
  6110. ;;
  6111. setnotify)
  6112. setnotify "$_notify_hook" "$_notify_level" "$_notify_mode"
  6113. ;;
  6114. *)
  6115. if [ "$_CMD" ]; then
  6116. _err "Invalid command: $_CMD"
  6117. fi
  6118. showhelp
  6119. return 1
  6120. ;;
  6121. esac
  6122. _ret="$?"
  6123. if [ "$_ret" != "0" ]; then
  6124. return $_ret
  6125. fi
  6126. if [ "${_CMD}" = "install" ]; then
  6127. if [ "$_log" ]; then
  6128. if [ -z "$LOG_FILE" ]; then
  6129. LOG_FILE="$DEFAULT_LOG_FILE"
  6130. fi
  6131. _saveaccountconf "LOG_FILE" "$LOG_FILE"
  6132. fi
  6133. if [ "$_log_level" ]; then
  6134. _saveaccountconf "LOG_LEVEL" "$_log_level"
  6135. fi
  6136. if [ "$_syslog" ]; then
  6137. if _exists logger; then
  6138. if [ "$_syslog" = "0" ]; then
  6139. _clearaccountconf "SYS_LOG"
  6140. else
  6141. _saveaccountconf "SYS_LOG" "$_syslog"
  6142. fi
  6143. else
  6144. _err "The 'logger' command is not found, can not enable syslog."
  6145. _clearaccountconf "SYS_LOG"
  6146. SYS_LOG=""
  6147. fi
  6148. fi
  6149. _processAccountConf
  6150. fi
  6151. }
  6152. if [ "$INSTALLONLINE" ]; then
  6153. INSTALLONLINE=""
  6154. _installOnline
  6155. exit
  6156. fi
  6157. main() {
  6158. [ -z "$1" ] && showhelp && return
  6159. if _startswith "$1" '-'; then _process "$@"; else "$@"; fi
  6160. }
  6161. main "$@"