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.

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