You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

nickserv.go 50KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434
  1. // Copyright (c) 2017 Daniel Oaks <daniel@danieloaks.net>
  2. // released under the MIT license
  3. package irc
  4. import (
  5. "fmt"
  6. "regexp"
  7. "sort"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "github.com/goshuirc/irc-go/ircfmt"
  12. "github.com/ergochat/ergo/irc/custime"
  13. "github.com/ergochat/ergo/irc/passwd"
  14. "github.com/ergochat/ergo/irc/sno"
  15. "github.com/ergochat/ergo/irc/utils"
  16. )
  17. // "enabled" callbacks for specific nickserv commands
  18. func servCmdRequiresAccreg(config *Config) bool {
  19. return config.Accounts.Registration.Enabled
  20. }
  21. func servCmdRequiresAuthEnabled(config *Config) bool {
  22. return config.Accounts.AuthenticationEnabled
  23. }
  24. func servCmdRequiresNickRes(config *Config) bool {
  25. return config.Accounts.AuthenticationEnabled && config.Accounts.NickReservation.Enabled
  26. }
  27. func servCmdRequiresBouncerEnabled(config *Config) bool {
  28. return config.Accounts.Multiclient.Enabled
  29. }
  30. const nickservHelp = `NickServ lets you register, log in to, and manage an account.`
  31. var (
  32. nickservCommands = map[string]*serviceCommand{
  33. "clients": {
  34. handler: nsClientsHandler,
  35. help: `Syntax: $bCLIENTS LIST [nickname]$b
  36. CLIENTS LIST shows information about the clients currently attached, via
  37. the server's multiclient functionality, to your nickname. An administrator
  38. can use this command to list another user's clients.
  39. Syntax: $bCLIENTS LOGOUT [nickname] [client_id/all]$b
  40. CLIENTS LOGOUT detaches a single client, or all other clients currently
  41. attached, via the server's multiclient functionality, to your nickname. An
  42. administrator can use this command to logout another user's clients.`,
  43. helpShort: `$bCLIENTS$b can list and logout the sessions attached to a nickname.`,
  44. enabled: servCmdRequiresBouncerEnabled,
  45. minParams: 1,
  46. },
  47. "drop": {
  48. handler: nsDropHandler,
  49. help: `Syntax: $bDROP [nickname]$b
  50. DROP de-links the given (or your current) nickname from your user account.`,
  51. helpShort: `$bDROP$b de-links your current (or the given) nickname from your user account.`,
  52. enabled: servCmdRequiresNickRes,
  53. authRequired: true,
  54. },
  55. "enforce": {
  56. hidden: true,
  57. handler: nsEnforceHandler,
  58. help: `Syntax: $bENFORCE [method]$b
  59. ENFORCE is an alias for $bGET enforce$b and $bSET enforce$b. See the help
  60. entry for $bSET$b for more information.`,
  61. authRequired: true,
  62. enabled: servCmdRequiresNickRes,
  63. },
  64. "ghost": {
  65. handler: nsGhostHandler,
  66. help: `Syntax: $bGHOST <nickname>$b
  67. GHOST disconnects the given user from the network if they're logged in with the
  68. same user account, letting you reclaim your nickname.`,
  69. helpShort: `$bGHOST$b reclaims your nickname.`,
  70. enabled: servCmdRequiresNickRes,
  71. authRequired: true,
  72. minParams: 1,
  73. },
  74. "group": {
  75. handler: nsGroupHandler,
  76. help: `Syntax: $bGROUP$b
  77. GROUP links your current nickname with your logged-in account, so other people
  78. will not be able to use it.`,
  79. helpShort: `$bGROUP$b links your current nickname to your user account.`,
  80. enabled: servCmdRequiresNickRes,
  81. authRequired: true,
  82. },
  83. "identify": {
  84. handler: nsIdentifyHandler,
  85. help: `Syntax: $bIDENTIFY <username> [password]$b
  86. IDENTIFY lets you login to the given username using either password auth, or
  87. certfp (your client certificate) if a password is not given.`,
  88. helpShort: `$bIDENTIFY$b lets you login to your account.`,
  89. enabled: servCmdRequiresAuthEnabled,
  90. minParams: 1,
  91. },
  92. "list": {
  93. handler: nsListHandler,
  94. help: `Syntax: $bLIST [regex]$b
  95. LIST returns the list of registered nicknames, which match the given regex.
  96. If no regex is provided, all registered nicknames are returned.`,
  97. helpShort: `$bLIST$b searches the list of registered nicknames.`,
  98. enabled: servCmdRequiresAuthEnabled,
  99. capabs: []string{"accreg"},
  100. minParams: 0,
  101. },
  102. "info": {
  103. handler: nsInfoHandler,
  104. help: `Syntax: $bINFO [username]$b
  105. INFO gives you information about the given (or your own) user account.`,
  106. helpShort: `$bINFO$b gives you information on a user account.`,
  107. },
  108. "register": {
  109. handler: nsRegisterHandler,
  110. // TODO: "email" is an oversimplification here; it's actually any callback, e.g.,
  111. // person@example.com, mailto:person@example.com, tel:16505551234.
  112. help: `Syntax: $bREGISTER <password> [email]$b
  113. REGISTER lets you register your current nickname as a user account. If the
  114. server allows anonymous registration, you can omit the e-mail address.
  115. If you are currently logged in with a TLS client certificate and wish to use
  116. it instead of a password to log in, send * as the password.`,
  117. helpShort: `$bREGISTER$b lets you register a user account.`,
  118. enabled: servCmdRequiresAccreg,
  119. minParams: 1,
  120. maxParams: 2,
  121. },
  122. "sadrop": {
  123. handler: nsDropHandler,
  124. help: `Syntax: $bSADROP <nickname>$b
  125. SADROP forcibly de-links the given nickname from the attached user account.`,
  126. helpShort: `$bSADROP$b forcibly de-links the given nickname from its user account.`,
  127. capabs: []string{"accreg"},
  128. enabled: servCmdRequiresNickRes,
  129. minParams: 1,
  130. },
  131. "saregister": {
  132. handler: nsSaregisterHandler,
  133. help: `Syntax: $bSAREGISTER <username> [password]$b
  134. SAREGISTER registers an account on someone else's behalf.
  135. This is for use in configurations that require SASL for all connections;
  136. an administrator can set use this command to set up user accounts.`,
  137. helpShort: `$bSAREGISTER$b registers an account on someone else's behalf.`,
  138. enabled: servCmdRequiresAuthEnabled,
  139. capabs: []string{"accreg"},
  140. minParams: 1,
  141. },
  142. "sessions": {
  143. hidden: true,
  144. handler: nsClientsHandler,
  145. help: `Syntax: $bSESSIONS [nickname]$b
  146. SESSIONS is an alias for $bCLIENTS LIST$b. See the help entry for $bCLIENTS$b
  147. for more information.`,
  148. enabled: servCmdRequiresBouncerEnabled,
  149. },
  150. "unregister": {
  151. handler: nsUnregisterHandler,
  152. help: `Syntax: $bUNREGISTER <username> [code]$b
  153. UNREGISTER lets you delete your user account (or someone else's, if you're an
  154. IRC operator with the correct permissions). To prevent accidental
  155. unregistrations, a verification code is required; invoking the command without
  156. a code will display the necessary code.`,
  157. helpShort: `$bUNREGISTER$b lets you delete your user account.`,
  158. enabled: servCmdRequiresAuthEnabled,
  159. minParams: 1,
  160. },
  161. "erase": {
  162. handler: nsUnregisterHandler,
  163. help: `Syntax: $bERASE <username> [code]$b
  164. ERASE deletes all records of an account, allowing it to be re-registered.
  165. This should be used with caution, because it violates an expectation that
  166. account names are permanent identifiers. Typically, UNREGISTER should be
  167. used instead. A confirmation code is required; invoking the command
  168. without a code will display the necessary code.`,
  169. helpShort: `$bERASE$b erases all records of an account, allowing reuse.`,
  170. enabled: servCmdRequiresAuthEnabled,
  171. capabs: []string{"accreg"},
  172. minParams: 1,
  173. },
  174. "verify": {
  175. handler: nsVerifyHandler,
  176. help: `Syntax: $bVERIFY <username> <code>$b
  177. VERIFY lets you complete an account registration, if the server requires email
  178. or other verification.`,
  179. helpShort: `$bVERIFY$b lets you complete account registration.`,
  180. enabled: servCmdRequiresAccreg,
  181. minParams: 2,
  182. },
  183. "passwd": {
  184. handler: nsPasswdHandler,
  185. help: `Syntax: $bPASSWD <current> <new> <new_again>$b
  186. Or: $bPASSWD <username> <new>$b
  187. PASSWD lets you change your account password. You must supply your current
  188. password and confirm the new one by typing it twice. If you're an IRC operator
  189. with the correct permissions, you can use PASSWD to reset someone else's
  190. password by supplying their username and then the desired password. To
  191. indicate an empty password, use * instead.`,
  192. helpShort: `$bPASSWD$b lets you change your password.`,
  193. enabled: servCmdRequiresAuthEnabled,
  194. minParams: 2,
  195. },
  196. "password": {
  197. aliasOf: "passwd",
  198. },
  199. "get": {
  200. handler: nsGetHandler,
  201. help: `Syntax: $bGET <setting>$b
  202. GET queries the current values of your account settings. For more information
  203. on the settings and their possible values, see HELP SET.`,
  204. helpShort: `$bGET$b queries the current values of your account settings`,
  205. authRequired: true,
  206. enabled: servCmdRequiresAuthEnabled,
  207. minParams: 1,
  208. },
  209. "saget": {
  210. handler: nsGetHandler,
  211. help: `Syntax: $bSAGET <account> <setting>$b
  212. SAGET queries the values of someone else's account settings. For more
  213. information on the settings and their possible values, see HELP SET.`,
  214. helpShort: `$bSAGET$b queries the current values of another user's account settings`,
  215. enabled: servCmdRequiresAuthEnabled,
  216. minParams: 2,
  217. capabs: []string{"accreg"},
  218. },
  219. "set": {
  220. handler: nsSetHandler,
  221. helpShort: `$bSET$b modifies your account settings`,
  222. // these are broken out as separate strings so they can be translated separately
  223. helpStrings: []string{
  224. `Syntax $bSET <setting> <value>$b
  225. SET modifies your account settings. The following settings are available:`,
  226. `$bENFORCE$b
  227. 'enforce' lets you specify a custom enforcement mechanism for your registered
  228. nicknames. Your options are:
  229. 1. 'none' [no enforcement, overriding the server default]
  230. 2. 'strict' [you must already be authenticated to use the nick]
  231. 3. 'default' [use the server default]`,
  232. `$bMULTICLIENT$b
  233. If 'multiclient' is enabled and you are already logged in and using a nick, a
  234. second client of yours that authenticates with SASL and requests the same nick
  235. is allowed to attach to the nick as well (this is comparable to the behavior
  236. of IRC "bouncers" like ZNC). Your options are 'on' (allow this behavior),
  237. 'off' (disallow it), and 'default' (use the server default value).`,
  238. `$bAUTOREPLAY-LINES$b
  239. 'autoreplay-lines' controls the number of lines of channel history that will
  240. be replayed to you automatically when joining a channel. Your options are any
  241. positive number, 0 to disable the feature, and 'default' to use the server
  242. default.`,
  243. `$bREPLAY-JOINS$b
  244. 'replay-joins' controls whether replayed channel history will include
  245. lines for join and part. This provides more information about the context of
  246. messages, but may be spammy. Your options are 'always', 'never', and the default
  247. of 'commands-only' (the messages will be replayed in /HISTORY output, but not
  248. during autoreplay).`,
  249. `$bALWAYS-ON$b
  250. 'always-on' controls whether your nickname/identity will remain active
  251. even while you are disconnected from the server. Your options are 'true',
  252. 'false', and 'default' (use the server default value).`,
  253. `$bAUTOREPLAY-MISSED$b
  254. 'autoreplay-missed' is only effective for always-on clients. If enabled,
  255. if you have at most one active session, the server will remember the time
  256. you disconnect and then replay missed messages to you when you reconnect.
  257. Your options are 'on' and 'off'.`,
  258. `$bDM-HISTORY$b
  259. 'dm-history' is only effective for always-on clients. It lets you control
  260. how the history of your direct messages is stored. Your options are:
  261. 1. 'off' [no history]
  262. 2. 'ephemeral' [a limited amount of temporary history, not stored on disk]
  263. 3. 'on' [history stored in a permanent database, if available]
  264. 4. 'default' [use the server default]`,
  265. `$bAUTO-AWAY$b
  266. 'auto-away' is only effective for always-on clients. If enabled, you will
  267. automatically be marked away when all your sessions are disconnected, and
  268. automatically return from away when you connect again.`,
  269. },
  270. authRequired: true,
  271. enabled: servCmdRequiresAuthEnabled,
  272. minParams: 2,
  273. },
  274. "saset": {
  275. handler: nsSetHandler,
  276. help: `Syntax: $bSASET <account> <setting> <value>$b
  277. SASET modifies the values of someone else's account settings. For more
  278. information on the settings and their possible values, see HELP SET.`,
  279. helpShort: `$bSASET$b modifies another user's account settings`,
  280. enabled: servCmdRequiresAuthEnabled,
  281. minParams: 3,
  282. capabs: []string{"accreg"},
  283. },
  284. "cert": {
  285. handler: nsCertHandler,
  286. help: `Syntax: $bCERT <LIST | ADD | DEL> [account] [certfp]$b
  287. CERT examines or modifies the TLS certificate fingerprints that can be used to
  288. log into an account. Specifically, $bCERT LIST$b lists the authorized
  289. fingerprints, $bCERT ADD <fingerprint>$b adds a new fingerprint, and
  290. $bCERT DEL <fingerprint>$b removes a fingerprint. If you're an IRC operator
  291. with the correct permissions, you can act on another user's account, for
  292. example with $bCERT ADD <account> <fingerprint>$b.`,
  293. helpShort: `$bCERT$b controls a user account's certificate fingerprints`,
  294. enabled: servCmdRequiresAuthEnabled,
  295. minParams: 1,
  296. },
  297. "suspend": {
  298. handler: nsSuspendHandler,
  299. help: `Syntax: $bSUSPEND ADD <nickname> [DURATION duration] [reason]$b
  300. $bSUSPEND DEL <nickname>$b
  301. $bSUSPEND LIST$b
  302. Suspending an account disables it (preventing new logins) and disconnects
  303. all associated clients. You can specify a time limit or a reason for
  304. the suspension. The $bDEL$b subcommand reverses a suspension, and the $bLIST$b
  305. command lists all current suspensions.`,
  306. helpShort: `$bSUSPEND$b manages account suspensions`,
  307. minParams: 1,
  308. capabs: []string{"accreg"},
  309. },
  310. "rename": {
  311. handler: nsRenameHandler,
  312. help: `Syntax: $bRENAME <account> <newname>$b
  313. RENAME allows a server administrator to change the name of an account.
  314. Currently, you can only change the canonical casefolding of an account
  315. (e.g., you can change "Alice" to "alice", but not "Alice" to "Amanda").`,
  316. helpShort: `$bRENAME$b renames an account`,
  317. minParams: 2,
  318. capabs: []string{"accreg"},
  319. },
  320. }
  321. )
  322. func nsGetHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  323. var account string
  324. if command == "saget" {
  325. account = params[0]
  326. params = params[1:]
  327. } else {
  328. account = client.Account()
  329. }
  330. accountData, err := server.accounts.LoadAccount(account)
  331. if err == errAccountDoesNotExist {
  332. service.Notice(rb, client.t("No such account"))
  333. return
  334. } else if err != nil {
  335. service.Notice(rb, client.t("Error loading account data"))
  336. return
  337. }
  338. displaySetting(service, params[0], accountData.Settings, client, rb)
  339. }
  340. func displaySetting(service *ircService, settingName string, settings AccountSettings, client *Client, rb *ResponseBuffer) {
  341. config := client.server.Config()
  342. switch strings.ToLower(settingName) {
  343. case "enforce":
  344. storedValue := settings.NickEnforcement
  345. serializedStoredValue := nickReservationToString(storedValue)
  346. service.Notice(rb, fmt.Sprintf(client.t("Your stored nickname enforcement setting is: %s"), serializedStoredValue))
  347. serializedActualValue := nickReservationToString(configuredEnforcementMethod(config, storedValue))
  348. service.Notice(rb, fmt.Sprintf(client.t("Given current server settings, your nickname is enforced with: %s"), serializedActualValue))
  349. case "autoreplay-lines":
  350. if settings.AutoreplayLines == nil {
  351. service.Notice(rb, fmt.Sprintf(client.t("You will receive the server default of %d lines of autoreplayed history"), config.History.AutoreplayOnJoin))
  352. } else {
  353. service.Notice(rb, fmt.Sprintf(client.t("You will receive %d lines of autoreplayed history"), *settings.AutoreplayLines))
  354. }
  355. case "replay-joins":
  356. switch settings.ReplayJoins {
  357. case ReplayJoinsCommandsOnly:
  358. service.Notice(rb, client.t("You will see JOINs and PARTs in /HISTORY output, but not in autoreplay"))
  359. case ReplayJoinsAlways:
  360. service.Notice(rb, client.t("You will see JOINs and PARTs in /HISTORY output and in autoreplay"))
  361. case ReplayJoinsNever:
  362. service.Notice(rb, client.t("You will not see JOINs and PARTs in /HISTORY output or in autoreplay"))
  363. }
  364. case "multiclient":
  365. if !config.Accounts.Multiclient.Enabled {
  366. service.Notice(rb, client.t("This feature has been disabled by the server administrators"))
  367. } else {
  368. switch settings.AllowBouncer {
  369. case MulticlientAllowedServerDefault:
  370. if config.Accounts.Multiclient.AllowedByDefault {
  371. service.Notice(rb, client.t("Multiclient functionality is currently enabled for your account, but you can opt out"))
  372. } else {
  373. service.Notice(rb, client.t("Multiclient functionality is currently disabled for your account, but you can opt in"))
  374. }
  375. case MulticlientDisallowedByUser:
  376. service.Notice(rb, client.t("Multiclient functionality is currently disabled for your account"))
  377. case MulticlientAllowedByUser:
  378. service.Notice(rb, client.t("Multiclient functionality is currently enabled for your account"))
  379. }
  380. }
  381. case "always-on":
  382. stored := settings.AlwaysOn
  383. actual := persistenceEnabled(config.Accounts.Multiclient.AlwaysOn, stored)
  384. service.Notice(rb, fmt.Sprintf(client.t("Your stored always-on setting is: %s"), userPersistentStatusToString(stored)))
  385. if actual {
  386. service.Notice(rb, client.t("Given current server settings, your client is always-on"))
  387. } else {
  388. service.Notice(rb, client.t("Given current server settings, your client is not always-on"))
  389. }
  390. case "autoreplay-missed":
  391. stored := settings.AutoreplayMissed
  392. if stored {
  393. alwaysOn := persistenceEnabled(config.Accounts.Multiclient.AlwaysOn, settings.AlwaysOn)
  394. if alwaysOn {
  395. service.Notice(rb, client.t("Autoreplay of missed messages is enabled"))
  396. } else {
  397. service.Notice(rb, client.t("You have enabled autoreplay of missed messages, but you can't receive them because your client isn't set to always-on"))
  398. }
  399. } else {
  400. service.Notice(rb, client.t("Your account is not configured to receive autoreplayed missed messages"))
  401. }
  402. case "auto-away":
  403. stored := settings.AutoAway
  404. alwaysOn := persistenceEnabled(config.Accounts.Multiclient.AlwaysOn, settings.AlwaysOn)
  405. actual := persistenceEnabled(config.Accounts.Multiclient.AutoAway, settings.AutoAway)
  406. service.Notice(rb, fmt.Sprintf(client.t("Your stored auto-away setting is: %s"), userPersistentStatusToString(stored)))
  407. if actual && alwaysOn {
  408. service.Notice(rb, client.t("Given current server settings, auto-away is enabled for your client"))
  409. } else if actual && !alwaysOn {
  410. service.Notice(rb, client.t("Because your client is not always-on, auto-away is disabled"))
  411. } else if !actual {
  412. service.Notice(rb, client.t("Given current server settings, auto-away is disabled for your client"))
  413. }
  414. case "dm-history":
  415. effectiveValue := historyEnabled(config.History.Persistent.DirectMessages, settings.DMHistory)
  416. service.Notice(rb, fmt.Sprintf(client.t("Your stored direct message history setting is: %s"), historyStatusToString(settings.DMHistory)))
  417. service.Notice(rb, fmt.Sprintf(client.t("Given current server settings, your direct message history setting is: %s"), historyStatusToString(effectiveValue)))
  418. default:
  419. service.Notice(rb, client.t("No such setting"))
  420. }
  421. }
  422. func userPersistentStatusToString(status PersistentStatus) string {
  423. // #1544: "mandatory" as a user setting should display as "enabled"
  424. result := persistentStatusToString(status)
  425. if result == "mandatory" {
  426. result = "enabled"
  427. }
  428. return result
  429. }
  430. func nsSetHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  431. var account string
  432. if command == "saset" {
  433. account = params[0]
  434. params = params[1:]
  435. } else {
  436. account = client.Account()
  437. }
  438. var munger settingsMunger
  439. var finalSettings AccountSettings
  440. var err error
  441. switch strings.ToLower(params[0]) {
  442. case "pass", "password":
  443. service.Notice(rb, client.t("To change a password, use the PASSWD command. For details, /msg NickServ HELP PASSWD"))
  444. return
  445. case "enforce":
  446. var method NickEnforcementMethod
  447. method, err = nickReservationFromString(params[1])
  448. if err != nil {
  449. err = errInvalidParams
  450. break
  451. }
  452. // updating enforcement settings is special-cased, because it requires
  453. // an update to server.accounts.accountToMethod
  454. finalSettings, err = server.accounts.SetEnforcementStatus(account, method)
  455. if err == nil {
  456. finalSettings.NickEnforcement = method // success
  457. }
  458. case "autoreplay-lines":
  459. var newValue *int
  460. if strings.ToLower(params[1]) != "default" {
  461. val, err_ := strconv.Atoi(params[1])
  462. if err_ != nil || val < 0 {
  463. err = errInvalidParams
  464. break
  465. }
  466. newValue = new(int)
  467. *newValue = val
  468. }
  469. munger = func(in AccountSettings) (out AccountSettings, err error) {
  470. out = in
  471. out.AutoreplayLines = newValue
  472. return
  473. }
  474. case "multiclient":
  475. var newValue MulticlientAllowedSetting
  476. if strings.ToLower(params[1]) == "default" {
  477. newValue = MulticlientAllowedServerDefault
  478. } else {
  479. var enabled bool
  480. enabled, err = utils.StringToBool(params[1])
  481. if enabled {
  482. newValue = MulticlientAllowedByUser
  483. } else {
  484. newValue = MulticlientDisallowedByUser
  485. }
  486. }
  487. if err == nil {
  488. munger = func(in AccountSettings) (out AccountSettings, err error) {
  489. out = in
  490. out.AllowBouncer = newValue
  491. return
  492. }
  493. }
  494. case "replay-joins":
  495. var newValue ReplayJoinsSetting
  496. newValue, err = replayJoinsSettingFromString(params[1])
  497. if err == nil {
  498. munger = func(in AccountSettings) (out AccountSettings, err error) {
  499. out = in
  500. out.ReplayJoins = newValue
  501. return
  502. }
  503. }
  504. case "always-on":
  505. // #821: it's problematic to alter the value of always-on if you're not
  506. // the (actual or potential) always-on client yourself. make an exception
  507. // for `saset` to give operators an escape hatch (any consistency problems
  508. // can probably be fixed by restarting the server):
  509. if command != "saset" {
  510. details := client.Details()
  511. if details.nick != details.accountName {
  512. err = errNickAccountMismatch
  513. }
  514. }
  515. if err == nil {
  516. var newValue PersistentStatus
  517. newValue, err = persistentStatusFromString(params[1])
  518. // "opt-in" and "opt-out" don't make sense as user preferences
  519. if err == nil && newValue != PersistentOptIn && newValue != PersistentOptOut {
  520. munger = func(in AccountSettings) (out AccountSettings, err error) {
  521. out = in
  522. out.AlwaysOn = newValue
  523. return
  524. }
  525. }
  526. }
  527. case "autoreplay-missed":
  528. var newValue bool
  529. newValue, err = utils.StringToBool(params[1])
  530. if err == nil {
  531. munger = func(in AccountSettings) (out AccountSettings, err error) {
  532. out = in
  533. out.AutoreplayMissed = newValue
  534. return
  535. }
  536. }
  537. case "auto-away":
  538. var newValue PersistentStatus
  539. newValue, err = persistentStatusFromString(params[1])
  540. // "opt-in" and "opt-out" don't make sense as user preferences
  541. if err == nil && newValue != PersistentOptIn && newValue != PersistentOptOut {
  542. munger = func(in AccountSettings) (out AccountSettings, err error) {
  543. out = in
  544. out.AutoAway = newValue
  545. return
  546. }
  547. }
  548. case "dm-history":
  549. var newValue HistoryStatus
  550. newValue, err = historyStatusFromString(params[1])
  551. if err == nil {
  552. munger = func(in AccountSettings) (out AccountSettings, err error) {
  553. out = in
  554. out.DMHistory = newValue
  555. return
  556. }
  557. }
  558. default:
  559. err = errInvalidParams
  560. }
  561. if munger != nil {
  562. finalSettings, err = server.accounts.ModifyAccountSettings(account, munger)
  563. }
  564. switch err {
  565. case nil:
  566. service.Notice(rb, client.t("Successfully changed your account settings"))
  567. displaySetting(service, params[0], finalSettings, client, rb)
  568. case errInvalidParams, errAccountDoesNotExist, errFeatureDisabled, errAccountUnverified, errAccountUpdateFailed:
  569. service.Notice(rb, client.t(err.Error()))
  570. case errNickAccountMismatch:
  571. service.Notice(rb, fmt.Sprintf(client.t("Your nickname must match your account name %s exactly to modify this setting. Try changing it with /NICK, or logging out and back in with the correct nickname."), client.AccountName()))
  572. default:
  573. // unknown error
  574. service.Notice(rb, client.t("An error occurred"))
  575. }
  576. }
  577. func nsDropHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  578. sadrop := command == "sadrop"
  579. var nick string
  580. if len(params) > 0 {
  581. nick = params[0]
  582. } else {
  583. nick = client.NickCasefolded()
  584. }
  585. err := server.accounts.SetNickReserved(client, nick, sadrop, false)
  586. if err == nil {
  587. service.Notice(rb, fmt.Sprintf(client.t("Successfully ungrouped nick %s with your account"), nick))
  588. } else if err == errAccountNotLoggedIn {
  589. service.Notice(rb, client.t("You're not logged into an account"))
  590. } else if err == errAccountCantDropPrimaryNick {
  591. service.Notice(rb, client.t("You can't ungroup your primary nickname (try unregistering your account instead)"))
  592. } else {
  593. service.Notice(rb, client.t("Could not ungroup nick"))
  594. }
  595. }
  596. func nsGhostHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  597. nick := params[0]
  598. ghost := server.clients.Get(nick)
  599. if ghost == nil {
  600. service.Notice(rb, client.t("No such nick"))
  601. return
  602. } else if ghost == client {
  603. service.Notice(rb, client.t("You can't GHOST yourself (try /QUIT instead)"))
  604. return
  605. } else if ghost.AlwaysOn() {
  606. service.Notice(rb, client.t("You can't GHOST an always-on client"))
  607. return
  608. }
  609. authorized := false
  610. account := client.Account()
  611. if account != "" {
  612. // the user must either own the nick, or the target client
  613. authorized = (server.accounts.NickToAccount(nick) == account) || (ghost.Account() == account)
  614. }
  615. if !authorized {
  616. service.Notice(rb, client.t("You don't own that nick"))
  617. return
  618. }
  619. ghost.Quit(fmt.Sprintf(ghost.t("GHOSTed by %s"), client.Nick()), nil)
  620. ghost.destroy(nil)
  621. }
  622. func nsGroupHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  623. nick := client.Nick()
  624. err := server.accounts.SetNickReserved(client, nick, false, true)
  625. if err == nil {
  626. service.Notice(rb, fmt.Sprintf(client.t("Successfully grouped nick %s with your account"), nick))
  627. } else if err == errAccountTooManyNicks {
  628. service.Notice(rb, client.t("You have too many nicks reserved already (you can remove some with /NS DROP)"))
  629. } else if err == errNicknameReserved {
  630. service.Notice(rb, client.t("That nickname is already reserved by someone else"))
  631. } else {
  632. service.Notice(rb, client.t("Error reserving nickname"))
  633. }
  634. }
  635. func nsLoginThrottleCheck(service *ircService, client *Client, rb *ResponseBuffer) (success bool) {
  636. throttled, remainingTime := client.checkLoginThrottle()
  637. if throttled {
  638. service.Notice(rb, fmt.Sprintf(client.t("Please wait at least %v and try again"), remainingTime))
  639. }
  640. return !throttled
  641. }
  642. func nsIdentifyHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  643. if client.LoggedIntoAccount() {
  644. service.Notice(rb, client.t("You're already logged into an account"))
  645. return
  646. }
  647. var err error
  648. loginSuccessful := false
  649. var username, passphrase string
  650. if len(params) == 1 {
  651. if rb.session.certfp != "" {
  652. username = params[0]
  653. } else {
  654. // XXX undocumented compatibility mode with other nickservs, allowing
  655. // /msg NickServ identify passphrase
  656. username = client.NickCasefolded()
  657. passphrase = params[0]
  658. }
  659. } else {
  660. username = params[0]
  661. passphrase = params[1]
  662. }
  663. // try passphrase
  664. if passphrase != "" {
  665. err = server.accounts.AuthenticateByPassphrase(client, username, passphrase)
  666. loginSuccessful = (err == nil)
  667. }
  668. // try certfp
  669. if !loginSuccessful && rb.session.certfp != "" {
  670. err = server.accounts.AuthenticateByCertificate(client, rb.session.certfp, rb.session.peerCerts, "")
  671. loginSuccessful = (err == nil)
  672. }
  673. nickFixupFailed := false
  674. if loginSuccessful {
  675. if !fixupNickEqualsAccount(client, rb, server.Config(), service.prefix) {
  676. loginSuccessful = false
  677. // fixupNickEqualsAccount sends its own error message, don't send another
  678. nickFixupFailed = true
  679. }
  680. }
  681. if loginSuccessful {
  682. sendSuccessfulAccountAuth(service, client, rb, true)
  683. } else if !nickFixupFailed {
  684. service.Notice(rb, fmt.Sprintf(client.t("Authentication failed: %s"), authErrorToMessage(server, err)))
  685. }
  686. }
  687. func nsListHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  688. if !client.HasRoleCapabs("accreg") {
  689. service.Notice(rb, client.t("Insufficient privileges"))
  690. return
  691. }
  692. var searchRegex *regexp.Regexp
  693. if len(params) > 0 {
  694. var err error
  695. searchRegex, err = regexp.Compile(params[0])
  696. if err != nil {
  697. service.Notice(rb, client.t("Invalid regex"))
  698. return
  699. }
  700. }
  701. service.Notice(rb, ircfmt.Unescape(client.t("*** $bNickServ LIST$b ***")))
  702. nicks := server.accounts.AllNicks()
  703. for _, nick := range nicks {
  704. if searchRegex == nil || searchRegex.MatchString(nick) {
  705. service.Notice(rb, fmt.Sprintf(" %s", nick))
  706. }
  707. }
  708. service.Notice(rb, ircfmt.Unescape(client.t("*** $bEnd of NickServ LIST$b ***")))
  709. }
  710. func nsInfoHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  711. if !server.Config().Accounts.AuthenticationEnabled && !client.HasRoleCapabs("accreg") {
  712. service.Notice(rb, client.t("This command has been disabled by the server administrators"))
  713. return
  714. }
  715. var accountName string
  716. if len(params) > 0 {
  717. nick := params[0]
  718. if server.Config().Accounts.NickReservation.Enabled {
  719. accountName = server.accounts.NickToAccount(nick)
  720. if accountName == "" {
  721. service.Notice(rb, client.t("That nickname is not registered"))
  722. return
  723. }
  724. } else {
  725. accountName = nick
  726. }
  727. } else {
  728. accountName = client.Account()
  729. if accountName == "" {
  730. service.Notice(rb, client.t("You're not logged into an account"))
  731. return
  732. }
  733. }
  734. account, err := server.accounts.LoadAccount(accountName)
  735. if err != nil || !account.Verified {
  736. service.Notice(rb, client.t("Account does not exist"))
  737. return
  738. }
  739. service.Notice(rb, fmt.Sprintf(client.t("Account: %s"), account.Name))
  740. registeredAt := account.RegisteredAt.Format(time.RFC1123)
  741. service.Notice(rb, fmt.Sprintf(client.t("Registered at: %s"), registeredAt))
  742. // TODO nicer formatting for this
  743. for _, nick := range account.AdditionalNicks {
  744. service.Notice(rb, fmt.Sprintf(client.t("Additional grouped nick: %s"), nick))
  745. }
  746. listRegisteredChannels(service, accountName, rb)
  747. if account.Suspended != nil {
  748. service.Notice(rb, suspensionToString(client, *account.Suspended))
  749. }
  750. }
  751. func listRegisteredChannels(service *ircService, accountName string, rb *ResponseBuffer) {
  752. client := rb.session.client
  753. channels := client.server.accounts.ChannelsForAccount(accountName)
  754. service.Notice(rb, fmt.Sprintf(client.t("Account %s has %d registered channel(s)."), accountName, len(channels)))
  755. for _, channel := range rb.session.client.server.accounts.ChannelsForAccount(accountName) {
  756. service.Notice(rb, fmt.Sprintf(client.t("Registered channel: %s"), channel))
  757. }
  758. }
  759. func nsRegisterHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  760. details := client.Details()
  761. passphrase := params[0]
  762. var email string
  763. if 1 < len(params) {
  764. email = params[1]
  765. }
  766. certfp := rb.session.certfp
  767. if passphrase == "*" {
  768. if certfp == "" {
  769. service.Notice(rb, client.t("You must be connected with TLS and a client certificate to do this"))
  770. return
  771. } else {
  772. passphrase = ""
  773. }
  774. }
  775. if passphrase != "" {
  776. cfPassphrase, err := Casefold(passphrase)
  777. if err == nil && cfPassphrase == details.nickCasefolded {
  778. service.Notice(rb, client.t("Usage: REGISTER <passphrase> [email]")) // #1179
  779. return
  780. }
  781. }
  782. if !nsLoginThrottleCheck(service, client, rb) {
  783. return
  784. }
  785. config := server.Config()
  786. account := details.nick
  787. if config.Accounts.NickReservation.ForceGuestFormat {
  788. matches := config.Accounts.NickReservation.guestRegexp.FindStringSubmatch(account)
  789. if matches == nil || len(matches) < 2 {
  790. service.Notice(rb, client.t("Erroneous nickname"))
  791. return
  792. }
  793. account = matches[1]
  794. }
  795. callbackNamespace, callbackValue, validationErr := parseCallback(email, config)
  796. if validationErr != nil {
  797. service.Notice(rb, client.t("Registration requires a valid e-mail address"))
  798. return
  799. }
  800. err := server.accounts.Register(client, account, callbackNamespace, callbackValue, passphrase, rb.session.certfp)
  801. if err == nil {
  802. if callbackNamespace == "*" {
  803. err = server.accounts.Verify(client, account, "")
  804. if err == nil && fixupNickEqualsAccount(client, rb, config, service.prefix) {
  805. sendSuccessfulRegResponse(service, client, rb)
  806. }
  807. } else {
  808. messageTemplate := client.t("Account created, pending verification; verification code has been sent to %s")
  809. message := fmt.Sprintf(messageTemplate, callbackValue)
  810. service.Notice(rb, message)
  811. }
  812. } else {
  813. // details could not be stored and relevant numerics have been dispatched, abort
  814. message := registrationErrorToMessage(err)
  815. service.Notice(rb, client.t(message))
  816. }
  817. }
  818. func nsSaregisterHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  819. var account, passphrase string
  820. account = params[0]
  821. if 1 < len(params) && params[1] != "*" {
  822. passphrase = params[1]
  823. }
  824. err := server.accounts.SARegister(account, passphrase)
  825. if err != nil {
  826. var errMsg string
  827. if err == errAccountAlreadyRegistered || err == errAccountAlreadyVerified {
  828. errMsg = client.t("Account already exists")
  829. } else if err == errAccountBadPassphrase {
  830. errMsg = client.t("Passphrase contains forbidden characters or is otherwise invalid")
  831. } else {
  832. server.logger.Error("services", "unknown error from saregister", err.Error())
  833. errMsg = client.t("Could not register")
  834. }
  835. service.Notice(rb, errMsg)
  836. } else {
  837. service.Notice(rb, fmt.Sprintf(client.t("Successfully registered account %s"), account))
  838. server.snomasks.Send(sno.LocalAccounts, fmt.Sprintf(ircfmt.Unescape("Operator $c[grey][$r%s$c[grey]] registered account $c[grey][$r%s$c[grey]] with SAREGISTER"), client.Oper().Name, account))
  839. }
  840. }
  841. func nsUnregisterHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  842. erase := command == "erase"
  843. username := params[0]
  844. var verificationCode string
  845. if len(params) > 1 {
  846. verificationCode = params[1]
  847. }
  848. if username == "" {
  849. service.Notice(rb, client.t("You must specify an account"))
  850. return
  851. }
  852. var accountName string
  853. var registeredAt time.Time
  854. if erase {
  855. // account may not be in a loadable state, e.g., if it was unregistered
  856. accountName = username
  857. // make the confirmation code nondeterministic for ERASE
  858. registeredAt = server.ctime
  859. } else {
  860. account, err := server.accounts.LoadAccount(username)
  861. if err == errAccountDoesNotExist {
  862. service.Notice(rb, client.t("Invalid account name"))
  863. return
  864. } else if err != nil {
  865. service.Notice(rb, client.t("Internal error"))
  866. return
  867. }
  868. accountName = account.Name
  869. registeredAt = account.RegisteredAt
  870. }
  871. if !(accountName == client.AccountName() || client.HasRoleCapabs("accreg")) {
  872. service.Notice(rb, client.t("Insufficient oper privs"))
  873. return
  874. }
  875. expectedCode := utils.ConfirmationCode(accountName, registeredAt)
  876. if expectedCode != verificationCode {
  877. if erase {
  878. service.Notice(rb, ircfmt.Unescape(client.t("$bWarning: erasing this account will allow it to be re-registered; consider UNREGISTER instead.$b")))
  879. } else {
  880. service.Notice(rb, ircfmt.Unescape(client.t("$bWarning: unregistering this account will remove its stored privileges.$b")))
  881. service.Notice(rb, ircfmt.Unescape(client.t("$bNote that an unregistered account name remains reserved and cannot be re-registered.$b")))
  882. service.Notice(rb, ircfmt.Unescape(client.t("$bIf you are having problems with your account, contact an administrator.$b")))
  883. }
  884. service.Notice(rb, fmt.Sprintf(client.t("To confirm, run this command: %s"), fmt.Sprintf("/NS %s %s %s", strings.ToUpper(command), accountName, expectedCode)))
  885. return
  886. }
  887. err := server.accounts.Unregister(accountName, erase)
  888. if err == errAccountDoesNotExist {
  889. service.Notice(rb, client.t(err.Error()))
  890. } else if err != nil {
  891. service.Notice(rb, client.t("Error while unregistering account"))
  892. } else {
  893. service.Notice(rb, fmt.Sprintf(client.t("Successfully unregistered account %s"), accountName))
  894. server.logger.Info("accounts", "client", client.Nick(), "unregistered account", accountName)
  895. client.server.snomasks.Send(sno.LocalAccounts, fmt.Sprintf(ircfmt.Unescape("Client $c[grey][$r%s$c[grey]] unregistered account $c[grey][$r%s$c[grey]]"), client.NickMaskString(), accountName))
  896. }
  897. }
  898. func nsVerifyHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  899. username, code := params[0], params[1]
  900. err := server.accounts.Verify(client, username, code)
  901. var errorMessage string
  902. if err != nil {
  903. switch err {
  904. case errAccountAlreadyLoggedIn, errAccountVerificationInvalidCode, errAccountAlreadyVerified:
  905. errorMessage = err.Error()
  906. default:
  907. errorMessage = errAccountVerificationFailed.Error()
  908. }
  909. }
  910. if errorMessage != "" {
  911. service.Notice(rb, client.t(errorMessage))
  912. return
  913. }
  914. if fixupNickEqualsAccount(client, rb, server.Config(), service.prefix) {
  915. sendSuccessfulRegResponse(service, client, rb)
  916. }
  917. }
  918. func nsPasswdHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  919. var target string
  920. var newPassword string
  921. var errorMessage string
  922. var oper *Oper
  923. switch len(params) {
  924. case 2:
  925. oper = client.Oper()
  926. if !oper.HasRoleCapab("accreg") {
  927. errorMessage = `Insufficient privileges`
  928. } else {
  929. target, newPassword = params[0], params[1]
  930. if newPassword == "*" {
  931. newPassword = ""
  932. }
  933. message := fmt.Sprintf("Operator %s ran NS PASSWD for account %s", oper.Name, target)
  934. server.snomasks.Send(sno.LocalOpers, message)
  935. server.logger.Info("opers", message)
  936. }
  937. case 3:
  938. target = client.Account()
  939. if target == "" {
  940. errorMessage = `You're not logged into an account`
  941. } else if params[1] != params[2] {
  942. errorMessage = `Passwords do not match`
  943. } else {
  944. if !nsLoginThrottleCheck(service, client, rb) {
  945. return
  946. }
  947. accountData, err := server.accounts.LoadAccount(target)
  948. if err != nil {
  949. errorMessage = `You're not logged into an account`
  950. } else {
  951. hash := accountData.Credentials.PassphraseHash
  952. if hash != nil && passwd.CompareHashAndPassword(hash, []byte(params[0])) != nil {
  953. errorMessage = `Password incorrect`
  954. } else {
  955. newPassword = params[1]
  956. if newPassword == "*" {
  957. newPassword = ""
  958. }
  959. }
  960. }
  961. }
  962. default:
  963. errorMessage = `Invalid parameters`
  964. }
  965. if errorMessage != "" {
  966. service.Notice(rb, client.t(errorMessage))
  967. return
  968. }
  969. err := server.accounts.setPassword(target, newPassword, oper != nil)
  970. switch err {
  971. case nil:
  972. service.Notice(rb, client.t("Password changed"))
  973. case errEmptyCredentials:
  974. service.Notice(rb, client.t("You can't delete your password unless you add a certificate fingerprint"))
  975. case errCredsExternallyManaged:
  976. service.Notice(rb, client.t("Your account credentials are managed externally and cannot be changed here"))
  977. case errCASFailed:
  978. service.Notice(rb, client.t("Try again later"))
  979. default:
  980. server.logger.Error("internal", "could not upgrade user password:", err.Error())
  981. service.Notice(rb, client.t("Password could not be changed due to server error"))
  982. }
  983. }
  984. func nsEnforceHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  985. newParams := []string{"enforce"}
  986. if len(params) == 0 {
  987. nsGetHandler(service, server, client, "get", newParams, rb)
  988. } else {
  989. newParams = append(newParams, params[0])
  990. nsSetHandler(service, server, client, "set", newParams, rb)
  991. }
  992. }
  993. func nsClientsHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  994. var verb string
  995. if command == "sessions" {
  996. // Legacy "SESSIONS" command is an alias for CLIENTS LIST.
  997. verb = "list"
  998. } else if len(params) > 0 {
  999. verb = strings.ToLower(params[0])
  1000. params = params[1:]
  1001. }
  1002. switch verb {
  1003. case "list":
  1004. nsClientsListHandler(service, server, client, params, rb)
  1005. case "logout":
  1006. nsClientsLogoutHandler(service, server, client, params, rb)
  1007. default:
  1008. service.Notice(rb, client.t("Invalid parameters"))
  1009. }
  1010. }
  1011. func nsClientsListHandler(service *ircService, server *Server, client *Client, params []string, rb *ResponseBuffer) {
  1012. target := client
  1013. hasPrivs := client.HasRoleCapabs("ban")
  1014. if 0 < len(params) {
  1015. target = server.clients.Get(params[0])
  1016. if target == nil {
  1017. service.Notice(rb, client.t("No such nick"))
  1018. return
  1019. }
  1020. if target != client && !hasPrivs {
  1021. service.Notice(rb, client.t("Command restricted"))
  1022. return
  1023. }
  1024. }
  1025. sessionData, currentIndex := target.AllSessionData(rb.session, hasPrivs)
  1026. service.Notice(rb, fmt.Sprintf(client.t("Nickname %[1]s has %[2]d attached clients(s)"), target.Nick(), len(sessionData)))
  1027. for i, session := range sessionData {
  1028. if currentIndex == i {
  1029. service.Notice(rb, fmt.Sprintf(client.t("Client %d (currently attached client):"), session.sessionID))
  1030. } else {
  1031. service.Notice(rb, fmt.Sprintf(client.t("Client %d:"), session.sessionID))
  1032. }
  1033. if session.deviceID != "" {
  1034. service.Notice(rb, fmt.Sprintf(client.t("Device ID: %s"), session.deviceID))
  1035. }
  1036. service.Notice(rb, fmt.Sprintf(client.t("IP address: %s"), session.ip.String()))
  1037. service.Notice(rb, fmt.Sprintf(client.t("Hostname: %s"), session.hostname))
  1038. if hasPrivs {
  1039. service.Notice(rb, fmt.Sprintf(client.t("Connection: %s"), session.connInfo))
  1040. }
  1041. service.Notice(rb, fmt.Sprintf(client.t("Created at: %s"), session.ctime.Format(time.RFC1123)))
  1042. service.Notice(rb, fmt.Sprintf(client.t("Last active: %s"), session.atime.Format(time.RFC1123)))
  1043. if session.certfp != "" {
  1044. service.Notice(rb, fmt.Sprintf(client.t("Certfp: %s"), session.certfp))
  1045. }
  1046. for _, capStr := range session.caps {
  1047. if capStr != "" {
  1048. service.Notice(rb, fmt.Sprintf(client.t("IRCv3 CAPs: %s"), capStr))
  1049. }
  1050. }
  1051. }
  1052. }
  1053. func nsClientsLogoutHandler(service *ircService, server *Server, client *Client, params []string, rb *ResponseBuffer) {
  1054. if len(params) < 1 {
  1055. service.Notice(rb, client.t("Missing client ID to logout (or \"all\")"))
  1056. return
  1057. }
  1058. target := client
  1059. if len(params) >= 2 {
  1060. // CLIENTS LOGOUT [nickname] [client ID]
  1061. target = server.clients.Get(params[0])
  1062. if target == nil {
  1063. service.Notice(rb, client.t("No such nick"))
  1064. return
  1065. }
  1066. // User must have "kill" privileges to logout other user sessions.
  1067. if target != client {
  1068. oper := client.Oper()
  1069. if !oper.HasRoleCapab("kill") {
  1070. service.Notice(rb, client.t("Insufficient oper privs"))
  1071. return
  1072. }
  1073. }
  1074. params = params[1:]
  1075. }
  1076. var sessionToDestroy *Session // target.destroy(nil) will logout all sessions
  1077. if strings.ToLower(params[0]) != "all" {
  1078. sessionID, err := strconv.ParseInt(params[0], 10, 64)
  1079. if err != nil {
  1080. service.Notice(rb, client.t("Client ID to logout should be an integer (or \"all\")"))
  1081. return
  1082. }
  1083. // Find the client ID that the user requested to logout.
  1084. sessions := target.Sessions()
  1085. for _, session := range sessions {
  1086. if session.sessionID == sessionID {
  1087. sessionToDestroy = session
  1088. }
  1089. }
  1090. if sessionToDestroy == nil {
  1091. service.Notice(rb, client.t("Specified client ID does not exist"))
  1092. return
  1093. }
  1094. }
  1095. target.destroy(sessionToDestroy)
  1096. if (sessionToDestroy != nil && rb.session != sessionToDestroy) || client != target {
  1097. if sessionToDestroy != nil {
  1098. service.Notice(rb, client.t("Successfully logged out session"))
  1099. } else {
  1100. service.Notice(rb, client.t("Successfully logged out all sessions"))
  1101. }
  1102. }
  1103. }
  1104. func nsCertHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  1105. verb := strings.ToLower(params[0])
  1106. params = params[1:]
  1107. var target, certfp string
  1108. switch verb {
  1109. case "list":
  1110. if 1 <= len(params) {
  1111. target = params[0]
  1112. }
  1113. case "add", "del":
  1114. if 2 <= len(params) {
  1115. target, certfp = params[0], params[1]
  1116. } else if len(params) == 1 {
  1117. certfp = params[0]
  1118. } else if len(params) == 0 && verb == "add" && rb.session.certfp != "" {
  1119. certfp = rb.session.certfp // #1059
  1120. } else {
  1121. service.Notice(rb, client.t("Invalid parameters"))
  1122. return
  1123. }
  1124. default:
  1125. service.Notice(rb, client.t("Invalid parameters"))
  1126. return
  1127. }
  1128. hasPrivs := client.HasRoleCapabs("accreg")
  1129. if target != "" && !hasPrivs {
  1130. service.Notice(rb, client.t("Insufficient privileges"))
  1131. return
  1132. } else if target == "" {
  1133. target = client.Account()
  1134. if target == "" {
  1135. service.Notice(rb, client.t("You're not logged into an account"))
  1136. return
  1137. }
  1138. }
  1139. var err error
  1140. switch verb {
  1141. case "list":
  1142. accountData, err := server.accounts.LoadAccount(target)
  1143. if err == errAccountDoesNotExist {
  1144. service.Notice(rb, client.t("Account does not exist"))
  1145. return
  1146. } else if err != nil {
  1147. service.Notice(rb, client.t("An error occurred"))
  1148. return
  1149. }
  1150. certfps := accountData.Credentials.Certfps
  1151. service.Notice(rb, fmt.Sprintf(client.t("There are %[1]d certificate fingerprint(s) authorized for account %[2]s."), len(certfps), accountData.Name))
  1152. for i, certfp := range certfps {
  1153. service.Notice(rb, fmt.Sprintf("%d: %s", i+1, certfp))
  1154. }
  1155. return
  1156. case "add":
  1157. err = server.accounts.addRemoveCertfp(target, certfp, true, hasPrivs)
  1158. case "del":
  1159. err = server.accounts.addRemoveCertfp(target, certfp, false, hasPrivs)
  1160. }
  1161. switch err {
  1162. case nil:
  1163. if verb == "add" {
  1164. service.Notice(rb, client.t("Certificate fingerprint successfully added"))
  1165. } else {
  1166. service.Notice(rb, client.t("Certificate fingerprint successfully removed"))
  1167. }
  1168. case errNoop:
  1169. if verb == "add" {
  1170. service.Notice(rb, client.t("That certificate fingerprint was already authorized"))
  1171. } else {
  1172. service.Notice(rb, client.t("Certificate fingerprint not found"))
  1173. }
  1174. case errAccountDoesNotExist:
  1175. service.Notice(rb, client.t("Account does not exist"))
  1176. case errLimitExceeded:
  1177. service.Notice(rb, client.t("You already have too many certificate fingerprints"))
  1178. case utils.ErrInvalidCertfp:
  1179. service.Notice(rb, client.t("Invalid certificate fingerprint"))
  1180. case errCertfpAlreadyExists:
  1181. service.Notice(rb, client.t("That certificate fingerprint is already associated with another account"))
  1182. case errEmptyCredentials:
  1183. service.Notice(rb, client.t("You can't remove all your certificate fingerprints unless you add a password"))
  1184. case errCredsExternallyManaged:
  1185. service.Notice(rb, client.t("Your account credentials are managed externally and cannot be changed here"))
  1186. case errCASFailed:
  1187. service.Notice(rb, client.t("Try again later"))
  1188. default:
  1189. server.logger.Error("internal", "could not modify certificates:", err.Error())
  1190. service.Notice(rb, client.t("An error occurred"))
  1191. }
  1192. }
  1193. func nsSuspendHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  1194. subCmd := strings.ToLower(params[0])
  1195. params = params[1:]
  1196. switch subCmd {
  1197. case "add":
  1198. nsSuspendAddHandler(service, server, client, command, params, rb)
  1199. case "del", "delete", "remove":
  1200. nsSuspendRemoveHandler(service, server, client, command, params, rb)
  1201. case "list":
  1202. nsSuspendListHandler(service, server, client, command, params, rb)
  1203. default:
  1204. service.Notice(rb, client.t("Invalid parameters"))
  1205. }
  1206. }
  1207. func nsSuspendAddHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  1208. if len(params) == 0 {
  1209. service.Notice(rb, client.t("Invalid parameters"))
  1210. return
  1211. }
  1212. account := params[0]
  1213. params = params[1:]
  1214. var duration time.Duration
  1215. if 2 <= len(params) && strings.ToLower(params[0]) == "duration" {
  1216. var err error
  1217. cDuration, err := custime.ParseDuration(params[1])
  1218. if err != nil {
  1219. service.Notice(rb, client.t("Invalid time duration for NS SUSPEND"))
  1220. return
  1221. }
  1222. duration = time.Duration(cDuration)
  1223. params = params[2:]
  1224. }
  1225. var reason string
  1226. if len(params) != 0 {
  1227. reason = strings.Join(params, " ")
  1228. }
  1229. name := client.Oper().Name
  1230. err := server.accounts.Suspend(account, duration, name, reason)
  1231. switch err {
  1232. case nil:
  1233. service.Notice(rb, fmt.Sprintf(client.t("Successfully suspended account %s"), account))
  1234. case errAccountDoesNotExist:
  1235. service.Notice(rb, client.t("No such account"))
  1236. default:
  1237. service.Notice(rb, client.t("An error occurred"))
  1238. }
  1239. }
  1240. func nsSuspendRemoveHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  1241. if len(params) == 0 {
  1242. service.Notice(rb, client.t("Invalid parameters"))
  1243. return
  1244. }
  1245. err := server.accounts.Unsuspend(params[0])
  1246. switch err {
  1247. case nil:
  1248. service.Notice(rb, fmt.Sprintf(client.t("Successfully un-suspended account %s"), params[0]))
  1249. case errAccountDoesNotExist:
  1250. service.Notice(rb, client.t("No such account"))
  1251. case errNoop:
  1252. service.Notice(rb, client.t("Account was not suspended"))
  1253. default:
  1254. service.Notice(rb, client.t("An error occurred"))
  1255. }
  1256. }
  1257. // sort in reverse order of creation time
  1258. type ByCreationTime []AccountSuspension
  1259. func (a ByCreationTime) Len() int { return len(a) }
  1260. func (a ByCreationTime) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  1261. func (a ByCreationTime) Less(i, j int) bool { return a[i].TimeCreated.After(a[j].TimeCreated) }
  1262. func nsSuspendListHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  1263. listAccountSuspensions(client, rb, service.prefix)
  1264. }
  1265. func listAccountSuspensions(client *Client, rb *ResponseBuffer, source string) {
  1266. suspensions := client.server.accounts.ListSuspended()
  1267. sort.Sort(ByCreationTime(suspensions))
  1268. nick := client.Nick()
  1269. rb.Add(nil, source, "NOTICE", nick, fmt.Sprintf(client.t("There are %d active account suspensions."), len(suspensions)))
  1270. for _, suspension := range suspensions {
  1271. rb.Add(nil, source, "NOTICE", nick, suspensionToString(client, suspension))
  1272. }
  1273. }
  1274. func suspensionToString(client *Client, suspension AccountSuspension) (result string) {
  1275. duration := client.t("indefinite")
  1276. if suspension.Duration != time.Duration(0) {
  1277. duration = suspension.Duration.String()
  1278. }
  1279. ts := suspension.TimeCreated.Format(time.RFC1123)
  1280. reason := client.t("No reason given.")
  1281. if suspension.Reason != "" {
  1282. reason = fmt.Sprintf(client.t("Reason: %s"), suspension.Reason)
  1283. }
  1284. return fmt.Sprintf(client.t("Account %[1]s suspended at %[2]s. Duration: %[3]s. %[4]s"), suspension.AccountName, ts, duration, reason)
  1285. }
  1286. func nsRenameHandler(service *ircService, server *Server, client *Client, command string, params []string, rb *ResponseBuffer) {
  1287. oldName, newName := params[0], params[1]
  1288. err := server.accounts.Rename(oldName, newName)
  1289. if err != nil {
  1290. service.Notice(rb, fmt.Sprintf(client.t("Couldn't rename account: %s"), client.t(err.Error())))
  1291. return
  1292. }
  1293. service.Notice(rb, client.t("Successfully renamed account"))
  1294. if server.Config().Accounts.NickReservation.ForceNickEqualsAccount {
  1295. if curClient := server.clients.Get(oldName); curClient != nil {
  1296. renameErr := performNickChange(client.server, client, curClient, nil, newName, rb)
  1297. if renameErr != nil && renameErr != errNoop {
  1298. service.Notice(rb, fmt.Sprintf(client.t("Warning: could not rename affected client: %v"), err))
  1299. }
  1300. }
  1301. }
  1302. }