HttpHelper.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832
  1. /*
  2. * Copyright: JessMA Open Source (ldcsaa@gmail.com)
  3. *
  4. * Version : 4.2.1
  5. * Author : Bruce Liang
  6. * Website : http://www.jessma.org
  7. * Project : https://github.com/ldcsaa
  8. * Blog : http://www.cnblogs.com/ldcsaa
  9. * Wiki : http://www.oschina.net/p/hp-socket
  10. * QQ Group : 75375912
  11. *
  12. * Licensed under the Apache License, Version 2.0 (the "License");
  13. * you may not use this file except in compliance with the License.
  14. * You may obtain a copy of the License at
  15. *
  16. * http://www.apache.org/licenses/LICENSE-2.0
  17. *
  18. * Unless required by applicable law or agreed to in writing, software
  19. * distributed under the License is distributed on an "AS IS" BASIS,
  20. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21. * See the License for the specific language governing permissions and
  22. * limitations under the License.
  23. */
  24. #include "stdafx.h"
  25. #include "HttpHelper.h"
  26. ///////////////////////////////////////////////////////////////////////////////////////////////////////
  27. CStringA& GetHttpVersionStr(EnHttpVersion enVersion, CStringA& strResult)
  28. {
  29. strResult.Format("HTTP/%d.%d", LOBYTE(enVersion), HIBYTE(enVersion));
  30. return strResult;
  31. }
  32. CStringA& AdjustRequestPath(LPCSTR lpszPath, CStringA& strPath)
  33. {
  34. strPath = lpszPath;
  35. if(strPath.IsEmpty() || strPath.GetAt(0) != HTTP_PATH_SEPARATOR_CHAR)
  36. strPath.Insert(0, HTTP_PATH_SEPARATOR_CHAR);
  37. return strPath;
  38. }
  39. LPCSTR GetHttpDefaultStatusCodeDesc(EnHttpStatusCode enCode)
  40. {
  41. switch(enCode)
  42. {
  43. case HSC_CONTINUE : return "Continue";
  44. case HSC_SWITCHING_PROTOCOLS : return "Switching Protocols";
  45. case HSC_PROCESSING : return "Processing";
  46. case HSC_OK : return "OK";
  47. case HSC_CREATED : return "Created";
  48. case HSC_ACCEPTED : return "Accepted";
  49. case HSC_NON_AUTHORITATIVE_INFORMATION : return "Non-Authoritative Information";
  50. case HSC_NO_CONTENT : return "No Content";
  51. case HSC_RESET_CONTENT : return "Reset Content";
  52. case HSC_PARTIAL_CONTENT : return "Partial Content";
  53. case HSC_MULTI_STATUS : return "Multi-Status";
  54. case HSC_ALREADY_REPORTED : return "Already Reported";
  55. case HSC_IM_USED : return "IM Used";
  56. case HSC_MULTIPLE_CHOICES : return "Multiple Choices";
  57. case HSC_MOVED_PERMANENTLY : return "Moved Permanently";
  58. case HSC_MOVED_TEMPORARILY : return "Move temporarily";
  59. case HSC_SEE_OTHER : return "See Other";
  60. case HSC_NOT_MODIFIED : return "Not Modified";
  61. case HSC_USE_PROXY : return "Use Proxy";
  62. case HSC_SWITCH_PROXY : return "Switch Proxy";
  63. case HSC_TEMPORARY_REDIRECT : return "Temporary Redirect";
  64. case HSC_PERMANENT_REDIRECT : return "Permanent Redirect";
  65. case HSC_BAD_REQUEST : return "Bad Request";
  66. case HSC_UNAUTHORIZED : return "Unauthorized";
  67. case HSC_PAYMENT_REQUIRED : return "Payment Required";
  68. case HSC_FORBIDDEN : return "Forbidden";
  69. case HSC_NOT_FOUND : return "Not Found";
  70. case HSC_METHOD_NOT_ALLOWED : return "Method Not Allowed";
  71. case HSC_NOT_ACCEPTABLE : return "Not Acceptable";
  72. case HSC_PROXY_AUTHENTICATION_REQUIRED : return "Proxy Authentication Required";
  73. case HSC_REQUEST_TIMEOUT : return "Request Timeout";
  74. case HSC_CONFLICT : return "Conflict";
  75. case HSC_GONE : return "Gone";
  76. case HSC_LENGTH_REQUIRED : return "Length Required";
  77. case HSC_PRECONDITION_FAILED : return "Precondition Failed";
  78. case HSC_REQUEST_ENTITY_TOO_LARGE : return "Request Entity Too Large";
  79. case HSC_REQUEST_URI_TOO_LONG : return "Request-URI Too Long";
  80. case HSC_UNSUPPORTED_MEDIA_TYPE : return "Unsupported Media Type";
  81. case HSC_REQUESTED_RANGE_NOT_SATISFIABLE: return "Requested Range Not Satisfiable";
  82. case HSC_EXPECTATION_FAILED : return "Expectation Failed";
  83. case HSC_MISDIRECTED_REQUEST : return "Misdirected Request";
  84. case HSC_UNPROCESSABLE_ENTITY : return "Unprocessable Entity";
  85. case HSC_LOCKED : return "Locked";
  86. case HSC_FAILED_DEPENDENCY : return "Failed Dependency";
  87. case HSC_UNORDERED_COLLECTION : return "Unordered Collection";
  88. case HSC_UPGRADE_REQUIRED : return "Upgrade Required";
  89. case HSC_PRECONDITION_REQUIRED : return "Precondition Required";
  90. case HSC_TOO_MANY_REQUESTS : return "Too Many Requests";
  91. case HSC_REQUEST_HEADER_FIELDS_TOO_LARGE: return "Request Header Fields Too Large";
  92. case HSC_UNAVAILABLE_FOR_LEGAL_REASONS : return "Unavailable For Legal Reasons";
  93. case HSC_RETRY_WITH : return "Retry With";
  94. case HSC_INTERNAL_SERVER_ERROR : return "Internal Server Error";
  95. case HSC_NOT_IMPLEMENTED : return "Not Implemented";
  96. case HSC_BAD_GATEWAY : return "Bad Gateway";
  97. case HSC_SERVICE_UNAVAILABLE : return "Service Unavailable";
  98. case HSC_GATEWAY_TIMEOUT : return "Gateway Timeout";
  99. case HSC_HTTP_VERSION_NOT_SUPPORTED : return "HTTP Version Not Supported";
  100. case HSC_VARIANT_ALSO_NEGOTIATES : return "Variant Also Negotiates";
  101. case HSC_INSUFFICIENT_STORAGE : return "Insufficient Storage";
  102. case HSC_LOOP_DETECTED : return "Loop Detected";
  103. case HSC_BANDWIDTH_LIMIT_EXCEEDED : return "Bandwidth Limit Exceeded";
  104. case HSC_NOT_EXTENDED : return "Not Extended";
  105. case HSC_NETWORK_AUTHENTICATION_REQUIRED: return "Network Authentication Required";
  106. case HSC_UNPARSEABLE_RESPONSE_HEADERS : return "Unparseable Response Headers";
  107. default : return "***";
  108. }
  109. }
  110. static inline CStringA& AppendHeader(LPCSTR lpszName, LPCSTR lpszValue, CStringA& strValue)
  111. {
  112. strValue.Append(lpszName);
  113. strValue.Append(HTTP_HEADER_SEPARATOR);
  114. strValue.Append(lpszValue);
  115. strValue.Append(HTTP_CRLF);
  116. return strValue;
  117. }
  118. void MakeRequestLine(LPCSTR lpszMethod, LPCSTR lpszPath, EnHttpVersion enVersion, CStringA& strValue)
  119. {
  120. ASSERT(lpszMethod);
  121. strValue.Format("%s %s HTTP/%d.%d%s", CStringA(lpszMethod).MakeUpper(), lpszPath, LOBYTE(enVersion), HIBYTE(enVersion), HTTP_CRLF);
  122. }
  123. void MakeStatusLine(EnHttpVersion enVersion, USHORT usStatusCode, LPCSTR lpszDesc, CStringA& strValue)
  124. {
  125. if(!lpszDesc) lpszDesc = ::GetHttpDefaultStatusCodeDesc((EnHttpStatusCode)usStatusCode);
  126. strValue.Format("HTTP/%d.%d %d %s%s", LOBYTE(enVersion), HIBYTE(enVersion), usStatusCode, lpszDesc, HTTP_CRLF);
  127. }
  128. void MakeHeaderLines(const THeader lpHeaders[], int iHeaderCount, const TCookieMap* pCookies, int iBodyLength, BOOL bRequest, int iConnFlag, LPCSTR lpszDefaultHost, USHORT usPort, CStringA& strValue)
  129. {
  130. unordered_set<LPCSTR, str_hash_func::hash, str_hash_func::equal_to> szHeaderNames;
  131. if(iHeaderCount > 0)
  132. {
  133. ASSERT(lpHeaders);
  134. for(int i = 0; i < iHeaderCount; i++)
  135. {
  136. const THeader& header = lpHeaders[i];
  137. if(header.name != nullptr)
  138. {
  139. ASSERT(strlen(header.name) > 0);
  140. szHeaderNames.emplace(header.name);
  141. AppendHeader(header.name, header.value, strValue);
  142. }
  143. }
  144. }
  145. if( (!bRequest || iBodyLength > 0) &&
  146. (szHeaderNames.empty() ||
  147. (szHeaderNames.find(HTTP_HEADER_CONTENT_LENGTH) == szHeaderNames.end() &&
  148. szHeaderNames.find(HTTP_HEADER_TRANSFER_ENCODING) == szHeaderNames.end())))
  149. {
  150. char szBodyLength[16];
  151. _itoa(iBodyLength, szBodyLength, 10);
  152. AppendHeader(HTTP_HEADER_CONTENT_LENGTH, szBodyLength, strValue);
  153. }
  154. if( (iConnFlag == 0 || iConnFlag == 1) &&
  155. (szHeaderNames.empty() ||
  156. szHeaderNames.find(HTTP_HEADER_CONNECTION) == szHeaderNames.end() ))
  157. {
  158. LPCSTR lpszValue = iConnFlag == 0 ? HTTP_CONNECTION_CLOSE_VALUE : HTTP_CONNECTION_KEEPALIVE_VALUE;
  159. AppendHeader(HTTP_HEADER_CONNECTION, lpszValue, strValue);
  160. }
  161. if( bRequest && lpszDefaultHost && lpszDefaultHost[0] != 0 &&
  162. (szHeaderNames.empty() ||
  163. (szHeaderNames.find(HTTP_HEADER_HOST) == szHeaderNames.end()) ))
  164. {
  165. CStringA strHost(lpszDefaultHost);
  166. if(usPort != 0) strHost.AppendFormat(":%u", usPort);
  167. AppendHeader(HTTP_HEADER_HOST, strHost, strValue);
  168. }
  169. szHeaderNames.clear();
  170. if(pCookies != nullptr)
  171. {
  172. DWORD dwSize = (DWORD)pCookies->size();
  173. if(dwSize > 0)
  174. {
  175. strValue.Append(HTTP_HEADER_COOKIE);
  176. strValue.Append(HTTP_HEADER_SEPARATOR);
  177. DWORD dwIndex = 0;
  178. for(TCookieMapCI it = pCookies->begin(), end = pCookies->end(); it != end; ++it, ++dwIndex)
  179. {
  180. strValue.Append(it->first);
  181. strValue.AppendChar(COOKIE_KV_SEP_CHAR);
  182. strValue.Append(it->second);
  183. if(dwIndex < dwSize - 1)
  184. strValue.Append(HTTP_COOKIE_SEPARATOR);
  185. }
  186. strValue.Append(HTTP_CRLF);
  187. }
  188. }
  189. strValue.Append(HTTP_CRLF);
  190. }
  191. void MakeHttpPacket(const CStringA& strHeader, const BYTE* pBody, int iLength, WSABUF szBuffer[2])
  192. {
  193. ASSERT(pBody != nullptr || iLength == 0);
  194. szBuffer[0].buf = (LPSTR)(LPCSTR)strHeader;
  195. szBuffer[0].len = strHeader.GetLength();
  196. szBuffer[1].buf = (LPSTR)(LPCSTR)pBody;
  197. szBuffer[1].len = iLength;
  198. }
  199. BOOL MakeWSPacket(BOOL bFinal, BYTE iReserved, BYTE iOperationCode, const BYTE lpszMask[4], BYTE* pData, int iLength, ULONGLONG ullBodyLen, BYTE szHeader[HTTP_MAX_WS_HEADER_LEN], WSABUF szBuffer[2])
  200. {
  201. ULONGLONG ullLength = (ULONGLONG)iLength;
  202. ASSERT(pData != nullptr || iLength == 0);
  203. ASSERT(ullBodyLen == 0 || ullBodyLen >= ullLength);
  204. if(ullBodyLen == 0)
  205. ullBodyLen = ullLength;
  206. else if(ullBodyLen < ullLength)
  207. {
  208. ::SetLastError(ERROR_INVALID_PARAMETER);
  209. return FALSE;
  210. }
  211. TBaseWSHeader bh(szHeader, TRUE);
  212. int iHeaderLen = HTTP_MIN_WS_HEADER_LEN;
  213. bh.set_fin(bFinal);
  214. bh.set_rsv(iReserved);
  215. bh.set_code(iOperationCode);
  216. bh.set_mask(lpszMask ? TRUE : FALSE);
  217. if(ullBodyLen < 126)
  218. bh.set_len((BYTE)ullBodyLen);
  219. else if(ullBodyLen <= 0xFFFF)
  220. {
  221. bh.set_len(126);
  222. bh.set_extlen((USHORT)ullBodyLen);
  223. iHeaderLen += 2;
  224. }
  225. else
  226. {
  227. bh.set_len(127);
  228. *(ULONGLONG*)(szHeader + HTTP_MIN_WS_HEADER_LEN) = ::HToN64(ullBodyLen);
  229. iHeaderLen += 8;
  230. }
  231. if(lpszMask)
  232. {
  233. memcpy(szHeader + iHeaderLen, lpszMask, 4);
  234. for(int i = 0; i < iLength; i++)
  235. pData[i] = pData[i] ^ lpszMask[i & 0x03];
  236. iHeaderLen += 4;
  237. }
  238. szBuffer[0].buf = (LPSTR)(LPCSTR)szHeader;
  239. szBuffer[0].len = iHeaderLen;
  240. szBuffer[1].buf = (LPSTR)(LPCSTR)pData;
  241. szBuffer[1].len = iLength;
  242. return TRUE;
  243. }
  244. BOOL ParseUrl(const CStringA& strUrl, BOOL& bHttps, CStringA& strHost, USHORT& usPort, CStringA& strPath)
  245. {
  246. int iSchemaLength = (int)strlen(HTTP_SCHEMA);
  247. CStringA strSchema = strUrl.Left(iSchemaLength);
  248. strSchema.MakeLower();
  249. if(strSchema.Compare(HTTP_SCHEMA) == 0)
  250. bHttps = FALSE;
  251. else
  252. {
  253. iSchemaLength = (int)strlen(HTTPS_SCHEMA);
  254. strSchema = strUrl.Left(iSchemaLength);
  255. strSchema.MakeLower();
  256. if(strSchema.Compare(HTTPS_SCHEMA) == 0)
  257. bHttps = TRUE;
  258. else
  259. return FALSE;
  260. }
  261. int i = strUrl.Find(HTTP_PATH_SEPARATOR_CHAR, iSchemaLength);
  262. if(i > 0)
  263. {
  264. strHost = strUrl.Mid(iSchemaLength, i - iSchemaLength);
  265. strPath = strUrl.Mid(i);
  266. }
  267. else
  268. {
  269. strHost = strUrl.Mid(iSchemaLength);
  270. strPath = HTTP_PATH_SEPARATOR;
  271. }
  272. if(strHost.IsEmpty() || !::isalnum(strHost.GetAt(0)))
  273. return FALSE;
  274. i = strHost.Find(HTTP_PORT_SEPARATOR_CHAR);
  275. if(i > 0)
  276. {
  277. CStringA strPort = strHost.Mid(i + 1);
  278. int iLength = strPort.GetLength();
  279. if(iLength == 0)
  280. return FALSE;
  281. for(int j = 0; j < iLength; j++)
  282. {
  283. if(!::isdigit(strPort.GetAt(j)))
  284. return FALSE;
  285. }
  286. usPort = (USHORT)::atoi(strPort);
  287. strHost = strHost.Mid(0, i);
  288. }
  289. else
  290. {
  291. usPort = bHttps ? HTTPS_DEFAULT_PORT : HTTP_DEFAULT_PORT;
  292. }
  293. return TRUE;
  294. }
  295. BOOL CodePageToUnicode(int iCodePage, const char szSrc[], WCHAR szDest[], int& iDestLength)
  296. {
  297. ASSERT(szSrc);
  298. int iSize = ::MultiByteToWideChar(iCodePage, 0, szSrc, -1, nullptr, 0);
  299. if(iSize == 0 || iSize > iDestLength || !szDest || iDestLength == 0)
  300. {
  301. iDestLength = iSize;
  302. return FALSE;
  303. }
  304. if(::MultiByteToWideChar(iCodePage, 0, szSrc, -1, szDest, iSize) != 0)
  305. iDestLength = iSize;
  306. else
  307. iDestLength = 0;
  308. return iDestLength != 0;
  309. }
  310. BOOL UnicodeToCodePage(int iCodePage, const WCHAR szSrc[], char szDest[], int& iDestLength)
  311. {
  312. ASSERT(szSrc);
  313. int iSize = ::WideCharToMultiByte(iCodePage, 0, szSrc, -1, nullptr, 0, nullptr, nullptr);
  314. if(iSize == 0 || iSize > iDestLength || !szDest || iDestLength == 0)
  315. {
  316. iDestLength = iSize;
  317. return FALSE;
  318. }
  319. if(::WideCharToMultiByte(iCodePage, 0, szSrc, -1, szDest, iSize, nullptr, nullptr) != 0)
  320. iDestLength = iSize;
  321. else
  322. iDestLength = 0;
  323. return iDestLength != 0;
  324. }
  325. BOOL GbkToUnicode(const char szSrc[], WCHAR szDest[], int& iDestLength)
  326. {
  327. return CodePageToUnicode(CP_ACP, szSrc, szDest, iDestLength);
  328. }
  329. BOOL UnicodeToGbk(const WCHAR szSrc[], char szDest[], int& iDestLength)
  330. {
  331. return UnicodeToCodePage(CP_ACP, szSrc, szDest, iDestLength);
  332. }
  333. BOOL Utf8ToUnicode(const char szSrc[], WCHAR szDest[], int& iDestLength)
  334. {
  335. return CodePageToUnicode(CP_UTF8, szSrc, szDest, iDestLength);
  336. }
  337. BOOL UnicodeToUtf8(const WCHAR szSrc[], char szDest[], int& iDestLength)
  338. {
  339. return UnicodeToCodePage(CP_UTF8, szSrc, szDest, iDestLength);
  340. }
  341. BOOL GbkToUtf8(const char szSrc[], char szDest[], int& iDestLength)
  342. {
  343. int iMiddleLength = 0;
  344. GbkToUnicode(szSrc, nullptr, iMiddleLength);
  345. if(iMiddleLength == 0)
  346. {
  347. iDestLength = 0;
  348. return FALSE;
  349. }
  350. unique_ptr<WCHAR[]> p(new WCHAR[iMiddleLength]);
  351. VERIFY(GbkToUnicode(szSrc, p.get(), iMiddleLength));
  352. return UnicodeToUtf8(p.get(), szDest, iDestLength);
  353. }
  354. BOOL Utf8ToGbk(const char szSrc[], char szDest[], int& iDestLength)
  355. {
  356. int iMiddleLength = 0;
  357. Utf8ToUnicode(szSrc, nullptr, iMiddleLength);
  358. if(iMiddleLength == 0)
  359. {
  360. iDestLength = 0;
  361. return FALSE;
  362. }
  363. unique_ptr<WCHAR[]> p(new WCHAR[iMiddleLength]);
  364. VERIFY(Utf8ToUnicode(szSrc, p.get(), iMiddleLength));
  365. return UnicodeToGbk(p.get(), szDest, iDestLength);
  366. }
  367. int Compress(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen)
  368. {
  369. return CompressEx(lpszSrc, dwSrcLen, lpszDest, dwDestLen);
  370. }
  371. int CompressEx(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen, int iLevel, int iMethod, int iWindowBits, int iMemLevel, int iStrategy)
  372. {
  373. z_stream stream;
  374. stream.next_in = (z_const Bytef*)lpszSrc;
  375. stream.avail_in = dwSrcLen;
  376. stream.next_out = lpszDest;
  377. stream.avail_out = dwDestLen;
  378. stream.zalloc = nullptr;
  379. stream.zfree = nullptr;
  380. stream.opaque = nullptr;
  381. int err = ::deflateInit2(&stream, iLevel, iMethod, iWindowBits, iMemLevel, iStrategy);
  382. if(err != Z_OK) return err;
  383. err = ::deflate(&stream, Z_FINISH);
  384. if(err != Z_STREAM_END)
  385. {
  386. ::deflateEnd(&stream);
  387. return err == Z_OK ? Z_BUF_ERROR : err;
  388. }
  389. if(dwDestLen > stream.total_out)
  390. {
  391. lpszDest[stream.total_out] = 0;
  392. dwDestLen = stream.total_out;
  393. }
  394. return ::deflateEnd(&stream);
  395. }
  396. int Uncompress(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen)
  397. {
  398. return UncompressEx(lpszSrc, dwSrcLen, lpszDest, dwDestLen);
  399. }
  400. int UncompressEx(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen, int iWindowBits)
  401. {
  402. z_stream stream;
  403. stream.next_in = (z_const Bytef*)lpszSrc;
  404. stream.avail_in = (uInt)dwSrcLen;
  405. stream.next_out = lpszDest;
  406. stream.avail_out = dwDestLen;
  407. stream.zalloc = nullptr;
  408. stream.zfree = nullptr;
  409. int err = ::inflateInit2(&stream, iWindowBits);
  410. if(err != Z_OK) return err;
  411. err = ::inflate(&stream, Z_FINISH);
  412. if(err != Z_STREAM_END)
  413. {
  414. ::inflateEnd(&stream);
  415. return (err == Z_NEED_DICT || (err == Z_BUF_ERROR && stream.avail_in == 0)) ? Z_DATA_ERROR : err;
  416. }
  417. if(dwDestLen > stream.total_out)
  418. {
  419. lpszDest[stream.total_out] = 0;
  420. dwDestLen = stream.total_out;
  421. }
  422. return inflateEnd(&stream);
  423. }
  424. DWORD GuessCompressBound(DWORD dwSrcLen, BOOL bGZip)
  425. {
  426. DWORD dwBound = ::compressBound(dwSrcLen);
  427. if(bGZip) dwBound += 11;
  428. return dwBound;
  429. }
  430. int GZipCompress(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen)
  431. {
  432. return CompressEx(lpszSrc, dwSrcLen, lpszDest, dwDestLen, Z_DEFAULT_COMPRESSION, Z_DEFLATED, MAX_WBITS + 16);
  433. }
  434. int GZipUncompress(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen)
  435. {
  436. return UncompressEx(lpszSrc, dwSrcLen, lpszDest, dwDestLen, MAX_WBITS + 32);
  437. }
  438. DWORD GZipGuessUncompressBound(const BYTE* lpszSrc, DWORD dwSrcLen)
  439. {
  440. if(dwSrcLen < 20 || *(USHORT*)lpszSrc != 0x8B1F)
  441. return 0;
  442. return *(DWORD*)(lpszSrc + dwSrcLen - 4);
  443. }
  444. DWORD GuessBase64EncodeBound(DWORD dwSrcLen)
  445. {
  446. return 4 * ((dwSrcLen + 2) / 3);
  447. }
  448. DWORD GuessBase64DecodeBound(const BYTE* lpszSrc, DWORD dwSrcLen)
  449. {
  450. if(dwSrcLen < 2)
  451. return 0;
  452. if(lpszSrc[dwSrcLen - 2] == '=')
  453. dwSrcLen -= 2;
  454. else if(lpszSrc[dwSrcLen - 1] == '=')
  455. --dwSrcLen;
  456. DWORD dwMod = dwSrcLen % 4;
  457. DWORD dwAdd = dwMod == 2 ? 1 : (dwMod == 3 ? 2 : 0);
  458. return 3 * (dwSrcLen / 4) + dwAdd;
  459. }
  460. int Base64Encode(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen)
  461. {
  462. static const BYTE CODES[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  463. DWORD dwRealLen = GuessBase64EncodeBound(dwSrcLen);
  464. if(lpszDest == nullptr || dwDestLen < dwRealLen)
  465. {
  466. dwDestLen = dwRealLen;
  467. return -5;
  468. }
  469. BYTE* p = lpszDest;
  470. DWORD leven = 3 * (dwSrcLen / 3);
  471. DWORD i = 0;
  472. for (; i < leven; i += 3)
  473. {
  474. *p++ = CODES[lpszSrc[0] >> 2];
  475. *p++ = CODES[((lpszSrc[0] & 3) << 4) + (lpszSrc[1] >> 4)];
  476. *p++ = CODES[((lpszSrc[1] & 0xf) << 2) + (lpszSrc[2] >> 6)];
  477. *p++ = CODES[lpszSrc[2] & 0x3f];
  478. lpszSrc += 3;
  479. }
  480. if(i < dwSrcLen)
  481. {
  482. BYTE a = lpszSrc[0];
  483. BYTE b = (i + 1 < dwSrcLen) ? lpszSrc[1] : 0;
  484. *p++ = CODES[a >> 2];
  485. *p++ = CODES[((a & 3) << 4) + (b >> 4)];
  486. *p++ = (i + 1 < dwSrcLen) ? CODES[((b & 0xf) << 2)] : '=';
  487. *p++ = '=';
  488. }
  489. ASSERT(dwRealLen == p - lpszDest);
  490. if(dwDestLen > dwRealLen)
  491. {
  492. *p = 0;
  493. dwDestLen = dwRealLen;
  494. }
  495. return 0;
  496. }
  497. int Base64Decode(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen)
  498. {
  499. static const BYTE MAP[256] =
  500. {
  501. 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 253, 255,
  502. 255, 253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  503. 255, 255, 255, 255, 255, 255, 255, 255, 253, 255, 255, 255,
  504. 255, 255, 255, 255, 255, 255, 255, 62, 255, 255, 255, 63,
  505. 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255,
  506. 255, 254, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6,
  507. 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
  508. 19, 20, 21, 22, 23, 24, 25, 255, 255, 255, 255, 255,
  509. 255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
  510. 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
  511. 49, 50, 51, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  512. 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  513. 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  514. 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  515. 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  516. 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  517. 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  518. 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  519. 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  520. 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  521. 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
  522. 255, 255, 255, 255
  523. };
  524. DWORD dwRealLen = GuessBase64DecodeBound(lpszSrc, dwSrcLen);
  525. if(lpszDest == nullptr || dwDestLen < dwRealLen)
  526. {
  527. dwDestLen = dwRealLen;
  528. return -5;
  529. }
  530. BYTE c;
  531. int g = 3;
  532. DWORD i, x, y, z;
  533. for(i = x = y = z = 0; i < dwSrcLen || x != 0;)
  534. {
  535. c = i < dwSrcLen ? MAP[lpszSrc[i++]] : 254;
  536. if(c == 255) {dwDestLen = 0; return -3;}
  537. else if(c == 254) {c = 0; g--;}
  538. else if(c == 253) continue;
  539. z = (z << 6) | c;
  540. if(++x == 4)
  541. {
  542. lpszDest[y++] = (BYTE)((z >> 16) & 255);
  543. if (g > 1) lpszDest[y++] = (BYTE)((z >> 8) & 255);
  544. if (g > 2) lpszDest[y++] = (BYTE)(z & 255);
  545. x = z = 0;
  546. }
  547. }
  548. BOOL isOK = (y == dwRealLen);
  549. if(!isOK)
  550. dwDestLen = 0;
  551. else
  552. {
  553. if(dwDestLen > dwRealLen)
  554. {
  555. lpszDest[dwRealLen] = 0;
  556. dwDestLen = dwRealLen;
  557. }
  558. }
  559. return isOK ? 0 : -3;
  560. }
  561. DWORD GuessUrlEncodeBound(const BYTE* lpszSrc, DWORD dwSrcLen)
  562. {
  563. DWORD dwAdd = 0;
  564. for(DWORD i = 0; i < dwSrcLen; i++)
  565. {
  566. BYTE c = lpszSrc[i];
  567. if(!(isalnum(c) || c == ' ' || c == '.' || c == '-' || c == '_' || c == '*'))
  568. dwAdd += 2;
  569. }
  570. return dwSrcLen + dwAdd;
  571. }
  572. DWORD GuessUrlDecodeBound(const BYTE* lpszSrc, DWORD dwSrcLen)
  573. {
  574. DWORD dwPercent = 0;
  575. for(DWORD i = 0; i < dwSrcLen; i++)
  576. {
  577. if(lpszSrc[i] == '%')
  578. {
  579. ++dwPercent;
  580. i += 2;
  581. }
  582. }
  583. DWORD dwSub = dwPercent * 2;
  584. if(dwSrcLen < dwSub)
  585. return 0;
  586. return dwSrcLen - dwSub;
  587. }
  588. #define HEX_CHAR_TO_VALUE(c) (c <= '9' ? c - '0' : (c <= 'F' ? c - 'A' + 0x0A : c - 'a' + 0X0A))
  589. #define HEX_DOUBLE_CHAR_TO_VALUE(pc) (((HEX_CHAR_TO_VALUE(*(pc))) << 4) | (HEX_CHAR_TO_VALUE(*(pc + 1))))
  590. #define HEX_VALUE_TO_CHAR(n) (n <= 9 ? n + '0' : (n <= 'F' ? n + 'A' - 0X0A : n + 'a' - 0X0A))
  591. #define HEX_VALUE_TO_DOUBLE_CHAR(pc, n) {*(pc) = HEX_VALUE_TO_CHAR((n >> 4)); *((pc) + 1) = HEX_VALUE_TO_CHAR((n & 0X0F));}
  592. int UrlEncode(BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen)
  593. {
  594. if(lpszDest == nullptr || dwDestLen == 0)
  595. goto ERROR_DEST_LEN;
  596. BYTE c;
  597. DWORD j = 0;
  598. for(DWORD i = 0; i < dwSrcLen; i++)
  599. {
  600. if(j >= dwDestLen)
  601. goto ERROR_DEST_LEN;
  602. c = lpszSrc[i];
  603. if (isalnum(c) || c == '.' || c == '-' || c == '_' || c == '*')
  604. lpszDest[j++] = c;
  605. else if(c == ' ')
  606. lpszDest[j++] = '+';
  607. else
  608. {
  609. if(j + 3 >= dwDestLen)
  610. goto ERROR_DEST_LEN;
  611. lpszDest[j++] = '%';
  612. HEX_VALUE_TO_DOUBLE_CHAR(lpszDest + j, c);
  613. j += 2;
  614. }
  615. }
  616. if(dwDestLen > j)
  617. {
  618. lpszDest[j] = 0;
  619. dwDestLen = j;
  620. }
  621. return 0;
  622. ERROR_DEST_LEN:
  623. dwDestLen = GuessUrlEncodeBound(lpszSrc, dwSrcLen);
  624. return -5;
  625. }
  626. int UrlDecode(BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen)
  627. {
  628. if(lpszDest == nullptr || dwDestLen == 0)
  629. goto ERROR_DEST_LEN;
  630. char c;
  631. DWORD j = 0;
  632. for(DWORD i = 0; i < dwSrcLen; i++)
  633. {
  634. if(j >= dwDestLen)
  635. goto ERROR_DEST_LEN;
  636. c = lpszSrc[i];
  637. if(c == '+')
  638. lpszDest[j++] = ' ';
  639. else if(c != '%')
  640. lpszDest[j++] = c;
  641. else
  642. {
  643. if(i + 2 >= dwSrcLen)
  644. goto ERROR_SRC_DATA;
  645. lpszDest[j++] = HEX_DOUBLE_CHAR_TO_VALUE(lpszSrc + i + 1);
  646. i += 2;
  647. }
  648. }
  649. if(dwDestLen > j)
  650. {
  651. lpszDest[j] = 0;
  652. dwDestLen = j;
  653. }
  654. return 0;
  655. ERROR_SRC_DATA:
  656. dwDestLen = 0;
  657. return -3;
  658. ERROR_DEST_LEN:
  659. dwDestLen = GuessUrlDecodeBound(lpszSrc, dwSrcLen);
  660. return -5;
  661. }