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

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