utils.h 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806
  1. #pragma once
  2. static const char threadTimestampFmt[] = "%Y/%m/%d %H:%M:%S %Z";
  3. static const char httpTimestampFmt[] = "%a, %d %b %Y %H:%M:%S GMT";
  4. static void *
  5. memmem_priv(const void *l, size_t l_len, const void *s, size_t s_len)
  6. {
  7. register char *cur, *last;
  8. const char *cl = (const char *)l;
  9. const char *cs = (const char *)s;
  10. /* we need something to compare */
  11. if (l_len == 0 || s_len == 0)
  12. return NULL;
  13. /* "s" must be smaller or equal to "l" */
  14. if (l_len < s_len)
  15. return NULL;
  16. /* special case where s_len == 1 */
  17. if (s_len == 1)
  18. return (void *)memchr(l, (int)*cs, l_len);
  19. /* the last position where its possible to find "s" in "l" */
  20. last = (char *)cl + l_len - s_len;
  21. for (cur = (char *)cl; cur <= last; cur++)
  22. if (cur[0] == cs[0] && memcmp(cur, cs, s_len) == 0)
  23. return cur;
  24. return NULL;
  25. }
  26. static int decryptMail(unsigned char *decrypted, char *encrypted)
  27. {
  28. char current[5]="0x";
  29. unsigned char *ptr = decrypted;
  30. current[2] = encrypted[0];
  31. current[3] = encrypted[1];
  32. unsigned int r = strtol(current,NULL,16);
  33. int len = strlen(encrypted);
  34. int n = 2;
  35. for(;n<len;n+=2) {
  36. current[2] = encrypted[n];
  37. current[3] = encrypted[n+1];
  38. unsigned int i = strtol(current,NULL,16);
  39. *ptr++ = i^r;
  40. }
  41. *ptr = 0;
  42. //fprintf(stderr,"%s->%s\n",encrypted,decrypted);
  43. return ptr - decrypted;
  44. }
  45. static size_t header_callback_proxy(char *buffer, size_t size, size_t nitems, void *userdata)
  46. {
  47. BBS2chProxyConnection *conn = reinterpret_cast<BBS2chProxyConnection *>(userdata);
  48. if(conn->status > 0) return size*nitems;
  49. else if(conn->status == -1) {
  50. if(!memcmp(buffer,"\r\n",2)) {
  51. conn->status = 0;
  52. }
  53. return size*nitems;
  54. }
  55. if(!strncasecmp("HTTP/", buffer, 5) && !strchr(buffer, ':')) {
  56. const char *ptr = buffer + 5;
  57. const char *end = buffer + size*nitems;
  58. while(*ptr != ' ' && ptr < end) ptr++;
  59. while(*ptr == ' ' && ptr < end) ptr++;
  60. if(ptr < end) {
  61. int code = atoi(ptr);
  62. if (code == 100) {
  63. conn->status = -1;
  64. return size*nitems;
  65. }
  66. }
  67. }
  68. if(!strncasecmp("Connection",buffer,10)) {
  69. conn->socketToClient->writeString("Connection: Close\r\n");
  70. return size*nitems;
  71. }
  72. else if(!strncasecmp("Transfer-Encoding",buffer,17)) {
  73. if(allow_chunked && !conn->isClientHttp1_0 && strstr(buffer+19,"chunked")) {
  74. conn->isResponseChunked = true;
  75. //fprintf(stderr,"%s",buffer);
  76. size_t ret = conn->socketToClient->write(buffer, size*nitems);
  77. return ret;
  78. }
  79. return size*nitems;
  80. }
  81. else if(conn->force5ch && !strncasecmp("Set-Cookie:",buffer,11)) {
  82. char *ptr = (char *)memmem_priv(buffer,size*nitems,"domain=",7);
  83. if(ptr) {
  84. char *end = ptr;
  85. while(*end != ';' && *end != '\r') end++;
  86. ptr = (char *)memmem_priv(ptr,end-ptr,"5ch.net",7);
  87. if(ptr) {
  88. conn->socketToClient->write(buffer, ptr-buffer);
  89. conn->socketToClient->write("2", 1);
  90. conn->socketToClient->write(ptr+1, size*nitems-(ptr+1-buffer));
  91. return size*nitems;
  92. }
  93. }
  94. return conn->socketToClient->write(buffer, size*nitems);
  95. }
  96. else {
  97. if (conn->bbscgi) {
  98. if (!strncasecmp("X-Chx-Error:", buffer, 12)) {
  99. const char *ptr = buffer + 12;
  100. while (*ptr == ' ') ptr++;
  101. log_printf(0, "Posting to bbs.cgi has been cancelled. Reason: %s", ptr);
  102. if (*ptr == 'E') {
  103. int code = atoi(ptr+1);
  104. if ((code >= 3310 && code <= 3311) || /* inconsistent with User-Agent or something? */
  105. (code >= 3320 && code <= 3324) || /* key expiration? */
  106. (code >= 3390 && code <= 3392)) /* 3390: BAN, 3391-3392: key expiration? */
  107. conn->setMonaKey("", code);
  108. }
  109. }
  110. else if (!strncasecmp("X-MonaKey:", buffer, 10)) {
  111. const char *ptr = buffer + 10;
  112. while (*ptr == ' ') ptr++;
  113. const char *end = ptr;
  114. while (*end != '\n' && *end != '\r' && *end) end++;
  115. conn->setMonaKey(std::string(ptr, end-ptr), 0);
  116. }
  117. }
  118. size_t ret = conn->socketToClient->write(buffer, size*nitems);
  119. //fprintf(stderr,"%s",buffer);
  120. if(!memcmp(buffer,"\r\n",2)) {
  121. conn->status = 1;
  122. }
  123. return ret;
  124. }
  125. }
  126. static size_t header_callback_bbscgi(char *buffer, size_t size, size_t nitems, void *userdata)
  127. {
  128. BBS2chProxyConnection *conn = reinterpret_cast<BBS2chProxyConnection *>(userdata);
  129. if(conn->status > 0) return size*nitems;
  130. else if(conn->status == -1) {
  131. if(!memcmp(buffer,"\r\n",2)) {
  132. conn->status = 0;
  133. }
  134. return size*nitems;
  135. }
  136. if(!strncasecmp("HTTP/", buffer, 5) && !strchr(buffer, ':')) {
  137. const char *ptr = buffer + 5;
  138. const char *end = buffer + size*nitems;
  139. while(*ptr != ' ' && ptr < end) ptr++;
  140. while(*ptr == ' ' && ptr < end) ptr++;
  141. if(ptr < end) {
  142. int code = atoi(ptr);
  143. if (code == 100) {
  144. conn->status = -1;
  145. return size*nitems;
  146. }
  147. }
  148. }
  149. if(!strncasecmp("Connection",buffer,10)) {
  150. conn->responseHeaders.append("Connection: Close\r\n");
  151. return size*nitems;
  152. }
  153. else if(!strncasecmp("Transfer-Encoding",buffer,17)) {
  154. if(allow_chunked && !conn->isClientHttp1_0 && strstr(buffer+19,"chunked")) {
  155. conn->isResponseChunked = true;
  156. //fprintf(stderr,"%s",buffer);
  157. conn->responseHeaders.append(buffer, size*nitems);
  158. }
  159. return size*nitems;
  160. }
  161. else if(conn->force5ch && !strncasecmp("Set-Cookie:",buffer,11)) {
  162. char *ptr = (char *)memmem_priv(buffer,size*nitems,"domain=",7);
  163. if(ptr) {
  164. char *end = ptr;
  165. while(*end != ';' && *end != '\r') end++;
  166. ptr = (char *)memmem_priv(ptr,end-ptr,"5ch.net",7);
  167. if(ptr) {
  168. conn->responseHeaders.append(buffer, ptr-buffer);
  169. conn->responseHeaders.append(1, '2');
  170. conn->responseHeaders.append(ptr+1, size*nitems-(ptr+1-buffer));
  171. return size*nitems;
  172. }
  173. }
  174. conn->responseHeaders.append(buffer, size*nitems);
  175. return size*nitems;
  176. }
  177. else {
  178. if (!strncasecmp("X-Chx-Error:", buffer, 12)) {
  179. const char *ptr = buffer + 12;
  180. while (*ptr == ' ') ptr++;
  181. log_printf(0, "Posting to bbs.cgi has been cancelled. Reason: %s", ptr);
  182. if (*ptr == 'E') {
  183. int code = atoi(ptr+1);
  184. if ((code >= 3310 && code <= 3311) || /* inconsistent with User-Agent or something? */
  185. (code >= 3320 && code <= 3324) || /* key expiration? */
  186. (code >= 3390 && code <= 3392)) /* 3390: BAN, 3391-3392: key expiration? */
  187. {
  188. conn->setMonaKey("", code);
  189. conn->status = 2;
  190. return 0;
  191. }
  192. }
  193. }
  194. else if (!strncasecmp("X-MonaKey:", buffer, 10)) {
  195. const char *ptr = buffer + 10;
  196. while (*ptr == ' ') ptr++;
  197. const char *end = ptr;
  198. while (*end != '\n' && *end != '\r' && *end) end++;
  199. conn->setMonaKey(std::string(ptr, end-ptr), 0);
  200. }
  201. conn->responseHeaders.append(buffer, size*nitems);
  202. //fprintf(stderr,"%s",buffer);
  203. if(!memcmp(buffer,"\r\n",2)) {
  204. conn->socketToClient->write(conn->responseHeaders.data(), conn->responseHeaders.size());
  205. conn->status = 1;
  206. }
  207. return size*nitems;
  208. }
  209. }
  210. static size_t write_callback_proxy(char *buffer, size_t size, size_t nitems, void *userdata)
  211. {
  212. BBS2chProxyConnection *conn = reinterpret_cast<BBS2chProxyConnection *>(userdata);
  213. if(conn->isResponseChunked) {
  214. char buf[64];
  215. snprintf(buf, 64, "%lx\r\n", size*nitems);
  216. conn->socketToClient->write(buf, strlen(buf));
  217. }
  218. size_t ret = conn->socketToClient->write(buffer, size*nitems);
  219. if(conn->isResponseChunked) conn->socketToClient->writeString("\r\n");
  220. return ret;
  221. }
  222. static size_t header_callback_download(char *buffer, size_t size, size_t nitems, void *userdata)
  223. {
  224. DataStorage *data = reinterpret_cast<DataStorage *>(userdata);
  225. if(!strncasecmp("Connection",buffer,10)) {
  226. data->appendBytes("Connection: Close\r\n",19);
  227. return size*nitems;
  228. }
  229. else if(!strncasecmp("Transfer-Encoding",buffer,17)) {
  230. return size*nitems;
  231. }
  232. else {
  233. data->appendBytes(buffer,size*nitems);
  234. return size*nitems;
  235. }
  236. }
  237. static size_t write_callback_download(char *buffer, size_t size, size_t nitems, void *userdata)
  238. {
  239. DataStorage *data = reinterpret_cast<DataStorage *>(userdata);
  240. size_t downloaded = size*nitems;
  241. data->appendBytes(buffer, downloaded);
  242. return downloaded;
  243. }
  244. static size_t read_callback_proxy(char *buffer, size_t size, size_t nitems, void *userdata)
  245. {
  246. BBS2chProxyConnection *conn = reinterpret_cast<BBS2chProxyConnection *>(userdata);
  247. if (size*nitems < 1) return 0;
  248. if (conn->isClientChunked) {
  249. size_t chunkSize;
  250. char tmp[64];
  251. if (!conn->content_length) {
  252. if (!conn->socketToClient->readLine(tmp, 64)) return 0;
  253. chunkSize = strtol(tmp, NULL, 16);
  254. if (chunkSize == 0) {
  255. return 0;
  256. }
  257. }
  258. else {
  259. chunkSize = conn->content_length;
  260. conn->content_length = 0;
  261. }
  262. if (chunkSize <= size*nitems) {
  263. size_t ret = conn->socketToClient->read(buffer, chunkSize);
  264. if (ret <= 0) return 0;
  265. conn->socketToClient->readLine(tmp, 64);
  266. return ret;
  267. }
  268. else {
  269. size_t ret = conn->socketToClient->read(buffer, size*nitems);
  270. if (ret <= 0) return 0;
  271. conn->content_length = chunkSize - ret;
  272. return ret;
  273. }
  274. }
  275. else if (conn->content_length) {
  276. size_t bytesToRead = conn->content_length;
  277. if (size*nitems < conn->content_length) bytesToRead = size*nitems;
  278. size_t ret = conn->socketToClient->read(buffer, bytesToRead);
  279. conn->content_length -= ret;
  280. return ret;
  281. }
  282. return 0;
  283. }
  284. static void sendBasicHeaders(int respCode, const char *respMsg, IBBS2chProxySocket *socket)
  285. {
  286. char date[256];
  287. time_t now = time(0);
  288. strftime(date, 256, httpTimestampFmt, gmtime(&now));
  289. std::ostringstream ss;
  290. ss << "HTTP/1.1 " << respCode << " " << respMsg << "\r\n";
  291. if(0 >= socket->writeString(ss.str())) return;
  292. if(0 >= socket->writeString("Connection: Close\r\n")) return;
  293. if(0 >= socket->writeString("Server: 2ch Proxy\r\n")) return;
  294. if(0 >= socket->writeString(std::string("Date: ") + date + "\r\n")) return;
  295. }
  296. static void sendResponse(int respCode, const char *respMsg, IBBS2chProxySocket *socket)
  297. {
  298. sendBasicHeaders(respCode, respMsg, socket);
  299. if(0 >= socket->writeString("Content-Type: text/plain; charset=UTF-8\r\n")) return;
  300. if(0 >= socket->writeString("\r\n")) return;
  301. if(respCode >= 400) {
  302. if(0 >= socket->writeString("   ∧_∧   / ̄ ̄ ̄ ̄ ̄\n")) return;
  303. if(0 >= socket->writeString(std::string("  ( ´∀`)< ") + respMsg + "\n")) return;
  304. if(0 >= socket->writeString("  (    ) \_____\n")) return;
  305. if(0 >= socket->writeString("   │ │ │\n")) return;
  306. if(0 >= socket->writeString("  (__)_)\n")) return;
  307. }
  308. }
  309. static double getCurrentTime(void)
  310. {
  311. #ifdef _WIN32
  312. FILETIME ft;
  313. GetSystemTimeAsFileTime(&ft);
  314. unsigned long long now = ft.dwHighDateTime;
  315. now <<= 32;
  316. now |= ft.dwLowDateTime;
  317. return (double)(now * 1e-7 - 11644473600.0);
  318. #else
  319. struct timeval tv;
  320. gettimeofday(&tv, NULL);
  321. return (double)(tv.tv_sec + tv.tv_usec * 1e-6);
  322. #endif
  323. }
  324. static std::string decodeURIComponent(const char *input, size_t inputLength, bool decodePlus)
  325. {
  326. std::string output;
  327. for (int i=0;i<inputLength;i++) {
  328. if (input[i] == '%') {
  329. if (i < inputLength - 2) {
  330. char from[3];
  331. char *end;
  332. from[0] = input[i+1];
  333. from[1] = input[i+2];
  334. from[2] = 0;
  335. unsigned long n = strtoul(from, &end, 16);
  336. if (n < 256 && end == from+2) {
  337. output.append(1, n);
  338. i += 2;
  339. continue;
  340. }
  341. }
  342. }
  343. else if (decodePlus && input[i] == '+') {
  344. output.append(" ");
  345. continue;
  346. }
  347. output.append(1, input[i]);
  348. }
  349. return output;
  350. }
  351. static std::string encodeURIComponent(const char *input, size_t inputLength, bool spaceAsPlus)
  352. {
  353. std::string output;
  354. for (int i=0;i<inputLength;i++) {
  355. unsigned char c = (unsigned char)input[i];
  356. if ((c >= '0' && c <= '9') ||
  357. (c >= 'A' && c <= 'Z') ||
  358. (c >= 'a' && c <= 'z') ||
  359. (c == '*') || (c == '-') || (c == '.') || (c == '_')) {
  360. output.append(1, c);
  361. }
  362. else if (c == ' ' && spaceAsPlus) {
  363. output.append("+");
  364. }
  365. else {
  366. char percentEncoded[4];
  367. snprintf(percentEncoded, 4, "%%%02X", c);
  368. output.append(percentEncoded);
  369. }
  370. }
  371. return output;
  372. }
  373. static bool isValidAsUTF8(const char *input, size_t inputLength) {
  374. for (int i=0; i<inputLength; i++) {
  375. unsigned char c1 = input[i];
  376. if (c1 < 0x80) continue;
  377. else if (c1 >= 0xc2 && c1 <= 0xdf) {
  378. if (i >= inputLength - 1) return false;
  379. unsigned char c2 = input[++i];
  380. if (c2 < 0x80 || c2 > 0xbf) return false;
  381. unsigned int unicode = c2 & 0xf;
  382. unicode |= (((c2 >> 4) & 0x3) | ((c1 & 0x3) << 2)) << 4;
  383. unicode |= ((c1 >> 2) & 0x7) << 8;
  384. if (unicode < 0x80 || unicode > 0x7ff) return false;
  385. }
  386. else if (c1 >= 0xe0 && c1 <= 0xef) {
  387. if (i >= inputLength - 2) return false;
  388. unsigned char c2 = input[++i];
  389. if (c2 < 0x80 || c2 > 0xbf) return false;
  390. unsigned char c3 = input[++i];
  391. if (c3 < 0x80 || c3 > 0xbf) return false;
  392. unsigned int unicode = c3 & 0xf;
  393. unicode |= (((c3 >> 4) & 0x3) | ((c2 & 0x3) << 2)) << 4;
  394. unicode |= ((c2 >> 2) & 0xf) << 8;
  395. unicode |= (c1 & 0xf) << 12;
  396. if (unicode < 0x800 || unicode > 0xffff) return false;
  397. else if (unicode >= 0xd800 && unicode <= 0xdfff) return false; /* for surrogate pairs */
  398. }
  399. else if (c1 >= 0xf0 && c1 <= 0xf7) {
  400. if (i >= inputLength - 3) return false;
  401. unsigned char c2 = input[++i];
  402. if (c2 < 0x80 || c2 > 0xbf) return false;
  403. unsigned char c3 = input[++i];
  404. if (c3 < 0x80 || c3 > 0xbf) return false;
  405. unsigned char c4 = input[++i];
  406. if (c4 < 0x80 || c4 > 0xbf) return false;
  407. unsigned int unicode = c4 & 0xf;
  408. unicode |= (((c4 >> 4) & 0x3) | ((c3 & 0x3) << 2)) << 4;
  409. unicode |= ((c3 >> 2) & 0xf) << 8;
  410. unicode |= (c2 & 0xf) << 12;
  411. unicode |= (((c2 >> 4) & 0x3) | ((c1 & 0x3) << 2)) << 16;
  412. unicode |= ((c1 >> 2) & 0x1) << 20;
  413. if (unicode < 0x10000 || unicode > 0x10ffff) return false;
  414. }
  415. }
  416. return true;
  417. }
  418. static void appendPostSignature(const char *body, const std::string &userAgent, const std::string &monaKey, BBS2chProxyHttpHeaders *headers)
  419. {
  420. std::map<std::string, std::string> fields;
  421. const char *ptr = body;
  422. while (1) {
  423. const char *tmp = ptr;
  424. while (*tmp != '=' && *tmp != 0) tmp++;
  425. if (*tmp == 0) break;
  426. std::string key(ptr, tmp-ptr);
  427. tmp++;
  428. ptr = tmp;
  429. while (*tmp != '&' && *tmp != 0) tmp++;
  430. std::string deocdedValue = decodeURIComponent(ptr, tmp-ptr, true);
  431. fields.insert(std::make_pair(key, deocdedValue));
  432. if (*tmp == 0) break;
  433. ptr = tmp + 1;
  434. }
  435. char nonce[32];
  436. snprintf(nonce, 32, "%.3f", getCurrentTime());
  437. std::string message;
  438. message.append(fields["bbs"]);
  439. message.append("<>");
  440. message.append(fields["key"]);
  441. message.append("<>");
  442. message.append(fields["time"]);
  443. message.append("<>");
  444. message.append(fields["FROM"]);
  445. message.append("<>");
  446. message.append(fields["mail"]);
  447. message.append("<>");
  448. message.append(fields["MESSAGE"]);
  449. message.append("<>");
  450. message.append(fields["subject"]);
  451. message.append("<>");
  452. message.append(userAgent);
  453. message.append("<>");
  454. message.append(monaKey);
  455. message.append("<>");
  456. message.append("<>");
  457. message.append(nonce);
  458. unsigned char digest[32];
  459. char digestStr[65];
  460. static const char *table = "0123456789abcdef";
  461. proxy2ch_HMAC_SHA256(hmacKey, strlen(hmacKey), message.data(), message.length(), digest);
  462. for (int i=0; i<32; i++) {
  463. unsigned char c = digest[i];
  464. unsigned char upper = (c >> 4) & 0xf;
  465. unsigned char lower = c & 0xf;
  466. digestStr[i*2] = table[upper];
  467. digestStr[i*2+1] = table[lower];
  468. }
  469. digestStr[64] = 0;
  470. headers->set("X-APIKey", appKey);
  471. log_printf(1, "Appended header \"X-APIKey: %s\"\n", appKey);
  472. headers->set("X-PostSig", digestStr);
  473. log_printf(1, "Appended header \"X-PostSig: %s\"\n", digestStr);
  474. headers->set("X-PostNonce", nonce);
  475. log_printf(1, "Appended header \"X-PostNonce: %s\"\n", nonce);
  476. headers->set("X-MonaKey", monaKey);
  477. log_printf(1, "Appended header \"X-MonaKey: %s\"\n", monaKey.c_str());
  478. }
  479. static std::string convertBodyToUTF8(const char *body)
  480. {
  481. std::string newBody;
  482. bool shouldConvertToUTF8 = true;
  483. bool shouldCheckWholeBody = true;
  484. const char *ptr = strstr(body, "submit=");
  485. if (ptr && (ptr == body || *(ptr-1) == '&')) {
  486. ptr += 7;
  487. const char *start = ptr;
  488. while (*ptr != '&' && *ptr != 0) ptr++;
  489. std::string decoded = decodeURIComponent(start, ptr-start, true);
  490. if (decoded.length() != (ptr-start)) {
  491. if (isValidAsUTF8(decoded.data(), decoded.length())) {
  492. shouldConvertToUTF8 = false;
  493. }
  494. shouldCheckWholeBody = false;
  495. }
  496. }
  497. if (shouldCheckWholeBody) {
  498. std::string decoded = decodeURIComponent(body, strlen(body), true);
  499. if (isValidAsUTF8(decoded.data(), decoded.length())) {
  500. shouldConvertToUTF8 = false;
  501. }
  502. }
  503. if (shouldConvertToUTF8) {
  504. ptr = body;
  505. while (1) {
  506. const char *tmp = ptr;
  507. while (*tmp != '=' && *tmp != 0) tmp++;
  508. if (*tmp == 0) break;
  509. std::string key(ptr, tmp-ptr);
  510. tmp++;
  511. ptr = tmp;
  512. while (*tmp != '&' && *tmp != 0) tmp++;
  513. std::string deocdedValue = decodeURIComponent(ptr, tmp-ptr, true);
  514. if (!deocdedValue.empty()) {
  515. char *converted = convertShiftJISToUTF8(deocdedValue.data(), deocdedValue.length());
  516. if (converted) {
  517. deocdedValue = std::string(converted);
  518. free(converted);
  519. }
  520. }
  521. if (!newBody.empty()) newBody.append("&");
  522. newBody.append(key);
  523. newBody.append("=");
  524. newBody.append(encodeURIComponent(deocdedValue.data(), deocdedValue.length(), true));
  525. if (*tmp == 0) break;
  526. ptr = tmp + 1;
  527. }
  528. }
  529. return newBody;
  530. }
  531. #ifdef _WIN32
  532. const char * strp_weekdays[] =
  533. { "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"};
  534. const char * strp_monthnames[] =
  535. { "january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"};
  536. bool strp_atoi(const char * & s, int & result, int low, int high, int offset)
  537. {
  538. bool worked = false;
  539. char * end;
  540. unsigned long num = strtoul(s, & end, 10);
  541. if (num >= (unsigned long)low && num <= (unsigned long)high)
  542. {
  543. result = (int)(num + offset);
  544. s = end;
  545. worked = true;
  546. }
  547. return worked;
  548. }
  549. char * strptime(const char *s, const char *format, struct tm *tm)
  550. {
  551. bool working = true;
  552. while (working && *format && *s)
  553. {
  554. switch (*format)
  555. {
  556. case '%':
  557. {
  558. ++format;
  559. switch (*format)
  560. {
  561. case 'a':
  562. case 'A': // weekday name
  563. tm->tm_wday = -1;
  564. working = false;
  565. for (size_t i = 0; i < 7; ++ i)
  566. {
  567. size_t len = strlen(strp_weekdays[i]);
  568. if (!strnicmp(strp_weekdays[i], s, len))
  569. {
  570. tm->tm_wday = i;
  571. s += len;
  572. working = true;
  573. break;
  574. }
  575. else if (!strnicmp(strp_weekdays[i], s, 3))
  576. {
  577. tm->tm_wday = i;
  578. s += 3;
  579. working = true;
  580. break;
  581. }
  582. }
  583. break;
  584. case 'b':
  585. case 'B':
  586. case 'h': // month name
  587. tm->tm_mon = -1;
  588. working = false;
  589. for (size_t i = 0; i < 12; ++ i)
  590. {
  591. size_t len = strlen(strp_monthnames[i]);
  592. if (!strnicmp(strp_monthnames[i], s, len))
  593. {
  594. tm->tm_mon = i;
  595. s += len;
  596. working = true;
  597. break;
  598. }
  599. else if (!strnicmp(strp_monthnames[i], s, 3))
  600. {
  601. tm->tm_mon = i;
  602. s += 3;
  603. working = true;
  604. break;
  605. }
  606. }
  607. break;
  608. case 'd':
  609. case 'e': // day of month number
  610. working = strp_atoi(s, tm->tm_mday, 1, 31, 0);
  611. break;
  612. case 'D': // %m/%d/%y
  613. {
  614. const char * s_save = s;
  615. working = strp_atoi(s, tm->tm_mon, 1, 12, -1);
  616. if (working && *s == '/')
  617. {
  618. ++ s;
  619. working = strp_atoi(s, tm->tm_mday, 1, 31, 0);
  620. if (working && *s == '/')
  621. {
  622. ++ s;
  623. working = strp_atoi(s, tm->tm_year, 0, 99, 0);
  624. if (working && tm->tm_year < 69)
  625. tm->tm_year += 100;
  626. }
  627. }
  628. if (!working)
  629. s = s_save;
  630. }
  631. break;
  632. case 'H': // hour
  633. working = strp_atoi(s, tm->tm_hour, 0, 23, 0);
  634. break;
  635. case 'I': // hour 12-hour clock
  636. working = strp_atoi(s, tm->tm_hour, 1, 12, 0);
  637. break;
  638. case 'j': // day number of year
  639. working = strp_atoi(s, tm->tm_yday, 1, 366, -1);
  640. break;
  641. case 'm': // month number
  642. working = strp_atoi(s, tm->tm_mon, 1, 12, -1);
  643. break;
  644. case 'M': // minute
  645. working = strp_atoi(s, tm->tm_min, 0, 59, 0);
  646. break;
  647. case 'n': // arbitrary whitespace
  648. case 't':
  649. while (isspace((int)*s))
  650. ++s;
  651. break;
  652. case 'p': // am / pm
  653. if (!strnicmp(s, "am", 2))
  654. { // the hour will be 1 -> 12 maps to 12 am, 1 am .. 11 am, 12 noon 12 pm .. 11 pm
  655. if (tm->tm_hour == 12) // 12 am == 00 hours
  656. tm->tm_hour = 0;
  657. }
  658. else if (!strnicmp(s, "pm", 2))
  659. {
  660. if (tm->tm_hour < 12) // 12 pm == 12 hours
  661. tm->tm_hour += 12; // 1 pm -> 13 hours, 11 pm -> 23 hours
  662. }
  663. else
  664. working = false;
  665. break;
  666. case 'r': // 12 hour clock %I:%M:%S %p
  667. {
  668. const char * s_save = s;
  669. working = strp_atoi(s, tm->tm_hour, 1, 12, 0);
  670. if (working && *s == ':')
  671. {
  672. ++ s;
  673. working = strp_atoi(s, tm->tm_min, 0, 59, 0);
  674. if (working && *s == ':')
  675. {
  676. ++ s;
  677. working = strp_atoi(s, tm->tm_sec, 0, 60, 0);
  678. if (working && isspace((int)*s))
  679. {
  680. ++ s;
  681. while (isspace((int)*s))
  682. ++s;
  683. if (!strnicmp(s, "am", 2))
  684. { // the hour will be 1 -> 12 maps to 12 am, 1 am .. 11 am, 12 noon 12 pm .. 11 pm
  685. if (tm->tm_hour == 12) // 12 am == 00 hours
  686. tm->tm_hour = 0;
  687. }
  688. else if (!strnicmp(s, "pm", 2))
  689. {
  690. if (tm->tm_hour < 12) // 12 pm == 12 hours
  691. tm->tm_hour += 12; // 1 pm -> 13 hours, 11 pm -> 23 hours
  692. }
  693. else
  694. working = false;
  695. }
  696. }
  697. }
  698. if (!working)
  699. s = s_save;
  700. }
  701. break;
  702. case 'R': // %H:%M
  703. {
  704. const char * s_save = s;
  705. working = strp_atoi(s, tm->tm_hour, 0, 23, 0);
  706. if (working && *s == ':')
  707. {
  708. ++ s;
  709. working = strp_atoi(s, tm->tm_min, 0, 59, 0);
  710. }
  711. if (!working)
  712. s = s_save;
  713. }
  714. break;
  715. case 'S': // seconds
  716. working = strp_atoi(s, tm->tm_sec, 0, 60, 0);
  717. break;
  718. case 'T': // %H:%M:%S
  719. {
  720. const char * s_save = s;
  721. working = strp_atoi(s, tm->tm_hour, 0, 23, 0);
  722. if (working && *s == ':')
  723. {
  724. ++ s;
  725. working = strp_atoi(s, tm->tm_min, 0, 59, 0);
  726. if (working && *s == ':')
  727. {
  728. ++ s;
  729. working = strp_atoi(s, tm->tm_sec, 0, 60, 0);
  730. }
  731. }
  732. if (!working)
  733. s = s_save;
  734. }
  735. break;
  736. case 'w': // weekday number 0->6 sunday->saturday
  737. working = strp_atoi(s, tm->tm_wday, 0, 6, 0);
  738. break;
  739. case 'Y': // year
  740. working = strp_atoi(s, tm->tm_year, 1900, 65535, -1900);
  741. break;
  742. case 'y': // 2-digit year
  743. working = strp_atoi(s, tm->tm_year, 0, 99, 0);
  744. if (working && tm->tm_year < 69)
  745. tm->tm_year += 100;
  746. break;
  747. case '%': // escaped
  748. if (*s != '%')
  749. working = false;
  750. ++s;
  751. break;
  752. default:
  753. working = false;
  754. }
  755. }
  756. break;
  757. case ' ':
  758. case '\t':
  759. case '\r':
  760. case '\n':
  761. case '\f':
  762. case '\v':
  763. // zero or more whitespaces:
  764. while (isspace((int)*s))
  765. ++ s;
  766. break;
  767. default:
  768. // match character
  769. if (*s != *format)
  770. working = false;
  771. else
  772. ++s;
  773. break;
  774. }
  775. ++format;
  776. }
  777. return (working?(char *)s:0);
  778. }
  779. #endif