您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

config.go 47KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557
  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.Enabled {
  1015. config.Accounts.NickReservation.ForceNickEqualsAccount = false
  1016. }
  1017. if config.Accounts.NickReservation.ForceNickEqualsAccount && !config.Accounts.Multiclient.Enabled {
  1018. return nil, errors.New("force-nick-equals-account requires enabling multiclient as well")
  1019. }
  1020. // handle guest format, including the legacy key rename-prefix
  1021. if config.Accounts.NickReservation.GuestFormat == "" {
  1022. renamePrefix := config.Accounts.NickReservation.RenamePrefix
  1023. if renamePrefix == "" {
  1024. renamePrefix = "Guest-"
  1025. }
  1026. config.Accounts.NickReservation.GuestFormat = renamePrefix + "*"
  1027. }
  1028. config.Accounts.NickReservation.guestRegexp, config.Accounts.NickReservation.guestRegexpFolded, err = compileGuestRegexp(config.Accounts.NickReservation.GuestFormat, config.Server.Casemapping)
  1029. if err != nil {
  1030. return nil, err
  1031. }
  1032. var newLogConfigs []logger.LoggingConfig
  1033. for _, logConfig := range config.Logging {
  1034. // methods
  1035. methods := make(map[string]bool)
  1036. for _, method := range strings.Split(logConfig.Method, " ") {
  1037. if len(method) > 0 {
  1038. methods[strings.ToLower(method)] = true
  1039. }
  1040. }
  1041. if methods["file"] && logConfig.Filename == "" {
  1042. return nil, errors.New("Logging configuration specifies 'file' method but 'filename' is empty")
  1043. }
  1044. logConfig.MethodFile = methods["file"]
  1045. logConfig.MethodStdout = methods["stdout"]
  1046. logConfig.MethodStderr = methods["stderr"]
  1047. // levels
  1048. level, exists := logger.LogLevelNames[strings.ToLower(logConfig.LevelString)]
  1049. if !exists {
  1050. return nil, fmt.Errorf("Could not translate log leve [%s]", logConfig.LevelString)
  1051. }
  1052. logConfig.Level = level
  1053. // types
  1054. for _, typeStr := range strings.Split(logConfig.TypeString, " ") {
  1055. if len(typeStr) == 0 {
  1056. continue
  1057. }
  1058. if typeStr == "-" {
  1059. return nil, errors.New("Encountered logging type '-' with no type to exclude")
  1060. }
  1061. if typeStr[0] == '-' {
  1062. typeStr = typeStr[1:]
  1063. logConfig.ExcludedTypes = append(logConfig.ExcludedTypes, typeStr)
  1064. } else {
  1065. logConfig.Types = append(logConfig.Types, typeStr)
  1066. }
  1067. }
  1068. if len(logConfig.Types) < 1 {
  1069. return nil, errors.New("Logger has no types to log")
  1070. }
  1071. newLogConfigs = append(newLogConfigs, logConfig)
  1072. }
  1073. config.Logging = newLogConfigs
  1074. if config.Accounts.Registration.EmailVerification.Enabled {
  1075. err := config.Accounts.Registration.EmailVerification.Postprocess(config.Server.Name)
  1076. if err != nil {
  1077. return nil, err
  1078. }
  1079. } else {
  1080. // TODO: this processes the legacy "callback" config, clean this up in 2.5 or later
  1081. // TODO: also clean up the legacy "inline" MTA config format (from ee05a4324dfde)
  1082. mailtoEnabled := false
  1083. for _, name := range config.Accounts.Registration.LegacyEnabledCallbacks {
  1084. if name == "mailto" {
  1085. mailtoEnabled = true
  1086. break
  1087. }
  1088. }
  1089. if mailtoEnabled {
  1090. config.Accounts.Registration.EmailVerification = config.Accounts.Registration.LegacyCallbacks.Mailto
  1091. config.Accounts.Registration.EmailVerification.Enabled = true
  1092. err := config.Accounts.Registration.EmailVerification.Postprocess(config.Server.Name)
  1093. if err != nil {
  1094. return nil, err
  1095. }
  1096. }
  1097. }
  1098. config.Accounts.defaultUserModes = ParseDefaultUserModes(config.Accounts.DefaultUserModes)
  1099. config.Accounts.RequireSasl.exemptedNets, err = utils.ParseNetList(config.Accounts.RequireSasl.Exempted)
  1100. if err != nil {
  1101. return nil, fmt.Errorf("Could not parse require-sasl exempted nets: %v", err.Error())
  1102. }
  1103. config.Server.proxyAllowedFromNets, err = utils.ParseNetList(config.Server.ProxyAllowedFrom)
  1104. if err != nil {
  1105. return nil, fmt.Errorf("Could not parse proxy-allowed-from nets: %v", err.Error())
  1106. }
  1107. config.Server.secureNets, err = utils.ParseNetList(config.Server.SecureNetDefs)
  1108. if err != nil {
  1109. return nil, fmt.Errorf("Could not parse secure-nets: %v\n", err.Error())
  1110. }
  1111. rawRegexp := config.Accounts.VHosts.ValidRegexpRaw
  1112. if rawRegexp != "" {
  1113. regexp, err := regexp.Compile(rawRegexp)
  1114. if err == nil {
  1115. config.Accounts.VHosts.validRegexp = regexp
  1116. } else {
  1117. log.Printf("invalid vhost regexp: %s\n", err.Error())
  1118. }
  1119. }
  1120. if config.Accounts.VHosts.validRegexp == nil {
  1121. config.Accounts.VHosts.validRegexp = defaultValidVhostRegex
  1122. }
  1123. config.Server.capValues[caps.SASL] = "PLAIN,EXTERNAL"
  1124. if !config.Accounts.AuthenticationEnabled {
  1125. config.Server.supportedCaps.Disable(caps.SASL)
  1126. }
  1127. if !config.Accounts.Registration.Enabled {
  1128. config.Server.supportedCaps.Disable(caps.Register)
  1129. } else {
  1130. var registerValues []string
  1131. if config.Accounts.Registration.AllowBeforeConnect {
  1132. registerValues = append(registerValues, "before-connect")
  1133. }
  1134. if config.Accounts.Registration.EmailVerification.Enabled {
  1135. registerValues = append(registerValues, "email-required")
  1136. }
  1137. if config.Accounts.RequireSasl.Enabled {
  1138. registerValues = append(registerValues, "account-required")
  1139. }
  1140. if len(registerValues) != 0 {
  1141. config.Server.capValues[caps.Register] = strings.Join(registerValues, ",")
  1142. }
  1143. }
  1144. maxSendQBytes, err := bytefmt.ToBytes(config.Server.MaxSendQString)
  1145. if err != nil {
  1146. return nil, fmt.Errorf("Could not parse maximum SendQ size (make sure it only contains whole numbers): %s", err.Error())
  1147. }
  1148. config.Server.MaxSendQBytes = int(maxSendQBytes)
  1149. config.languageManager, err = languages.NewManager(config.Languages.Enabled, config.Languages.Path, config.Languages.Default)
  1150. if err != nil {
  1151. return nil, fmt.Errorf("Could not load languages: %s", err.Error())
  1152. }
  1153. config.Server.capValues[caps.Languages] = config.languageManager.CapValue()
  1154. if config.Server.Relaymsg.Enabled {
  1155. for _, char := range protocolBreakingNameCharacters {
  1156. if strings.ContainsRune(config.Server.Relaymsg.Separators, char) {
  1157. return nil, fmt.Errorf("RELAYMSG separators cannot include the characters %s", protocolBreakingNameCharacters)
  1158. }
  1159. }
  1160. config.Server.capValues[caps.Relaymsg] = config.Server.Relaymsg.Separators
  1161. } else {
  1162. config.Server.supportedCaps.Disable(caps.Relaymsg)
  1163. }
  1164. config.Debug.recoverFromErrors = utils.BoolDefaultTrue(config.Debug.RecoverFromErrors)
  1165. // process operator definitions, store them to config.operators
  1166. operclasses, err := config.OperatorClasses()
  1167. if err != nil {
  1168. return nil, err
  1169. }
  1170. opers, err := config.Operators(operclasses)
  1171. if err != nil {
  1172. return nil, err
  1173. }
  1174. config.operators = opers
  1175. // parse default channel modes
  1176. config.Channels.defaultModes = ParseDefaultChannelModes(config.Channels.DefaultModes)
  1177. if config.Server.Password != "" {
  1178. config.Server.passwordBytes, err = decodeLegacyPasswordHash(config.Server.Password)
  1179. if err != nil {
  1180. return nil, err
  1181. }
  1182. if config.Accounts.LoginViaPassCommand && !config.Accounts.SkipServerPassword {
  1183. return nil, errors.New("Using a server password and login-via-pass-command requires skip-server-password as well")
  1184. }
  1185. }
  1186. if config.Accounts.Registration.BcryptCost == 0 {
  1187. config.Accounts.Registration.BcryptCost = passwd.DefaultCost
  1188. }
  1189. if config.Channels.MaxChannelsPerClient == 0 {
  1190. config.Channels.MaxChannelsPerClient = 100
  1191. }
  1192. if config.Channels.Registration.MaxChannelsPerAccount == 0 {
  1193. config.Channels.Registration.MaxChannelsPerAccount = 15
  1194. }
  1195. config.Server.Compatibility.forceTrailing = utils.BoolDefaultTrue(config.Server.Compatibility.ForceTrailing)
  1196. config.loadMOTD()
  1197. // in the current implementation, we disable history by creating a history buffer
  1198. // with zero capacity. but the `enabled` config option MUST be respected regardless
  1199. // of this detail
  1200. if !config.History.Enabled {
  1201. config.History.ChannelLength = 0
  1202. config.History.ClientLength = 0
  1203. }
  1204. if !config.History.Enabled || !config.History.Persistent.Enabled {
  1205. config.History.Persistent.Enabled = false
  1206. config.History.Persistent.UnregisteredChannels = false
  1207. config.History.Persistent.RegisteredChannels = PersistentDisabled
  1208. config.History.Persistent.DirectMessages = PersistentDisabled
  1209. }
  1210. if config.History.Persistent.Enabled && !config.Datastore.MySQL.Enabled {
  1211. return nil, fmt.Errorf("You must configure a MySQL server in order to enable persistent history")
  1212. }
  1213. if config.History.ZNCMax == 0 {
  1214. config.History.ZNCMax = config.History.ChathistoryMax
  1215. }
  1216. config.Roleplay.addSuffix = utils.BoolDefaultTrue(config.Roleplay.AddSuffix)
  1217. config.Datastore.MySQL.ExpireTime = time.Duration(config.History.Restrictions.ExpireTime)
  1218. config.Datastore.MySQL.TrackAccountMessages = config.History.Retention.EnableAccountIndexing
  1219. config.Server.Cloaks.Initialize()
  1220. if config.Server.Cloaks.Enabled {
  1221. if !utils.IsHostname(config.Server.Cloaks.Netname) {
  1222. return nil, fmt.Errorf("Invalid netname for cloaked hostnames: %s", config.Server.Cloaks.Netname)
  1223. }
  1224. }
  1225. err = config.processExtjwt()
  1226. if err != nil {
  1227. return nil, err
  1228. }
  1229. // now that all postprocessing is complete, regenerate ISUPPORT:
  1230. err = config.generateISupport()
  1231. if err != nil {
  1232. return nil, err
  1233. }
  1234. err = config.prepareListeners()
  1235. if err != nil {
  1236. return nil, fmt.Errorf("failed to prepare listeners: %v", err)
  1237. }
  1238. // #1428: Tor listeners should never see STS
  1239. config.Server.supportedCapsWithoutSTS = caps.NewSet()
  1240. config.Server.supportedCapsWithoutSTS.Union(config.Server.supportedCaps)
  1241. config.Server.supportedCapsWithoutSTS.Disable(caps.STS)
  1242. return config, nil
  1243. }
  1244. func (config *Config) getOutputPath(filename string) string {
  1245. return filepath.Join(config.Server.OutputPath, filename)
  1246. }
  1247. func (config *Config) isRelaymsgIdentifier(nick string) bool {
  1248. if !config.Server.Relaymsg.Enabled {
  1249. return false
  1250. }
  1251. for _, char := range config.Server.Relaymsg.Separators {
  1252. if strings.ContainsRune(nick, char) {
  1253. return true
  1254. }
  1255. }
  1256. return false
  1257. }
  1258. // setISupport sets up our RPL_ISUPPORT reply.
  1259. func (config *Config) generateISupport() (err error) {
  1260. maxTargetsString := strconv.Itoa(maxTargets)
  1261. // add RPL_ISUPPORT tokens
  1262. isupport := &config.Server.isupport
  1263. isupport.Initialize()
  1264. isupport.Add("AWAYLEN", strconv.Itoa(config.Limits.AwayLen))
  1265. isupport.Add("BOT", "B")
  1266. isupport.Add("CASEMAPPING", "ascii")
  1267. isupport.Add("CHANLIMIT", fmt.Sprintf("%s:%d", chanTypes, config.Channels.MaxChannelsPerClient))
  1268. isupport.Add("CHANMODES", chanmodesToken)
  1269. if config.History.Enabled && config.History.ChathistoryMax > 0 {
  1270. isupport.Add("draft/CHATHISTORY", strconv.Itoa(config.History.ChathistoryMax))
  1271. }
  1272. isupport.Add("CHANNELLEN", strconv.Itoa(config.Limits.ChannelLen))
  1273. isupport.Add("CHANTYPES", chanTypes)
  1274. isupport.Add("ELIST", "U")
  1275. isupport.Add("EXCEPTS", "")
  1276. if config.Extjwt.Default.Enabled() || len(config.Extjwt.Services) != 0 {
  1277. isupport.Add("EXTJWT", "1")
  1278. }
  1279. isupport.Add("EXTBAN", ",m")
  1280. isupport.Add("INVEX", "")
  1281. isupport.Add("KICKLEN", strconv.Itoa(config.Limits.KickLen))
  1282. isupport.Add("MAXLIST", fmt.Sprintf("beI:%s", strconv.Itoa(config.Limits.ChanListModes)))
  1283. isupport.Add("MAXTARGETS", maxTargetsString)
  1284. isupport.Add("MODES", "")
  1285. isupport.Add("MONITOR", strconv.Itoa(config.Limits.MonitorEntries))
  1286. isupport.Add("NETWORK", config.Network.Name)
  1287. isupport.Add("NICKLEN", strconv.Itoa(config.Limits.NickLen))
  1288. isupport.Add("PREFIX", "(qaohv)~&@%+")
  1289. if config.Roleplay.Enabled {
  1290. isupport.Add("RPCHAN", "E")
  1291. isupport.Add("RPUSER", "E")
  1292. }
  1293. isupport.Add("STATUSMSG", "~&@%+")
  1294. 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))
  1295. isupport.Add("TOPICLEN", strconv.Itoa(config.Limits.TopicLen))
  1296. if config.Server.Casemapping == CasemappingPRECIS {
  1297. isupport.Add("UTF8MAPPING", precisUTF8MappingToken)
  1298. }
  1299. isupport.Add("WHOX", "")
  1300. err = isupport.RegenerateCachedReply()
  1301. return
  1302. }
  1303. // Diff returns changes in supported caps across a rehash.
  1304. func (config *Config) Diff(oldConfig *Config) (addedCaps, removedCaps *caps.Set) {
  1305. addedCaps = caps.NewSet()
  1306. removedCaps = caps.NewSet()
  1307. if oldConfig == nil {
  1308. return
  1309. }
  1310. if oldConfig.Server.capValues[caps.Languages] != config.Server.capValues[caps.Languages] {
  1311. // XXX updated caps get a DEL line and then a NEW line with the new value
  1312. addedCaps.Add(caps.Languages)
  1313. removedCaps.Add(caps.Languages)
  1314. }
  1315. if !oldConfig.Accounts.AuthenticationEnabled && config.Accounts.AuthenticationEnabled {
  1316. addedCaps.Add(caps.SASL)
  1317. } else if oldConfig.Accounts.AuthenticationEnabled && !config.Accounts.AuthenticationEnabled {
  1318. removedCaps.Add(caps.SASL)
  1319. }
  1320. if oldConfig.Limits.Multiline.MaxBytes != 0 && config.Limits.Multiline.MaxBytes == 0 {
  1321. removedCaps.Add(caps.Multiline)
  1322. } else if oldConfig.Limits.Multiline.MaxBytes == 0 && config.Limits.Multiline.MaxBytes != 0 {
  1323. addedCaps.Add(caps.Multiline)
  1324. } else if oldConfig.Limits.Multiline != config.Limits.Multiline {
  1325. removedCaps.Add(caps.Multiline)
  1326. addedCaps.Add(caps.Multiline)
  1327. }
  1328. if oldConfig.Server.STS.Enabled != config.Server.STS.Enabled || oldConfig.Server.capValues[caps.STS] != config.Server.capValues[caps.STS] {
  1329. // XXX: STS is always removed by CAP NEW sts=duration=0, not CAP DEL
  1330. // so the appropriate notify is always a CAP NEW; put it in addedCaps for any change
  1331. addedCaps.Add(caps.STS)
  1332. }
  1333. return
  1334. }
  1335. // determine whether we need to resize / create / destroy
  1336. // the in-memory history buffers:
  1337. func (config *Config) historyChangedFrom(oldConfig *Config) bool {
  1338. return config.History.Enabled != oldConfig.History.Enabled ||
  1339. config.History.ChannelLength != oldConfig.History.ChannelLength ||
  1340. config.History.ClientLength != oldConfig.History.ClientLength ||
  1341. config.History.AutoresizeWindow != oldConfig.History.AutoresizeWindow ||
  1342. config.History.Persistent != oldConfig.History.Persistent
  1343. }
  1344. func compileGuestRegexp(guestFormat string, casemapping Casemapping) (standard, folded *regexp.Regexp, err error) {
  1345. if strings.Count(guestFormat, "?") != 0 || strings.Count(guestFormat, "*") != 1 {
  1346. err = errors.New("guest format must contain 1 '*' and no '?'s")
  1347. return
  1348. }
  1349. standard, err = utils.CompileGlob(guestFormat, true)
  1350. if err != nil {
  1351. return
  1352. }
  1353. starIndex := strings.IndexByte(guestFormat, '*')
  1354. initial := guestFormat[:starIndex]
  1355. final := guestFormat[starIndex+1:]
  1356. initialFolded, err := casefoldWithSetting(initial, casemapping)
  1357. if err != nil {
  1358. return
  1359. }
  1360. finalFolded, err := casefoldWithSetting(final, casemapping)
  1361. if err != nil {
  1362. return
  1363. }
  1364. folded, err = utils.CompileGlob(fmt.Sprintf("%s*%s", initialFolded, finalFolded), false)
  1365. return
  1366. }
  1367. func (config *Config) loadMOTD() error {
  1368. if config.Server.MOTD != "" {
  1369. file, err := os.Open(config.Server.MOTD)
  1370. if err != nil {
  1371. return err
  1372. }
  1373. defer file.Close()
  1374. contents, err := ioutil.ReadAll(file)
  1375. if err != nil {
  1376. return err
  1377. }
  1378. lines := bytes.Split(contents, []byte{'\n'})
  1379. for i, line := range lines {
  1380. lineToSend := string(bytes.TrimRight(line, "\r\n"))
  1381. if len(lineToSend) == 0 && i == len(lines)-1 {
  1382. // if the last line of the MOTD was properly terminated with \n,
  1383. // there's no need to send a blank line to clients
  1384. continue
  1385. }
  1386. if config.Server.MOTDFormatting {
  1387. lineToSend = ircfmt.Unescape(lineToSend)
  1388. }
  1389. // "- " is the required prefix for MOTD
  1390. lineToSend = fmt.Sprintf("- %s", lineToSend)
  1391. config.Server.motdLines = append(config.Server.motdLines, lineToSend)
  1392. }
  1393. }
  1394. return nil
  1395. }