Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

strings.go 8.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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. "fmt"
  8. "regexp"
  9. "strings"
  10. "github.com/oragono/confusables"
  11. "golang.org/x/text/cases"
  12. "golang.org/x/text/secure/precis"
  13. "golang.org/x/text/unicode/norm"
  14. "golang.org/x/text/width"
  15. )
  16. const (
  17. precisUTF8MappingToken = "rfc8265"
  18. )
  19. var (
  20. // reviving the old ergonomadic nickname regex:
  21. // in permissive mode, allow arbitrary letters, numbers, punctuation, and symbols
  22. permissiveCharsRegex = regexp.MustCompile(`^[\pL\pN\pP\pS]*$`)
  23. )
  24. type Casemapping uint
  25. const (
  26. // "precis" is the default / zero value:
  27. // casefolding/validation: PRECIS + ircd restrictions (like no *)
  28. // confusables detection: standard skeleton algorithm
  29. CasemappingPRECIS Casemapping = iota
  30. // "ascii" is the traditional ircd behavior:
  31. // casefolding/validation: must be pure ASCII and follow ircd restrictions, ASCII lowercasing
  32. // confusables detection: none
  33. CasemappingASCII
  34. // "permissive" is an insecure mode:
  35. // casefolding/validation: arbitrary unicodes that follow ircd restrictions, unicode casefolding
  36. // confusables detection: standard skeleton algorithm (which may be ineffective
  37. // over the larger set of permitted identifiers)
  38. CasemappingPermissive
  39. )
  40. // XXX this is a global variable without explicit synchronization.
  41. // it gets set during the initial Server.applyConfig and cannot be changed by rehash:
  42. // this happens-before all IRC connections and all casefolding operations.
  43. var globalCasemappingSetting Casemapping = CasemappingPRECIS
  44. // XXX analogous unsynchronized global variable controlling utf8 validation
  45. // if this is off, you get the traditional IRC behavior (relaying any valid RFC1459
  46. // octets) and invalid utf8 messages are silently dropped for websocket clients only.
  47. // if this is on, invalid utf8 inputs get a FAIL reply.
  48. var globalUtf8EnforcementSetting bool
  49. // Each pass of PRECIS casefolding is a composition of idempotent operations,
  50. // but not idempotent itself. Therefore, the spec says "do it four times and hope
  51. // it converges" (lolwtf). Golang's PRECIS implementation has a "repeat" option,
  52. // which provides this functionality, but unfortunately it's not exposed publicly.
  53. func iterateFolding(profile *precis.Profile, oldStr string) (str string, err error) {
  54. str = oldStr
  55. // follow the stabilizing rules laid out here:
  56. // https://tools.ietf.org/html/draft-ietf-precis-7564bis-10.html#section-7
  57. for i := 0; i < 4; i++ {
  58. str, err = profile.CompareKey(str)
  59. if err != nil {
  60. return "", err
  61. }
  62. if oldStr == str {
  63. break
  64. }
  65. oldStr = str
  66. }
  67. if oldStr != str {
  68. return "", errCouldNotStabilize
  69. }
  70. return str, nil
  71. }
  72. // Casefold returns a casefolded string, without doing any name or channel character checks.
  73. func Casefold(str string) (string, error) {
  74. return casefoldWithSetting(str, globalCasemappingSetting)
  75. }
  76. func casefoldWithSetting(str string, setting Casemapping) (string, error) {
  77. switch setting {
  78. default:
  79. return iterateFolding(precis.UsernameCaseMapped, str)
  80. case CasemappingASCII:
  81. return foldASCII(str)
  82. case CasemappingPermissive:
  83. return foldPermissive(str)
  84. }
  85. }
  86. // CasefoldChannel returns a casefolded version of a channel name.
  87. func CasefoldChannel(name string) (string, error) {
  88. if len(name) == 0 {
  89. return "", errStringIsEmpty
  90. }
  91. // don't casefold the preceding #'s
  92. var start int
  93. for start = 0; start < len(name) && name[start] == '#'; start += 1 {
  94. }
  95. if start == 0 {
  96. // no preceding #'s
  97. return "", errInvalidCharacter
  98. }
  99. lowered, err := Casefold(name[start:])
  100. if err != nil {
  101. return "", err
  102. }
  103. // space can't be used
  104. // , is used as a separator
  105. // * is used in mask matching
  106. // ? is used in mask matching
  107. if strings.ContainsAny(lowered, " ,*?") {
  108. return "", errInvalidCharacter
  109. }
  110. return name[:start] + lowered, err
  111. }
  112. // CasefoldName returns a casefolded version of a nick/user name.
  113. func CasefoldName(name string) (string, error) {
  114. lowered, err := Casefold(name)
  115. if err != nil {
  116. return "", err
  117. } else if len(lowered) == 0 {
  118. return "", errStringIsEmpty
  119. }
  120. // space can't be used
  121. // , is used as a separator
  122. // * is used in mask matching
  123. // ? is used in mask matching
  124. // . denotes a server name
  125. // ! separates nickname from username
  126. // @ separates username from hostname
  127. // : means trailing
  128. // # is a channel prefix
  129. // ~&@%+ are channel membership prefixes
  130. // - I feel like disallowing
  131. if strings.ContainsAny(lowered, " ,*?.!@:") || strings.ContainsAny(string(lowered[0]), "#~&@%+-") {
  132. return "", errInvalidCharacter
  133. }
  134. return lowered, err
  135. }
  136. // returns true if the given name is a valid ident, using a mix of Insp and
  137. // Chary's ident restrictions.
  138. func isIdent(name string) bool {
  139. if len(name) < 1 {
  140. return false
  141. }
  142. for i := 0; i < len(name); i++ {
  143. chr := name[i]
  144. if (chr >= 'a' && chr <= 'z') || (chr >= 'A' && chr <= 'Z') || (chr >= '0' && chr <= '9') {
  145. continue // alphanumerics
  146. }
  147. if i == 0 {
  148. return false // first char must be alnum
  149. }
  150. switch chr {
  151. case '[', '\\', ']', '^', '_', '{', '|', '}', '-', '.', '`':
  152. continue // allowed chars
  153. default:
  154. return false // disallowed chars
  155. }
  156. }
  157. return true
  158. }
  159. // Skeleton produces a canonicalized identifier that tries to catch
  160. // homoglyphic / confusable identifiers. It's a tweaked version of the TR39
  161. // skeleton algorithm. We apply the skeleton algorithm first and only then casefold,
  162. // because casefolding first would lose some information about visual confusability.
  163. // This has the weird consequence that the skeleton is not a function of the
  164. // casefolded identifier --- therefore it must always be computed
  165. // from the original (unfolded) identifier and stored/tracked separately from the
  166. // casefolded identifier.
  167. func Skeleton(name string) (string, error) {
  168. switch globalCasemappingSetting {
  169. default:
  170. return realSkeleton(name)
  171. case CasemappingASCII:
  172. // identity function is fine because we independently case-normalize in Casefold
  173. return name, nil
  174. }
  175. }
  176. func realSkeleton(name string) (string, error) {
  177. // XXX the confusables table includes some, but not all, fullwidth->standard
  178. // mappings for latin characters. do a pass of explicit width folding,
  179. // same as PRECIS:
  180. name = width.Fold.String(name)
  181. name = confusables.SkeletonTweaked(name)
  182. // internationalized lowercasing for skeletons; this is much more lenient than
  183. // Casefold. In particular, skeletons are expected to mix scripts (which may
  184. // violate the bidi rule). We also don't care if they contain runes
  185. // that are disallowed by PRECIS, because every identifier must independently
  186. // pass PRECIS --- we are just further canonicalizing the skeleton.
  187. return cases.Fold().String(name), nil
  188. }
  189. // maps a nickmask fragment to an expanded, casefolded wildcard:
  190. // Shivaram@good-fortune -> *!shivaram@good-fortune
  191. // EDMUND -> edmund!*@*
  192. func CanonicalizeMaskWildcard(userhost string) (expanded string, err error) {
  193. var nick, user, host string
  194. bangIndex := strings.IndexByte(userhost, '!')
  195. strudelIndex := strings.IndexByte(userhost, '@')
  196. if bangIndex != -1 && bangIndex < strudelIndex {
  197. nick = userhost[:bangIndex]
  198. user = userhost[bangIndex+1 : strudelIndex]
  199. host = userhost[strudelIndex+1:]
  200. } else if bangIndex != -1 && strudelIndex == -1 {
  201. nick = userhost[:bangIndex]
  202. user = userhost[bangIndex+1:]
  203. } else if bangIndex != -1 && strudelIndex < bangIndex {
  204. // @ before !, fail
  205. return "", errNicknameInvalid
  206. } else if bangIndex == -1 && strudelIndex != -1 {
  207. user = userhost[:strudelIndex]
  208. host = userhost[strudelIndex+1:]
  209. } else if bangIndex == -1 && strudelIndex == -1 {
  210. nick = userhost
  211. } else {
  212. // shouldn't be possible
  213. return "", errInvalidParams
  214. }
  215. if nick == "" {
  216. nick = "*"
  217. }
  218. if nick != "*" {
  219. // XXX wildcards are not accepted with most unicode nicks,
  220. // because the * character breaks casefolding
  221. nick, err = Casefold(nick)
  222. if err != nil {
  223. return "", err
  224. }
  225. }
  226. if user == "" {
  227. user = "*"
  228. }
  229. if user != "*" {
  230. user = strings.ToLower(user)
  231. }
  232. if host == "" {
  233. host = "*"
  234. }
  235. if host != "*" {
  236. host = strings.ToLower(host)
  237. }
  238. return fmt.Sprintf("%s!%s@%s", nick, user, host), nil
  239. }
  240. func foldASCII(str string) (result string, err error) {
  241. if !IsPrintableASCII(str) {
  242. return "", errInvalidCharacter
  243. }
  244. return strings.ToLower(str), nil
  245. }
  246. func IsPrintableASCII(str string) bool {
  247. for i := 0; i < len(str); i++ {
  248. // allow space here because it's technically printable;
  249. // it will be disallowed later by CasefoldName/CasefoldChannel
  250. chr := str[i]
  251. if chr < ' ' || chr > '~' {
  252. return false
  253. }
  254. }
  255. return true
  256. }
  257. func foldPermissive(str string) (result string, err error) {
  258. if !permissiveCharsRegex.MatchString(str) {
  259. return "", errInvalidCharacter
  260. }
  261. // YOLO
  262. str = norm.NFD.String(str)
  263. str = cases.Fold().String(str)
  264. str = norm.NFD.String(str)
  265. return str, nil
  266. }