user.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. package state
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "strconv"
  7. "strings"
  8. "time"
  9. "unicode"
  10. "github.com/mk6i/open-oscar-server/wire"
  11. )
  12. var (
  13. // ErrDupUser indicates that a user already exists.
  14. ErrDupUser = errors.New("user already exists")
  15. // ErrNoUser indicates that a user does not exist.
  16. ErrNoUser = errors.New("user does not exist")
  17. // ErrNoEmailAddress indicates that a user has not set an email address.
  18. ErrNoEmailAddress = errors.New("user has no email address")
  19. // ErrLinkExists indicates that a linked account relationship already exists.
  20. ErrLinkExists = errors.New("linked account relationship already exists")
  21. )
  22. // IdentScreenName struct stores the normalized version of a user's screen name.
  23. // This format is used for uniformity in storage and comparison by removing spaces
  24. // and converting all characters to lowercase.
  25. type IdentScreenName struct {
  26. // screenName contains the identifier screen name value. Do not assign this
  27. // value directly. Rather, set it through NewIdentScreenName. This ensures
  28. // that when an instance of IdentScreenName is present, it's guaranteed to
  29. // have a normalized value.
  30. screenName string
  31. }
  32. // String returns the string representation of the IdentScreenName.
  33. func (i IdentScreenName) String() string {
  34. return i.screenName
  35. }
  36. // UIN returns a numeric UIN representation of the IdentScreenName.
  37. func (i IdentScreenName) UIN() uint32 {
  38. v, _ := strconv.Atoi(i.screenName)
  39. return uint32(v)
  40. }
  41. // NewIdentScreenName creates a new IdentScreenName.
  42. func NewIdentScreenName(screenName string) IdentScreenName {
  43. str := strings.ReplaceAll(screenName, " ", "")
  44. str = strings.ToLower(str)
  45. return IdentScreenName{screenName: str}
  46. }
  47. // DisplayScreenName type represents the screen name in the user-defined format.
  48. // This includes the original casing and spacing as defined by the user.
  49. type DisplayScreenName string
  50. var (
  51. ErrAIMHandleInvalidFormat = errors.New("screen name must start with a letter, cannot end with a space, and must contain only letters, numbers, and spaces")
  52. ErrAIMHandleLength = errors.New("screen name must be between 3 and 16 characters")
  53. ErrPasswordInvalid = errors.New("invalid password length")
  54. ErrICQUINInvalidFormat = errors.New("uin must be a number in the range 10000-2147483646")
  55. )
  56. // ValidateAIMHandle returns an error if the instance is not a valid AIM screen name.
  57. // Possible errors:
  58. // - ErrAIMHandleLength: if the screen name has less than 3 non-space
  59. // characters or more than 16 characters (including spaces).
  60. // - ErrAIMHandleInvalidFormat: if the screen name does not start with a
  61. // letter, ends with a space, or contains invalid characters
  62. func (s DisplayScreenName) ValidateAIMHandle() error {
  63. if len(s) > 16 {
  64. return ErrAIMHandleLength
  65. }
  66. c := 0
  67. for _, r := range s {
  68. switch {
  69. case unicode.IsLetter(r) || unicode.IsDigit(r):
  70. c++
  71. case r != ' ':
  72. return ErrAIMHandleInvalidFormat
  73. }
  74. }
  75. if c < 3 {
  76. return ErrAIMHandleLength
  77. }
  78. // Must start with a letter, cannot end with a space, and must contain only
  79. // letters, numbers, and spaces.
  80. if !unicode.IsLetter(rune(s[0])) || s[len(s)-1] == ' ' {
  81. return ErrAIMHandleInvalidFormat
  82. }
  83. return nil
  84. }
  85. // IsUIN indicates whether the screen name is an ICQ UIN.
  86. func (s DisplayScreenName) IsUIN() bool {
  87. if len(s) == 0 {
  88. return false
  89. }
  90. for _, r := range s {
  91. if !unicode.IsDigit(r) {
  92. return false
  93. }
  94. }
  95. return true
  96. }
  97. // ValidateUIN returns an error if the instance is not a valid ICQ UIN.
  98. // Possible errors:
  99. // - ErrICQUINInvalidFormat: if the UIN is not a number or is not in the valid
  100. // range
  101. func (s DisplayScreenName) ValidateUIN() error {
  102. uin, err := strconv.Atoi(string(s))
  103. if err != nil || uin < 10000 || uin > 2147483646 {
  104. return ErrICQUINInvalidFormat
  105. }
  106. return nil
  107. }
  108. // IdentScreenName converts the DisplayScreenName to an IdentScreenName by applying
  109. // the normalization process defined in NewIdentScreenName.
  110. func (s DisplayScreenName) IdentScreenName() IdentScreenName {
  111. return NewIdentScreenName(string(s))
  112. }
  113. // String returns the original display string of the screen name, preserving the user-defined
  114. // casing and spaces.
  115. func (s DisplayScreenName) String() string {
  116. return string(s)
  117. }
  118. // ICQInfo groups ICQ profile segments stored for a user. Sub-structs are
  119. // named fields (not anonymously embedded) because ICQBasicInfo and ICQWorkInfo
  120. // share exported field names (e.g. Address, City), which would make field
  121. // promotion into User invalid or ambiguous.
  122. type ICQInfo struct {
  123. // Affiliations holds information about the user's affiliations,
  124. // including past and current affiliations.
  125. Affiliations ICQAffiliations
  126. // Interests holds information about the user's interests, categorized
  127. // by code and associated keywords.
  128. Interests ICQInterests
  129. // More contains additional information about the user.
  130. More ICQMoreInfo
  131. // Permissions specifies the user's privacy settings.
  132. Permissions ICQPermissions
  133. // Basic contains the user's basic profile information, including
  134. // contact details and personal identifiers.
  135. Basic ICQBasicInfo
  136. // Notes allows the user to store personal notes or additional
  137. // information within their profile.
  138. Notes ICQUserNotes
  139. // Work contains the user's professional information, including
  140. // their workplace address and job-related details.
  141. Work ICQWorkInfo
  142. // HomepageCategory contains homepage category information for the user.
  143. // Used by V5 META_SET_HPCAT (0x0442) command.
  144. HomepageCategory ICQHomepageCategory
  145. }
  146. // User represents a user account.
  147. type User struct {
  148. // IdentScreenName is the AIM screen name.
  149. IdentScreenName IdentScreenName
  150. // DisplayScreenName is the formatted screen name.
  151. DisplayScreenName DisplayScreenName
  152. // AuthKey is the salt for the MD5 password hash.
  153. AuthKey string
  154. // StrongMD5Pass is the MD5 password hash format used by AIM v4.8-v5.9.
  155. StrongMD5Pass []byte
  156. // WeakMD5Pass is the MD5 password hash format used by AIM v3.5-v4.7. This
  157. // hash is used to authenticate roasted passwords for AIM v1.0-v3.0.
  158. WeakMD5Pass []byte
  159. // IsICQ indicates whether the user is an ICQ account (true) or an AIM
  160. // account (false).
  161. IsICQ bool
  162. // ConfirmStatus indicates whether the user has confirmed their AIM account.
  163. ConfirmStatus bool
  164. // RegStatus is the AIM registration status.
  165. // 1: no disclosure
  166. // 2: limit disclosure
  167. // 3: full disclosure
  168. RegStatus int
  169. // SuspendedStatus is the account suspended status
  170. SuspendedStatus uint16
  171. // EmailAddress is the email address set by the AIM client.
  172. EmailAddress string
  173. // ICQInfo holds ICQ-specific profile segments for ICQ accounts.
  174. ICQInfo ICQInfo
  175. AIMDirectoryInfo AIMNameAndAddr
  176. // TOCConfig is the user's saved server-side info (buddy list, etc) for
  177. // on the TOC service.
  178. TOCConfig string
  179. // IsBot indicates whether the user is a bot.
  180. IsBot bool
  181. // LastWarnUpdate is the timestamp when the user's warning level was last updated.
  182. LastWarnUpdate time.Time
  183. // LastWarnLevel is the warning level when the user last signed off.
  184. LastWarnLevel uint16
  185. // OfflineMsgCount is the count of offline messages for the user.
  186. OfflineMsgCount int
  187. }
  188. // UserProfile represents a user's profile information.
  189. type UserProfile struct {
  190. // ProfileText is the free-form profile body content.
  191. ProfileText string
  192. // MIMEType is the MIME type of the profile content.
  193. MIMEType string
  194. // UpdateTime is when the profile was last updated.
  195. UpdateTime time.Time
  196. }
  197. // IsZero returns true if the profile has not been set.
  198. func (p UserProfile) IsZero() bool {
  199. return p.UpdateTime.IsZero()
  200. }
  201. // IsEmpty returns true of the profile is empty (including not set).
  202. func (p UserProfile) IsEmpty() bool {
  203. return p.IsZero() || p.ProfileText == "" || p.ProfileText == "\x00"
  204. }
  205. // AIMNameAndAddr holds name and address AIM directory information.
  206. type AIMNameAndAddr struct {
  207. // FirstName is the user's first name.
  208. FirstName string
  209. // LastName is the user's last name.
  210. LastName string
  211. // MiddleName is the user's middle name.
  212. MiddleName string
  213. // MaidenName is the user's maiden name.
  214. MaidenName string
  215. // Country is the user's country of residence.
  216. Country string
  217. // State is the user's state or region of residence.
  218. State string
  219. // City is the user's city of residence.
  220. City string
  221. // NickName is the user's chosen nickname.
  222. NickName string
  223. // ZIPCode is the user's postal or ZIP code.
  224. ZIPCode string
  225. // Address is the user's street address.
  226. Address string
  227. }
  228. // ICQBasicInfo holds basic information about an ICQ user, including their name, contact details, and location.
  229. type ICQBasicInfo struct {
  230. // Address is the user's residential address.
  231. Address string
  232. // CellPhone is the user's mobile phone number.
  233. CellPhone string
  234. // City is the city where the user resides.
  235. City string
  236. // CountryCode is the code representing the user's country of residence.
  237. CountryCode uint16
  238. // EmailAddress is the user's primary email address.
  239. EmailAddress string
  240. // Fax is the user's fax number.
  241. Fax string
  242. // FirstName is the user's first name.
  243. FirstName string
  244. // GMTOffset is the user's time zone offset from GMT.
  245. GMTOffset uint8
  246. // LastName is the user's last name.
  247. LastName string
  248. // Nickname is the user's nickname or preferred name.
  249. Nickname string
  250. // Phone is the user's landline phone number.
  251. Phone string
  252. // PublishEmail indicates whether the user's email address is public.
  253. PublishEmail bool
  254. // State is the state or region where the user resides.
  255. State string
  256. // ZIPCode is the user's postal code.
  257. ZIPCode string
  258. // OriginallyFromCity is the city the user is originally from (ICQ profile).
  259. OriginallyFromCity string
  260. // OriginallyFromState is the state or region the user is originally from (ICQ profile).
  261. OriginallyFromState string
  262. // OriginallyFromCountryCode is the country code for the user's original home (ICQ profile).
  263. OriginallyFromCountryCode uint16
  264. }
  265. // ICQAffiliations contains information about the user's affiliations, both past and present.
  266. type ICQAffiliations struct {
  267. // PastCount is the number of past affiliations set (0-3).
  268. PastCount uint8
  269. // PastCode1 is the code representing the user's first past affiliation.
  270. PastCode1 uint16
  271. // PastKeyword1 is the keyword associated with the user's first past affiliation.
  272. PastKeyword1 string
  273. // PastCode2 is the code representing the user's second past affiliation.
  274. PastCode2 uint16
  275. // PastKeyword2 is the keyword associated with the user's second past affiliation.
  276. PastKeyword2 string
  277. // PastCode3 is the code representing the user's third past affiliation.
  278. PastCode3 uint16
  279. // PastKeyword3 is the keyword associated with the user's third past affiliation.
  280. PastKeyword3 string
  281. // CurrentCount is the number of current affiliations set (0-3).
  282. CurrentCount uint8
  283. // CurrentCode1 is the code representing the user's current first affiliation.
  284. CurrentCode1 uint16
  285. // CurrentKeyword1 is the keyword associated with the user's current first affiliation.
  286. CurrentKeyword1 string
  287. // CurrentCode2 is the code representing the user's current second affiliation.
  288. CurrentCode2 uint16
  289. // CurrentKeyword2 is the keyword associated with the user's current second affiliation.
  290. CurrentKeyword2 string
  291. // CurrentCode3 is the code representing the user's current third affiliation.
  292. CurrentCode3 uint16
  293. // CurrentKeyword3 is the keyword associated with the user's current third affiliation.
  294. CurrentKeyword3 string
  295. }
  296. // ICQInterests holds information about the user's interests, categorized by
  297. // interest code and associated keyword.
  298. type ICQInterests struct {
  299. // Count is the number of interests set (0-4).
  300. Count uint8
  301. // Code1 is the code representing the user's first interest.
  302. Code1 uint16
  303. // Keyword1 is the keyword associated with the user's first interest.
  304. Keyword1 string
  305. // Code2 is the code representing the user's second interest.
  306. Code2 uint16
  307. // Keyword2 is the keyword associated with the user's second interest.
  308. Keyword2 string
  309. // Code3 is the code representing the user's third interest.
  310. Code3 uint16
  311. // Keyword3 is the keyword associated with the user's third interest.
  312. Keyword3 string
  313. // Code4 is the code representing the user's fourth interest.
  314. Code4 uint16
  315. // Keyword4 is the keyword associated with the user's fourth interest.
  316. Keyword4 string
  317. }
  318. // ICQUserNotes contains personal notes or additional information added by the user.
  319. type ICQUserNotes struct {
  320. // Notes are the personal notes or additional information the user has
  321. // entered in their profile.
  322. Notes string
  323. }
  324. // ICQMoreInfo contains additional information about the user, such as
  325. // demographic and language preferences.
  326. type ICQMoreInfo struct {
  327. // Gender is the user's gender, represented by a code.
  328. Gender uint16
  329. // HomePageAddr is the URL of the user's personal homepage.
  330. HomePageAddr string
  331. // BirthYear is the user's birth year.
  332. BirthYear uint16
  333. // BirthMonth is the user's birth month.
  334. BirthMonth uint8
  335. // BirthDay is the user's birth day.
  336. BirthDay uint8
  337. // Lang1 is the code for the user's primary language.
  338. Lang1 uint8
  339. // Lang2 is the code for the user's secondary language.
  340. Lang2 uint8
  341. // Lang3 is the code for the user's tertiary language.
  342. Lang3 uint8
  343. }
  344. // ICQWorkInfo contains information about the user's professional life,
  345. // including their workplace and job title.
  346. type ICQWorkInfo struct {
  347. // Address is the address of the user's workplace.
  348. Address string
  349. // City is the city where the user's workplace is located.
  350. City string
  351. // Company is the name of the user's employer or company.
  352. Company string
  353. // CountryCode is the code representing the country where the user's
  354. // workplace is located.
  355. CountryCode uint16
  356. // Department is the name of the department within the user's company.
  357. Department string
  358. // Fax is the fax number for the user's workplace.
  359. Fax string
  360. // OccupationCode is the code representing the user's occupation.
  361. OccupationCode uint16
  362. // Phone is the phone number for the user's workplace.
  363. Phone string
  364. // Position is the user's job title or position within the company.
  365. Position string
  366. // State is the state or region where the user's workplace is located.
  367. State string
  368. // WebPage is the URL of the user's company's website.
  369. WebPage string
  370. // ZIPCode is the postal code for the user's workplace.
  371. ZIPCode string
  372. }
  373. // ICQPermissions specifies the privacy settings of an ICQ user.
  374. type ICQPermissions struct {
  375. // AuthRequired indicates where users must ask this permission to add them
  376. // to their contact list.
  377. AuthRequired bool
  378. // WebAware indicates whether the user's online status is visible via web.
  379. WebAware bool
  380. // AllowSpam indicates whether to allow messages from users not on the contact list.
  381. AllowSpam bool
  382. }
  383. // ICQHomepageCategory contains homepage category information for an ICQ user.
  384. // This is used by the V5 META_SET_HPCAT (0x0442) command.
  385. type ICQHomepageCategory struct {
  386. // Enabled indicates whether the homepage category is enabled.
  387. Enabled bool
  388. // Index is the homepage category index/code.
  389. Index uint16
  390. // Description is the homepage category description/keyword.
  391. Description string
  392. }
  393. // Age returns the user's age relative to their birthday and timeNow.
  394. func (u *User) Age(timeNow func() time.Time) uint16 {
  395. now := timeNow().UTC()
  396. switch {
  397. case u.ICQInfo.More.BirthYear > 0 && u.ICQInfo.More.BirthDay == 0 && u.ICQInfo.More.BirthMonth == 0:
  398. bday := time.Date(int(u.ICQInfo.More.BirthYear), time.January, 1, 0, 0, 0, 0, time.UTC)
  399. return uint16(now.Year() - bday.Year())
  400. case u.ICQInfo.More.BirthYear > 0 && u.ICQInfo.More.BirthDay > 0 && u.ICQInfo.More.BirthMonth > 0:
  401. bday := time.Date(int(u.ICQInfo.More.BirthYear), time.Month(u.ICQInfo.More.BirthMonth), int(u.ICQInfo.More.BirthDay), 0, 0, 0, 0, time.UTC)
  402. years := now.Year() - bday.Year()
  403. if now.YearDay() < bday.YearDay() {
  404. years--
  405. }
  406. return uint16(years)
  407. default: // invalid date
  408. return 0
  409. }
  410. }
  411. // ValidateHash validates MD5-hashed passwords for BUCP auth. It handles
  412. // hashes used in early AIM 4.x versions ("weak" hashes) and later AIM 4.x-5.x
  413. // versions ("strong" hashes).
  414. func (u *User) ValidateHash(md5Hash []byte) bool {
  415. return bytes.Equal(u.StrongMD5Pass, md5Hash) || bytes.Equal(u.WeakMD5Pass, md5Hash)
  416. }
  417. // ValidateRoastedPass validates roasted passwords for FLAP auth.
  418. func (u *User) ValidateRoastedPass(roastedPass []byte) bool {
  419. clearPass := wire.RoastOSCARPassword(roastedPass)
  420. md5Hash := wire.WeakMD5PasswordHash(string(clearPass), u.AuthKey)
  421. return bytes.Equal(u.WeakMD5Pass, md5Hash)
  422. }
  423. // ValidateRoastedJavaPass validates roasted passwords for the Java AIM client FLAP auth.
  424. func (u *User) ValidateRoastedJavaPass(roastedPass []byte) bool {
  425. clearPass := wire.RoastOSCARJavaPassword(roastedPass)
  426. md5Hash := wire.WeakMD5PasswordHash(string(clearPass), u.AuthKey)
  427. return bytes.Equal(u.WeakMD5Pass, md5Hash)
  428. }
  429. // ValidateRoastedTOCPass validates roasted passwords for TOC auth.
  430. func (u *User) ValidateRoastedTOCPass(roastedPass []byte) bool {
  431. clearPass := wire.RoastTOCPassword(roastedPass)
  432. md5Hash := wire.WeakMD5PasswordHash(string(clearPass), u.AuthKey)
  433. return bytes.Equal(u.WeakMD5Pass, md5Hash)
  434. }
  435. // ValidatePlaintextPass validates plaintext passwords used in Kerberos auth.
  436. func (u *User) ValidatePlaintextPass(plaintextPass []byte) bool {
  437. md5Hash := wire.WeakMD5PasswordHash(string(plaintextPass), u.AuthKey)
  438. return bytes.Equal(u.WeakMD5Pass, md5Hash)
  439. }
  440. // ValidateRoastedKerberosPass validates roasted passwords used in Kerberos auth.
  441. func (u *User) ValidateRoastedKerberosPass(roastedPass []byte) bool {
  442. clearPass := wire.RoastKerberosPassword(roastedPass)
  443. md5Hash := wire.WeakMD5PasswordHash(string(clearPass), u.AuthKey)
  444. return bytes.Equal(u.WeakMD5Pass, md5Hash)
  445. }
  446. // HashPassword computes MD5 hashes of the user's password. It computes both
  447. // weak and strong variants and stores them in the struct.
  448. func (u *User) HashPassword(passwd string) error {
  449. if u.IsICQ {
  450. if err := validateICQPassword(passwd); err != nil {
  451. return err
  452. }
  453. } else {
  454. if err := validateAIMPassword(passwd); err != nil {
  455. return err
  456. }
  457. }
  458. u.WeakMD5Pass = wire.WeakMD5PasswordHash(passwd, u.AuthKey)
  459. u.StrongMD5Pass = wire.StrongMD5PasswordHash(passwd, u.AuthKey)
  460. return nil
  461. }
  462. // validateAIMPassword returns an error if the AIM password is invalid.
  463. // A valid password is 4-16 characters long. The min and max password length
  464. // values reflect AOL's password validation rules circa 2000.
  465. func validateAIMPassword(pass string) error {
  466. if len(pass) < 4 || len(pass) > 16 {
  467. return fmt.Errorf("%w: password length must be between 4-16 characters", ErrPasswordInvalid)
  468. }
  469. return nil
  470. }
  471. // validateICQPassword returns an error if the ICQ password is invalid.
  472. // A valid password is 6-8 characters long. It's unclear what min length the
  473. // ICQ service required, so a plausible minimum value is set. The max length
  474. // reflects the password limitation imposed by old ICQ clients.
  475. func validateICQPassword(pass string) error {
  476. if len(pass) < 6 || len(pass) > 8 {
  477. return fmt.Errorf("%w: password must be between 6-8 characters", ErrPasswordInvalid)
  478. }
  479. return nil
  480. }
  481. type OfflineMessage struct {
  482. Sender IdentScreenName
  483. Recipient IdentScreenName
  484. Message wire.SNAC_0x04_0x06_ICBMChannelMsgToHost
  485. Sent time.Time
  486. }
  487. // Category represents an AIM directory category.
  488. type Category struct {
  489. // ID is the category ID
  490. ID uint8
  491. // Name is the category name
  492. Name string `oscar:"len_prefix=uint16"`
  493. }
  494. // Keyword represents an AIM directory keyword.
  495. type Keyword struct {
  496. // ID is the keyword ID
  497. ID uint8
  498. // Name is the keyword name
  499. Name string `oscar:"len_prefix=uint16"`
  500. }