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

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