You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

config.go 36KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211
  1. // Copyright (c) 2012-2014 Jeremy Latt
  2. // Copyright (c) 2014-2015 Edmund Huber
  3. // Copyright (c) 2016-2017 Daniel Oaks <daniel@danieloaks.net>
  4. // released under the MIT license
  5. package irc
  6. import (
  7. "crypto/tls"
  8. "errors"
  9. "fmt"
  10. "io/ioutil"
  11. "log"
  12. "net"
  13. "os"
  14. "regexp"
  15. "sort"
  16. "strconv"
  17. "strings"
  18. "time"
  19. "code.cloudfoundry.org/bytefmt"
  20. "github.com/oragono/oragono/irc/caps"
  21. "github.com/oragono/oragono/irc/cloaks"
  22. "github.com/oragono/oragono/irc/connection_limits"
  23. "github.com/oragono/oragono/irc/custime"
  24. "github.com/oragono/oragono/irc/isupport"
  25. "github.com/oragono/oragono/irc/languages"
  26. "github.com/oragono/oragono/irc/ldap"
  27. "github.com/oragono/oragono/irc/logger"
  28. "github.com/oragono/oragono/irc/modes"
  29. "github.com/oragono/oragono/irc/mysql"
  30. "github.com/oragono/oragono/irc/passwd"
  31. "github.com/oragono/oragono/irc/utils"
  32. "gopkg.in/yaml.v2"
  33. )
  34. // here's how this works: exported (capitalized) members of the config structs
  35. // are defined in the YAML file and deserialized directly from there. They may
  36. // be postprocessed and overwritten by LoadConfig. Unexported (lowercase) members
  37. // are derived from the exported members in LoadConfig.
  38. // TLSListenConfig defines configuration options for listening on TLS.
  39. type TLSListenConfig struct {
  40. Cert string
  41. Key string
  42. Proxy bool
  43. }
  44. // This is the YAML-deserializable type of the value of the `Server.Listeners` map
  45. type listenerConfigBlock struct {
  46. TLS TLSListenConfig
  47. Tor bool
  48. STSOnly bool `yaml:"sts-only"`
  49. }
  50. // listenerConfig is the config governing a particular listener (bound address),
  51. // in particular whether it has TLS or Tor (or both) enabled.
  52. type listenerConfig struct {
  53. TLSConfig *tls.Config
  54. Tor bool
  55. STSOnly bool
  56. ProxyBeforeTLS bool
  57. }
  58. type PersistentStatus uint
  59. const (
  60. PersistentUnspecified PersistentStatus = iota
  61. PersistentDisabled
  62. PersistentOptIn
  63. PersistentOptOut
  64. PersistentMandatory
  65. )
  66. func persistentStatusToString(status PersistentStatus) string {
  67. switch status {
  68. case PersistentUnspecified:
  69. return "default"
  70. case PersistentDisabled:
  71. return "disabled"
  72. case PersistentOptIn:
  73. return "opt-in"
  74. case PersistentOptOut:
  75. return "opt-out"
  76. case PersistentMandatory:
  77. return "mandatory"
  78. default:
  79. return ""
  80. }
  81. }
  82. func persistentStatusFromString(status string) (PersistentStatus, error) {
  83. switch strings.ToLower(status) {
  84. case "default":
  85. return PersistentUnspecified, nil
  86. case "":
  87. return PersistentDisabled, nil
  88. case "opt-in":
  89. return PersistentOptIn, nil
  90. case "opt-out":
  91. return PersistentOptOut, nil
  92. case "mandatory":
  93. return PersistentMandatory, nil
  94. default:
  95. b, err := utils.StringToBool(status)
  96. if b {
  97. return PersistentMandatory, err
  98. } else {
  99. return PersistentDisabled, err
  100. }
  101. }
  102. }
  103. func (ps *PersistentStatus) UnmarshalYAML(unmarshal func(interface{}) error) error {
  104. var orig string
  105. var err error
  106. if err = unmarshal(&orig); err != nil {
  107. return err
  108. }
  109. result, err := persistentStatusFromString(orig)
  110. if err == nil {
  111. if result == PersistentUnspecified {
  112. result = PersistentDisabled
  113. }
  114. *ps = result
  115. }
  116. return err
  117. }
  118. func persistenceEnabled(serverSetting, clientSetting PersistentStatus) (enabled bool) {
  119. if serverSetting == PersistentDisabled {
  120. return false
  121. } else if serverSetting == PersistentMandatory {
  122. return true
  123. } else if clientSetting == PersistentDisabled {
  124. return false
  125. } else if clientSetting == PersistentMandatory {
  126. return true
  127. } else if serverSetting == PersistentOptOut {
  128. return true
  129. } else {
  130. return false
  131. }
  132. }
  133. type HistoryStatus uint
  134. const (
  135. HistoryDefault HistoryStatus = iota
  136. HistoryDisabled
  137. HistoryEphemeral
  138. HistoryPersistent
  139. )
  140. func historyStatusFromString(str string) (status HistoryStatus, err error) {
  141. switch strings.ToLower(str) {
  142. case "default":
  143. return HistoryDefault, nil
  144. case "ephemeral":
  145. return HistoryEphemeral, nil
  146. case "persistent":
  147. return HistoryPersistent, nil
  148. default:
  149. b, err := utils.StringToBool(str)
  150. if b {
  151. return HistoryPersistent, err
  152. } else {
  153. return HistoryDisabled, err
  154. }
  155. }
  156. }
  157. func historyStatusToString(status HistoryStatus) string {
  158. switch status {
  159. case HistoryDefault:
  160. return "default"
  161. case HistoryDisabled:
  162. return "disabled"
  163. case HistoryEphemeral:
  164. return "ephemeral"
  165. case HistoryPersistent:
  166. return "persistent"
  167. default:
  168. return ""
  169. }
  170. }
  171. // XXX you must have already checked History.Enabled before calling this
  172. func historyEnabled(serverSetting PersistentStatus, localSetting HistoryStatus) (result HistoryStatus) {
  173. switch serverSetting {
  174. case PersistentMandatory:
  175. return HistoryPersistent
  176. case PersistentOptOut:
  177. if localSetting == HistoryDefault {
  178. return HistoryPersistent
  179. } else {
  180. return localSetting
  181. }
  182. case PersistentOptIn:
  183. switch localSetting {
  184. case HistoryPersistent:
  185. return HistoryPersistent
  186. case HistoryEphemeral, HistoryDefault:
  187. return HistoryEphemeral
  188. default:
  189. return HistoryDisabled
  190. }
  191. case PersistentDisabled:
  192. if localSetting == HistoryDisabled {
  193. return HistoryDisabled
  194. } else {
  195. return HistoryEphemeral
  196. }
  197. default:
  198. // PersistentUnspecified: shouldn't happen because the deserializer converts it
  199. // to PersistentDisabled
  200. if localSetting == HistoryDefault {
  201. return HistoryEphemeral
  202. } else {
  203. return localSetting
  204. }
  205. }
  206. }
  207. type MulticlientConfig struct {
  208. Enabled bool
  209. AllowedByDefault bool `yaml:"allowed-by-default"`
  210. AlwaysOn PersistentStatus `yaml:"always-on"`
  211. }
  212. type AccountConfig struct {
  213. Registration AccountRegistrationConfig
  214. AuthenticationEnabled bool `yaml:"authentication-enabled"`
  215. RequireSasl struct {
  216. Enabled bool
  217. Exempted []string
  218. exemptedNets []net.IPNet
  219. } `yaml:"require-sasl"`
  220. LDAP ldap.ServerConfig
  221. LoginThrottling struct {
  222. Enabled bool
  223. Duration time.Duration
  224. MaxAttempts int `yaml:"max-attempts"`
  225. } `yaml:"login-throttling"`
  226. SkipServerPassword bool `yaml:"skip-server-password"`
  227. NickReservation struct {
  228. Enabled bool
  229. AdditionalNickLimit int `yaml:"additional-nick-limit"`
  230. Method NickEnforcementMethod
  231. AllowCustomEnforcement bool `yaml:"allow-custom-enforcement"`
  232. RenameTimeout time.Duration `yaml:"rename-timeout"`
  233. // RenamePrefix is the legacy field, GuestFormat is the new version
  234. RenamePrefix string `yaml:"rename-prefix"`
  235. GuestFormat string `yaml:"guest-nickname-format"`
  236. guestRegexp *regexp.Regexp
  237. guestRegexpFolded *regexp.Regexp
  238. ForceGuestFormat bool `yaml:"force-guest-format"`
  239. ForceNickEqualsAccount bool `yaml:"force-nick-equals-account"`
  240. } `yaml:"nick-reservation"`
  241. Multiclient MulticlientConfig
  242. Bouncer *MulticlientConfig // # handle old name for 'multiclient'
  243. VHosts VHostConfig
  244. }
  245. // AccountRegistrationConfig controls account registration.
  246. type AccountRegistrationConfig struct {
  247. Enabled bool
  248. EnabledCallbacks []string `yaml:"enabled-callbacks"`
  249. EnabledCredentialTypes []string `yaml:"-"`
  250. VerifyTimeout custime.Duration `yaml:"verify-timeout"`
  251. Callbacks struct {
  252. Mailto struct {
  253. Server string
  254. Port int
  255. TLS struct {
  256. Enabled bool
  257. InsecureSkipVerify bool `yaml:"insecure_skip_verify"`
  258. ServerName string `yaml:"servername"`
  259. }
  260. Username string
  261. Password string
  262. Sender string
  263. VerifyMessageSubject string `yaml:"verify-message-subject"`
  264. VerifyMessage string `yaml:"verify-message"`
  265. }
  266. }
  267. BcryptCost uint `yaml:"bcrypt-cost"`
  268. }
  269. type VHostConfig struct {
  270. Enabled bool
  271. MaxLength int `yaml:"max-length"`
  272. ValidRegexpRaw string `yaml:"valid-regexp"`
  273. ValidRegexp *regexp.Regexp
  274. UserRequests struct {
  275. Enabled bool
  276. Channel string
  277. Cooldown custime.Duration
  278. } `yaml:"user-requests"`
  279. OfferList []string `yaml:"offer-list"`
  280. }
  281. type NickEnforcementMethod int
  282. const (
  283. // NickEnforcementOptional is the zero value; it serializes to
  284. // "optional" in the yaml config, and "default" as an arg to `NS ENFORCE`.
  285. // in both cases, it means "defer to the other source of truth", i.e.,
  286. // in the config, defer to the user's custom setting, and as a custom setting,
  287. // defer to the default in the config. if both are NickEnforcementOptional then
  288. // there is no enforcement.
  289. // XXX: these are serialized as numbers in the database, so beware of collisions
  290. // when refactoring (any numbers currently in use must keep their meanings, or
  291. // else be fixed up by a schema change)
  292. NickEnforcementOptional NickEnforcementMethod = iota
  293. NickEnforcementNone
  294. NickEnforcementWithTimeout
  295. NickEnforcementStrict
  296. )
  297. func nickReservationToString(method NickEnforcementMethod) string {
  298. switch method {
  299. case NickEnforcementOptional:
  300. return "default"
  301. case NickEnforcementNone:
  302. return "none"
  303. case NickEnforcementWithTimeout:
  304. return "timeout"
  305. case NickEnforcementStrict:
  306. return "strict"
  307. default:
  308. return ""
  309. }
  310. }
  311. func nickReservationFromString(method string) (NickEnforcementMethod, error) {
  312. switch strings.ToLower(method) {
  313. case "default":
  314. return NickEnforcementOptional, nil
  315. case "optional":
  316. return NickEnforcementOptional, nil
  317. case "none":
  318. return NickEnforcementNone, nil
  319. case "timeout":
  320. return NickEnforcementWithTimeout, nil
  321. case "strict":
  322. return NickEnforcementStrict, nil
  323. default:
  324. return NickEnforcementOptional, fmt.Errorf("invalid nick-reservation.method value: %s", method)
  325. }
  326. }
  327. func (nr *NickEnforcementMethod) UnmarshalYAML(unmarshal func(interface{}) error) error {
  328. var orig string
  329. var err error
  330. if err = unmarshal(&orig); err != nil {
  331. return err
  332. }
  333. method, err := nickReservationFromString(orig)
  334. if err == nil {
  335. *nr = method
  336. }
  337. return err
  338. }
  339. func (cm *Casemapping) UnmarshalYAML(unmarshal func(interface{}) error) (err error) {
  340. var orig string
  341. if err = unmarshal(&orig); err != nil {
  342. return err
  343. }
  344. var result Casemapping
  345. switch strings.ToLower(orig) {
  346. case "ascii":
  347. result = CasemappingASCII
  348. case "precis", "rfc7613", "rfc8265":
  349. result = CasemappingPRECIS
  350. case "permissive", "fun":
  351. result = CasemappingPermissive
  352. default:
  353. return fmt.Errorf("invalid casemapping value: %s", orig)
  354. }
  355. *cm = result
  356. return nil
  357. }
  358. // OperClassConfig defines a specific operator class.
  359. type OperClassConfig struct {
  360. Title string
  361. WhoisLine string
  362. Extends string
  363. Capabilities []string
  364. }
  365. // OperConfig defines a specific operator's configuration.
  366. type OperConfig struct {
  367. Class string
  368. Vhost string
  369. WhoisLine string `yaml:"whois-line"`
  370. Password string
  371. Fingerprint string
  372. Auto bool
  373. Modes string
  374. }
  375. // Various server-enforced limits on data size.
  376. type Limits struct {
  377. AwayLen int `yaml:"awaylen"`
  378. ChanListModes int `yaml:"chan-list-modes"`
  379. ChannelLen int `yaml:"channellen"`
  380. IdentLen int `yaml:"identlen"`
  381. KickLen int `yaml:"kicklen"`
  382. MonitorEntries int `yaml:"monitor-entries"`
  383. NickLen int `yaml:"nicklen"`
  384. TopicLen int `yaml:"topiclen"`
  385. WhowasEntries int `yaml:"whowas-entries"`
  386. RegistrationMessages int `yaml:"registration-messages"`
  387. Multiline struct {
  388. MaxBytes int `yaml:"max-bytes"`
  389. MaxLines int `yaml:"max-lines"`
  390. }
  391. }
  392. // STSConfig controls the STS configuration/
  393. type STSConfig struct {
  394. Enabled bool
  395. Duration custime.Duration
  396. Port int
  397. Preload bool
  398. STSOnlyBanner string `yaml:"sts-only-banner"`
  399. bannerLines []string
  400. }
  401. // Value returns the STS value to advertise in CAP
  402. func (sts *STSConfig) Value() string {
  403. val := fmt.Sprintf("duration=%d", int(time.Duration(sts.Duration).Seconds()))
  404. if sts.Enabled && sts.Port > 0 {
  405. val += fmt.Sprintf(",port=%d", sts.Port)
  406. }
  407. if sts.Enabled && sts.Preload {
  408. val += ",preload"
  409. }
  410. return val
  411. }
  412. type FakelagConfig struct {
  413. Enabled bool
  414. Window time.Duration
  415. BurstLimit uint `yaml:"burst-limit"`
  416. MessagesPerWindow uint `yaml:"messages-per-window"`
  417. Cooldown time.Duration
  418. }
  419. type TorListenersConfig struct {
  420. Listeners []string // legacy only
  421. RequireSasl bool `yaml:"require-sasl"`
  422. Vhost string
  423. MaxConnections int `yaml:"max-connections"`
  424. ThrottleDuration time.Duration `yaml:"throttle-duration"`
  425. MaxConnectionsPerDuration int `yaml:"max-connections-per-duration"`
  426. }
  427. // Config defines the overall configuration.
  428. type Config struct {
  429. Network struct {
  430. Name string
  431. }
  432. Server struct {
  433. Password string
  434. passwordBytes []byte
  435. Name string
  436. nameCasefolded string
  437. // Listeners is the new style for configuring listeners:
  438. Listeners map[string]listenerConfigBlock
  439. UnixBindMode os.FileMode `yaml:"unix-bind-mode"`
  440. TorListeners TorListenersConfig `yaml:"tor-listeners"`
  441. // they get parsed into this internal representation:
  442. trueListeners map[string]listenerConfig
  443. STS STSConfig
  444. LookupHostnames *bool `yaml:"lookup-hostnames"`
  445. lookupHostnames bool
  446. ForwardConfirmHostnames bool `yaml:"forward-confirm-hostnames"`
  447. CheckIdent bool `yaml:"check-ident"`
  448. MOTD string
  449. motdLines []string
  450. MOTDFormatting bool `yaml:"motd-formatting"`
  451. ProxyAllowedFrom []string `yaml:"proxy-allowed-from"`
  452. proxyAllowedFromNets []net.IPNet
  453. WebIRC []webircConfig `yaml:"webirc"`
  454. MaxSendQString string `yaml:"max-sendq"`
  455. MaxSendQBytes int
  456. AllowPlaintextResume bool `yaml:"allow-plaintext-resume"`
  457. Compatibility struct {
  458. ForceTrailing *bool `yaml:"force-trailing"`
  459. forceTrailing bool
  460. SendUnprefixedSasl bool `yaml:"send-unprefixed-sasl"`
  461. }
  462. isupport isupport.List
  463. IPLimits connection_limits.LimiterConfig `yaml:"ip-limits"`
  464. Cloaks cloaks.CloakConfig `yaml:"ip-cloaking"`
  465. SecureNetDefs []string `yaml:"secure-nets"`
  466. secureNets []net.IPNet
  467. supportedCaps *caps.Set
  468. capValues caps.Values
  469. Casemapping Casemapping
  470. }
  471. Languages struct {
  472. Enabled bool
  473. Path string
  474. Default string
  475. }
  476. languageManager *languages.Manager
  477. Datastore struct {
  478. Path string
  479. AutoUpgrade bool
  480. MySQL mysql.Config
  481. }
  482. Accounts AccountConfig
  483. Channels struct {
  484. DefaultModes *string `yaml:"default-modes"`
  485. defaultModes modes.Modes
  486. MaxChannelsPerClient int `yaml:"max-channels-per-client"`
  487. OpOnlyCreation bool `yaml:"operator-only-creation"`
  488. Registration struct {
  489. Enabled bool
  490. OperatorOnly bool `yaml:"operator-only"`
  491. MaxChannelsPerAccount int `yaml:"max-channels-per-account"`
  492. }
  493. }
  494. OperClasses map[string]*OperClassConfig `yaml:"oper-classes"`
  495. Opers map[string]*OperConfig
  496. // parsed operator definitions, unexported so they can't be defined
  497. // directly in YAML:
  498. operators map[string]*Oper
  499. Logging []logger.LoggingConfig
  500. Debug struct {
  501. RecoverFromErrors *bool `yaml:"recover-from-errors"`
  502. recoverFromErrors bool
  503. PprofListener *string `yaml:"pprof-listener"`
  504. }
  505. Limits Limits
  506. Fakelag FakelagConfig
  507. History struct {
  508. Enabled bool
  509. ChannelLength int `yaml:"channel-length"`
  510. ClientLength int `yaml:"client-length"`
  511. AutoresizeWindow time.Duration `yaml:"autoresize-window"`
  512. AutoreplayOnJoin int `yaml:"autoreplay-on-join"`
  513. ChathistoryMax int `yaml:"chathistory-maxmessages"`
  514. ZNCMax int `yaml:"znc-maxmessages"`
  515. Restrictions struct {
  516. ExpireTime custime.Duration `yaml:"expire-time"`
  517. EnforceRegistrationDate bool `yaml:"enforce-registration-date"`
  518. GracePeriod custime.Duration `yaml:"grace-period"`
  519. }
  520. Persistent struct {
  521. Enabled bool
  522. UnregisteredChannels bool `yaml:"unregistered-channels"`
  523. RegisteredChannels PersistentStatus `yaml:"registered-channels"`
  524. DirectMessages PersistentStatus `yaml:"direct-messages"`
  525. }
  526. }
  527. Filename string
  528. }
  529. // OperClass defines an assembled operator class.
  530. type OperClass struct {
  531. Title string
  532. WhoisLine string `yaml:"whois-line"`
  533. Capabilities StringSet // map to make lookups much easier
  534. }
  535. // OperatorClasses returns a map of assembled operator classes from the given config.
  536. func (conf *Config) OperatorClasses() (map[string]*OperClass, error) {
  537. fixupCapability := func(capab string) string {
  538. return strings.TrimPrefix(capab, "oper:") // #868
  539. }
  540. ocs := make(map[string]*OperClass)
  541. // loop from no extends to most extended, breaking if we can't add any more
  542. lenOfLastOcs := -1
  543. for {
  544. if lenOfLastOcs == len(ocs) {
  545. return nil, ErrOperClassDependencies
  546. }
  547. lenOfLastOcs = len(ocs)
  548. var anyMissing bool
  549. for name, info := range conf.OperClasses {
  550. _, exists := ocs[name]
  551. _, extendsExists := ocs[info.Extends]
  552. if exists {
  553. // class already exists
  554. continue
  555. } else if len(info.Extends) > 0 && !extendsExists {
  556. // class we extend on doesn't exist
  557. _, exists := conf.OperClasses[info.Extends]
  558. if !exists {
  559. return nil, fmt.Errorf("Operclass [%s] extends [%s], which doesn't exist", name, info.Extends)
  560. }
  561. anyMissing = true
  562. continue
  563. }
  564. // create new operclass
  565. var oc OperClass
  566. oc.Capabilities = make(StringSet)
  567. // get inhereted info from other operclasses
  568. if len(info.Extends) > 0 {
  569. einfo := ocs[info.Extends]
  570. for capab := range einfo.Capabilities {
  571. oc.Capabilities.Add(fixupCapability(capab))
  572. }
  573. }
  574. // add our own info
  575. oc.Title = info.Title
  576. for _, capab := range info.Capabilities {
  577. oc.Capabilities.Add(fixupCapability(capab))
  578. }
  579. if len(info.WhoisLine) > 0 {
  580. oc.WhoisLine = info.WhoisLine
  581. } else {
  582. oc.WhoisLine = "is a"
  583. if strings.Contains(strings.ToLower(string(oc.Title[0])), "aeiou") {
  584. oc.WhoisLine += "n"
  585. }
  586. oc.WhoisLine += " "
  587. oc.WhoisLine += oc.Title
  588. }
  589. ocs[name] = &oc
  590. }
  591. if !anyMissing {
  592. // we've got every operclass!
  593. break
  594. }
  595. }
  596. return ocs, nil
  597. }
  598. // Oper represents a single assembled operator's config.
  599. type Oper struct {
  600. Name string
  601. Class *OperClass
  602. WhoisLine string
  603. Vhost string
  604. Pass []byte
  605. Fingerprint string
  606. Auto bool
  607. Modes []modes.ModeChange
  608. }
  609. // Operators returns a map of operator configs from the given OperClass and config.
  610. func (conf *Config) Operators(oc map[string]*OperClass) (map[string]*Oper, error) {
  611. operators := make(map[string]*Oper)
  612. for name, opConf := range conf.Opers {
  613. var oper Oper
  614. // oper name
  615. name, err := CasefoldName(name)
  616. if err != nil {
  617. return nil, fmt.Errorf("Could not casefold oper name: %s", err.Error())
  618. }
  619. oper.Name = name
  620. if opConf.Password != "" {
  621. oper.Pass, err = decodeLegacyPasswordHash(opConf.Password)
  622. if err != nil {
  623. return nil, fmt.Errorf("Oper %s has an invalid password hash: %s", oper.Name, err.Error())
  624. }
  625. }
  626. if opConf.Fingerprint != "" {
  627. oper.Fingerprint, err = utils.NormalizeCertfp(opConf.Fingerprint)
  628. if err != nil {
  629. return nil, fmt.Errorf("Oper %s has an invalid fingerprint: %s", oper.Name, err.Error())
  630. }
  631. }
  632. oper.Auto = opConf.Auto
  633. if oper.Pass == nil && oper.Fingerprint == "" {
  634. return nil, fmt.Errorf("Oper %s has neither a password nor a fingerprint", name)
  635. }
  636. oper.Vhost = opConf.Vhost
  637. class, exists := oc[opConf.Class]
  638. if !exists {
  639. return nil, fmt.Errorf("Could not load operator [%s] - they use operclass [%s] which does not exist", name, opConf.Class)
  640. }
  641. oper.Class = class
  642. if len(opConf.WhoisLine) > 0 {
  643. oper.WhoisLine = opConf.WhoisLine
  644. } else {
  645. oper.WhoisLine = class.WhoisLine
  646. }
  647. modeStr := strings.TrimSpace(opConf.Modes)
  648. modeChanges, unknownChanges := modes.ParseUserModeChanges(strings.Split(modeStr, " ")...)
  649. if len(unknownChanges) > 0 {
  650. return nil, fmt.Errorf("Could not load operator [%s] due to unknown modes %v", name, unknownChanges)
  651. }
  652. oper.Modes = modeChanges
  653. // successful, attach to list of opers
  654. operators[name] = &oper
  655. }
  656. return operators, nil
  657. }
  658. func loadTlsConfig(config TLSListenConfig) (tlsConfig *tls.Config, err error) {
  659. cert, err := tls.LoadX509KeyPair(config.Cert, config.Key)
  660. if err != nil {
  661. return nil, ErrInvalidCertKeyPair
  662. }
  663. result := tls.Config{
  664. Certificates: []tls.Certificate{cert},
  665. ClientAuth: tls.RequestClientCert,
  666. }
  667. return &result, nil
  668. }
  669. // prepareListeners populates Config.Server.trueListeners
  670. func (conf *Config) prepareListeners() (err error) {
  671. if len(conf.Server.Listeners) == 0 {
  672. return fmt.Errorf("No listeners were configured")
  673. }
  674. conf.Server.trueListeners = make(map[string]listenerConfig)
  675. for addr, block := range conf.Server.Listeners {
  676. var lconf listenerConfig
  677. lconf.Tor = block.Tor
  678. lconf.STSOnly = block.STSOnly
  679. if lconf.STSOnly && !conf.Server.STS.Enabled {
  680. return fmt.Errorf("%s is configured as a STS-only listener, but STS is disabled", addr)
  681. }
  682. if block.TLS.Cert != "" {
  683. tlsConfig, err := loadTlsConfig(block.TLS)
  684. if err != nil {
  685. return err
  686. }
  687. lconf.TLSConfig = tlsConfig
  688. lconf.ProxyBeforeTLS = block.TLS.Proxy
  689. }
  690. conf.Server.trueListeners[addr] = lconf
  691. }
  692. return nil
  693. }
  694. // LoadRawConfig loads the config without doing any consistency checks or postprocessing
  695. func LoadRawConfig(filename string) (config *Config, err error) {
  696. data, err := ioutil.ReadFile(filename)
  697. if err != nil {
  698. return nil, err
  699. }
  700. err = yaml.Unmarshal(data, &config)
  701. if err != nil {
  702. return nil, err
  703. }
  704. return
  705. }
  706. // LoadConfig loads the given YAML configuration file.
  707. func LoadConfig(filename string) (config *Config, err error) {
  708. config, err = LoadRawConfig(filename)
  709. if err != nil {
  710. return nil, err
  711. }
  712. config.Filename = filename
  713. if config.Network.Name == "" {
  714. return nil, ErrNetworkNameMissing
  715. }
  716. if config.Server.Name == "" {
  717. return nil, ErrServerNameMissing
  718. }
  719. if !utils.IsServerName(config.Server.Name) {
  720. return nil, ErrServerNameNotHostname
  721. }
  722. config.Server.nameCasefolded = strings.ToLower(config.Server.Name)
  723. if config.Datastore.Path == "" {
  724. return nil, ErrDatastorePathMissing
  725. }
  726. //dan: automagically fix identlen until a few releases in the future (from now, 0.12.0), being a newly-introduced limit
  727. if config.Limits.IdentLen < 1 {
  728. config.Limits.IdentLen = 20
  729. }
  730. if config.Limits.NickLen < 1 || config.Limits.ChannelLen < 2 || config.Limits.AwayLen < 1 || config.Limits.KickLen < 1 || config.Limits.TopicLen < 1 {
  731. return nil, ErrLimitsAreInsane
  732. }
  733. if config.Limits.RegistrationMessages == 0 {
  734. config.Limits.RegistrationMessages = 1024
  735. }
  736. if config.Datastore.MySQL.Enabled {
  737. if config.Limits.NickLen > mysql.MaxTargetLength || config.Limits.ChannelLen > mysql.MaxTargetLength {
  738. return nil, fmt.Errorf("to use MySQL, nick and channel length limits must be %d or lower", mysql.MaxTargetLength)
  739. }
  740. }
  741. config.Server.supportedCaps = caps.NewCompleteSet()
  742. config.Server.capValues = make(caps.Values)
  743. err = config.prepareListeners()
  744. if err != nil {
  745. return nil, fmt.Errorf("failed to prepare listeners: %v", err)
  746. }
  747. if config.Server.STS.Enabled {
  748. if config.Server.STS.Port < 0 || config.Server.STS.Port > 65535 {
  749. return nil, fmt.Errorf("STS port is incorrect, should be 0 if disabled: %d", config.Server.STS.Port)
  750. }
  751. if config.Server.STS.STSOnlyBanner != "" {
  752. for _, line := range strings.Split(config.Server.STS.STSOnlyBanner, "\n") {
  753. config.Server.STS.bannerLines = append(config.Server.STS.bannerLines, strings.TrimSpace(line))
  754. }
  755. } else {
  756. config.Server.STS.bannerLines = []string{fmt.Sprintf("This server is only accessible over TLS. Please reconnect using TLS on port %d.", config.Server.STS.Port)}
  757. }
  758. } else {
  759. config.Server.supportedCaps.Disable(caps.STS)
  760. config.Server.STS.Duration = 0
  761. }
  762. // set this even if STS is disabled
  763. config.Server.capValues[caps.STS] = config.Server.STS.Value()
  764. // lookup-hostnames defaults to true if unset
  765. if config.Server.LookupHostnames != nil {
  766. config.Server.lookupHostnames = *config.Server.LookupHostnames
  767. } else {
  768. config.Server.lookupHostnames = true
  769. }
  770. // process webirc blocks
  771. var newWebIRC []webircConfig
  772. for _, webirc := range config.Server.WebIRC {
  773. // skip webirc blocks with no hosts (such as the example one)
  774. if len(webirc.Hosts) == 0 {
  775. continue
  776. }
  777. err = webirc.Populate()
  778. if err != nil {
  779. return nil, fmt.Errorf("Could not parse WebIRC config: %s", err.Error())
  780. }
  781. newWebIRC = append(newWebIRC, webirc)
  782. }
  783. config.Server.WebIRC = newWebIRC
  784. if config.Limits.Multiline.MaxBytes <= 0 {
  785. config.Server.supportedCaps.Disable(caps.Multiline)
  786. } else {
  787. var multilineCapValue string
  788. if config.Limits.Multiline.MaxLines == 0 {
  789. multilineCapValue = fmt.Sprintf("max-bytes=%d", config.Limits.Multiline.MaxBytes)
  790. } else {
  791. multilineCapValue = fmt.Sprintf("max-bytes=%d,max-lines=%d", config.Limits.Multiline.MaxBytes, config.Limits.Multiline.MaxLines)
  792. }
  793. config.Server.capValues[caps.Multiline] = multilineCapValue
  794. }
  795. // handle legacy name 'bouncer' for 'multiclient' section:
  796. if config.Accounts.Bouncer != nil {
  797. config.Accounts.Multiclient = *config.Accounts.Bouncer
  798. }
  799. if !config.Accounts.Multiclient.Enabled {
  800. config.Accounts.Multiclient.AlwaysOn = PersistentDisabled
  801. } else if config.Accounts.Multiclient.AlwaysOn >= PersistentOptOut {
  802. config.Accounts.Multiclient.AllowedByDefault = true
  803. }
  804. // handle guest format, including the legacy key rename-prefix
  805. if config.Accounts.NickReservation.GuestFormat == "" {
  806. renamePrefix := config.Accounts.NickReservation.RenamePrefix
  807. if renamePrefix == "" {
  808. renamePrefix = "Guest-"
  809. }
  810. config.Accounts.NickReservation.GuestFormat = renamePrefix + "*"
  811. }
  812. config.Accounts.NickReservation.guestRegexp, config.Accounts.NickReservation.guestRegexpFolded, err = compileGuestRegexp(config.Accounts.NickReservation.GuestFormat, config.Server.Casemapping)
  813. if err != nil {
  814. return nil, err
  815. }
  816. var newLogConfigs []logger.LoggingConfig
  817. for _, logConfig := range config.Logging {
  818. // methods
  819. methods := make(map[string]bool)
  820. for _, method := range strings.Split(logConfig.Method, " ") {
  821. if len(method) > 0 {
  822. methods[strings.ToLower(method)] = true
  823. }
  824. }
  825. if methods["file"] && logConfig.Filename == "" {
  826. return nil, ErrLoggerFilenameMissing
  827. }
  828. logConfig.MethodFile = methods["file"]
  829. logConfig.MethodStdout = methods["stdout"]
  830. logConfig.MethodStderr = methods["stderr"]
  831. // levels
  832. level, exists := logger.LogLevelNames[strings.ToLower(logConfig.LevelString)]
  833. if !exists {
  834. return nil, fmt.Errorf("Could not translate log leve [%s]", logConfig.LevelString)
  835. }
  836. logConfig.Level = level
  837. // types
  838. for _, typeStr := range strings.Split(logConfig.TypeString, " ") {
  839. if len(typeStr) == 0 {
  840. continue
  841. }
  842. if typeStr == "-" {
  843. return nil, ErrLoggerExcludeEmpty
  844. }
  845. if typeStr[0] == '-' {
  846. typeStr = typeStr[1:]
  847. logConfig.ExcludedTypes = append(logConfig.ExcludedTypes, typeStr)
  848. } else {
  849. logConfig.Types = append(logConfig.Types, typeStr)
  850. }
  851. }
  852. if len(logConfig.Types) < 1 {
  853. return nil, ErrLoggerHasNoTypes
  854. }
  855. newLogConfigs = append(newLogConfigs, logConfig)
  856. }
  857. config.Logging = newLogConfigs
  858. // hardcode this for now
  859. config.Accounts.Registration.EnabledCredentialTypes = []string{"passphrase", "certfp"}
  860. for i, name := range config.Accounts.Registration.EnabledCallbacks {
  861. if name == "none" {
  862. // we store "none" as "*" internally
  863. config.Accounts.Registration.EnabledCallbacks[i] = "*"
  864. }
  865. }
  866. sort.Strings(config.Accounts.Registration.EnabledCallbacks)
  867. config.Accounts.RequireSasl.exemptedNets, err = utils.ParseNetList(config.Accounts.RequireSasl.Exempted)
  868. if err != nil {
  869. return nil, fmt.Errorf("Could not parse require-sasl exempted nets: %v", err.Error())
  870. }
  871. config.Server.proxyAllowedFromNets, err = utils.ParseNetList(config.Server.ProxyAllowedFrom)
  872. if err != nil {
  873. return nil, fmt.Errorf("Could not parse proxy-allowed-from nets: %v", err.Error())
  874. }
  875. config.Server.secureNets, err = utils.ParseNetList(config.Server.SecureNetDefs)
  876. if err != nil {
  877. return nil, fmt.Errorf("Could not parse secure-nets: %v\n", err.Error())
  878. }
  879. rawRegexp := config.Accounts.VHosts.ValidRegexpRaw
  880. if rawRegexp != "" {
  881. regexp, err := regexp.Compile(rawRegexp)
  882. if err == nil {
  883. config.Accounts.VHosts.ValidRegexp = regexp
  884. } else {
  885. log.Printf("invalid vhost regexp: %s\n", err.Error())
  886. }
  887. }
  888. if config.Accounts.VHosts.ValidRegexp == nil {
  889. config.Accounts.VHosts.ValidRegexp = defaultValidVhostRegex
  890. }
  891. for _, vhost := range config.Accounts.VHosts.OfferList {
  892. if !config.Accounts.VHosts.ValidRegexp.MatchString(vhost) {
  893. return nil, fmt.Errorf("invalid offered vhost: %s", vhost)
  894. }
  895. }
  896. if !config.Accounts.LoginThrottling.Enabled {
  897. config.Accounts.LoginThrottling.MaxAttempts = 0 // limit of 0 means disabled
  898. }
  899. config.Server.capValues[caps.SASL] = "PLAIN,EXTERNAL"
  900. if !config.Accounts.AuthenticationEnabled {
  901. config.Server.supportedCaps.Disable(caps.SASL)
  902. }
  903. maxSendQBytes, err := bytefmt.ToBytes(config.Server.MaxSendQString)
  904. if err != nil {
  905. return nil, fmt.Errorf("Could not parse maximum SendQ size (make sure it only contains whole numbers): %s", err.Error())
  906. }
  907. config.Server.MaxSendQBytes = int(maxSendQBytes)
  908. config.languageManager, err = languages.NewManager(config.Languages.Enabled, config.Languages.Path, config.Languages.Default)
  909. if err != nil {
  910. return nil, fmt.Errorf("Could not load languages: %s", err.Error())
  911. }
  912. config.Server.capValues[caps.Languages] = config.languageManager.CapValue()
  913. // RecoverFromErrors defaults to true
  914. if config.Debug.RecoverFromErrors != nil {
  915. config.Debug.recoverFromErrors = *config.Debug.RecoverFromErrors
  916. } else {
  917. config.Debug.recoverFromErrors = true
  918. }
  919. // process operator definitions, store them to config.operators
  920. operclasses, err := config.OperatorClasses()
  921. if err != nil {
  922. return nil, err
  923. }
  924. opers, err := config.Operators(operclasses)
  925. if err != nil {
  926. return nil, err
  927. }
  928. config.operators = opers
  929. // parse default channel modes
  930. config.Channels.defaultModes = ParseDefaultChannelModes(config.Channels.DefaultModes)
  931. if config.Server.Password != "" {
  932. config.Server.passwordBytes, err = decodeLegacyPasswordHash(config.Server.Password)
  933. if err != nil {
  934. return nil, err
  935. }
  936. }
  937. if config.Accounts.Registration.BcryptCost == 0 {
  938. config.Accounts.Registration.BcryptCost = passwd.DefaultCost
  939. }
  940. if config.Channels.MaxChannelsPerClient == 0 {
  941. config.Channels.MaxChannelsPerClient = 100
  942. }
  943. if config.Channels.Registration.MaxChannelsPerAccount == 0 {
  944. config.Channels.Registration.MaxChannelsPerAccount = 15
  945. }
  946. forceTrailingPtr := config.Server.Compatibility.ForceTrailing
  947. if forceTrailingPtr != nil {
  948. config.Server.Compatibility.forceTrailing = *forceTrailingPtr
  949. } else {
  950. config.Server.Compatibility.forceTrailing = true
  951. }
  952. config.loadMOTD()
  953. // in the current implementation, we disable history by creating a history buffer
  954. // with zero capacity. but the `enabled` config option MUST be respected regardless
  955. // of this detail
  956. if !config.History.Enabled {
  957. config.History.ChannelLength = 0
  958. config.History.ClientLength = 0
  959. }
  960. if !config.History.Enabled || !config.History.Persistent.Enabled {
  961. config.History.Persistent.UnregisteredChannels = false
  962. config.History.Persistent.RegisteredChannels = PersistentDisabled
  963. config.History.Persistent.DirectMessages = PersistentDisabled
  964. }
  965. if config.History.ZNCMax == 0 {
  966. config.History.ZNCMax = config.History.ChathistoryMax
  967. }
  968. config.Datastore.MySQL.ExpireTime = time.Duration(config.History.Restrictions.ExpireTime)
  969. config.Server.Cloaks.Initialize()
  970. if config.Server.Cloaks.Enabled {
  971. if config.Server.Cloaks.Secret == "" || config.Server.Cloaks.Secret == "siaELnk6Kaeo65K3RCrwJjlWaZ-Bt3WuZ2L8MXLbNb4" {
  972. return nil, fmt.Errorf("You must generate a new value of server.ip-cloaking.secret to enable cloaking")
  973. }
  974. if !utils.IsHostname(config.Server.Cloaks.Netname) {
  975. return nil, fmt.Errorf("Invalid netname for cloaked hostnames: %s", config.Server.Cloaks.Netname)
  976. }
  977. }
  978. // now that all postprocessing is complete, regenerate ISUPPORT:
  979. err = config.generateISupport()
  980. if err != nil {
  981. return nil, err
  982. }
  983. err = config.prepareListeners()
  984. if err != nil {
  985. return nil, fmt.Errorf("failed to prepare listeners: %v", err)
  986. }
  987. return config, nil
  988. }
  989. // setISupport sets up our RPL_ISUPPORT reply.
  990. func (config *Config) generateISupport() (err error) {
  991. maxTargetsString := strconv.Itoa(maxTargets)
  992. // add RPL_ISUPPORT tokens
  993. isupport := &config.Server.isupport
  994. isupport.Initialize()
  995. isupport.Add("AWAYLEN", strconv.Itoa(config.Limits.AwayLen))
  996. isupport.Add("CASEMAPPING", "ascii")
  997. isupport.Add("CHANLIMIT", fmt.Sprintf("%s:%d", chanTypes, config.Channels.MaxChannelsPerClient))
  998. isupport.Add("CHANMODES", strings.Join([]string{modes.Modes{modes.BanMask, modes.ExceptMask, modes.InviteMask}.String(), "", modes.Modes{modes.UserLimit, modes.Key}.String(), modes.Modes{modes.InviteOnly, modes.Moderated, modes.NoOutside, modes.OpOnlyTopic, modes.ChanRoleplaying, modes.Secret, modes.NoCTCP, modes.RegisteredOnly}.String()}, ","))
  999. if config.History.Enabled && config.History.ChathistoryMax > 0 {
  1000. isupport.Add("draft/CHATHISTORY", strconv.Itoa(config.History.ChathistoryMax))
  1001. }
  1002. isupport.Add("CHANNELLEN", strconv.Itoa(config.Limits.ChannelLen))
  1003. isupport.Add("CHANTYPES", chanTypes)
  1004. isupport.Add("ELIST", "U")
  1005. isupport.Add("EXCEPTS", "")
  1006. isupport.Add("INVEX", "")
  1007. isupport.Add("KICKLEN", strconv.Itoa(config.Limits.KickLen))
  1008. isupport.Add("MAXLIST", fmt.Sprintf("beI:%s", strconv.Itoa(config.Limits.ChanListModes)))
  1009. isupport.Add("MAXTARGETS", maxTargetsString)
  1010. isupport.Add("MODES", "")
  1011. isupport.Add("MONITOR", strconv.Itoa(config.Limits.MonitorEntries))
  1012. isupport.Add("NETWORK", config.Network.Name)
  1013. isupport.Add("NICKLEN", strconv.Itoa(config.Limits.NickLen))
  1014. isupport.Add("PREFIX", "(qaohv)~&@%+")
  1015. isupport.Add("RPCHAN", "E")
  1016. isupport.Add("RPUSER", "E")
  1017. isupport.Add("STATUSMSG", "~&@%+")
  1018. isupport.Add("TARGMAX", fmt.Sprintf("NAMES:1,LIST:1,KICK:1,WHOIS:1,USERHOST:10,PRIVMSG:%s,TAGMSG:%s,NOTICE:%s,MONITOR:", maxTargetsString, maxTargetsString, maxTargetsString))
  1019. isupport.Add("TOPICLEN", strconv.Itoa(config.Limits.TopicLen))
  1020. if config.Server.Casemapping == CasemappingPRECIS {
  1021. isupport.Add("UTF8MAPPING", precisUTF8MappingToken)
  1022. }
  1023. err = isupport.RegenerateCachedReply()
  1024. return
  1025. }
  1026. // Diff returns changes in supported caps across a rehash.
  1027. func (config *Config) Diff(oldConfig *Config) (addedCaps, removedCaps *caps.Set) {
  1028. addedCaps = caps.NewSet()
  1029. removedCaps = caps.NewSet()
  1030. if oldConfig == nil {
  1031. return
  1032. }
  1033. if oldConfig.Server.capValues[caps.Languages] != config.Server.capValues[caps.Languages] {
  1034. // XXX updated caps get a DEL line and then a NEW line with the new value
  1035. addedCaps.Add(caps.Languages)
  1036. removedCaps.Add(caps.Languages)
  1037. }
  1038. if !oldConfig.Accounts.AuthenticationEnabled && config.Accounts.AuthenticationEnabled {
  1039. addedCaps.Add(caps.SASL)
  1040. } else if oldConfig.Accounts.AuthenticationEnabled && !config.Accounts.AuthenticationEnabled {
  1041. removedCaps.Add(caps.SASL)
  1042. }
  1043. if oldConfig.Limits.Multiline.MaxBytes != 0 && config.Limits.Multiline.MaxBytes == 0 {
  1044. removedCaps.Add(caps.Multiline)
  1045. } else if oldConfig.Limits.Multiline.MaxBytes == 0 && config.Limits.Multiline.MaxBytes != 0 {
  1046. addedCaps.Add(caps.Multiline)
  1047. } else if oldConfig.Limits.Multiline != config.Limits.Multiline {
  1048. removedCaps.Add(caps.Multiline)
  1049. addedCaps.Add(caps.Multiline)
  1050. }
  1051. if oldConfig.Server.STS.Enabled != config.Server.STS.Enabled || oldConfig.Server.capValues[caps.STS] != config.Server.capValues[caps.STS] {
  1052. // XXX: STS is always removed by CAP NEW sts=duration=0, not CAP DEL
  1053. // so the appropriate notify is always a CAP NEW; put it in addedCaps for any change
  1054. addedCaps.Add(caps.STS)
  1055. }
  1056. return
  1057. }
  1058. func compileGuestRegexp(guestFormat string, casemapping Casemapping) (standard, folded *regexp.Regexp, err error) {
  1059. starIndex := strings.IndexByte(guestFormat, '*')
  1060. if starIndex == -1 {
  1061. return nil, nil, errors.New("guest format must contain exactly one *")
  1062. }
  1063. initial := guestFormat[:starIndex]
  1064. final := guestFormat[starIndex+1:]
  1065. if strings.IndexByte(final, '*') != -1 {
  1066. return nil, nil, errors.New("guest format must contain exactly one *")
  1067. }
  1068. standard, err = regexp.Compile(fmt.Sprintf("^%s(.*)%s$", initial, final))
  1069. if err != nil {
  1070. return
  1071. }
  1072. initialFolded, err := casefoldWithSetting(initial, casemapping)
  1073. if err != nil {
  1074. return
  1075. }
  1076. finalFolded, err := casefoldWithSetting(final, casemapping)
  1077. if err != nil {
  1078. return
  1079. }
  1080. folded, err = regexp.Compile(fmt.Sprintf("^%s(.*)%s$", initialFolded, finalFolded))
  1081. return
  1082. }