Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

config.go 46KB

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