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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209
  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. // ChannelRegistrationConfig controls channel registration.
  359. type ChannelRegistrationConfig struct {
  360. Enabled bool
  361. MaxChannelsPerAccount int `yaml:"max-channels-per-account"`
  362. }
  363. // OperClassConfig defines a specific operator class.
  364. type OperClassConfig struct {
  365. Title string
  366. WhoisLine string
  367. Extends string
  368. Capabilities []string
  369. }
  370. // OperConfig defines a specific operator's configuration.
  371. type OperConfig struct {
  372. Class string
  373. Vhost string
  374. WhoisLine string `yaml:"whois-line"`
  375. Password string
  376. Fingerprint string
  377. Auto bool
  378. Modes string
  379. }
  380. // Various server-enforced limits on data size.
  381. type Limits struct {
  382. AwayLen int `yaml:"awaylen"`
  383. ChanListModes int `yaml:"chan-list-modes"`
  384. ChannelLen int `yaml:"channellen"`
  385. IdentLen int `yaml:"identlen"`
  386. KickLen int `yaml:"kicklen"`
  387. MonitorEntries int `yaml:"monitor-entries"`
  388. NickLen int `yaml:"nicklen"`
  389. TopicLen int `yaml:"topiclen"`
  390. WhowasEntries int `yaml:"whowas-entries"`
  391. RegistrationMessages int `yaml:"registration-messages"`
  392. Multiline struct {
  393. MaxBytes int `yaml:"max-bytes"`
  394. MaxLines int `yaml:"max-lines"`
  395. }
  396. }
  397. // STSConfig controls the STS configuration/
  398. type STSConfig struct {
  399. Enabled bool
  400. Duration custime.Duration
  401. Port int
  402. Preload bool
  403. STSOnlyBanner string `yaml:"sts-only-banner"`
  404. bannerLines []string
  405. }
  406. // Value returns the STS value to advertise in CAP
  407. func (sts *STSConfig) Value() string {
  408. val := fmt.Sprintf("duration=%d", int(time.Duration(sts.Duration).Seconds()))
  409. if sts.Enabled && sts.Port > 0 {
  410. val += fmt.Sprintf(",port=%d", sts.Port)
  411. }
  412. if sts.Enabled && sts.Preload {
  413. val += ",preload"
  414. }
  415. return val
  416. }
  417. type FakelagConfig struct {
  418. Enabled bool
  419. Window time.Duration
  420. BurstLimit uint `yaml:"burst-limit"`
  421. MessagesPerWindow uint `yaml:"messages-per-window"`
  422. Cooldown time.Duration
  423. }
  424. type TorListenersConfig struct {
  425. Listeners []string // legacy only
  426. RequireSasl bool `yaml:"require-sasl"`
  427. Vhost string
  428. MaxConnections int `yaml:"max-connections"`
  429. ThrottleDuration time.Duration `yaml:"throttle-duration"`
  430. MaxConnectionsPerDuration int `yaml:"max-connections-per-duration"`
  431. }
  432. // Config defines the overall configuration.
  433. type Config struct {
  434. Network struct {
  435. Name string
  436. }
  437. Server struct {
  438. Password string
  439. passwordBytes []byte
  440. Name string
  441. nameCasefolded string
  442. // Listeners is the new style for configuring listeners:
  443. Listeners map[string]listenerConfigBlock
  444. UnixBindMode os.FileMode `yaml:"unix-bind-mode"`
  445. TorListeners TorListenersConfig `yaml:"tor-listeners"`
  446. // they get parsed into this internal representation:
  447. trueListeners map[string]listenerConfig
  448. STS STSConfig
  449. LookupHostnames *bool `yaml:"lookup-hostnames"`
  450. lookupHostnames bool
  451. ForwardConfirmHostnames bool `yaml:"forward-confirm-hostnames"`
  452. CheckIdent bool `yaml:"check-ident"`
  453. MOTD string
  454. motdLines []string
  455. MOTDFormatting bool `yaml:"motd-formatting"`
  456. ProxyAllowedFrom []string `yaml:"proxy-allowed-from"`
  457. proxyAllowedFromNets []net.IPNet
  458. WebIRC []webircConfig `yaml:"webirc"`
  459. MaxSendQString string `yaml:"max-sendq"`
  460. MaxSendQBytes int
  461. AllowPlaintextResume bool `yaml:"allow-plaintext-resume"`
  462. Compatibility struct {
  463. ForceTrailing *bool `yaml:"force-trailing"`
  464. forceTrailing bool
  465. SendUnprefixedSasl bool `yaml:"send-unprefixed-sasl"`
  466. }
  467. isupport isupport.List
  468. IPLimits connection_limits.LimiterConfig `yaml:"ip-limits"`
  469. Cloaks cloaks.CloakConfig `yaml:"ip-cloaking"`
  470. SecureNetDefs []string `yaml:"secure-nets"`
  471. secureNets []net.IPNet
  472. supportedCaps *caps.Set
  473. capValues caps.Values
  474. Casemapping Casemapping
  475. }
  476. Languages struct {
  477. Enabled bool
  478. Path string
  479. Default string
  480. }
  481. languageManager *languages.Manager
  482. Datastore struct {
  483. Path string
  484. AutoUpgrade bool
  485. MySQL mysql.Config
  486. }
  487. Accounts AccountConfig
  488. Channels struct {
  489. DefaultModes *string `yaml:"default-modes"`
  490. defaultModes modes.Modes
  491. MaxChannelsPerClient int `yaml:"max-channels-per-client"`
  492. OpOnlyCreation bool `yaml:"operator-only-creation"`
  493. Registration ChannelRegistrationConfig
  494. }
  495. OperClasses map[string]*OperClassConfig `yaml:"oper-classes"`
  496. Opers map[string]*OperConfig
  497. // parsed operator definitions, unexported so they can't be defined
  498. // directly in YAML:
  499. operators map[string]*Oper
  500. Logging []logger.LoggingConfig
  501. Debug struct {
  502. RecoverFromErrors *bool `yaml:"recover-from-errors"`
  503. recoverFromErrors bool
  504. PprofListener *string `yaml:"pprof-listener"`
  505. }
  506. Limits Limits
  507. Fakelag FakelagConfig
  508. History struct {
  509. Enabled bool
  510. ChannelLength int `yaml:"channel-length"`
  511. ClientLength int `yaml:"client-length"`
  512. AutoresizeWindow time.Duration `yaml:"autoresize-window"`
  513. AutoreplayOnJoin int `yaml:"autoreplay-on-join"`
  514. ChathistoryMax int `yaml:"chathistory-maxmessages"`
  515. ZNCMax int `yaml:"znc-maxmessages"`
  516. Restrictions struct {
  517. ExpireTime custime.Duration `yaml:"expire-time"`
  518. EnforceRegistrationDate bool `yaml:"enforce-registration-date"`
  519. GracePeriod custime.Duration `yaml:"grace-period"`
  520. }
  521. Persistent struct {
  522. Enabled bool
  523. UnregisteredChannels bool `yaml:"unregistered-channels"`
  524. RegisteredChannels PersistentStatus `yaml:"registered-channels"`
  525. DirectMessages PersistentStatus `yaml:"direct-messages"`
  526. }
  527. }
  528. Filename string
  529. }
  530. // OperClass defines an assembled operator class.
  531. type OperClass struct {
  532. Title string
  533. WhoisLine string `yaml:"whois-line"`
  534. Capabilities map[string]bool // map to make lookups much easier
  535. }
  536. // OperatorClasses returns a map of assembled operator classes from the given config.
  537. func (conf *Config) OperatorClasses() (map[string]*OperClass, error) {
  538. ocs := make(map[string]*OperClass)
  539. // loop from no extends to most extended, breaking if we can't add any more
  540. lenOfLastOcs := -1
  541. for {
  542. if lenOfLastOcs == len(ocs) {
  543. return nil, ErrOperClassDependencies
  544. }
  545. lenOfLastOcs = len(ocs)
  546. var anyMissing bool
  547. for name, info := range conf.OperClasses {
  548. _, exists := ocs[name]
  549. _, extendsExists := ocs[info.Extends]
  550. if exists {
  551. // class already exists
  552. continue
  553. } else if len(info.Extends) > 0 && !extendsExists {
  554. // class we extend on doesn't exist
  555. _, exists := conf.OperClasses[info.Extends]
  556. if !exists {
  557. return nil, fmt.Errorf("Operclass [%s] extends [%s], which doesn't exist", name, info.Extends)
  558. }
  559. anyMissing = true
  560. continue
  561. }
  562. // create new operclass
  563. var oc OperClass
  564. oc.Capabilities = make(map[string]bool)
  565. // get inhereted info from other operclasses
  566. if len(info.Extends) > 0 {
  567. einfo := ocs[info.Extends]
  568. for capab := range einfo.Capabilities {
  569. oc.Capabilities[capab] = true
  570. }
  571. }
  572. // add our own info
  573. oc.Title = info.Title
  574. for _, capab := range info.Capabilities {
  575. oc.Capabilities[capab] = true
  576. }
  577. if len(info.WhoisLine) > 0 {
  578. oc.WhoisLine = info.WhoisLine
  579. } else {
  580. oc.WhoisLine = "is a"
  581. if strings.Contains(strings.ToLower(string(oc.Title[0])), "aeiou") {
  582. oc.WhoisLine += "n"
  583. }
  584. oc.WhoisLine += " "
  585. oc.WhoisLine += oc.Title
  586. }
  587. ocs[name] = &oc
  588. }
  589. if !anyMissing {
  590. // we've got every operclass!
  591. break
  592. }
  593. }
  594. return ocs, nil
  595. }
  596. // Oper represents a single assembled operator's config.
  597. type Oper struct {
  598. Name string
  599. Class *OperClass
  600. WhoisLine string
  601. Vhost string
  602. Pass []byte
  603. Fingerprint string
  604. Auto bool
  605. Modes []modes.ModeChange
  606. }
  607. // Operators returns a map of operator configs from the given OperClass and config.
  608. func (conf *Config) Operators(oc map[string]*OperClass) (map[string]*Oper, error) {
  609. operators := make(map[string]*Oper)
  610. for name, opConf := range conf.Opers {
  611. var oper Oper
  612. // oper name
  613. name, err := CasefoldName(name)
  614. if err != nil {
  615. return nil, fmt.Errorf("Could not casefold oper name: %s", err.Error())
  616. }
  617. oper.Name = name
  618. if opConf.Password != "" {
  619. oper.Pass, err = decodeLegacyPasswordHash(opConf.Password)
  620. if err != nil {
  621. return nil, fmt.Errorf("Oper %s has an invalid password hash: %s", oper.Name, err.Error())
  622. }
  623. }
  624. if opConf.Fingerprint != "" {
  625. oper.Fingerprint, err = utils.NormalizeCertfp(opConf.Fingerprint)
  626. if err != nil {
  627. return nil, fmt.Errorf("Oper %s has an invalid fingerprint: %s", oper.Name, err.Error())
  628. }
  629. }
  630. oper.Auto = opConf.Auto
  631. if oper.Pass == nil && oper.Fingerprint == "" {
  632. return nil, fmt.Errorf("Oper %s has neither a password nor a fingerprint", name)
  633. }
  634. oper.Vhost = opConf.Vhost
  635. class, exists := oc[opConf.Class]
  636. if !exists {
  637. return nil, fmt.Errorf("Could not load operator [%s] - they use operclass [%s] which does not exist", name, opConf.Class)
  638. }
  639. oper.Class = class
  640. if len(opConf.WhoisLine) > 0 {
  641. oper.WhoisLine = opConf.WhoisLine
  642. } else {
  643. oper.WhoisLine = class.WhoisLine
  644. }
  645. modeStr := strings.TrimSpace(opConf.Modes)
  646. modeChanges, unknownChanges := modes.ParseUserModeChanges(strings.Split(modeStr, " ")...)
  647. if len(unknownChanges) > 0 {
  648. return nil, fmt.Errorf("Could not load operator [%s] due to unknown modes %v", name, unknownChanges)
  649. }
  650. oper.Modes = modeChanges
  651. // successful, attach to list of opers
  652. operators[name] = &oper
  653. }
  654. return operators, nil
  655. }
  656. func loadTlsConfig(config TLSListenConfig) (tlsConfig *tls.Config, err error) {
  657. cert, err := tls.LoadX509KeyPair(config.Cert, config.Key)
  658. if err != nil {
  659. return nil, ErrInvalidCertKeyPair
  660. }
  661. result := tls.Config{
  662. Certificates: []tls.Certificate{cert},
  663. ClientAuth: tls.RequestClientCert,
  664. }
  665. return &result, nil
  666. }
  667. // prepareListeners populates Config.Server.trueListeners
  668. func (conf *Config) prepareListeners() (err error) {
  669. if len(conf.Server.Listeners) == 0 {
  670. return fmt.Errorf("No listeners were configured")
  671. }
  672. conf.Server.trueListeners = make(map[string]listenerConfig)
  673. for addr, block := range conf.Server.Listeners {
  674. var lconf listenerConfig
  675. lconf.Tor = block.Tor
  676. lconf.STSOnly = block.STSOnly
  677. if lconf.STSOnly && !conf.Server.STS.Enabled {
  678. return fmt.Errorf("%s is configured as a STS-only listener, but STS is disabled", addr)
  679. }
  680. if block.TLS.Cert != "" {
  681. tlsConfig, err := loadTlsConfig(block.TLS)
  682. if err != nil {
  683. return err
  684. }
  685. lconf.TLSConfig = tlsConfig
  686. lconf.ProxyBeforeTLS = block.TLS.Proxy
  687. }
  688. conf.Server.trueListeners[addr] = lconf
  689. }
  690. return nil
  691. }
  692. // LoadRawConfig loads the config without doing any consistency checks or postprocessing
  693. func LoadRawConfig(filename string) (config *Config, err error) {
  694. data, err := ioutil.ReadFile(filename)
  695. if err != nil {
  696. return nil, err
  697. }
  698. err = yaml.Unmarshal(data, &config)
  699. if err != nil {
  700. return nil, err
  701. }
  702. return
  703. }
  704. // LoadConfig loads the given YAML configuration file.
  705. func LoadConfig(filename string) (config *Config, err error) {
  706. config, err = LoadRawConfig(filename)
  707. if err != nil {
  708. return nil, err
  709. }
  710. config.Filename = filename
  711. if config.Network.Name == "" {
  712. return nil, ErrNetworkNameMissing
  713. }
  714. if config.Server.Name == "" {
  715. return nil, ErrServerNameMissing
  716. }
  717. if !utils.IsServerName(config.Server.Name) {
  718. return nil, ErrServerNameNotHostname
  719. }
  720. config.Server.nameCasefolded = strings.ToLower(config.Server.Name)
  721. if config.Datastore.Path == "" {
  722. return nil, ErrDatastorePathMissing
  723. }
  724. //dan: automagically fix identlen until a few releases in the future (from now, 0.12.0), being a newly-introduced limit
  725. if config.Limits.IdentLen < 1 {
  726. config.Limits.IdentLen = 20
  727. }
  728. if config.Limits.NickLen < 1 || config.Limits.ChannelLen < 2 || config.Limits.AwayLen < 1 || config.Limits.KickLen < 1 || config.Limits.TopicLen < 1 {
  729. return nil, ErrLimitsAreInsane
  730. }
  731. if config.Limits.RegistrationMessages == 0 {
  732. config.Limits.RegistrationMessages = 1024
  733. }
  734. if config.Datastore.MySQL.Enabled {
  735. if config.Limits.NickLen > mysql.MaxTargetLength || config.Limits.ChannelLen > mysql.MaxTargetLength {
  736. return nil, fmt.Errorf("to use MySQL, nick and channel length limits must be %d or lower", mysql.MaxTargetLength)
  737. }
  738. }
  739. config.Server.supportedCaps = caps.NewCompleteSet()
  740. config.Server.capValues = make(caps.Values)
  741. err = config.prepareListeners()
  742. if err != nil {
  743. return nil, fmt.Errorf("failed to prepare listeners: %v", err)
  744. }
  745. if config.Server.STS.Enabled {
  746. if config.Server.STS.Port < 0 || config.Server.STS.Port > 65535 {
  747. return nil, fmt.Errorf("STS port is incorrect, should be 0 if disabled: %d", config.Server.STS.Port)
  748. }
  749. if config.Server.STS.STSOnlyBanner != "" {
  750. for _, line := range strings.Split(config.Server.STS.STSOnlyBanner, "\n") {
  751. config.Server.STS.bannerLines = append(config.Server.STS.bannerLines, strings.TrimSpace(line))
  752. }
  753. } else {
  754. 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)}
  755. }
  756. } else {
  757. config.Server.supportedCaps.Disable(caps.STS)
  758. config.Server.STS.Duration = 0
  759. }
  760. // set this even if STS is disabled
  761. config.Server.capValues[caps.STS] = config.Server.STS.Value()
  762. // lookup-hostnames defaults to true if unset
  763. if config.Server.LookupHostnames != nil {
  764. config.Server.lookupHostnames = *config.Server.LookupHostnames
  765. } else {
  766. config.Server.lookupHostnames = true
  767. }
  768. // process webirc blocks
  769. var newWebIRC []webircConfig
  770. for _, webirc := range config.Server.WebIRC {
  771. // skip webirc blocks with no hosts (such as the example one)
  772. if len(webirc.Hosts) == 0 {
  773. continue
  774. }
  775. err = webirc.Populate()
  776. if err != nil {
  777. return nil, fmt.Errorf("Could not parse WebIRC config: %s", err.Error())
  778. }
  779. newWebIRC = append(newWebIRC, webirc)
  780. }
  781. config.Server.WebIRC = newWebIRC
  782. if config.Limits.Multiline.MaxBytes <= 0 {
  783. config.Server.supportedCaps.Disable(caps.Multiline)
  784. } else {
  785. var multilineCapValue string
  786. if config.Limits.Multiline.MaxLines == 0 {
  787. multilineCapValue = fmt.Sprintf("max-bytes=%d", config.Limits.Multiline.MaxBytes)
  788. } else {
  789. multilineCapValue = fmt.Sprintf("max-bytes=%d,max-lines=%d", config.Limits.Multiline.MaxBytes, config.Limits.Multiline.MaxLines)
  790. }
  791. config.Server.capValues[caps.Multiline] = multilineCapValue
  792. }
  793. // handle legacy name 'bouncer' for 'multiclient' section:
  794. if config.Accounts.Bouncer != nil {
  795. config.Accounts.Multiclient = *config.Accounts.Bouncer
  796. }
  797. if !config.Accounts.Multiclient.Enabled {
  798. config.Accounts.Multiclient.AlwaysOn = PersistentDisabled
  799. } else if config.Accounts.Multiclient.AlwaysOn >= PersistentOptOut {
  800. config.Accounts.Multiclient.AllowedByDefault = true
  801. }
  802. // handle guest format, including the legacy key rename-prefix
  803. if config.Accounts.NickReservation.GuestFormat == "" {
  804. renamePrefix := config.Accounts.NickReservation.RenamePrefix
  805. if renamePrefix == "" {
  806. renamePrefix = "Guest-"
  807. }
  808. config.Accounts.NickReservation.GuestFormat = renamePrefix + "*"
  809. }
  810. config.Accounts.NickReservation.guestRegexp, config.Accounts.NickReservation.guestRegexpFolded, err = compileGuestRegexp(config.Accounts.NickReservation.GuestFormat, config.Server.Casemapping)
  811. if err != nil {
  812. return nil, err
  813. }
  814. var newLogConfigs []logger.LoggingConfig
  815. for _, logConfig := range config.Logging {
  816. // methods
  817. methods := make(map[string]bool)
  818. for _, method := range strings.Split(logConfig.Method, " ") {
  819. if len(method) > 0 {
  820. methods[strings.ToLower(method)] = true
  821. }
  822. }
  823. if methods["file"] && logConfig.Filename == "" {
  824. return nil, ErrLoggerFilenameMissing
  825. }
  826. logConfig.MethodFile = methods["file"]
  827. logConfig.MethodStdout = methods["stdout"]
  828. logConfig.MethodStderr = methods["stderr"]
  829. // levels
  830. level, exists := logger.LogLevelNames[strings.ToLower(logConfig.LevelString)]
  831. if !exists {
  832. return nil, fmt.Errorf("Could not translate log leve [%s]", logConfig.LevelString)
  833. }
  834. logConfig.Level = level
  835. // types
  836. for _, typeStr := range strings.Split(logConfig.TypeString, " ") {
  837. if len(typeStr) == 0 {
  838. continue
  839. }
  840. if typeStr == "-" {
  841. return nil, ErrLoggerExcludeEmpty
  842. }
  843. if typeStr[0] == '-' {
  844. typeStr = typeStr[1:]
  845. logConfig.ExcludedTypes = append(logConfig.ExcludedTypes, typeStr)
  846. } else {
  847. logConfig.Types = append(logConfig.Types, typeStr)
  848. }
  849. }
  850. if len(logConfig.Types) < 1 {
  851. return nil, ErrLoggerHasNoTypes
  852. }
  853. newLogConfigs = append(newLogConfigs, logConfig)
  854. }
  855. config.Logging = newLogConfigs
  856. // hardcode this for now
  857. config.Accounts.Registration.EnabledCredentialTypes = []string{"passphrase", "certfp"}
  858. for i, name := range config.Accounts.Registration.EnabledCallbacks {
  859. if name == "none" {
  860. // we store "none" as "*" internally
  861. config.Accounts.Registration.EnabledCallbacks[i] = "*"
  862. }
  863. }
  864. sort.Strings(config.Accounts.Registration.EnabledCallbacks)
  865. config.Accounts.RequireSasl.exemptedNets, err = utils.ParseNetList(config.Accounts.RequireSasl.Exempted)
  866. if err != nil {
  867. return nil, fmt.Errorf("Could not parse require-sasl exempted nets: %v", err.Error())
  868. }
  869. config.Server.proxyAllowedFromNets, err = utils.ParseNetList(config.Server.ProxyAllowedFrom)
  870. if err != nil {
  871. return nil, fmt.Errorf("Could not parse proxy-allowed-from nets: %v", err.Error())
  872. }
  873. config.Server.secureNets, err = utils.ParseNetList(config.Server.SecureNetDefs)
  874. if err != nil {
  875. return nil, fmt.Errorf("Could not parse secure-nets: %v\n", err.Error())
  876. }
  877. rawRegexp := config.Accounts.VHosts.ValidRegexpRaw
  878. if rawRegexp != "" {
  879. regexp, err := regexp.Compile(rawRegexp)
  880. if err == nil {
  881. config.Accounts.VHosts.ValidRegexp = regexp
  882. } else {
  883. log.Printf("invalid vhost regexp: %s\n", err.Error())
  884. }
  885. }
  886. if config.Accounts.VHosts.ValidRegexp == nil {
  887. config.Accounts.VHosts.ValidRegexp = defaultValidVhostRegex
  888. }
  889. for _, vhost := range config.Accounts.VHosts.OfferList {
  890. if !config.Accounts.VHosts.ValidRegexp.MatchString(vhost) {
  891. return nil, fmt.Errorf("invalid offered vhost: %s", vhost)
  892. }
  893. }
  894. if !config.Accounts.LoginThrottling.Enabled {
  895. config.Accounts.LoginThrottling.MaxAttempts = 0 // limit of 0 means disabled
  896. }
  897. config.Server.capValues[caps.SASL] = "PLAIN,EXTERNAL"
  898. if !config.Accounts.AuthenticationEnabled {
  899. config.Server.supportedCaps.Disable(caps.SASL)
  900. }
  901. maxSendQBytes, err := bytefmt.ToBytes(config.Server.MaxSendQString)
  902. if err != nil {
  903. return nil, fmt.Errorf("Could not parse maximum SendQ size (make sure it only contains whole numbers): %s", err.Error())
  904. }
  905. config.Server.MaxSendQBytes = int(maxSendQBytes)
  906. config.languageManager, err = languages.NewManager(config.Languages.Enabled, config.Languages.Path, config.Languages.Default)
  907. if err != nil {
  908. return nil, fmt.Errorf("Could not load languages: %s", err.Error())
  909. }
  910. config.Server.capValues[caps.Languages] = config.languageManager.CapValue()
  911. // RecoverFromErrors defaults to true
  912. if config.Debug.RecoverFromErrors != nil {
  913. config.Debug.recoverFromErrors = *config.Debug.RecoverFromErrors
  914. } else {
  915. config.Debug.recoverFromErrors = true
  916. }
  917. // process operator definitions, store them to config.operators
  918. operclasses, err := config.OperatorClasses()
  919. if err != nil {
  920. return nil, err
  921. }
  922. opers, err := config.Operators(operclasses)
  923. if err != nil {
  924. return nil, err
  925. }
  926. config.operators = opers
  927. // parse default channel modes
  928. config.Channels.defaultModes = ParseDefaultChannelModes(config.Channels.DefaultModes)
  929. if config.Server.Password != "" {
  930. config.Server.passwordBytes, err = decodeLegacyPasswordHash(config.Server.Password)
  931. if err != nil {
  932. return nil, err
  933. }
  934. }
  935. if config.Accounts.Registration.BcryptCost == 0 {
  936. config.Accounts.Registration.BcryptCost = passwd.DefaultCost
  937. }
  938. if config.Channels.MaxChannelsPerClient == 0 {
  939. config.Channels.MaxChannelsPerClient = 100
  940. }
  941. if config.Channels.Registration.MaxChannelsPerAccount == 0 {
  942. config.Channels.Registration.MaxChannelsPerAccount = 15
  943. }
  944. forceTrailingPtr := config.Server.Compatibility.ForceTrailing
  945. if forceTrailingPtr != nil {
  946. config.Server.Compatibility.forceTrailing = *forceTrailingPtr
  947. } else {
  948. config.Server.Compatibility.forceTrailing = true
  949. }
  950. config.loadMOTD()
  951. // in the current implementation, we disable history by creating a history buffer
  952. // with zero capacity. but the `enabled` config option MUST be respected regardless
  953. // of this detail
  954. if !config.History.Enabled {
  955. config.History.ChannelLength = 0
  956. config.History.ClientLength = 0
  957. }
  958. if !config.History.Enabled || !config.History.Persistent.Enabled {
  959. config.History.Persistent.UnregisteredChannels = false
  960. config.History.Persistent.RegisteredChannels = PersistentDisabled
  961. config.History.Persistent.DirectMessages = PersistentDisabled
  962. }
  963. if config.History.ZNCMax == 0 {
  964. config.History.ZNCMax = config.History.ChathistoryMax
  965. }
  966. config.Datastore.MySQL.ExpireTime = time.Duration(config.History.Restrictions.ExpireTime)
  967. config.Server.Cloaks.Initialize()
  968. if config.Server.Cloaks.Enabled {
  969. if config.Server.Cloaks.Secret == "" || config.Server.Cloaks.Secret == "siaELnk6Kaeo65K3RCrwJjlWaZ-Bt3WuZ2L8MXLbNb4" {
  970. return nil, fmt.Errorf("You must generate a new value of server.ip-cloaking.secret to enable cloaking")
  971. }
  972. if !utils.IsHostname(config.Server.Cloaks.Netname) {
  973. return nil, fmt.Errorf("Invalid netname for cloaked hostnames: %s", config.Server.Cloaks.Netname)
  974. }
  975. }
  976. // now that all postprocessing is complete, regenerate ISUPPORT:
  977. err = config.generateISupport()
  978. if err != nil {
  979. return nil, err
  980. }
  981. err = config.prepareListeners()
  982. if err != nil {
  983. return nil, fmt.Errorf("failed to prepare listeners: %v", err)
  984. }
  985. return config, nil
  986. }
  987. // setISupport sets up our RPL_ISUPPORT reply.
  988. func (config *Config) generateISupport() (err error) {
  989. maxTargetsString := strconv.Itoa(maxTargets)
  990. // add RPL_ISUPPORT tokens
  991. isupport := &config.Server.isupport
  992. isupport.Initialize()
  993. isupport.Add("AWAYLEN", strconv.Itoa(config.Limits.AwayLen))
  994. isupport.Add("CASEMAPPING", "ascii")
  995. isupport.Add("CHANLIMIT", fmt.Sprintf("%s:%d", chanTypes, config.Channels.MaxChannelsPerClient))
  996. 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}.String()}, ","))
  997. if config.History.Enabled && config.History.ChathistoryMax > 0 {
  998. isupport.Add("draft/CHATHISTORY", strconv.Itoa(config.History.ChathistoryMax))
  999. }
  1000. isupport.Add("CHANNELLEN", strconv.Itoa(config.Limits.ChannelLen))
  1001. isupport.Add("CHANTYPES", chanTypes)
  1002. isupport.Add("ELIST", "U")
  1003. isupport.Add("EXCEPTS", "")
  1004. isupport.Add("INVEX", "")
  1005. isupport.Add("KICKLEN", strconv.Itoa(config.Limits.KickLen))
  1006. isupport.Add("MAXLIST", fmt.Sprintf("beI:%s", strconv.Itoa(config.Limits.ChanListModes)))
  1007. isupport.Add("MAXTARGETS", maxTargetsString)
  1008. isupport.Add("MODES", "")
  1009. isupport.Add("MONITOR", strconv.Itoa(config.Limits.MonitorEntries))
  1010. isupport.Add("NETWORK", config.Network.Name)
  1011. isupport.Add("NICKLEN", strconv.Itoa(config.Limits.NickLen))
  1012. isupport.Add("PREFIX", "(qaohv)~&@%+")
  1013. isupport.Add("RPCHAN", "E")
  1014. isupport.Add("RPUSER", "E")
  1015. isupport.Add("STATUSMSG", "~&@%+")
  1016. 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))
  1017. isupport.Add("TOPICLEN", strconv.Itoa(config.Limits.TopicLen))
  1018. if config.Server.Casemapping == CasemappingPRECIS {
  1019. isupport.Add("UTF8MAPPING", precisUTF8MappingToken)
  1020. }
  1021. err = isupport.RegenerateCachedReply()
  1022. return
  1023. }
  1024. // Diff returns changes in supported caps across a rehash.
  1025. func (config *Config) Diff(oldConfig *Config) (addedCaps, removedCaps *caps.Set) {
  1026. addedCaps = caps.NewSet()
  1027. removedCaps = caps.NewSet()
  1028. if oldConfig == nil {
  1029. return
  1030. }
  1031. if oldConfig.Server.capValues[caps.Languages] != config.Server.capValues[caps.Languages] {
  1032. // XXX updated caps get a DEL line and then a NEW line with the new value
  1033. addedCaps.Add(caps.Languages)
  1034. removedCaps.Add(caps.Languages)
  1035. }
  1036. if !oldConfig.Accounts.AuthenticationEnabled && config.Accounts.AuthenticationEnabled {
  1037. addedCaps.Add(caps.SASL)
  1038. } else if oldConfig.Accounts.AuthenticationEnabled && !config.Accounts.AuthenticationEnabled {
  1039. removedCaps.Add(caps.SASL)
  1040. }
  1041. if oldConfig.Limits.Multiline.MaxBytes != 0 && config.Limits.Multiline.MaxBytes == 0 {
  1042. removedCaps.Add(caps.Multiline)
  1043. } else if oldConfig.Limits.Multiline.MaxBytes == 0 && config.Limits.Multiline.MaxBytes != 0 {
  1044. addedCaps.Add(caps.Multiline)
  1045. } else if oldConfig.Limits.Multiline != config.Limits.Multiline {
  1046. removedCaps.Add(caps.Multiline)
  1047. addedCaps.Add(caps.Multiline)
  1048. }
  1049. if oldConfig.Server.STS.Enabled != config.Server.STS.Enabled || oldConfig.Server.capValues[caps.STS] != config.Server.capValues[caps.STS] {
  1050. // XXX: STS is always removed by CAP NEW sts=duration=0, not CAP DEL
  1051. // so the appropriate notify is always a CAP NEW; put it in addedCaps for any change
  1052. addedCaps.Add(caps.STS)
  1053. }
  1054. return
  1055. }
  1056. func compileGuestRegexp(guestFormat string, casemapping Casemapping) (standard, folded *regexp.Regexp, err error) {
  1057. starIndex := strings.IndexByte(guestFormat, '*')
  1058. if starIndex == -1 {
  1059. return nil, nil, errors.New("guest format must contain exactly one *")
  1060. }
  1061. initial := guestFormat[:starIndex]
  1062. final := guestFormat[starIndex+1:]
  1063. if strings.IndexByte(final, '*') != -1 {
  1064. return nil, nil, errors.New("guest format must contain exactly one *")
  1065. }
  1066. standard, err = regexp.Compile(fmt.Sprintf("^%s(.*)%s$", initial, final))
  1067. if err != nil {
  1068. return
  1069. }
  1070. initialFolded, err := casefoldWithSetting(initial, casemapping)
  1071. if err != nil {
  1072. return
  1073. }
  1074. finalFolded, err := casefoldWithSetting(final, casemapping)
  1075. if err != nil {
  1076. return
  1077. }
  1078. folded, err = regexp.Compile(fmt.Sprintf("^%s(.*)%s$", initialFolded, finalFolded))
  1079. return
  1080. }