utils.h 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  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 && strstr(buffer+19,"chunked")) {
  74. conn->chunked = 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 && strstr(buffer+19,"chunked")) {
  155. conn->chunked = 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->chunked) {
  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->chunked) 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 std::string appendPostSignature(char *body, const std::string &userAgent, const std::string &monaKey, BBS2chProxyHttpHeaders *headers)
  374. {
  375. bool shouldConvertToUTF8 = true;
  376. std::string newBody;
  377. if (headers->has("Content-Type")) {
  378. std::string contentType = headers->get("Content-Type");
  379. std::string tmp = contentType;
  380. std::transform(contentType.begin(), contentType.end(), tmp.begin(), tolower);
  381. if (tmp.find("charset=utf-8") != std::string::npos) {
  382. shouldConvertToUTF8 = false;
  383. }
  384. }
  385. std::map<std::string, std::string> fields;
  386. const char *ptr = body;
  387. while (1) {
  388. const char *tmp = ptr;
  389. while (*tmp != '=' && *tmp != 0) tmp++;
  390. if (*tmp == 0) break;
  391. std::string key(ptr, tmp-ptr);
  392. tmp++;
  393. ptr = tmp;
  394. while (*tmp != '&' && *tmp != 0) tmp++;
  395. std::string deocdedValue = decodeURIComponent(ptr, tmp-ptr, true);
  396. if (shouldConvertToUTF8) {
  397. if (!deocdedValue.empty()) {
  398. char *converted = convertShiftJISToUTF8(deocdedValue.data(), deocdedValue.length());
  399. if (converted) {
  400. deocdedValue = std::string(converted);
  401. free(converted);
  402. }
  403. }
  404. if (!newBody.empty()) newBody.append("&");
  405. newBody.append(key);
  406. newBody.append("=");
  407. newBody.append(encodeURIComponent(deocdedValue.data(), deocdedValue.length(), true));
  408. }
  409. fields.insert(std::make_pair(key, deocdedValue));
  410. if (*tmp == 0) break;
  411. ptr = tmp + 1;
  412. }
  413. char nonce[32];
  414. snprintf(nonce, 32, "%.3f", getCurrentTime());
  415. std::string message;
  416. message.append(fields["bbs"]);
  417. message.append("<>");
  418. message.append(fields["key"]);
  419. message.append("<>");
  420. message.append(fields["time"]);
  421. message.append("<>");
  422. message.append(fields["FROM"]);
  423. message.append("<>");
  424. message.append(fields["mail"]);
  425. message.append("<>");
  426. message.append(fields["MESSAGE"]);
  427. message.append("<>");
  428. message.append(fields["subject"]);
  429. message.append("<>");
  430. message.append(userAgent);
  431. message.append("<>");
  432. message.append(monaKey);
  433. message.append("<>");
  434. message.append("<>");
  435. message.append(nonce);
  436. unsigned char digest[32];
  437. char digestStr[65];
  438. static const char *table = "0123456789abcdef";
  439. proxy2ch_HMAC_SHA256(hmacKey, strlen(hmacKey), message.data(), message.length(), digest);
  440. for (int i=0; i<32; i++) {
  441. unsigned char c = digest[i];
  442. unsigned char upper = (c >> 4) & 0xf;
  443. unsigned char lower = c & 0xf;
  444. digestStr[i*2] = table[upper];
  445. digestStr[i*2+1] = table[lower];
  446. }
  447. digestStr[64] = 0;
  448. headers->set("X-APIKey", appKey);
  449. log_printf(1, "Appended header \"X-APIKey: %s\"\n", appKey);
  450. headers->set("X-PostSig", digestStr);
  451. log_printf(1, "Appended header \"X-PostSig: %s\"\n", digestStr);
  452. headers->set("X-PostNonce", nonce);
  453. log_printf(1, "Appended header \"X-PostNonce: %s\"\n", nonce);
  454. headers->set("X-MonaKey", monaKey);
  455. log_printf(1, "Appended header \"X-MonaKey: %s\"\n", monaKey.c_str());
  456. return newBody;
  457. }
  458. #ifdef _WIN32
  459. const char * strp_weekdays[] =
  460. { "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"};
  461. const char * strp_monthnames[] =
  462. { "january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"};
  463. bool strp_atoi(const char * & s, int & result, int low, int high, int offset)
  464. {
  465. bool worked = false;
  466. char * end;
  467. unsigned long num = strtoul(s, & end, 10);
  468. if (num >= (unsigned long)low && num <= (unsigned long)high)
  469. {
  470. result = (int)(num + offset);
  471. s = end;
  472. worked = true;
  473. }
  474. return worked;
  475. }
  476. char * strptime(const char *s, const char *format, struct tm *tm)
  477. {
  478. bool working = true;
  479. while (working && *format && *s)
  480. {
  481. switch (*format)
  482. {
  483. case '%':
  484. {
  485. ++format;
  486. switch (*format)
  487. {
  488. case 'a':
  489. case 'A': // weekday name
  490. tm->tm_wday = -1;
  491. working = false;
  492. for (size_t i = 0; i < 7; ++ i)
  493. {
  494. size_t len = strlen(strp_weekdays[i]);
  495. if (!strnicmp(strp_weekdays[i], s, len))
  496. {
  497. tm->tm_wday = i;
  498. s += len;
  499. working = true;
  500. break;
  501. }
  502. else if (!strnicmp(strp_weekdays[i], s, 3))
  503. {
  504. tm->tm_wday = i;
  505. s += 3;
  506. working = true;
  507. break;
  508. }
  509. }
  510. break;
  511. case 'b':
  512. case 'B':
  513. case 'h': // month name
  514. tm->tm_mon = -1;
  515. working = false;
  516. for (size_t i = 0; i < 12; ++ i)
  517. {
  518. size_t len = strlen(strp_monthnames[i]);
  519. if (!strnicmp(strp_monthnames[i], s, len))
  520. {
  521. tm->tm_mon = i;
  522. s += len;
  523. working = true;
  524. break;
  525. }
  526. else if (!strnicmp(strp_monthnames[i], s, 3))
  527. {
  528. tm->tm_mon = i;
  529. s += 3;
  530. working = true;
  531. break;
  532. }
  533. }
  534. break;
  535. case 'd':
  536. case 'e': // day of month number
  537. working = strp_atoi(s, tm->tm_mday, 1, 31, 0);
  538. break;
  539. case 'D': // %m/%d/%y
  540. {
  541. const char * s_save = s;
  542. working = strp_atoi(s, tm->tm_mon, 1, 12, -1);
  543. if (working && *s == '/')
  544. {
  545. ++ s;
  546. working = strp_atoi(s, tm->tm_mday, 1, 31, 0);
  547. if (working && *s == '/')
  548. {
  549. ++ s;
  550. working = strp_atoi(s, tm->tm_year, 0, 99, 0);
  551. if (working && tm->tm_year < 69)
  552. tm->tm_year += 100;
  553. }
  554. }
  555. if (!working)
  556. s = s_save;
  557. }
  558. break;
  559. case 'H': // hour
  560. working = strp_atoi(s, tm->tm_hour, 0, 23, 0);
  561. break;
  562. case 'I': // hour 12-hour clock
  563. working = strp_atoi(s, tm->tm_hour, 1, 12, 0);
  564. break;
  565. case 'j': // day number of year
  566. working = strp_atoi(s, tm->tm_yday, 1, 366, -1);
  567. break;
  568. case 'm': // month number
  569. working = strp_atoi(s, tm->tm_mon, 1, 12, -1);
  570. break;
  571. case 'M': // minute
  572. working = strp_atoi(s, tm->tm_min, 0, 59, 0);
  573. break;
  574. case 'n': // arbitrary whitespace
  575. case 't':
  576. while (isspace((int)*s))
  577. ++s;
  578. break;
  579. case 'p': // am / pm
  580. if (!strnicmp(s, "am", 2))
  581. { // the hour will be 1 -> 12 maps to 12 am, 1 am .. 11 am, 12 noon 12 pm .. 11 pm
  582. if (tm->tm_hour == 12) // 12 am == 00 hours
  583. tm->tm_hour = 0;
  584. }
  585. else if (!strnicmp(s, "pm", 2))
  586. {
  587. if (tm->tm_hour < 12) // 12 pm == 12 hours
  588. tm->tm_hour += 12; // 1 pm -> 13 hours, 11 pm -> 23 hours
  589. }
  590. else
  591. working = false;
  592. break;
  593. case 'r': // 12 hour clock %I:%M:%S %p
  594. {
  595. const char * s_save = s;
  596. working = strp_atoi(s, tm->tm_hour, 1, 12, 0);
  597. if (working && *s == ':')
  598. {
  599. ++ s;
  600. working = strp_atoi(s, tm->tm_min, 0, 59, 0);
  601. if (working && *s == ':')
  602. {
  603. ++ s;
  604. working = strp_atoi(s, tm->tm_sec, 0, 60, 0);
  605. if (working && isspace((int)*s))
  606. {
  607. ++ s;
  608. while (isspace((int)*s))
  609. ++s;
  610. if (!strnicmp(s, "am", 2))
  611. { // the hour will be 1 -> 12 maps to 12 am, 1 am .. 11 am, 12 noon 12 pm .. 11 pm
  612. if (tm->tm_hour == 12) // 12 am == 00 hours
  613. tm->tm_hour = 0;
  614. }
  615. else if (!strnicmp(s, "pm", 2))
  616. {
  617. if (tm->tm_hour < 12) // 12 pm == 12 hours
  618. tm->tm_hour += 12; // 1 pm -> 13 hours, 11 pm -> 23 hours
  619. }
  620. else
  621. working = false;
  622. }
  623. }
  624. }
  625. if (!working)
  626. s = s_save;
  627. }
  628. break;
  629. case 'R': // %H:%M
  630. {
  631. const char * s_save = s;
  632. working = strp_atoi(s, tm->tm_hour, 0, 23, 0);
  633. if (working && *s == ':')
  634. {
  635. ++ s;
  636. working = strp_atoi(s, tm->tm_min, 0, 59, 0);
  637. }
  638. if (!working)
  639. s = s_save;
  640. }
  641. break;
  642. case 'S': // seconds
  643. working = strp_atoi(s, tm->tm_sec, 0, 60, 0);
  644. break;
  645. case 'T': // %H:%M:%S
  646. {
  647. const char * s_save = s;
  648. working = strp_atoi(s, tm->tm_hour, 0, 23, 0);
  649. if (working && *s == ':')
  650. {
  651. ++ s;
  652. working = strp_atoi(s, tm->tm_min, 0, 59, 0);
  653. if (working && *s == ':')
  654. {
  655. ++ s;
  656. working = strp_atoi(s, tm->tm_sec, 0, 60, 0);
  657. }
  658. }
  659. if (!working)
  660. s = s_save;
  661. }
  662. break;
  663. case 'w': // weekday number 0->6 sunday->saturday
  664. working = strp_atoi(s, tm->tm_wday, 0, 6, 0);
  665. break;
  666. case 'Y': // year
  667. working = strp_atoi(s, tm->tm_year, 1900, 65535, -1900);
  668. break;
  669. case 'y': // 2-digit year
  670. working = strp_atoi(s, tm->tm_year, 0, 99, 0);
  671. if (working && tm->tm_year < 69)
  672. tm->tm_year += 100;
  673. break;
  674. case '%': // escaped
  675. if (*s != '%')
  676. working = false;
  677. ++s;
  678. break;
  679. default:
  680. working = false;
  681. }
  682. }
  683. break;
  684. case ' ':
  685. case '\t':
  686. case '\r':
  687. case '\n':
  688. case '\f':
  689. case '\v':
  690. // zero or more whitespaces:
  691. while (isspace((int)*s))
  692. ++ s;
  693. break;
  694. default:
  695. // match character
  696. if (*s != *format)
  697. working = false;
  698. else
  699. ++s;
  700. break;
  701. }
  702. ++format;
  703. }
  704. return (working?(char *)s:0);
  705. }
  706. #endif