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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545
  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. "bytes"
  8. "crypto/tls"
  9. "errors"
  10. "fmt"
  11. "io/ioutil"
  12. "log"
  13. "net"
  14. "os"
  15. "path/filepath"
  16. "reflect"
  17. "regexp"
  18. "strconv"
  19. "strings"
  20. "time"
  21. "code.cloudfoundry.org/bytefmt"
  22. "github.com/goshuirc/irc-go/ircfmt"
  23. "gopkg.in/yaml.v2"
  24. "github.com/oragono/oragono/irc/caps"
  25. "github.com/oragono/oragono/irc/cloaks"
  26. "github.com/oragono/oragono/irc/connection_limits"
  27. "github.com/oragono/oragono/irc/custime"
  28. "github.com/oragono/oragono/irc/email"
  29. "github.com/oragono/oragono/irc/isupport"
  30. "github.com/oragono/oragono/irc/jwt"
  31. "github.com/oragono/oragono/irc/languages"
  32. "github.com/oragono/oragono/irc/logger"
  33. "github.com/oragono/oragono/irc/modes"
  34. "github.com/oragono/oragono/irc/mysql"
  35. "github.com/oragono/oragono/irc/passwd"
  36. "github.com/oragono/oragono/irc/utils"
  37. )
  38. // here's how this works: exported (capitalized) members of the config structs
  39. // are defined in the YAML file and deserialized directly from there. They may
  40. // be postprocessed and overwritten by LoadConfig. Unexported (lowercase) members
  41. // are derived from the exported members in LoadConfig.
  42. // TLSListenConfig defines configuration options for listening on TLS.
  43. type TLSListenConfig struct {
  44. Cert string
  45. Key string
  46. Proxy bool // XXX: legacy key: it's preferred to specify this directly in listenerConfigBlock
  47. }
  48. // This is the YAML-deserializable type of the value of the `Server.Listeners` map
  49. type listenerConfigBlock struct {
  50. TLS TLSListenConfig
  51. Proxy bool
  52. Tor bool
  53. STSOnly bool `yaml:"sts-only"`
  54. WebSocket bool
  55. }
  56. type PersistentStatus uint
  57. const (
  58. PersistentUnspecified PersistentStatus = iota
  59. PersistentDisabled
  60. PersistentOptIn
  61. PersistentOptOut
  62. PersistentMandatory
  63. )
  64. func persistentStatusToString(status PersistentStatus) string {
  65. switch status {
  66. case PersistentUnspecified:
  67. return "default"
  68. case PersistentDisabled:
  69. return "disabled"
  70. case PersistentOptIn:
  71. return "opt-in"
  72. case PersistentOptOut:
  73. return "opt-out"
  74. case PersistentMandatory:
  75. return "mandatory"
  76. default:
  77. return ""
  78. }
  79. }
  80. func persistentStatusFromString(status string) (PersistentStatus, error) {
  81. switch strings.ToLower(status) {
  82. case "default":
  83. return PersistentUnspecified, nil
  84. case "":
  85. return PersistentDisabled, nil
  86. case "opt-in":
  87. return PersistentOptIn, nil
  88. case "opt-out":
  89. return PersistentOptOut, nil
  90. case "mandatory":
  91. return PersistentMandatory, nil
  92. default:
  93. b, err := utils.StringToBool(status)
  94. if b {
  95. return PersistentMandatory, err
  96. } else {
  97. return PersistentDisabled, err
  98. }
  99. }
  100. }
  101. func (ps *PersistentStatus) UnmarshalYAML(unmarshal func(interface{}) error) error {
  102. var orig string
  103. var err error
  104. if err = unmarshal(&orig); err != nil {
  105. return err
  106. }
  107. result, err := persistentStatusFromString(orig)
  108. if err == nil {
  109. if result == PersistentUnspecified {
  110. result = PersistentDisabled
  111. }
  112. *ps = result
  113. }
  114. return err
  115. }
  116. func persistenceEnabled(serverSetting, clientSetting PersistentStatus) (enabled bool) {
  117. if serverSetting == PersistentDisabled {
  118. return false
  119. } else if serverSetting == PersistentMandatory {
  120. return true
  121. } else if clientSetting == PersistentDisabled {
  122. return false
  123. } else if clientSetting == PersistentMandatory {
  124. return true
  125. } else if serverSetting == PersistentOptOut {
  126. return true
  127. } else {
  128. return false
  129. }
  130. }
  131. type HistoryStatus uint
  132. const (
  133. HistoryDefault HistoryStatus = iota
  134. HistoryDisabled
  135. HistoryEphemeral
  136. HistoryPersistent
  137. )
  138. func historyStatusFromString(str string) (status HistoryStatus, err error) {
  139. switch strings.ToLower(str) {
  140. case "default":
  141. return HistoryDefault, nil
  142. case "ephemeral":
  143. return HistoryEphemeral, nil
  144. case "persistent":
  145. return HistoryPersistent, nil
  146. default:
  147. b, err := utils.StringToBool(str)
  148. if b {
  149. return HistoryPersistent, err
  150. } else {
  151. return HistoryDisabled, err
  152. }
  153. }
  154. }
  155. func historyStatusToString(status HistoryStatus) string {
  156. switch status {
  157. case HistoryDefault:
  158. return "default"
  159. case HistoryDisabled:
  160. return "disabled"
  161. case HistoryEphemeral:
  162. return "ephemeral"
  163. case HistoryPersistent:
  164. return "persistent"
  165. default:
  166. return ""
  167. }
  168. }
  169. // XXX you must have already checked History.Enabled before calling this
  170. func historyEnabled(serverSetting PersistentStatus, localSetting HistoryStatus) (result HistoryStatus) {
  171. switch serverSetting {
  172. case PersistentMandatory:
  173. return HistoryPersistent
  174. case PersistentOptOut:
  175. if localSetting == HistoryDefault {
  176. return HistoryPersistent
  177. } else {
  178. return localSetting
  179. }
  180. case PersistentOptIn:
  181. switch localSetting {
  182. case HistoryPersistent:
  183. return HistoryPersistent
  184. case HistoryEphemeral, HistoryDefault:
  185. return HistoryEphemeral
  186. default:
  187. return HistoryDisabled
  188. }
  189. case PersistentDisabled:
  190. if localSetting == HistoryDisabled {
  191. return HistoryDisabled
  192. } else {
  193. return HistoryEphemeral
  194. }
  195. default:
  196. // PersistentUnspecified: shouldn't happen because the deserializer converts it
  197. // to PersistentDisabled
  198. if localSetting == HistoryDefault {
  199. return HistoryEphemeral
  200. } else {
  201. return localSetting
  202. }
  203. }
  204. }
  205. type MulticlientConfig struct {
  206. Enabled bool
  207. AllowedByDefault bool `yaml:"allowed-by-default"`
  208. AlwaysOn PersistentStatus `yaml:"always-on"`
  209. AutoAway PersistentStatus `yaml:"auto-away"`
  210. }
  211. type throttleConfig struct {
  212. Enabled bool
  213. Duration time.Duration
  214. MaxAttempts int `yaml:"max-attempts"`
  215. }
  216. type ThrottleConfig struct {
  217. throttleConfig
  218. }
  219. func (t *ThrottleConfig) UnmarshalYAML(unmarshal func(interface{}) error) (err error) {
  220. // note that this technique only works if the zero value of the struct
  221. // doesn't need any postprocessing (because if the field is omitted entirely
  222. // from the YAML, then UnmarshalYAML won't be called at all)
  223. if err = unmarshal(&t.throttleConfig); err != nil {
  224. return
  225. }
  226. if !t.Enabled {
  227. t.MaxAttempts = 0 // limit of 0 means disabled
  228. }
  229. return
  230. }
  231. type AccountConfig struct {
  232. Registration AccountRegistrationConfig
  233. AuthenticationEnabled bool `yaml:"authentication-enabled"`
  234. RequireSasl struct {
  235. Enabled bool
  236. Exempted []string
  237. exemptedNets []net.IPNet
  238. } `yaml:"require-sasl"`
  239. DefaultUserModes *string `yaml:"default-user-modes"`
  240. defaultUserModes modes.Modes
  241. LoginThrottling ThrottleConfig `yaml:"login-throttling"`
  242. SkipServerPassword bool `yaml:"skip-server-password"`
  243. LoginViaPassCommand bool `yaml:"login-via-pass-command"`
  244. NickReservation struct {
  245. Enabled bool
  246. AdditionalNickLimit int `yaml:"additional-nick-limit"`
  247. Method NickEnforcementMethod
  248. AllowCustomEnforcement bool `yaml:"allow-custom-enforcement"`
  249. // RenamePrefix is the legacy field, GuestFormat is the new version
  250. RenamePrefix string `yaml:"rename-prefix"`
  251. GuestFormat string `yaml:"guest-nickname-format"`
  252. guestRegexp *regexp.Regexp
  253. guestRegexpFolded *regexp.Regexp
  254. ForceGuestFormat bool `yaml:"force-guest-format"`
  255. ForceNickEqualsAccount bool `yaml:"force-nick-equals-account"`
  256. ForbidAnonNickChanges bool `yaml:"forbid-anonymous-nick-changes"`
  257. } `yaml:"nick-reservation"`
  258. Multiclient MulticlientConfig
  259. Bouncer *MulticlientConfig // # handle old name for 'multiclient'
  260. VHosts VHostConfig
  261. AuthScript AuthScriptConfig `yaml:"auth-script"`
  262. }
  263. type ScriptConfig struct {
  264. Enabled bool
  265. Command string
  266. Args []string
  267. Timeout time.Duration
  268. KillTimeout time.Duration `yaml:"kill-timeout"`
  269. MaxConcurrency uint `yaml:"max-concurrency"`
  270. }
  271. type AuthScriptConfig struct {
  272. ScriptConfig `yaml:",inline"`
  273. Autocreate bool
  274. }
  275. // AccountRegistrationConfig controls account registration.
  276. type AccountRegistrationConfig struct {
  277. Enabled bool
  278. AllowBeforeConnect bool `yaml:"allow-before-connect"`
  279. Throttling ThrottleConfig
  280. // new-style (v2.4 email verification config):
  281. EmailVerification email.MailtoConfig `yaml:"email-verification"`
  282. // old-style email verification config, with "callbacks":
  283. LegacyEnabledCallbacks []string `yaml:"enabled-callbacks"`
  284. LegacyCallbacks struct {
  285. Mailto email.MailtoConfig
  286. } `yaml:"callbacks"`
  287. VerifyTimeout custime.Duration `yaml:"verify-timeout"`
  288. BcryptCost uint `yaml:"bcrypt-cost"`
  289. }
  290. type VHostConfig struct {
  291. Enabled bool
  292. MaxLength int `yaml:"max-length"`
  293. ValidRegexpRaw string `yaml:"valid-regexp"`
  294. validRegexp *regexp.Regexp
  295. }
  296. type NickEnforcementMethod int
  297. const (
  298. // NickEnforcementOptional is the zero value; it serializes to
  299. // "optional" in the yaml config, and "default" as an arg to `NS ENFORCE`.
  300. // in both cases, it means "defer to the other source of truth", i.e.,
  301. // in the config, defer to the user's custom setting, and as a custom setting,
  302. // defer to the default in the config. if both are NickEnforcementOptional then
  303. // there is no enforcement.
  304. // XXX: these are serialized as numbers in the database, so beware of collisions
  305. // when refactoring (any numbers currently in use must keep their meanings, or
  306. // else be fixed up by a schema change)
  307. NickEnforcementOptional NickEnforcementMethod = iota
  308. NickEnforcementNone
  309. NickEnforcementStrict
  310. )
  311. func nickReservationToString(method NickEnforcementMethod) string {
  312. switch method {
  313. case NickEnforcementOptional:
  314. return "default"
  315. case NickEnforcementNone:
  316. return "none"
  317. case NickEnforcementStrict:
  318. return "strict"
  319. default:
  320. return ""
  321. }
  322. }
  323. func nickReservationFromString(method string) (NickEnforcementMethod, error) {
  324. switch strings.ToLower(method) {
  325. case "default":
  326. return NickEnforcementOptional, nil
  327. case "optional":
  328. return NickEnforcementOptional, nil
  329. case "none":
  330. return NickEnforcementNone, nil
  331. case "strict":
  332. return NickEnforcementStrict, nil
  333. default:
  334. return NickEnforcementOptional, fmt.Errorf("invalid nick-reservation.method value: %s", method)
  335. }
  336. }
  337. func (nr *NickEnforcementMethod) UnmarshalYAML(unmarshal func(interface{}) error) error {
  338. var orig string
  339. var err error
  340. if err = unmarshal(&orig); err != nil {
  341. return err
  342. }
  343. method, err := nickReservationFromString(orig)
  344. if err == nil {
  345. *nr = method
  346. }
  347. return err
  348. }
  349. func (cm *Casemapping) UnmarshalYAML(unmarshal func(interface{}) error) (err error) {
  350. var orig string
  351. if err = unmarshal(&orig); err != nil {
  352. return err
  353. }
  354. var result Casemapping
  355. switch strings.ToLower(orig) {
  356. case "ascii":
  357. result = CasemappingASCII
  358. case "precis", "rfc7613", "rfc8265":
  359. result = CasemappingPRECIS
  360. case "permissive", "fun":
  361. result = CasemappingPermissive
  362. default:
  363. return fmt.Errorf("invalid casemapping value: %s", orig)
  364. }
  365. *cm = result
  366. return nil
  367. }
  368. // OperClassConfig defines a specific operator class.
  369. type OperClassConfig struct {
  370. Title string
  371. WhoisLine string
  372. Extends string
  373. Capabilities []string
  374. }
  375. // OperConfig defines a specific operator's configuration.
  376. type OperConfig struct {
  377. Class string
  378. Vhost string
  379. WhoisLine string `yaml:"whois-line"`
  380. Password string
  381. Fingerprint *string // legacy name for certfp, #1050
  382. Certfp string
  383. Auto bool
  384. Hidden bool
  385. Modes string
  386. }
  387. // Various server-enforced limits on data size.
  388. type Limits struct {
  389. AwayLen int `yaml:"awaylen"`
  390. ChanListModes int `yaml:"chan-list-modes"`
  391. ChannelLen int `yaml:"channellen"`
  392. IdentLen int `yaml:"identlen"`
  393. KickLen int `yaml:"kicklen"`
  394. MonitorEntries int `yaml:"monitor-entries"`
  395. NickLen int `yaml:"nicklen"`
  396. TopicLen int `yaml:"topiclen"`
  397. WhowasEntries int `yaml:"whowas-entries"`
  398. RegistrationMessages int `yaml:"registration-messages"`
  399. Multiline struct {
  400. MaxBytes int `yaml:"max-bytes"`
  401. MaxLines int `yaml:"max-lines"`
  402. }
  403. }
  404. // STSConfig controls the STS configuration/
  405. type STSConfig struct {
  406. Enabled bool
  407. Duration custime.Duration
  408. Port int
  409. Preload bool
  410. STSOnlyBanner string `yaml:"sts-only-banner"`
  411. bannerLines []string
  412. }
  413. // Value returns the STS value to advertise in CAP
  414. func (sts *STSConfig) Value() string {
  415. val := fmt.Sprintf("duration=%d", int(time.Duration(sts.Duration).Seconds()))
  416. if sts.Enabled && sts.Port > 0 {
  417. val += fmt.Sprintf(",port=%d", sts.Port)
  418. }
  419. if sts.Enabled && sts.Preload {
  420. val += ",preload"
  421. }
  422. return val
  423. }
  424. type FakelagConfig struct {
  425. Enabled bool
  426. Window time.Duration
  427. BurstLimit uint `yaml:"burst-limit"`
  428. MessagesPerWindow uint `yaml:"messages-per-window"`
  429. Cooldown time.Duration
  430. }
  431. type TorListenersConfig struct {
  432. Listeners []string // legacy only
  433. RequireSasl bool `yaml:"require-sasl"`
  434. Vhost string
  435. MaxConnections int `yaml:"max-connections"`
  436. ThrottleDuration time.Duration `yaml:"throttle-duration"`
  437. MaxConnectionsPerDuration int `yaml:"max-connections-per-duration"`
  438. }
  439. // Config defines the overall configuration.
  440. type Config struct {
  441. AllowEnvironmentOverrides bool `yaml:"allow-environment-overrides"`
  442. Network struct {
  443. Name string
  444. }
  445. Server struct {
  446. Password string
  447. passwordBytes []byte
  448. Name string
  449. nameCasefolded string
  450. // Listeners is the new style for configuring listeners:
  451. Listeners map[string]listenerConfigBlock
  452. UnixBindMode os.FileMode `yaml:"unix-bind-mode"`
  453. TorListeners TorListenersConfig `yaml:"tor-listeners"`
  454. WebSockets struct {
  455. AllowedOrigins []string `yaml:"allowed-origins"`
  456. allowedOriginRegexps []*regexp.Regexp
  457. }
  458. // they get parsed into this internal representation:
  459. trueListeners map[string]utils.ListenerConfig
  460. STS STSConfig
  461. LookupHostnames *bool `yaml:"lookup-hostnames"`
  462. lookupHostnames bool
  463. ForwardConfirmHostnames bool `yaml:"forward-confirm-hostnames"`
  464. CheckIdent bool `yaml:"check-ident"`
  465. CoerceIdent string `yaml:"coerce-ident"`
  466. MOTD string
  467. motdLines []string
  468. MOTDFormatting bool `yaml:"motd-formatting"`
  469. Relaymsg struct {
  470. Enabled bool
  471. Separators string
  472. AvailableToChanops bool `yaml:"available-to-chanops"`
  473. }
  474. ProxyAllowedFrom []string `yaml:"proxy-allowed-from"`
  475. proxyAllowedFromNets []net.IPNet
  476. WebIRC []webircConfig `yaml:"webirc"`
  477. MaxSendQString string `yaml:"max-sendq"`
  478. MaxSendQBytes int
  479. AllowPlaintextResume bool `yaml:"allow-plaintext-resume"`
  480. Compatibility struct {
  481. ForceTrailing *bool `yaml:"force-trailing"`
  482. forceTrailing bool
  483. SendUnprefixedSasl bool `yaml:"send-unprefixed-sasl"`
  484. }
  485. isupport isupport.List
  486. IPLimits connection_limits.LimiterConfig `yaml:"ip-limits"`
  487. Cloaks cloaks.CloakConfig `yaml:"ip-cloaking"`
  488. SecureNetDefs []string `yaml:"secure-nets"`
  489. secureNets []net.IPNet
  490. supportedCaps *caps.Set
  491. capValues caps.Values
  492. Casemapping Casemapping
  493. EnforceUtf8 bool `yaml:"enforce-utf8"`
  494. OutputPath string `yaml:"output-path"`
  495. IPCheckScript ScriptConfig `yaml:"ip-check-script"`
  496. OverrideServicesHostname string `yaml:"override-services-hostname"`
  497. }
  498. Roleplay struct {
  499. Enabled bool
  500. RequireChanops bool `yaml:"require-chanops"`
  501. RequireOper bool `yaml:"require-oper"`
  502. AddSuffix *bool `yaml:"add-suffix"`
  503. addSuffix bool
  504. }
  505. Extjwt struct {
  506. Default jwt.JwtServiceConfig `yaml:",inline"`
  507. Services map[string]jwt.JwtServiceConfig `yaml:"services"`
  508. }
  509. Languages struct {
  510. Enabled bool
  511. Path string
  512. Default string
  513. }
  514. languageManager *languages.Manager
  515. Datastore struct {
  516. Path string
  517. AutoUpgrade bool
  518. MySQL mysql.Config
  519. }
  520. Accounts AccountConfig
  521. Channels struct {
  522. DefaultModes *string `yaml:"default-modes"`
  523. defaultModes modes.Modes
  524. MaxChannelsPerClient int `yaml:"max-channels-per-client"`
  525. OpOnlyCreation bool `yaml:"operator-only-creation"`
  526. Registration struct {
  527. Enabled bool
  528. OperatorOnly bool `yaml:"operator-only"`
  529. MaxChannelsPerAccount int `yaml:"max-channels-per-account"`
  530. }
  531. ListDelay time.Duration `yaml:"list-delay"`
  532. InviteExpiration custime.Duration `yaml:"invite-expiration"`
  533. }
  534. OperClasses map[string]*OperClassConfig `yaml:"oper-classes"`
  535. Opers map[string]*OperConfig
  536. // parsed operator definitions, unexported so they can't be defined
  537. // directly in YAML:
  538. operators map[string]*Oper
  539. Logging []logger.LoggingConfig
  540. Debug struct {
  541. RecoverFromErrors *bool `yaml:"recover-from-errors"`
  542. recoverFromErrors bool
  543. PprofListener *string `yaml:"pprof-listener"`
  544. }
  545. Limits Limits
  546. Fakelag FakelagConfig
  547. History struct {
  548. Enabled bool
  549. ChannelLength int `yaml:"channel-length"`
  550. ClientLength int `yaml:"client-length"`
  551. AutoresizeWindow custime.Duration `yaml:"autoresize-window"`
  552. AutoreplayOnJoin int `yaml:"autoreplay-on-join"`
  553. ChathistoryMax int `yaml:"chathistory-maxmessages"`
  554. ZNCMax int `yaml:"znc-maxmessages"`
  555. Restrictions struct {
  556. ExpireTime custime.Duration `yaml:"expire-time"`
  557. EnforceRegistrationDate bool `yaml:"enforce-registration-date"`
  558. GracePeriod custime.Duration `yaml:"grace-period"`
  559. }
  560. Persistent struct {
  561. Enabled bool
  562. UnregisteredChannels bool `yaml:"unregistered-channels"`
  563. RegisteredChannels PersistentStatus `yaml:"registered-channels"`
  564. DirectMessages PersistentStatus `yaml:"direct-messages"`
  565. }
  566. Retention struct {
  567. AllowIndividualDelete bool `yaml:"allow-individual-delete"`
  568. EnableAccountIndexing bool `yaml:"enable-account-indexing"`
  569. }
  570. TagmsgStorage struct {
  571. Default bool
  572. Whitelist []string
  573. Blacklist []string
  574. } `yaml:"tagmsg-storage"`
  575. }
  576. Filename string
  577. }
  578. // OperClass defines an assembled operator class.
  579. type OperClass struct {
  580. Title string
  581. WhoisLine string `yaml:"whois-line"`
  582. Capabilities utils.StringSet // map to make lookups much easier
  583. }
  584. // OperatorClasses returns a map of assembled operator classes from the given config.
  585. func (conf *Config) OperatorClasses() (map[string]*OperClass, error) {
  586. fixupCapability := func(capab string) string {
  587. return strings.TrimPrefix(capab, "oper:") // #868
  588. }
  589. ocs := make(map[string]*OperClass)
  590. // loop from no extends to most extended, breaking if we can't add any more
  591. lenOfLastOcs := -1
  592. for {
  593. if lenOfLastOcs == len(ocs) {
  594. return nil, errors.New("OperClasses contains a looping dependency, or a class extends from a class that doesn't exist")
  595. }
  596. lenOfLastOcs = len(ocs)
  597. var anyMissing bool
  598. for name, info := range conf.OperClasses {
  599. _, exists := ocs[name]
  600. _, extendsExists := ocs[info.Extends]
  601. if exists {
  602. // class already exists
  603. continue
  604. } else if len(info.Extends) > 0 && !extendsExists {
  605. // class we extend on doesn't exist
  606. _, exists := conf.OperClasses[info.Extends]
  607. if !exists {
  608. return nil, fmt.Errorf("Operclass [%s] extends [%s], which doesn't exist", name, info.Extends)
  609. }
  610. anyMissing = true
  611. continue
  612. }
  613. // create new operclass
  614. var oc OperClass
  615. oc.Capabilities = make(utils.StringSet)
  616. // get inhereted info from other operclasses
  617. if len(info.Extends) > 0 {
  618. einfo := ocs[info.Extends]
  619. for capab := range einfo.Capabilities {
  620. oc.Capabilities.Add(fixupCapability(capab))
  621. }
  622. }
  623. // add our own info
  624. oc.Title = info.Title
  625. for _, capab := range info.Capabilities {
  626. oc.Capabilities.Add(fixupCapability(capab))
  627. }
  628. if len(info.WhoisLine) > 0 {
  629. oc.WhoisLine = info.WhoisLine
  630. } else {
  631. oc.WhoisLine = "is a"
  632. if strings.Contains(strings.ToLower(string(oc.Title[0])), "aeiou") {
  633. oc.WhoisLine += "n"
  634. }
  635. oc.WhoisLine += " "
  636. oc.WhoisLine += oc.Title
  637. }
  638. ocs[name] = &oc
  639. }
  640. if !anyMissing {
  641. // we've got every operclass!
  642. break
  643. }
  644. }
  645. return ocs, nil
  646. }
  647. // Oper represents a single assembled operator's config.
  648. type Oper struct {
  649. Name string
  650. Class *OperClass
  651. WhoisLine string
  652. Vhost string
  653. Pass []byte
  654. Certfp string
  655. Auto bool
  656. Hidden bool
  657. Modes []modes.ModeChange
  658. }
  659. // Operators returns a map of operator configs from the given OperClass and config.
  660. func (conf *Config) Operators(oc map[string]*OperClass) (map[string]*Oper, error) {
  661. operators := make(map[string]*Oper)
  662. for name, opConf := range conf.Opers {
  663. var oper Oper
  664. // oper name
  665. name, err := CasefoldName(name)
  666. if err != nil {
  667. return nil, fmt.Errorf("Could not casefold oper name: %s", err.Error())
  668. }
  669. oper.Name = name
  670. if opConf.Password != "" {
  671. oper.Pass, err = decodeLegacyPasswordHash(opConf.Password)
  672. if err != nil {
  673. return nil, fmt.Errorf("Oper %s has an invalid password hash: %s", oper.Name, err.Error())
  674. }
  675. }
  676. certfp := opConf.Certfp
  677. if certfp == "" && opConf.Fingerprint != nil {
  678. certfp = *opConf.Fingerprint
  679. }
  680. if certfp != "" {
  681. oper.Certfp, err = utils.NormalizeCertfp(certfp)
  682. if err != nil {
  683. return nil, fmt.Errorf("Oper %s has an invalid fingerprint: %s", oper.Name, err.Error())
  684. }
  685. }
  686. oper.Auto = opConf.Auto
  687. oper.Hidden = opConf.Hidden
  688. if oper.Pass == nil && oper.Certfp == "" {
  689. return nil, fmt.Errorf("Oper %s has neither a password nor a fingerprint", name)
  690. }
  691. oper.Vhost = opConf.Vhost
  692. class, exists := oc[opConf.Class]
  693. if !exists {
  694. return nil, fmt.Errorf("Could not load operator [%s] - they use operclass [%s] which does not exist", name, opConf.Class)
  695. }
  696. oper.Class = class
  697. if len(opConf.WhoisLine) > 0 {
  698. oper.WhoisLine = opConf.WhoisLine
  699. } else {
  700. oper.WhoisLine = class.WhoisLine
  701. }
  702. modeStr := strings.TrimSpace(opConf.Modes)
  703. modeChanges, unknownChanges := modes.ParseUserModeChanges(strings.Split(modeStr, " ")...)
  704. if len(unknownChanges) > 0 {
  705. return nil, fmt.Errorf("Could not load operator [%s] due to unknown modes %v", name, unknownChanges)
  706. }
  707. oper.Modes = modeChanges
  708. // successful, attach to list of opers
  709. operators[name] = &oper
  710. }
  711. return operators, nil
  712. }
  713. func loadTlsConfig(config TLSListenConfig, webSocket bool) (tlsConfig *tls.Config, err error) {
  714. cert, err := tls.LoadX509KeyPair(config.Cert, config.Key)
  715. if err != nil {
  716. return nil, &CertKeyError{Err: err}
  717. }
  718. clientAuth := tls.RequestClientCert
  719. if webSocket {
  720. // if Chrome receives a server request for a client certificate
  721. // on a websocket connection, it will immediately disconnect:
  722. // https://bugs.chromium.org/p/chromium/issues/detail?id=329884
  723. // work around this behavior:
  724. clientAuth = tls.NoClientCert
  725. }
  726. result := tls.Config{
  727. Certificates: []tls.Certificate{cert},
  728. ClientAuth: clientAuth,
  729. }
  730. return &result, nil
  731. }
  732. // prepareListeners populates Config.Server.trueListeners
  733. func (conf *Config) prepareListeners() (err error) {
  734. if len(conf.Server.Listeners) == 0 {
  735. return fmt.Errorf("No listeners were configured")
  736. }
  737. conf.Server.trueListeners = make(map[string]utils.ListenerConfig)
  738. for addr, block := range conf.Server.Listeners {
  739. var lconf utils.ListenerConfig
  740. lconf.ProxyDeadline = RegisterTimeout
  741. lconf.Tor = block.Tor
  742. lconf.STSOnly = block.STSOnly
  743. if lconf.STSOnly && !conf.Server.STS.Enabled {
  744. return fmt.Errorf("%s is configured as a STS-only listener, but STS is disabled", addr)
  745. }
  746. if block.TLS.Cert != "" {
  747. tlsConfig, err := loadTlsConfig(block.TLS, block.WebSocket)
  748. if err != nil {
  749. return err
  750. }
  751. lconf.TLSConfig = tlsConfig
  752. }
  753. lconf.RequireProxy = block.TLS.Proxy || block.Proxy
  754. lconf.WebSocket = block.WebSocket
  755. conf.Server.trueListeners[addr] = lconf
  756. }
  757. return nil
  758. }
  759. func (config *Config) processExtjwt() (err error) {
  760. // first process the default service, which may be disabled
  761. err = config.Extjwt.Default.Postprocess()
  762. if err != nil {
  763. return
  764. }
  765. // now process the named services. it is an error if any is disabled
  766. // also, normalize the service names to lowercase
  767. services := make(map[string]jwt.JwtServiceConfig, len(config.Extjwt.Services))
  768. for service, sConf := range config.Extjwt.Services {
  769. err := sConf.Postprocess()
  770. if err != nil {
  771. return err
  772. }
  773. if !sConf.Enabled() {
  774. return fmt.Errorf("no keys enabled for extjwt service %s", service)
  775. }
  776. services[strings.ToLower(service)] = sConf
  777. }
  778. config.Extjwt.Services = services
  779. return nil
  780. }
  781. // LoadRawConfig loads the config without doing any consistency checks or postprocessing
  782. func LoadRawConfig(filename string) (config *Config, err error) {
  783. data, err := ioutil.ReadFile(filename)
  784. if err != nil {
  785. return nil, err
  786. }
  787. err = yaml.Unmarshal(data, &config)
  788. if err != nil {
  789. return nil, err
  790. }
  791. return
  792. }
  793. // convert, e.g., "ALLOWED_ORIGINS" to "allowed-origins"
  794. func screamingSnakeToKebab(in string) (out string) {
  795. var buf strings.Builder
  796. for i := 0; i < len(in); i++ {
  797. c := in[i]
  798. switch {
  799. case c == '_':
  800. buf.WriteByte('-')
  801. case 'A' <= c && c <= 'Z':
  802. buf.WriteByte(c + ('a' - 'A'))
  803. default:
  804. buf.WriteByte(c)
  805. }
  806. }
  807. return buf.String()
  808. }
  809. func isExported(field reflect.StructField) bool {
  810. return field.PkgPath == "" // https://golang.org/pkg/reflect/#StructField
  811. }
  812. // errors caused by config overrides
  813. type configPathError struct {
  814. name string
  815. desc string
  816. fatalErr error
  817. }
  818. func (ce *configPathError) Error() string {
  819. if ce.fatalErr != nil {
  820. return fmt.Sprintf("Couldn't apply config override `%s`: %s: %v", ce.name, ce.desc, ce.fatalErr)
  821. }
  822. return fmt.Sprintf("Couldn't apply config override `%s`: %s", ce.name, ce.desc)
  823. }
  824. func mungeFromEnvironment(config *Config, envPair string) (applied bool, err *configPathError) {
  825. equalIdx := strings.IndexByte(envPair, '=')
  826. name, value := envPair[:equalIdx], envPair[equalIdx+1:]
  827. if !strings.HasPrefix(name, "ORAGONO__") {
  828. return false, nil
  829. }
  830. name = strings.TrimPrefix(name, "ORAGONO__")
  831. pathComponents := strings.Split(name, "__")
  832. for i, pathComponent := range pathComponents {
  833. pathComponents[i] = screamingSnakeToKebab(pathComponent)
  834. }
  835. v := reflect.Indirect(reflect.ValueOf(config))
  836. t := v.Type()
  837. for _, component := range pathComponents {
  838. if component == "" {
  839. return false, &configPathError{name, "invalid", nil}
  840. }
  841. if v.Kind() != reflect.Struct {
  842. return false, &configPathError{name, "index into non-struct", nil}
  843. }
  844. var nextField reflect.StructField
  845. success := false
  846. n := t.NumField()
  847. // preferentially get a field with an exact yaml tag match,
  848. // then fall back to case-insensitive comparison of field names
  849. for i := 0; i < n; i++ {
  850. field := t.Field(i)
  851. if isExported(field) && field.Tag.Get("yaml") == component {
  852. nextField = field
  853. success = true
  854. break
  855. }
  856. }
  857. if !success {
  858. for i := 0; i < n; i++ {
  859. field := t.Field(i)
  860. if isExported(field) && strings.ToLower(field.Name) == component {
  861. nextField = field
  862. success = true
  863. break
  864. }
  865. }
  866. }
  867. if !success {
  868. return false, &configPathError{name, fmt.Sprintf("couldn't resolve path component: `%s`", component), nil}
  869. }
  870. v = v.FieldByName(nextField.Name)
  871. // dereference pointer field if necessary, initialize new value if necessary
  872. if v.Kind() == reflect.Ptr {
  873. if v.IsNil() {
  874. v.Set(reflect.New(v.Type().Elem()))
  875. }
  876. v = reflect.Indirect(v)
  877. }
  878. t = v.Type()
  879. }
  880. yamlErr := yaml.Unmarshal([]byte(value), v.Addr().Interface())
  881. if yamlErr != nil {
  882. return false, &configPathError{name, "couldn't deserialize YAML", yamlErr}
  883. }
  884. return true, nil
  885. }
  886. // LoadConfig loads the given YAML configuration file.
  887. func LoadConfig(filename string) (config *Config, err error) {
  888. config, err = LoadRawConfig(filename)
  889. if err != nil {
  890. return nil, err
  891. }
  892. if config.AllowEnvironmentOverrides {
  893. for _, envPair := range os.Environ() {
  894. applied, envErr := mungeFromEnvironment(config, envPair)
  895. if envErr != nil {
  896. if envErr.fatalErr != nil {
  897. return nil, envErr
  898. } else {
  899. log.Println(envErr.Error())
  900. }
  901. } else if applied {
  902. log.Printf("applied environment override: %s\n", envPair)
  903. }
  904. }
  905. }
  906. config.Filename = filename
  907. if config.Network.Name == "" {
  908. return nil, errors.New("Network name missing")
  909. }
  910. if config.Server.Name == "" {
  911. return nil, errors.New("Server name missing")
  912. }
  913. if !utils.IsServerName(config.Server.Name) {
  914. return nil, errors.New("Server name must match the format of a hostname")
  915. }
  916. config.Server.nameCasefolded = strings.ToLower(config.Server.Name)
  917. if config.Datastore.Path == "" {
  918. return nil, errors.New("Datastore path missing")
  919. }
  920. //dan: automagically fix identlen until a few releases in the future (from now, 0.12.0), being a newly-introduced limit
  921. if config.Limits.IdentLen < 1 {
  922. config.Limits.IdentLen = 20
  923. }
  924. if config.Limits.NickLen < 1 || config.Limits.ChannelLen < 2 || config.Limits.AwayLen < 1 || config.Limits.KickLen < 1 || config.Limits.TopicLen < 1 {
  925. return nil, errors.New("One or more limits values are too low")
  926. }
  927. if config.Limits.RegistrationMessages == 0 {
  928. config.Limits.RegistrationMessages = 1024
  929. }
  930. if config.Datastore.MySQL.Enabled {
  931. if config.Limits.NickLen > mysql.MaxTargetLength || config.Limits.ChannelLen > mysql.MaxTargetLength {
  932. return nil, fmt.Errorf("to use MySQL, nick and channel length limits must be %d or lower", mysql.MaxTargetLength)
  933. }
  934. }
  935. if config.Server.CoerceIdent != "" {
  936. if config.Server.CheckIdent {
  937. return nil, errors.New("Can't configure both check-ident and coerce-ident")
  938. }
  939. if config.Server.CoerceIdent[0] != '~' {
  940. return nil, errors.New("coerce-ident value must start with a ~")
  941. }
  942. if !isIdent(config.Server.CoerceIdent[1:]) {
  943. return nil, errors.New("coerce-ident must be valid as an IRC user/ident field")
  944. }
  945. }
  946. config.Server.supportedCaps = caps.NewCompleteSet()
  947. config.Server.capValues = make(caps.Values)
  948. err = config.prepareListeners()
  949. if err != nil {
  950. return nil, fmt.Errorf("failed to prepare listeners: %v", err)
  951. }
  952. for _, glob := range config.Server.WebSockets.AllowedOrigins {
  953. globre, err := utils.CompileGlob(glob, false)
  954. if err != nil {
  955. return nil, fmt.Errorf("invalid websocket allowed-origin expression: %s", glob)
  956. }
  957. config.Server.WebSockets.allowedOriginRegexps = append(config.Server.WebSockets.allowedOriginRegexps, globre)
  958. }
  959. if config.Server.STS.Enabled {
  960. if config.Server.STS.Port < 0 || config.Server.STS.Port > 65535 {
  961. return nil, fmt.Errorf("STS port is incorrect, should be 0 if disabled: %d", config.Server.STS.Port)
  962. }
  963. if config.Server.STS.STSOnlyBanner != "" {
  964. for _, line := range strings.Split(config.Server.STS.STSOnlyBanner, "\n") {
  965. config.Server.STS.bannerLines = append(config.Server.STS.bannerLines, strings.TrimSpace(line))
  966. }
  967. } else {
  968. 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)}
  969. }
  970. } else {
  971. config.Server.supportedCaps.Disable(caps.STS)
  972. config.Server.STS.Duration = 0
  973. }
  974. // set this even if STS is disabled
  975. config.Server.capValues[caps.STS] = config.Server.STS.Value()
  976. config.Server.lookupHostnames = utils.BoolDefaultTrue(config.Server.LookupHostnames)
  977. // process webirc blocks
  978. var newWebIRC []webircConfig
  979. for _, webirc := range config.Server.WebIRC {
  980. // skip webirc blocks with no hosts (such as the example one)
  981. if len(webirc.Hosts) == 0 {
  982. continue
  983. }
  984. err = webirc.Populate()
  985. if err != nil {
  986. return nil, fmt.Errorf("Could not parse WebIRC config: %s", err.Error())
  987. }
  988. newWebIRC = append(newWebIRC, webirc)
  989. }
  990. config.Server.WebIRC = newWebIRC
  991. if config.Limits.Multiline.MaxBytes <= 0 {
  992. config.Server.supportedCaps.Disable(caps.Multiline)
  993. } else {
  994. var multilineCapValue string
  995. if config.Limits.Multiline.MaxLines == 0 {
  996. multilineCapValue = fmt.Sprintf("max-bytes=%d", config.Limits.Multiline.MaxBytes)
  997. } else {
  998. multilineCapValue = fmt.Sprintf("max-bytes=%d,max-lines=%d", config.Limits.Multiline.MaxBytes, config.Limits.Multiline.MaxLines)
  999. }
  1000. config.Server.capValues[caps.Multiline] = multilineCapValue
  1001. }
  1002. // handle legacy name 'bouncer' for 'multiclient' section:
  1003. if config.Accounts.Bouncer != nil {
  1004. config.Accounts.Multiclient = *config.Accounts.Bouncer
  1005. }
  1006. if !config.Accounts.Multiclient.Enabled {
  1007. config.Accounts.Multiclient.AlwaysOn = PersistentDisabled
  1008. } else if config.Accounts.Multiclient.AlwaysOn >= PersistentOptOut {
  1009. config.Accounts.Multiclient.AllowedByDefault = true
  1010. }
  1011. if config.Accounts.NickReservation.ForceNickEqualsAccount && !config.Accounts.Multiclient.Enabled {
  1012. return nil, errors.New("force-nick-equals-account requires enabling multiclient as well")
  1013. }
  1014. // handle guest format, including the legacy key rename-prefix
  1015. if config.Accounts.NickReservation.GuestFormat == "" {
  1016. renamePrefix := config.Accounts.NickReservation.RenamePrefix
  1017. if renamePrefix == "" {
  1018. renamePrefix = "Guest-"
  1019. }
  1020. config.Accounts.NickReservation.GuestFormat = renamePrefix + "*"
  1021. }
  1022. config.Accounts.NickReservation.guestRegexp, config.Accounts.NickReservation.guestRegexpFolded, err = compileGuestRegexp(config.Accounts.NickReservation.GuestFormat, config.Server.Casemapping)
  1023. if err != nil {
  1024. return nil, err
  1025. }
  1026. var newLogConfigs []logger.LoggingConfig
  1027. for _, logConfig := range config.Logging {
  1028. // methods
  1029. methods := make(map[string]bool)
  1030. for _, method := range strings.Split(logConfig.Method, " ") {
  1031. if len(method) > 0 {
  1032. methods[strings.ToLower(method)] = true
  1033. }
  1034. }
  1035. if methods["file"] && logConfig.Filename == "" {
  1036. return nil, errors.New("Logging configuration specifies 'file' method but 'filename' is empty")
  1037. }
  1038. logConfig.MethodFile = methods["file"]
  1039. logConfig.MethodStdout = methods["stdout"]
  1040. logConfig.MethodStderr = methods["stderr"]
  1041. // levels
  1042. level, exists := logger.LogLevelNames[strings.ToLower(logConfig.LevelString)]
  1043. if !exists {
  1044. return nil, fmt.Errorf("Could not translate log leve [%s]", logConfig.LevelString)
  1045. }
  1046. logConfig.Level = level
  1047. // types
  1048. for _, typeStr := range strings.Split(logConfig.TypeString, " ") {
  1049. if len(typeStr) == 0 {
  1050. continue
  1051. }
  1052. if typeStr == "-" {
  1053. return nil, errors.New("Encountered logging type '-' with no type to exclude")
  1054. }
  1055. if typeStr[0] == '-' {
  1056. typeStr = typeStr[1:]
  1057. logConfig.ExcludedTypes = append(logConfig.ExcludedTypes, typeStr)
  1058. } else {
  1059. logConfig.Types = append(logConfig.Types, typeStr)
  1060. }
  1061. }
  1062. if len(logConfig.Types) < 1 {
  1063. return nil, errors.New("Logger has no types to log")
  1064. }
  1065. newLogConfigs = append(newLogConfigs, logConfig)
  1066. }
  1067. config.Logging = newLogConfigs
  1068. if config.Accounts.Registration.EmailVerification.Enabled {
  1069. err := config.Accounts.Registration.EmailVerification.Postprocess(config.Server.Name)
  1070. if err != nil {
  1071. return nil, err
  1072. }
  1073. } else {
  1074. // TODO: this processes the legacy "callback" config, clean this up in 2.5 or later
  1075. // TODO: also clean up the legacy "inline" MTA config format (from ee05a4324dfde)
  1076. mailtoEnabled := false
  1077. for _, name := range config.Accounts.Registration.LegacyEnabledCallbacks {
  1078. if name == "mailto" {
  1079. mailtoEnabled = true
  1080. break
  1081. }
  1082. }
  1083. if mailtoEnabled {
  1084. config.Accounts.Registration.EmailVerification = config.Accounts.Registration.LegacyCallbacks.Mailto
  1085. config.Accounts.Registration.EmailVerification.Enabled = true
  1086. err := config.Accounts.Registration.EmailVerification.Postprocess(config.Server.Name)
  1087. if err != nil {
  1088. return nil, err
  1089. }
  1090. }
  1091. }
  1092. config.Accounts.defaultUserModes = ParseDefaultUserModes(config.Accounts.DefaultUserModes)
  1093. config.Accounts.RequireSasl.exemptedNets, err = utils.ParseNetList(config.Accounts.RequireSasl.Exempted)
  1094. if err != nil {
  1095. return nil, fmt.Errorf("Could not parse require-sasl exempted nets: %v", err.Error())
  1096. }
  1097. config.Server.proxyAllowedFromNets, err = utils.ParseNetList(config.Server.ProxyAllowedFrom)
  1098. if err != nil {
  1099. return nil, fmt.Errorf("Could not parse proxy-allowed-from nets: %v", err.Error())
  1100. }
  1101. config.Server.secureNets, err = utils.ParseNetList(config.Server.SecureNetDefs)
  1102. if err != nil {
  1103. return nil, fmt.Errorf("Could not parse secure-nets: %v\n", err.Error())
  1104. }
  1105. rawRegexp := config.Accounts.VHosts.ValidRegexpRaw
  1106. if rawRegexp != "" {
  1107. regexp, err := regexp.Compile(rawRegexp)
  1108. if err == nil {
  1109. config.Accounts.VHosts.validRegexp = regexp
  1110. } else {
  1111. log.Printf("invalid vhost regexp: %s\n", err.Error())
  1112. }
  1113. }
  1114. if config.Accounts.VHosts.validRegexp == nil {
  1115. config.Accounts.VHosts.validRegexp = defaultValidVhostRegex
  1116. }
  1117. config.Server.capValues[caps.SASL] = "PLAIN,EXTERNAL"
  1118. if !config.Accounts.AuthenticationEnabled {
  1119. config.Server.supportedCaps.Disable(caps.SASL)
  1120. }
  1121. if !config.Accounts.Registration.Enabled {
  1122. config.Server.supportedCaps.Disable(caps.Register)
  1123. } else {
  1124. var registerValues []string
  1125. if config.Accounts.Registration.AllowBeforeConnect {
  1126. registerValues = append(registerValues, "before-connect")
  1127. }
  1128. if config.Accounts.Registration.EmailVerification.Enabled {
  1129. registerValues = append(registerValues, "email-required")
  1130. }
  1131. if config.Accounts.RequireSasl.Enabled {
  1132. registerValues = append(registerValues, "account-required")
  1133. }
  1134. if len(registerValues) != 0 {
  1135. config.Server.capValues[caps.Register] = strings.Join(registerValues, ",")
  1136. }
  1137. }
  1138. maxSendQBytes, err := bytefmt.ToBytes(config.Server.MaxSendQString)
  1139. if err != nil {
  1140. return nil, fmt.Errorf("Could not parse maximum SendQ size (make sure it only contains whole numbers): %s", err.Error())
  1141. }
  1142. config.Server.MaxSendQBytes = int(maxSendQBytes)
  1143. config.languageManager, err = languages.NewManager(config.Languages.Enabled, config.Languages.Path, config.Languages.Default)
  1144. if err != nil {
  1145. return nil, fmt.Errorf("Could not load languages: %s", err.Error())
  1146. }
  1147. config.Server.capValues[caps.Languages] = config.languageManager.CapValue()
  1148. if config.Server.Relaymsg.Enabled {
  1149. for _, char := range protocolBreakingNameCharacters {
  1150. if strings.ContainsRune(config.Server.Relaymsg.Separators, char) {
  1151. return nil, fmt.Errorf("RELAYMSG separators cannot include the characters %s", protocolBreakingNameCharacters)
  1152. }
  1153. }
  1154. config.Server.capValues[caps.Relaymsg] = config.Server.Relaymsg.Separators
  1155. } else {
  1156. config.Server.supportedCaps.Disable(caps.Relaymsg)
  1157. }
  1158. config.Debug.recoverFromErrors = utils.BoolDefaultTrue(config.Debug.RecoverFromErrors)
  1159. // process operator definitions, store them to config.operators
  1160. operclasses, err := config.OperatorClasses()
  1161. if err != nil {
  1162. return nil, err
  1163. }
  1164. opers, err := config.Operators(operclasses)
  1165. if err != nil {
  1166. return nil, err
  1167. }
  1168. config.operators = opers
  1169. // parse default channel modes
  1170. config.Channels.defaultModes = ParseDefaultChannelModes(config.Channels.DefaultModes)
  1171. if config.Server.Password != "" {
  1172. config.Server.passwordBytes, err = decodeLegacyPasswordHash(config.Server.Password)
  1173. if err != nil {
  1174. return nil, err
  1175. }
  1176. if config.Accounts.LoginViaPassCommand && !config.Accounts.SkipServerPassword {
  1177. return nil, errors.New("Using a server password and login-via-pass-command requires skip-server-password as well")
  1178. }
  1179. }
  1180. if config.Accounts.Registration.BcryptCost == 0 {
  1181. config.Accounts.Registration.BcryptCost = passwd.DefaultCost
  1182. }
  1183. if config.Channels.MaxChannelsPerClient == 0 {
  1184. config.Channels.MaxChannelsPerClient = 100
  1185. }
  1186. if config.Channels.Registration.MaxChannelsPerAccount == 0 {
  1187. config.Channels.Registration.MaxChannelsPerAccount = 15
  1188. }
  1189. config.Server.Compatibility.forceTrailing = utils.BoolDefaultTrue(config.Server.Compatibility.ForceTrailing)
  1190. config.loadMOTD()
  1191. // in the current implementation, we disable history by creating a history buffer
  1192. // with zero capacity. but the `enabled` config option MUST be respected regardless
  1193. // of this detail
  1194. if !config.History.Enabled {
  1195. config.History.ChannelLength = 0
  1196. config.History.ClientLength = 0
  1197. }
  1198. if !config.History.Enabled || !config.History.Persistent.Enabled {
  1199. config.History.Persistent.Enabled = false
  1200. config.History.Persistent.UnregisteredChannels = false
  1201. config.History.Persistent.RegisteredChannels = PersistentDisabled
  1202. config.History.Persistent.DirectMessages = PersistentDisabled
  1203. }
  1204. if config.History.Persistent.Enabled && !config.Datastore.MySQL.Enabled {
  1205. return nil, fmt.Errorf("You must configure a MySQL server in order to enable persistent history")
  1206. }
  1207. if config.History.ZNCMax == 0 {
  1208. config.History.ZNCMax = config.History.ChathistoryMax
  1209. }
  1210. config.Roleplay.addSuffix = utils.BoolDefaultTrue(config.Roleplay.AddSuffix)
  1211. config.Datastore.MySQL.ExpireTime = time.Duration(config.History.Restrictions.ExpireTime)
  1212. config.Datastore.MySQL.TrackAccountMessages = config.History.Retention.EnableAccountIndexing
  1213. config.Server.Cloaks.Initialize()
  1214. if config.Server.Cloaks.Enabled {
  1215. if !utils.IsHostname(config.Server.Cloaks.Netname) {
  1216. return nil, fmt.Errorf("Invalid netname for cloaked hostnames: %s", config.Server.Cloaks.Netname)
  1217. }
  1218. }
  1219. err = config.processExtjwt()
  1220. if err != nil {
  1221. return nil, err
  1222. }
  1223. // now that all postprocessing is complete, regenerate ISUPPORT:
  1224. err = config.generateISupport()
  1225. if err != nil {
  1226. return nil, err
  1227. }
  1228. err = config.prepareListeners()
  1229. if err != nil {
  1230. return nil, fmt.Errorf("failed to prepare listeners: %v", err)
  1231. }
  1232. return config, nil
  1233. }
  1234. func (config *Config) getOutputPath(filename string) string {
  1235. return filepath.Join(config.Server.OutputPath, filename)
  1236. }
  1237. func (config *Config) isRelaymsgIdentifier(nick string) bool {
  1238. if !config.Server.Relaymsg.Enabled {
  1239. return false
  1240. }
  1241. for _, char := range config.Server.Relaymsg.Separators {
  1242. if strings.ContainsRune(nick, char) {
  1243. return true
  1244. }
  1245. }
  1246. return false
  1247. }
  1248. // setISupport sets up our RPL_ISUPPORT reply.
  1249. func (config *Config) generateISupport() (err error) {
  1250. maxTargetsString := strconv.Itoa(maxTargets)
  1251. // add RPL_ISUPPORT tokens
  1252. isupport := &config.Server.isupport
  1253. isupport.Initialize()
  1254. isupport.Add("AWAYLEN", strconv.Itoa(config.Limits.AwayLen))
  1255. isupport.Add("BOT", "B")
  1256. isupport.Add("CASEMAPPING", "ascii")
  1257. isupport.Add("CHANLIMIT", fmt.Sprintf("%s:%d", chanTypes, config.Channels.MaxChannelsPerClient))
  1258. isupport.Add("CHANMODES", chanmodesToken)
  1259. if config.History.Enabled && config.History.ChathistoryMax > 0 {
  1260. isupport.Add("draft/CHATHISTORY", strconv.Itoa(config.History.ChathistoryMax))
  1261. }
  1262. isupport.Add("CHANNELLEN", strconv.Itoa(config.Limits.ChannelLen))
  1263. isupport.Add("CHANTYPES", chanTypes)
  1264. isupport.Add("ELIST", "U")
  1265. isupport.Add("EXCEPTS", "")
  1266. if config.Extjwt.Default.Enabled() || len(config.Extjwt.Services) != 0 {
  1267. isupport.Add("EXTJWT", "1")
  1268. }
  1269. isupport.Add("EXTBAN", ",m")
  1270. isupport.Add("INVEX", "")
  1271. isupport.Add("KICKLEN", strconv.Itoa(config.Limits.KickLen))
  1272. isupport.Add("MAXLIST", fmt.Sprintf("beI:%s", strconv.Itoa(config.Limits.ChanListModes)))
  1273. isupport.Add("MAXTARGETS", maxTargetsString)
  1274. isupport.Add("MODES", "")
  1275. isupport.Add("MONITOR", strconv.Itoa(config.Limits.MonitorEntries))
  1276. isupport.Add("NETWORK", config.Network.Name)
  1277. isupport.Add("NICKLEN", strconv.Itoa(config.Limits.NickLen))
  1278. isupport.Add("PREFIX", "(qaohv)~&@%+")
  1279. if config.Roleplay.Enabled {
  1280. isupport.Add("RPCHAN", "E")
  1281. isupport.Add("RPUSER", "E")
  1282. }
  1283. isupport.Add("STATUSMSG", "~&@%+")
  1284. isupport.Add("TARGMAX", fmt.Sprintf("NAMES:1,LIST:1,KICK:1,WHOIS:1,USERHOST:10,PRIVMSG:%s,TAGMSG:%s,NOTICE:%s,MONITOR:%d", maxTargetsString, maxTargetsString, maxTargetsString, config.Limits.MonitorEntries))
  1285. isupport.Add("TOPICLEN", strconv.Itoa(config.Limits.TopicLen))
  1286. if config.Server.Casemapping == CasemappingPRECIS {
  1287. isupport.Add("UTF8MAPPING", precisUTF8MappingToken)
  1288. }
  1289. isupport.Add("WHOX", "")
  1290. err = isupport.RegenerateCachedReply()
  1291. return
  1292. }
  1293. // Diff returns changes in supported caps across a rehash.
  1294. func (config *Config) Diff(oldConfig *Config) (addedCaps, removedCaps *caps.Set) {
  1295. addedCaps = caps.NewSet()
  1296. removedCaps = caps.NewSet()
  1297. if oldConfig == nil {
  1298. return
  1299. }
  1300. if oldConfig.Server.capValues[caps.Languages] != config.Server.capValues[caps.Languages] {
  1301. // XXX updated caps get a DEL line and then a NEW line with the new value
  1302. addedCaps.Add(caps.Languages)
  1303. removedCaps.Add(caps.Languages)
  1304. }
  1305. if !oldConfig.Accounts.AuthenticationEnabled && config.Accounts.AuthenticationEnabled {
  1306. addedCaps.Add(caps.SASL)
  1307. } else if oldConfig.Accounts.AuthenticationEnabled && !config.Accounts.AuthenticationEnabled {
  1308. removedCaps.Add(caps.SASL)
  1309. }
  1310. if oldConfig.Limits.Multiline.MaxBytes != 0 && config.Limits.Multiline.MaxBytes == 0 {
  1311. removedCaps.Add(caps.Multiline)
  1312. } else if oldConfig.Limits.Multiline.MaxBytes == 0 && config.Limits.Multiline.MaxBytes != 0 {
  1313. addedCaps.Add(caps.Multiline)
  1314. } else if oldConfig.Limits.Multiline != config.Limits.Multiline {
  1315. removedCaps.Add(caps.Multiline)
  1316. addedCaps.Add(caps.Multiline)
  1317. }
  1318. if oldConfig.Server.STS.Enabled != config.Server.STS.Enabled || oldConfig.Server.capValues[caps.STS] != config.Server.capValues[caps.STS] {
  1319. // XXX: STS is always removed by CAP NEW sts=duration=0, not CAP DEL
  1320. // so the appropriate notify is always a CAP NEW; put it in addedCaps for any change
  1321. addedCaps.Add(caps.STS)
  1322. }
  1323. return
  1324. }
  1325. // determine whether we need to resize / create / destroy
  1326. // the in-memory history buffers:
  1327. func (config *Config) historyChangedFrom(oldConfig *Config) bool {
  1328. return config.History.Enabled != oldConfig.History.Enabled ||
  1329. config.History.ChannelLength != oldConfig.History.ChannelLength ||
  1330. config.History.ClientLength != oldConfig.History.ClientLength ||
  1331. config.History.AutoresizeWindow != oldConfig.History.AutoresizeWindow ||
  1332. config.History.Persistent != oldConfig.History.Persistent
  1333. }
  1334. func compileGuestRegexp(guestFormat string, casemapping Casemapping) (standard, folded *regexp.Regexp, err error) {
  1335. if strings.Count(guestFormat, "?") != 0 || strings.Count(guestFormat, "*") != 1 {
  1336. err = errors.New("guest format must contain 1 '*' and no '?'s")
  1337. return
  1338. }
  1339. standard, err = utils.CompileGlob(guestFormat, true)
  1340. if err != nil {
  1341. return
  1342. }
  1343. starIndex := strings.IndexByte(guestFormat, '*')
  1344. initial := guestFormat[:starIndex]
  1345. final := guestFormat[starIndex+1:]
  1346. initialFolded, err := casefoldWithSetting(initial, casemapping)
  1347. if err != nil {
  1348. return
  1349. }
  1350. finalFolded, err := casefoldWithSetting(final, casemapping)
  1351. if err != nil {
  1352. return
  1353. }
  1354. folded, err = utils.CompileGlob(fmt.Sprintf("%s*%s", initialFolded, finalFolded), false)
  1355. return
  1356. }
  1357. func (config *Config) loadMOTD() error {
  1358. if config.Server.MOTD != "" {
  1359. file, err := os.Open(config.Server.MOTD)
  1360. if err != nil {
  1361. return err
  1362. }
  1363. defer file.Close()
  1364. contents, err := ioutil.ReadAll(file)
  1365. if err != nil {
  1366. return err
  1367. }
  1368. lines := bytes.Split(contents, []byte{'\n'})
  1369. for i, line := range lines {
  1370. lineToSend := string(bytes.TrimRight(line, "\r\n"))
  1371. if len(lineToSend) == 0 && i == len(lines)-1 {
  1372. // if the last line of the MOTD was properly terminated with \n,
  1373. // there's no need to send a blank line to clients
  1374. continue
  1375. }
  1376. if config.Server.MOTDFormatting {
  1377. lineToSend = ircfmt.Unescape(lineToSend)
  1378. }
  1379. // "- " is the required prefix for MOTD
  1380. lineToSend = fmt.Sprintf("- %s", lineToSend)
  1381. config.Server.motdLines = append(config.Server.motdLines, lineToSend)
  1382. }
  1383. }
  1384. return nil
  1385. }