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 37KB

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