acme.sh 185 KB

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