Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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