Magic World game server
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.

105 lines
2.4 KiB

5 years ago
  1. #include <MWUtils.h>
  2. #include <MW.h>
  3. #include <sstream>
  4. #include <algorithm>
  5. using namespace std;
  6. static const unsigned int maxNameSize = 12;
  7. static const unsigned int minNameSize = 3;
  8. static const string nameRange = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  9. static const string isEmptyTokens = "\t\r\n\f\v ";
  10. static const unsigned int maxMessageSize = 1024;
  11. string
  12. validateName(const string& in)
  13. {
  14. if(in.size() > maxNameSize || in.size() < minNameSize)
  15. {
  16. ostringstream msg;
  17. msg << "Your name must be between " << minNameSize << " and " << maxNameSize << " characters in length.";
  18. throw invalid_argument(msg.str());
  19. }
  20. if(in.find_last_not_of(nameRange) != string::npos)
  21. {
  22. throw invalid_argument("Invalid character in name. Valid characters are letter and digits.");
  23. }
  24. string out = in;
  25. transform(out.begin(), out.end(), out.begin(), ::tolower);
  26. if(out.begin() != out.end())
  27. {
  28. transform(out.begin(), out.begin() + 1, out.begin(), ::toupper);
  29. }
  30. return out;
  31. }
  32. string
  33. validateMessage(const string& in)
  34. {
  35. if(in.size() > maxMessageSize)
  36. {
  37. ostringstream os;
  38. os << "Message length exceeded, maximum length is " << maxMessageSize << " characters.";
  39. throw MW::InvalidMessageException(os.str());
  40. }
  41. if(in.find_last_not_of(isEmptyTokens) == string::npos)
  42. {
  43. throw invalid_argument("Your message is empty and was ignored.");
  44. }
  45. // Strip html codes in the message
  46. string out;
  47. for(char c : in)
  48. {
  49. switch(c)
  50. {
  51. case '&':
  52. {
  53. out.append("&amp;");
  54. break;
  55. }
  56. case '"':
  57. {
  58. out.append("&quot;");
  59. break;
  60. }
  61. case '\'':
  62. {
  63. out.append("&#39;");
  64. break;
  65. }
  66. case '<':
  67. {
  68. out.append("&lt;");
  69. break;
  70. }
  71. case '>':
  72. {
  73. out.append("&gt;");
  74. break;
  75. }
  76. case '\r':
  77. case '\n':
  78. case '\v':
  79. case '\f':
  80. case '\t':
  81. {
  82. out.append(" ");
  83. break;
  84. }
  85. default:
  86. {
  87. out.push_back(c);
  88. break;
  89. }
  90. }
  91. }
  92. return out;
  93. }