Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

config.go 46KB

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