1
0

request.c 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811
  1. /** **************************************************************************
  2. * request.c
  3. *
  4. * Copyright 2008 Bryan Ischo <[email protected]>
  5. *
  6. * This file is part of libs3.
  7. *
  8. * libs3 is free software: you can redistribute it and/or modify it under the
  9. * terms of the GNU Lesser General Public License as published by the Free
  10. * Software Foundation, version 3 or above of the License. You can also
  11. * redistribute and/or modify it under the terms of the GNU General Public
  12. * License, version 2 or above of the License.
  13. *
  14. * In addition, as a special exception, the copyright holders give
  15. * permission to link the code of this library and its programs with the
  16. * OpenSSL library, and distribute linked combinations including the two.
  17. *
  18. * libs3 is distributed in the hope that it will be useful, but WITHOUT ANY
  19. * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  20. * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
  21. * details.
  22. *
  23. * You should have received a copy of the GNU Lesser General Public License
  24. * version 3 along with libs3, in a file named COPYING. If not, see
  25. * <https://www.gnu.org/licenses/>.
  26. *
  27. * You should also have received a copy of the GNU General Public License
  28. * version 2 along with libs3, in a file named COPYING-GPLv2. If not, see
  29. * <https://www.gnu.org/licenses/>.
  30. *
  31. ************************************************************************** **/
  32. #include <ctype.h>
  33. #include <pthread.h>
  34. #include <stdlib.h>
  35. #include <string.h>
  36. #include <sys/utsname.h>
  37. #include <expat.h>
  38. #include "request.h"
  39. #include "request_context.h"
  40. #include "response_headers_handler.h"
  41. #ifdef __APPLE__
  42. #include <CommonCrypto/CommonHMAC.h>
  43. #define S3_SHA256_DIGEST_LENGTH CC_SHA256_DIGEST_LENGTH
  44. #else
  45. #include <openssl/hmac.h>
  46. #include <openssl/sha.h>
  47. #define S3_SHA256_DIGEST_LENGTH SHA256_DIGEST_LENGTH
  48. #endif
  49. #define USER_AGENT_SIZE 256
  50. #define REQUEST_STACK_SIZE 32
  51. #define SIGNATURE_SCOPE_SIZE 64
  52. #ifdef WINSCP
  53. #define SIGNATURE_DEBUG
  54. #endif
  55. static char userAgentG[USER_AGENT_SIZE];
  56. #ifndef WINSCP
  57. static pthread_mutex_t requestStackMutexG;
  58. static Request *requestStackG[REQUEST_STACK_SIZE];
  59. static int requestStackCountG;
  60. #endif
  61. char defaultHostNameG[S3_MAX_HOSTNAME_SIZE];
  62. typedef struct RequestComputedValues
  63. {
  64. // All x-amz- headers, in normalized form (i.e. NAME: VALUE, no other ws)
  65. char *amzHeaders[S3_MAX_METADATA_COUNT + 2]; // + 2 for acl and date
  66. // The number of x-amz- headers
  67. int amzHeadersCount;
  68. // Storage for amzHeaders (the +256 is for x-amz-acl and x-amz-date)
  69. char amzHeadersRaw[COMPACTED_METADATA_BUFFER_SIZE + 256 + 1];
  70. // Length of populated data in raw buffer
  71. int amzHeadersRawLength;
  72. // Canonicalized headers for signature
  73. string_multibuffer(canonicalizedSignatureHeaders,
  74. COMPACTED_METADATA_BUFFER_SIZE + 256 + 1);
  75. // Delimited list of header names used for signature
  76. char signedHeaders[COMPACTED_METADATA_BUFFER_SIZE];
  77. // URL-Encoded key
  78. char urlEncodedKey[MAX_URLENCODED_KEY_SIZE + 1];
  79. // Canonicalized resource
  80. char canonicalURI[MAX_CANONICALIZED_RESOURCE_SIZE + 1];
  81. // Canonical sub-resource & query string
  82. char canonicalQueryString[MAX_CANONICALIZED_RESOURCE_SIZE + 1];
  83. // Cache-Control header (or empty)
  84. char cacheControlHeader[128];
  85. // Content-Type header (or empty)
  86. char contentTypeHeader[128];
  87. // Content-MD5 header (or empty)
  88. char md5Header[128];
  89. // Content-Disposition header (or empty)
  90. char contentDispositionHeader[128];
  91. // Content-Encoding header (or empty)
  92. char contentEncodingHeader[128];
  93. // Expires header (or empty)
  94. char expiresHeader[128];
  95. // If-Modified-Since header
  96. char ifModifiedSinceHeader[128];
  97. // If-Unmodified-Since header
  98. char ifUnmodifiedSinceHeader[128];
  99. // If-Match header
  100. char ifMatchHeader[128];
  101. // If-None-Match header
  102. char ifNoneMatchHeader[128];
  103. // Range header
  104. char rangeHeader[128];
  105. // Authorization header
  106. char authorizationHeader[4096];
  107. // Request date stamp
  108. char requestDateISO8601[64];
  109. // Credential used for authorization signature
  110. char authCredential[MAX_CREDENTIAL_SIZE + 1];
  111. // Computed request signature (hex string)
  112. char requestSignatureHex[S3_SHA256_DIGEST_LENGTH * 2 + 1];
  113. // Host header
  114. char hostHeader[128];
  115. // Hex string of hash of request payload
  116. char payloadHash[S3_SHA256_DIGEST_LENGTH * 2 + 1];
  117. } RequestComputedValues;
  118. // Called whenever we detect that the request headers have been completely
  119. // processed; which happens either when we get our first read/write callback,
  120. // or the request is finished being processed. Returns nonzero on success,
  121. // zero on failure.
  122. static void request_headers_done(Request *request)
  123. {
  124. if (request->propertiesCallbackMade) {
  125. return;
  126. }
  127. request->propertiesCallbackMade = 1;
  128. request->httpResponseCode = ne_get_status(request->NeonRequest)->code; // WINSCP (neon)
  129. response_headers_handler_done(&(request->responseHeadersHandler),
  130. request->NeonRequest); // WINSCP (neon)
  131. // Only make the callback if it was a successful request; otherwise we're
  132. // returning information about the error response itself
  133. if (request->propertiesCallback &&
  134. (request->httpResponseCode >= 200) &&
  135. (request->httpResponseCode <= 299)) {
  136. request->status = (*(request->propertiesCallback))
  137. (&(request->responseHeadersHandler.responseProperties),
  138. request->callbackData);
  139. }
  140. }
  141. // WINSCP (neon)
  142. static int neon_header_func(void * userdata, ne_request * NeonRequest, const ne_status * status)
  143. {
  144. Request *request = (Request *) userdata;
  145. void * cursor = NULL;
  146. const char * header_name;
  147. const char * header_value;
  148. while ((cursor = ne_response_header_iterate(NeonRequest, cursor, &header_name, &header_value)) != NULL)
  149. {
  150. response_headers_handler_add
  151. (&(request->responseHeadersHandler), header_name, header_value);
  152. }
  153. return 1;
  154. }
  155. // WINSCP (neon)
  156. static int neon_read_func(void * userdata, char * buf, size_t len)
  157. {
  158. Request *request = (Request *) userdata;
  159. const void * ptr = buf;
  160. // CURL may call this function before response headers are available,
  161. // so don't assume response headers are available and attempt to parse
  162. // them. Leave that to curl_write_func, which is guaranteed to be called
  163. // only after headers are available.
  164. if (request->status != S3StatusOK) {
  165. return 0;
  166. }
  167. // If there is no data callback, or the data callback has already returned
  168. // contentLength bytes, return 0;
  169. if (!request->toS3Callback || !request->toS3CallbackBytesRemaining) {
  170. return 0;
  171. }
  172. // Don't tell the callback that we are willing to accept more data than we
  173. // really are
  174. if (len > request->toS3CallbackBytesRemaining) {
  175. len = request->toS3CallbackBytesRemaining;
  176. }
  177. // Otherwise, make the data callback
  178. int ret = (*(request->toS3Callback))
  179. (len, (char *) ptr, request->callbackData);
  180. if (ret < 0) {
  181. request->status = S3StatusAbortedByCallback;
  182. return -1;
  183. }
  184. else {
  185. if (ret > request->toS3CallbackBytesRemaining) {
  186. ret = request->toS3CallbackBytesRemaining;
  187. }
  188. request->toS3CallbackBytesRemaining -= ret;
  189. return ret;
  190. }
  191. }
  192. // WINSCP (neon)
  193. static int neon_write_func(void * data, const char * buf, size_t len)
  194. {
  195. Request *request = (Request *) data;
  196. // WinSCP (ignore empty responses)
  197. if (len == 0)
  198. {
  199. return 0;
  200. }
  201. request_headers_done(request);
  202. if (request->requestContext->responseDataCallback != NULL)
  203. {
  204. request->requestContext->responseDataCallback(buf, len, request->requestContext->responseDataCallbackData);
  205. }
  206. if (request->status != S3StatusOK) {
  207. return 1;
  208. }
  209. // On HTTP error, we expect to parse an HTTP error response
  210. if ((request->httpResponseCode < 200) ||
  211. (request->httpResponseCode > 299)) {
  212. request->status = error_parser_add
  213. (&(request->errorParser), buf, len);
  214. }
  215. // If there was a callback registered, make it
  216. else if (request->fromS3Callback) {
  217. request->status = (*(request->fromS3Callback))
  218. (len, buf, request->callbackData);
  219. }
  220. // Else, consider this an error - S3 has sent back data when it was not
  221. // expected
  222. else {
  223. request->status = S3StatusInternalError;
  224. }
  225. return ((request->status == S3StatusOK) ? 0 : 1);
  226. }
  227. static S3Status append_amz_header(RequestComputedValues *values,
  228. int addPrefix,
  229. const char *headerName,
  230. const char *headerValue)
  231. {
  232. int rawPos = values->amzHeadersRawLength + 1;
  233. values->amzHeaders[values->amzHeadersCount++] = &(values->amzHeadersRaw[rawPos]);
  234. const char *headerStr = headerName;
  235. char headerNameWithPrefix[S3_MAX_METADATA_SIZE - sizeof(": v")];
  236. if (addPrefix) {
  237. snprintf(headerNameWithPrefix, sizeof(headerNameWithPrefix),
  238. S3_METADATA_HEADER_NAME_PREFIX "%s", headerName);
  239. headerStr = headerNameWithPrefix;
  240. }
  241. // Make sure the new header (plus ": " plus string terminator) will fit
  242. // in the buffer.
  243. if ((values->amzHeadersRawLength + strlen(headerStr) + strlen(headerValue)
  244. + 3) >= sizeof(values->amzHeadersRaw)) {
  245. return S3StatusMetaDataHeadersTooLong;
  246. }
  247. unsigned long i = 0;
  248. for (; i < strlen(headerStr); i++) {
  249. values->amzHeadersRaw[rawPos++] = tolower(headerStr[i]);
  250. }
  251. snprintf(&(values->amzHeadersRaw[rawPos]), 3, ": ");
  252. rawPos += 2;
  253. for (i = 0; i < strlen(headerValue); i++) {
  254. values->amzHeadersRaw[rawPos++] = headerValue[i];
  255. }
  256. rawPos--;
  257. while (isblank(values->amzHeadersRaw[rawPos])) {
  258. rawPos--;
  259. }
  260. values->amzHeadersRaw[++rawPos] = '\0';
  261. values->amzHeadersRawLength = rawPos;
  262. return S3StatusOK;
  263. }
  264. // This function 'normalizes' all x-amz-meta headers provided in
  265. // params->requestHeaders, which means it removes all whitespace from
  266. // them such that they all look exactly like this:
  267. // x-amz-meta-${NAME}: ${VALUE}
  268. // It also adds the x-amz-acl, x-amz-copy-source, x-amz-metadata-directive,
  269. // and x-amz-server-side-encryption headers if necessary, and always adds the
  270. // x-amz-date header. It copies the raw string values into
  271. // params->amzHeadersRaw, and creates an array of string pointers representing
  272. // these headers in params->amzHeaders (and also sets params->amzHeadersCount
  273. // to be the count of the total number of x-amz- headers thus created).
  274. static S3Status compose_amz_headers(const RequestParams *params,
  275. int forceUnsignedPayload,
  276. RequestComputedValues *values)
  277. {
  278. const S3PutProperties *properties = params->putProperties;
  279. values->amzHeadersCount = 0;
  280. values->amzHeadersRaw[0] = '\0';
  281. values->amzHeadersRawLength = 0;
  282. // Check and copy in the x-amz-meta headers
  283. if (properties) {
  284. int i;
  285. for (i = 0; i < properties->metaDataCount; i++) {
  286. const S3NameValue *property = &(properties->metaData[i]);
  287. append_amz_header(values, 1, property->name, property->value);
  288. }
  289. // Add the x-amz-acl header, if necessary
  290. const char *cannedAclString;
  291. switch (properties->cannedAcl) {
  292. case S3CannedAclPrivate:
  293. cannedAclString = NULL;
  294. break;
  295. case S3CannedAclPublicRead:
  296. cannedAclString = "public-read";
  297. break;
  298. case S3CannedAclPublicReadWrite:
  299. cannedAclString = "public-read-write";
  300. break;
  301. case S3CannedAclBucketOwnerFullControl:
  302. cannedAclString = "bucket-owner-full-control";
  303. break;
  304. default: // S3CannedAclAuthenticatedRead
  305. cannedAclString = "authenticated-read";
  306. break;
  307. }
  308. if (cannedAclString) {
  309. append_amz_header(values, 0, "x-amz-acl", cannedAclString);
  310. }
  311. // Add the x-amz-server-side-encryption header, if necessary
  312. if (properties->useServerSideEncryption) {
  313. append_amz_header(values, 0, "x-amz-server-side-encryption",
  314. "AES256");
  315. }
  316. }
  317. // Add the x-amz-date header
  318. append_amz_header(values, 0, "x-amz-date", values->requestDateISO8601);
  319. if (params->httpRequestType == HttpRequestTypeCOPY) {
  320. // Add the x-amz-copy-source header
  321. if (params->copySourceBucketName && params->copySourceBucketName[0]
  322. && params->copySourceKey && params->copySourceKey[0]) {
  323. // WINSCP
  324. char bucketKey[1 + S3_MAX_BUCKET_NAME_SIZE + 1 + MAX_URLENCODED_KEY_SIZE + 1];
  325. snprintf(bucketKey, 1 + S3_MAX_BUCKET_NAME_SIZE + 1 + 1, "/%s/", params->copySourceBucketName);
  326. if (!urlEncode(bucketKey + strlen(bucketKey), params->copySourceKey, S3_MAX_KEY_SIZE, 0))
  327. {
  328. return S3StatusUriTooLong;
  329. }
  330. append_amz_header(values, 0, "x-amz-copy-source", bucketKey);
  331. }
  332. // If byteCount != 0 then we're just copying a range, add header
  333. if (params->byteCount > 0) {
  334. char byteRange[S3_MAX_METADATA_SIZE];
  335. snprintf(byteRange, sizeof(byteRange), "bytes=%zd-%zd",
  336. params->startByte, params->startByte + params->byteCount);
  337. append_amz_header(values, 0, "x-amz-copy-source-range", byteRange);
  338. }
  339. // And the x-amz-metadata-directive header
  340. if (properties) {
  341. append_amz_header(values, 0, "x-amz-metadata-directive", "REPLACE");
  342. }
  343. }
  344. // Add the x-amz-security-token header if necessary
  345. if (params->bucketContext.securityToken) {
  346. append_amz_header(values, 0, "x-amz-security-token",
  347. params->bucketContext.securityToken);
  348. }
  349. if (!forceUnsignedPayload
  350. && (params->httpRequestType == HttpRequestTypeGET
  351. || params->httpRequestType == HttpRequestTypeCOPY
  352. || params->httpRequestType == HttpRequestTypeDELETE
  353. || params->httpRequestType == HttpRequestTypeHEAD)) {
  354. // empty payload
  355. unsigned char md[S3_SHA256_DIGEST_LENGTH];
  356. #ifdef __APPLE__
  357. CC_SHA256("", 0, md);
  358. #else
  359. SHA256((const unsigned char*) "", 0, md);
  360. #endif
  361. values->payloadHash[0] = '\0';
  362. int i = 0;
  363. for (; i < S3_SHA256_DIGEST_LENGTH; i++) {
  364. snprintf(&(values->payloadHash[i * 2]), 3, "%02x", md[i]);
  365. }
  366. }
  367. else {
  368. // TODO: figure out how to manage signed payloads
  369. strcpy(values->payloadHash, "UNSIGNED-PAYLOAD");
  370. }
  371. append_amz_header(values, 0, "x-amz-content-sha256",
  372. values->payloadHash);
  373. return S3StatusOK;
  374. }
  375. // Composes the other headers
  376. static S3Status compose_standard_headers(const RequestParams *params,
  377. RequestComputedValues *values)
  378. {
  379. #define do_put_header(fmt, sourceField, destField, badError, tooLongError) \
  380. do { \
  381. if (params->putProperties && \
  382. params->putProperties-> sourceField && \
  383. params->putProperties-> sourceField[0]) { \
  384. /* Skip whitespace at beginning of val */ \
  385. const char *val = params->putProperties-> sourceField; \
  386. while (*val && is_blank(*val)) { \
  387. val++; \
  388. } \
  389. if (!*val) { \
  390. return badError; \
  391. } \
  392. /* Compose header, make sure it all fit */ \
  393. int len = snprintf(values-> destField, \
  394. sizeof(values-> destField), fmt, val); \
  395. if (len >= (int) sizeof(values-> destField)) { \
  396. return tooLongError; \
  397. } \
  398. /* Now remove the whitespace at the end */ \
  399. while (is_blank(values-> destField[len])) { \
  400. len--; \
  401. } \
  402. values-> destField[len] = 0; \
  403. } \
  404. else { \
  405. values-> destField[0] = 0; \
  406. } \
  407. } while (0)
  408. #define do_get_header(fmt, sourceField, destField, badError, tooLongError) \
  409. do { \
  410. if (params->getConditions && \
  411. params->getConditions-> sourceField && \
  412. params->getConditions-> sourceField[0]) { \
  413. /* Skip whitespace at beginning of val */ \
  414. const char *val = params->getConditions-> sourceField; \
  415. while (*val && is_blank(*val)) { \
  416. val++; \
  417. } \
  418. if (!*val) { \
  419. return badError; \
  420. } \
  421. /* Compose header, make sure it all fit */ \
  422. int len = snprintf(values-> destField, \
  423. sizeof(values-> destField), fmt, val); \
  424. if (len >= (int) sizeof(values-> destField)) { \
  425. return tooLongError; \
  426. } \
  427. /* Now remove the whitespace at the end */ \
  428. while (is_blank(values-> destField[len])) { \
  429. len--; \
  430. } \
  431. values-> destField[len] = 0; \
  432. } \
  433. else { \
  434. values-> destField[0] = 0; \
  435. } \
  436. } while (0)
  437. // Host
  438. if (params->bucketContext.uriStyle == S3UriStyleVirtualHost) {
  439. const char *requestHostName = params->bucketContext.hostName
  440. ? params->bucketContext.hostName : defaultHostNameG;
  441. size_t len = snprintf(values->hostHeader, sizeof(values->hostHeader),
  442. "Host: %s.%s", params->bucketContext.bucketName,
  443. requestHostName);
  444. if (len >= sizeof(values->hostHeader)) {
  445. return S3StatusUriTooLong;
  446. }
  447. while (is_blank(values->hostHeader[len])) {
  448. len--;
  449. }
  450. values->hostHeader[len] = 0;
  451. }
  452. else {
  453. size_t len = snprintf(
  454. values->hostHeader,
  455. sizeof(values->hostHeader),
  456. "Host: %s",
  457. params->bucketContext.hostName ?
  458. params->bucketContext.hostName : defaultHostNameG);
  459. if (len >= sizeof(values->hostHeader)) {
  460. return S3StatusUriTooLong;
  461. }
  462. while (is_blank(values->hostHeader[len])) {
  463. len--;
  464. }
  465. values->hostHeader[len] = 0;
  466. }
  467. // Cache-Control
  468. do_put_header("Cache-Control: %s", cacheControl, cacheControlHeader,
  469. S3StatusBadCacheControl, S3StatusCacheControlTooLong);
  470. // ContentType
  471. do_put_header("Content-Type: %s", contentType, contentTypeHeader,
  472. S3StatusBadContentType, S3StatusContentTypeTooLong);
  473. // MD5
  474. do_put_header("Content-MD5: %s", md5, md5Header, S3StatusBadMD5,
  475. S3StatusMD5TooLong);
  476. // Content-Disposition
  477. do_put_header("Content-Disposition: attachment; filename=\"%s\"",
  478. contentDispositionFilename, contentDispositionHeader,
  479. S3StatusBadContentDispositionFilename,
  480. S3StatusContentDispositionFilenameTooLong);
  481. // ContentEncoding
  482. do_put_header("Content-Encoding: %s", contentEncoding,
  483. contentEncodingHeader, S3StatusBadContentEncoding,
  484. S3StatusContentEncodingTooLong);
  485. // Expires
  486. // WINSCP (not implemented)
  487. values->expiresHeader[0] = 0;
  488. // If-Modified-Since
  489. // WINSCP (not implemented)
  490. values->ifModifiedSinceHeader[0] = 0;
  491. // If-Unmodified-Since header
  492. // WINSCP (not implemented)
  493. values->ifUnmodifiedSinceHeader[0] = 0;
  494. // If-Match header
  495. do_get_header("If-Match: %s", ifMatchETag, ifMatchHeader,
  496. S3StatusBadIfMatchETag, S3StatusIfMatchETagTooLong);
  497. // If-None-Match header
  498. do_get_header("If-None-Match: %s", ifNotMatchETag, ifNoneMatchHeader,
  499. S3StatusBadIfNotMatchETag,
  500. S3StatusIfNotMatchETagTooLong);
  501. // Range header
  502. if (params->startByte || params->byteCount) {
  503. if (params->byteCount) {
  504. snprintf(values->rangeHeader, sizeof(values->rangeHeader),
  505. "Range: bytes=%llu-%llu",
  506. (unsigned long long) params->startByte,
  507. (unsigned long long) (params->startByte +
  508. params->byteCount - 1));
  509. }
  510. else {
  511. snprintf(values->rangeHeader, sizeof(values->rangeHeader),
  512. "Range: bytes=%llu-",
  513. (unsigned long long) params->startByte);
  514. }
  515. }
  516. else {
  517. values->rangeHeader[0] = 0;
  518. }
  519. return S3StatusOK;
  520. }
  521. // URL encodes the params->key value into params->urlEncodedKey
  522. static S3Status encode_key(const RequestParams *params,
  523. RequestComputedValues *values)
  524. {
  525. return (urlEncode(values->urlEncodedKey, params->key, S3_MAX_KEY_SIZE, 0) ?
  526. S3StatusOK : S3StatusUriTooLong);
  527. }
  528. // Simple comparison function for comparing two "<key><delim><value>"
  529. // delimited strings, returning true if the key of s1 comes
  530. // before the key of s2 alphabetically, false if not
  531. static int headerle(const char *s1, const char *s2, char delim)
  532. {
  533. while (1) {
  534. if (*s1 == delim) {
  535. return (*s2 != delim);
  536. }
  537. else if (*s2 == delim) {
  538. return 0;
  539. }
  540. else if (*s2 < *s1) {
  541. return 0;
  542. }
  543. else if (*s2 > *s1) {
  544. return 1;
  545. }
  546. s1++, s2++;
  547. }
  548. #ifndef WINSCP
  549. return 0;
  550. #endif
  551. }
  552. // Replace this with merge sort eventually, it's the best stable sort. But
  553. // since typically the number of elements being sorted is small, it doesn't
  554. // matter that much which sort is used, and gnome sort is the world's simplest
  555. // stable sort. Added a slight twist to the standard gnome_sort - don't go
  556. // forward +1, go forward to the last highest index considered. This saves
  557. // all the string comparisons that would be done "going forward", and thus
  558. // only does the necessary string comparisons to move values back into their
  559. // sorted position.
  560. static void kv_gnome_sort(const char **values, int size, char delim)
  561. {
  562. int i = 0, last_highest = 0;
  563. while (i < size) {
  564. if ((i == 0) || headerle(values[i - 1], values[i], delim)) {
  565. i = ++last_highest;
  566. }
  567. else {
  568. const char *tmp = values[i];
  569. values[i] = values[i - 1];
  570. values[--i] = tmp;
  571. }
  572. }
  573. }
  574. // Canonicalizes the signature headers into the canonicalizedSignatureHeaders buffer
  575. static void canonicalize_signature_headers(RequestComputedValues *values)
  576. {
  577. // Make a copy of the headers that will be sorted
  578. const char *sortedHeaders[S3_MAX_METADATA_COUNT + 3];
  579. memcpy(sortedHeaders, values->amzHeaders,
  580. (values->amzHeadersCount * sizeof(sortedHeaders[0])));
  581. // add the content-type header and host header
  582. int headerCount = values->amzHeadersCount;
  583. if (values->contentTypeHeader[0]) {
  584. sortedHeaders[headerCount++] = values->contentTypeHeader;
  585. }
  586. if (values->hostHeader[0]) {
  587. sortedHeaders[headerCount++] = values->hostHeader;
  588. }
  589. if (values->rangeHeader[0]) {
  590. sortedHeaders[headerCount++] = values->rangeHeader;
  591. }
  592. if (values->md5Header[0]) {
  593. sortedHeaders[headerCount++] = values->md5Header;
  594. }
  595. // Now sort these
  596. kv_gnome_sort(sortedHeaders, headerCount, ':');
  597. // Now copy this sorted list into the buffer, all the while:
  598. // - folding repeated headers into single lines, and
  599. // - folding multiple lines
  600. // - removing the space after the colon
  601. int lastHeaderLen = 0;
  602. char *buffer = values->canonicalizedSignatureHeaders;
  603. char *hbuf = values->signedHeaders;
  604. int i = 0;
  605. for (; i < headerCount; i++) {
  606. const char *header = sortedHeaders[i];
  607. const char *c = header;
  608. char v;
  609. // If the header names are the same, append the next value
  610. if ((i > 0) &&
  611. !strncmp(header, sortedHeaders[i - 1], lastHeaderLen)) {
  612. // Replacing the previous newline with a comma
  613. *(buffer - 1) = ',';
  614. // Skip the header name and space
  615. c += (lastHeaderLen + 1);
  616. }
  617. // Else this is a new header
  618. else {
  619. // Copy in everything up to the space in the ": "
  620. while (*c != ' ') {
  621. v = tolower(*c++);
  622. *buffer++ = v;
  623. *hbuf++ = v;
  624. }
  625. // replace the ":" with a ";"
  626. *(hbuf - 1) = ';';
  627. // Save the header len since it's a new header
  628. lastHeaderLen = c - header;
  629. // Skip the space
  630. c++;
  631. }
  632. // Now copy in the value, folding the lines
  633. while (*c) {
  634. // If c points to a \r\n[whitespace] sequence, then fold
  635. // this newline out
  636. if ((*c == '\r') && (*(c + 1) == '\n') && is_blank(*(c + 2))) {
  637. c += 3;
  638. while (is_blank(*c)) {
  639. c++;
  640. }
  641. // Also, what has most recently been copied into buffer may
  642. // have been whitespace, and since we're folding whitespace
  643. // out around this newline sequence, back buffer up over
  644. // any whitespace it contains
  645. while (is_blank(*(buffer - 1))) {
  646. buffer--;
  647. }
  648. continue;
  649. }
  650. *buffer++ = *c++;
  651. }
  652. // Finally, add the newline
  653. *buffer++ = '\n';
  654. }
  655. // Remove the extra trailing semicolon from the header name list
  656. // and terminate the string.
  657. *(hbuf - 1) = '\0';
  658. // Terminate the buffer
  659. *buffer = 0;
  660. }
  661. // Canonicalizes the resource into params->canonicalizedResource
  662. static void canonicalize_resource(const S3BucketContext *context,
  663. const char *urlEncodedKey,
  664. char *buffer, unsigned int buffer_max)
  665. {
  666. int len = 0;
  667. *buffer = 0;
  668. #define append(str) len += snprintf(&(buffer[len]), buffer_max - len, "%s", str)
  669. if (context->uriStyle == S3UriStylePath) {
  670. if (context->bucketName && context->bucketName[0]) {
  671. buffer[len++] = '/';
  672. append(context->bucketName);
  673. }
  674. }
  675. append("/");
  676. if (urlEncodedKey && urlEncodedKey[0]) {
  677. append(urlEncodedKey);
  678. }
  679. #undef append
  680. }
  681. static void sort_query_string(const char *queryString, char *result,
  682. unsigned int result_size)
  683. {
  684. #ifdef SIGNATURE_DEBUG
  685. ne_debug(NULL, NE_DBG_HTTPBODY, "\n--\nsort_and_urlencode\nqueryString: %s\n", queryString);
  686. #endif
  687. unsigned int numParams = 1;
  688. const char *tmp = queryString;
  689. while ((tmp = strchr(tmp, '&')) != NULL) {
  690. numParams++;
  691. tmp++;
  692. }
  693. const char** params = new const char*[numParams]; // WINSCP (heap allocation)
  694. // Where did strdup go?!??
  695. int queryStringLen = strlen(queryString);
  696. char *buf = (char *) malloc(queryStringLen + 1);
  697. char *tok = buf;
  698. strcpy(tok, queryString);
  699. const char *token = NULL;
  700. char *save = NULL;
  701. unsigned int i = 0;
  702. while ((token = strtok_r(tok, "&", &save)) != NULL) {
  703. tok = NULL;
  704. params[i++] = token;
  705. }
  706. kv_gnome_sort(params, numParams, '=');
  707. #ifdef SIGNATURE_DEBUG
  708. for (i = 0; i < numParams; i++) {
  709. ne_debug(NULL, NE_DBG_HTTPBODY, "%d: %s\n", i, params[i]);
  710. }
  711. #endif
  712. // All params are urlEncoded
  713. #define append(str) len += snprintf(&(result[len]), result_size - len, "%s", str)
  714. unsigned int pi = 0;
  715. unsigned int len = 0;
  716. for (; pi < numParams; pi++) {
  717. append(params[pi]);
  718. append("&");
  719. }
  720. // Take off the extra '&'
  721. if (len > 0) {
  722. result[len - 1] = 0;
  723. }
  724. #undef append
  725. delete[] params; // WINSCP (heap allocation)
  726. free(buf);
  727. }
  728. // Canonicalize the query string part of the request into a buffer
  729. static void canonicalize_query_string(const char *queryParams,
  730. const char *subResource,
  731. char *buffer, unsigned int buffer_size)
  732. {
  733. int len = 0;
  734. *buffer = 0;
  735. #define append(str) len += snprintf(&(buffer[len]), buffer_size - len, "%s", str)
  736. if (queryParams && queryParams[0]) {
  737. int sortedLen = strlen(queryParams) * 2;
  738. char * sorted = new char[sortedLen]; // WINSCP (heap allocation)
  739. sorted[0] = '\0';
  740. sort_query_string(queryParams, sorted, sortedLen);
  741. append(sorted);
  742. delete[] sorted; // WINSCP (heap allocation)
  743. }
  744. if (subResource && subResource[0]) {
  745. if (queryParams && queryParams[0]) {
  746. append("&");
  747. }
  748. append(subResource);
  749. if (!strchr(subResource, '=')) {
  750. append("=");
  751. }
  752. }
  753. #undef append
  754. }
  755. static HttpRequestType http_request_method_to_type(const char *method)
  756. {
  757. if (!method) {
  758. return HttpRequestTypeInvalid;
  759. }
  760. if (strcmp(method, "POST") == 0) {
  761. return HttpRequestTypePOST;
  762. }
  763. else if (strcmp(method, "GET") == 0) {
  764. return HttpRequestTypeGET;
  765. }
  766. else if (strcmp(method, "HEAD") == 0) {
  767. return HttpRequestTypeHEAD;
  768. }
  769. else if (strcmp(method, "PUT") == 0) {
  770. return HttpRequestTypePUT;
  771. }
  772. else if (strcmp(method, "COPY") == 0) {
  773. return HttpRequestTypeCOPY;
  774. }
  775. else if (strcmp(method, "DELETE") == 0) {
  776. return HttpRequestTypeDELETE;
  777. }
  778. return HttpRequestTypeInvalid;
  779. }
  780. // Convert an HttpRequestType to an HTTP Verb string
  781. static const char *http_request_type_to_verb(HttpRequestType requestType)
  782. {
  783. switch (requestType) {
  784. case HttpRequestTypePOST:
  785. return "POST";
  786. case HttpRequestTypeGET:
  787. return "GET";
  788. case HttpRequestTypeHEAD:
  789. return "HEAD";
  790. case HttpRequestTypePUT:
  791. case HttpRequestTypeCOPY:
  792. return "PUT";
  793. default: // HttpRequestTypeDELETE
  794. return "DELETE";
  795. }
  796. }
  797. // Composes the Authorization header for the request
  798. static S3Status compose_auth_header(const RequestParams *params,
  799. RequestComputedValues *values)
  800. {
  801. const char *httpMethod = http_request_type_to_verb(params->httpRequestType);
  802. int canonicalRequestLen = strlen(httpMethod) + 1 +
  803. strlen(values->canonicalURI) + 1 +
  804. strlen(values->canonicalQueryString) + 1 +
  805. strlen(values->canonicalizedSignatureHeaders) + 1 +
  806. strlen(values->signedHeaders) + 1 +
  807. 2 * S3_SHA256_DIGEST_LENGTH + 1; // 2 hex digits for each byte
  808. int len = 0;
  809. char * canonicalRequest = new char[canonicalRequestLen]; // WINSCP (heap allocation)
  810. // WINSCP (heap allocation)
  811. #define buf_append(buf, format, ...) \
  812. len += snprintf(&(buf[len]), size - len, \
  813. format, __VA_ARGS__)
  814. canonicalRequest[0] = '\0';
  815. int size = canonicalRequestLen; // WINSCP
  816. buf_append(canonicalRequest, "%s\n", httpMethod);
  817. buf_append(canonicalRequest, "%s\n", values->canonicalURI);
  818. buf_append(canonicalRequest, "%s\n", values->canonicalQueryString);
  819. buf_append(canonicalRequest, "%s\n", values->canonicalizedSignatureHeaders);
  820. buf_append(canonicalRequest, "%s\n", values->signedHeaders);
  821. buf_append(canonicalRequest, "%s", values->payloadHash);
  822. #ifdef SIGNATURE_DEBUG
  823. ne_debug(NULL, NE_DBG_HTTPBODY, "--\nCanonical Request:\n%s\n", canonicalRequest);
  824. #endif
  825. len = 0;
  826. unsigned char canonicalRequestHash[S3_SHA256_DIGEST_LENGTH];
  827. #ifdef __APPLE__
  828. CC_SHA256(canonicalRequest, strlen(canonicalRequest), canonicalRequestHash);
  829. #else
  830. const unsigned char *rqstData = (const unsigned char*) canonicalRequest;
  831. SHA256(rqstData, strlen(canonicalRequest), canonicalRequestHash);
  832. #endif
  833. delete[] canonicalRequest; // WINSCP
  834. char canonicalRequestHashHex[2 * S3_SHA256_DIGEST_LENGTH + 1];
  835. size = sizeof(canonicalRequestHashHex); // WINSCP
  836. canonicalRequestHashHex[0] = '\0';
  837. int i = 0;
  838. for (; i < S3_SHA256_DIGEST_LENGTH; i++) {
  839. buf_append(canonicalRequestHashHex, "%02x", canonicalRequestHash[i]);
  840. }
  841. const char *awsRegion = S3_DEFAULT_REGION;
  842. if (params->bucketContext.authRegion) {
  843. awsRegion = params->bucketContext.authRegion;
  844. }
  845. char scope[sizeof(values->requestDateISO8601) + sizeof(awsRegion) +
  846. sizeof("//s3/aws4_request") + 1];
  847. snprintf(scope, sizeof(scope), "%.8s/%s/s3/aws4_request",
  848. values->requestDateISO8601, awsRegion);
  849. const int stringToSignLen = 17 + 17 + sizeof(values->requestDateISO8601) +
  850. sizeof(scope) + sizeof(canonicalRequestHashHex) + 1; // WINSCP (heap allocation)
  851. char * stringToSign = new char[stringToSignLen];
  852. snprintf(stringToSign, stringToSignLen, "AWS4-HMAC-SHA256\n%s\n%s\n%s",
  853. values->requestDateISO8601, scope, canonicalRequestHashHex);
  854. #ifdef SIGNATURE_DEBUG
  855. ne_debug(NULL, NE_DBG_HTTPBODY, "--\nString to Sign:\n%s\n", stringToSign);
  856. #endif
  857. const char *secretAccessKey = params->bucketContext.secretAccessKey;
  858. const int accessKeyLen = strlen(secretAccessKey) + 5; // WINSCP (heap allocation)
  859. char * accessKey = new char[accessKeyLen];
  860. snprintf(accessKey, accessKeyLen, "AWS4%s", secretAccessKey);
  861. #ifdef __APPLE__
  862. unsigned char dateKey[S3_SHA256_DIGEST_LENGTH];
  863. CCHmac(kCCHmacAlgSHA256, accessKey, strlen(accessKey),
  864. values->requestDateISO8601, 8, dateKey);
  865. unsigned char dateRegionKey[S3_SHA256_DIGEST_LENGTH];
  866. CCHmac(kCCHmacAlgSHA256, dateKey, S3_SHA256_DIGEST_LENGTH, awsRegion,
  867. strlen(awsRegion), dateRegionKey);
  868. unsigned char dateRegionServiceKey[S3_SHA256_DIGEST_LENGTH];
  869. CCHmac(kCCHmacAlgSHA256, dateRegionKey, S3_SHA256_DIGEST_LENGTH, "s3", 2,
  870. dateRegionServiceKey);
  871. unsigned char signingKey[S3_SHA256_DIGEST_LENGTH];
  872. CCHmac(kCCHmacAlgSHA256, dateRegionServiceKey, S3_SHA256_DIGEST_LENGTH,
  873. "aws4_request", strlen("aws4_request"), signingKey);
  874. unsigned char finalSignature[S3_SHA256_DIGEST_LENGTH];
  875. CCHmac(kCCHmacAlgSHA256, signingKey, S3_SHA256_DIGEST_LENGTH, stringToSign,
  876. strlen(stringToSign), finalSignature);
  877. #else
  878. const EVP_MD *sha256evp = EVP_sha256();
  879. unsigned char dateKey[S3_SHA256_DIGEST_LENGTH];
  880. HMAC(sha256evp, accessKey, strlen(accessKey),
  881. (const unsigned char*) values->requestDateISO8601, 8, dateKey,
  882. NULL);
  883. unsigned char dateRegionKey[S3_SHA256_DIGEST_LENGTH];
  884. HMAC(sha256evp, dateKey, S3_SHA256_DIGEST_LENGTH,
  885. (const unsigned char*) awsRegion, strlen(awsRegion), dateRegionKey,
  886. NULL);
  887. unsigned char dateRegionServiceKey[S3_SHA256_DIGEST_LENGTH];
  888. HMAC(sha256evp, dateRegionKey, S3_SHA256_DIGEST_LENGTH,
  889. (const unsigned char*) "s3", 2, dateRegionServiceKey, NULL);
  890. unsigned char signingKey[S3_SHA256_DIGEST_LENGTH];
  891. HMAC(sha256evp, dateRegionServiceKey, S3_SHA256_DIGEST_LENGTH,
  892. (const unsigned char*) "aws4_request", strlen("aws4_request"),
  893. signingKey,
  894. NULL);
  895. unsigned char finalSignature[S3_SHA256_DIGEST_LENGTH];
  896. HMAC(sha256evp, signingKey, S3_SHA256_DIGEST_LENGTH,
  897. (const unsigned char*) stringToSign, strlen(stringToSign),
  898. finalSignature, NULL);
  899. #endif
  900. delete[] accessKey; // WINSCP
  901. delete[] stringToSign; // WINSCP
  902. len = 0;
  903. size = sizeof(values->requestSignatureHex); // WINSCP
  904. values->requestSignatureHex[0] = '\0';
  905. for (i = 0; i < S3_SHA256_DIGEST_LENGTH; i++) {
  906. buf_append(values->requestSignatureHex, "%02x", finalSignature[i]);
  907. }
  908. snprintf(values->authCredential, sizeof(values->authCredential),
  909. "%s/%.8s/%s/s3/aws4_request", params->bucketContext.accessKeyId,
  910. values->requestDateISO8601, awsRegion);
  911. snprintf(values->authorizationHeader,
  912. sizeof(values->authorizationHeader),
  913. "Authorization: AWS4-HMAC-SHA256 Credential=%s,SignedHeaders=%s,Signature=%s",
  914. values->authCredential, values->signedHeaders,
  915. values->requestSignatureHex);
  916. #ifdef SIGNATURE_DEBUG
  917. ne_debug(NULL, NE_DBG_HTTPBODY, "--\nAuthorization Header:\n%s\n", values->authorizationHeader);
  918. #endif
  919. return S3StatusOK;
  920. #undef buf_append
  921. }
  922. // Compose the URI to use for the request given the request parameters
  923. static S3Status compose_uri(char *buffer, int bufferSize,
  924. const S3BucketContext *bucketContext,
  925. const char *urlEncodedKey,
  926. const char *subResource, const char *queryParams)
  927. {
  928. int len = 0;
  929. #define uri_append(fmt, ...) \
  930. do { \
  931. len += snprintf(&(buffer[len]), bufferSize - len, fmt, __VA_ARGS__); \
  932. if (len >= bufferSize) { \
  933. return S3StatusUriTooLong; \
  934. } \
  935. } while (0)
  936. uri_append("http%s://",
  937. (bucketContext->protocol == S3ProtocolHTTP) ? "" : "s");
  938. const char *hostName =
  939. bucketContext->hostName ? bucketContext->hostName : defaultHostNameG;
  940. if (bucketContext->bucketName &&
  941. bucketContext->bucketName[0]) {
  942. if (bucketContext->uriStyle == S3UriStyleVirtualHost) {
  943. #ifndef WINSCP
  944. // We cannot change Host: header with neon.
  945. // Instead we tweak host name validation
  946. if (strchr(bucketContext->bucketName, '.') == NULL) {
  947. #endif
  948. uri_append("%s.%s", bucketContext->bucketName, hostName);
  949. #ifndef WINSCP
  950. }
  951. else {
  952. // We'll use the hostName in the URL, and then explicitly set
  953. // the Host header to match bucket.host so that host validation
  954. // works.
  955. uri_append("%s", hostName);
  956. }
  957. #endif
  958. }
  959. else {
  960. uri_append("%s/%s", hostName, bucketContext->bucketName);
  961. }
  962. }
  963. else {
  964. uri_append("%s", hostName);
  965. }
  966. uri_append("%s", "/");
  967. uri_append("%s", urlEncodedKey);
  968. if (subResource && subResource[0]) {
  969. uri_append("?%s", subResource);
  970. }
  971. if (queryParams) {
  972. uri_append("%s%s", (subResource && subResource[0]) ? "&" : "?",
  973. queryParams);
  974. }
  975. return S3StatusOK;
  976. }
  977. #ifdef WINSCP
  978. int neon_ssl_callback(void * user_data, int failures, const ne_ssl_certificate * certificate)
  979. {
  980. Request *request = (Request *) user_data;
  981. int result = NE_ERROR;
  982. if (request->requestContext->sslCallback != NULL)
  983. {
  984. result = request->requestContext->sslCallback(failures, certificate, request->requestContext->sslCallbackData);
  985. }
  986. return result;
  987. }
  988. #endif
  989. // WINSCP (neon)
  990. // Sets up the neon handle given the completely computed RequestParams
  991. static S3Status setup_neon(Request *request,
  992. const RequestParams *params,
  993. const RequestComputedValues *values)
  994. {
  995. NeonCode status;
  996. ne_uri uri;
  997. if (ne_uri_parse(request->uri, &uri) != 0)
  998. {
  999. return S3StatusFailedToInitializeRequest;
  1000. }
  1001. int port = uri.port;
  1002. if (port == 0)
  1003. {
  1004. port = ne_uri_defaultport(uri.scheme);
  1005. }
  1006. request->NeonSession = ne_session_create(uri.scheme, uri.host, port);
  1007. if (request->requestContext->sessionCallback != NULL)
  1008. {
  1009. request->requestContext->sessionCallback(request->NeonSession, request->requestContext->sessionCallbackData);
  1010. }
  1011. char method[64];
  1012. strcpy(method, "GET");
  1013. switch (params->httpRequestType) {
  1014. case HttpRequestTypeHEAD:
  1015. strcpy(method, "HEAD");
  1016. break;
  1017. case HttpRequestTypePOST:
  1018. strcpy(method, "POST");
  1019. break;
  1020. case HttpRequestTypePUT:
  1021. case HttpRequestTypeCOPY:
  1022. strcpy(method, "PUT");
  1023. break;
  1024. case HttpRequestTypeDELETE:
  1025. strcpy(method, "DELETE");
  1026. break;
  1027. default: // HttpRequestTypeGET
  1028. break;
  1029. }
  1030. ne_buffer * buf = ne_buffer_create();
  1031. ne_buffer_zappend(buf, uri.path);
  1032. if (uri.query != NULL)
  1033. {
  1034. ne_buffer_concat(buf, "?", uri.query, NULL);
  1035. }
  1036. request->NeonRequest = ne_request_create(request->NeonSession, method, buf->data);
  1037. ne_buffer_destroy(buf);
  1038. ne_uri_free(&uri);
  1039. // Set header callback and data
  1040. // Set read callback, data, and readSize
  1041. ne_add_response_body_reader(request->NeonRequest, neon_header_func, neon_write_func, request);
  1042. // Set write callback and data
  1043. if ((params->httpRequestType == HttpRequestTypePUT) ||
  1044. (params->httpRequestType == HttpRequestTypePOST))
  1045. {
  1046. ne_set_request_body_provider(request->NeonRequest, (ne_off_t)params->toS3CallbackTotalSize, neon_read_func, request);
  1047. }
  1048. // WINSCP (Last-Modified parsed in response_headers_handler_done)
  1049. // xxx todo - support setting the proxy for Curl to use (can't use https
  1050. // for proxies though)
  1051. // xxx todo - support setting the network interface for Curl to use
  1052. // WINSCP (neon sets "nodelay" unconditionally)
  1053. // WINSCP (we should verify peer always)
  1054. ne_ssl_set_verify(request->NeonSession, neon_ssl_callback, request);
  1055. ne_ssl_trust_default_ca(request->NeonSession);
  1056. // Follow any redirection directives that S3 sends
  1057. // TODO
  1058. // Set the User-Agent; maybe Amazon will track these?
  1059. ne_set_useragent(request->NeonSession, userAgentG);
  1060. if (params->timeoutMs > 0) {
  1061. ne_set_read_timeout(request->NeonSession, params->timeoutMs);
  1062. ne_set_connect_timeout(request->NeonSession, params->timeoutMs);
  1063. }
  1064. #define do_add_header(header) \
  1065. { \
  1066. char * buf = new char[strlen(header) + 1]; \
  1067. strcpy(buf, header); \
  1068. char * p = strchr(buf, ':'); \
  1069. if (p != NULL) \
  1070. { \
  1071. *p = '\0'; \
  1072. p++; \
  1073. while (is_blank(p[0])) p++; \
  1074. ne_add_request_header(request->NeonRequest, buf, p); \
  1075. } \
  1076. delete[] buf; \
  1077. }
  1078. // Append standard headers
  1079. #define append_standard_header(fieldName) \
  1080. if (values-> fieldName [0]) { \
  1081. do_add_header(values-> fieldName); \
  1082. }
  1083. // WINSCP (hostHeader is added implicitly by neon based on uri, but for certificate check, we use base hostname
  1084. // as the bucket name can contain dots, for which the certificate check would fail)
  1085. char * hostName = strdup(params->bucketContext.hostName ? params->bucketContext.hostName : defaultHostNameG);
  1086. char * colon = strchr(hostName, ':');
  1087. if (colon != NULL)
  1088. {
  1089. *colon = '\0';
  1090. }
  1091. ne_set_realhost(request->NeonSession, hostName);
  1092. free(hostName);
  1093. append_standard_header(cacheControlHeader);
  1094. append_standard_header(contentTypeHeader);
  1095. append_standard_header(md5Header);
  1096. append_standard_header(contentDispositionHeader);
  1097. append_standard_header(contentEncodingHeader);
  1098. append_standard_header(expiresHeader);
  1099. append_standard_header(ifModifiedSinceHeader);
  1100. append_standard_header(ifUnmodifiedSinceHeader);
  1101. append_standard_header(ifMatchHeader);
  1102. append_standard_header(ifNoneMatchHeader);
  1103. append_standard_header(rangeHeader);
  1104. append_standard_header(authorizationHeader);
  1105. // Append x-amz- headers
  1106. int i;
  1107. for (i = 0; i < values->amzHeadersCount; i++) {
  1108. do_add_header(values->amzHeaders[i]);
  1109. }
  1110. return S3StatusOK;
  1111. }
  1112. static void request_deinitialize(Request *request)
  1113. {
  1114. ne_request_destroy(request->NeonRequest);
  1115. ne_session_destroy(request->NeonSession);
  1116. error_parser_deinitialize(&(request->errorParser));
  1117. }
  1118. static S3Status request_get(const RequestParams *params,
  1119. const RequestComputedValues *values,
  1120. S3RequestContext *context, // WINSCP (non-const)
  1121. Request **reqReturn)
  1122. {
  1123. Request *request = 0;
  1124. #ifndef WINSCP
  1125. // Try to get one from the request stack. We hold the lock for the
  1126. // shortest time possible here.
  1127. pthread_mutex_lock(&requestStackMutexG);
  1128. if (requestStackCountG) {
  1129. request = requestStackG[--requestStackCountG];
  1130. }
  1131. pthread_mutex_unlock(&requestStackMutexG);
  1132. // If we got one, deinitialize it for re-use
  1133. if (request) {
  1134. request_deinitialize(request);
  1135. }
  1136. // Else there wasn't one available in the request stack, so create one
  1137. else {
  1138. #endif
  1139. if ((request = (Request *) malloc(sizeof(Request))) == NULL) {
  1140. return S3StatusOutOfMemory;
  1141. }
  1142. request->NeonSession = NULL;
  1143. #ifndef WINSCP
  1144. }
  1145. #endif
  1146. // Initialize the request
  1147. #ifndef WINSCP
  1148. request->prev = 0;
  1149. request->next = 0;
  1150. #else
  1151. request->requestContext = context;
  1152. string_buffer_initialize(request->statusMessage);
  1153. #endif
  1154. // Request status is initialized to no error, will be updated whenever
  1155. // an error occurs
  1156. request->status = S3StatusOK;
  1157. S3Status status;
  1158. // Compute the URL
  1159. if ((status = compose_uri
  1160. (request->uri, sizeof(request->uri),
  1161. &(params->bucketContext), values->urlEncodedKey,
  1162. params->subResource, params->queryParams)) != S3StatusOK) {
  1163. free(request);
  1164. return status;
  1165. }
  1166. // Set all of the handle options
  1167. if ((status = setup_neon(request, params, values)) != S3StatusOK) {
  1168. free(request);
  1169. return status;
  1170. }
  1171. #ifndef WINSCP
  1172. if (context && context->setupCurlCallback &&
  1173. (status = context->setupCurlCallback(
  1174. context->curlm, request->curl,
  1175. context->setupCurlCallbackData)) != S3StatusOK) {
  1176. curl_easy_cleanup(request->curl);
  1177. free(request);
  1178. return status;
  1179. }
  1180. #endif
  1181. request->propertiesCallback = params->propertiesCallback;
  1182. request->toS3Callback = params->toS3Callback;
  1183. request->toS3CallbackBytesRemaining = params->toS3CallbackTotalSize;
  1184. request->fromS3Callback = params->fromS3Callback;
  1185. request->completeCallback = params->completeCallback;
  1186. request->callbackData = params->callbackData;
  1187. response_headers_handler_initialize(&(request->responseHeadersHandler));
  1188. request->propertiesCallbackMade = 0;
  1189. error_parser_initialize(&(request->errorParser));
  1190. *reqReturn = request;
  1191. return S3StatusOK;
  1192. }
  1193. static void request_destroy(Request *request)
  1194. {
  1195. request_deinitialize(request);
  1196. free(request);
  1197. }
  1198. static void request_release(Request *request)
  1199. {
  1200. #ifndef WINSCP
  1201. pthread_mutex_lock(&requestStackMutexG);
  1202. // If the request stack is full, destroy this one
  1203. if (requestStackCountG == REQUEST_STACK_SIZE) {
  1204. pthread_mutex_unlock(&requestStackMutexG);
  1205. #endif
  1206. request_destroy(request);
  1207. #ifndef WINSCP
  1208. }
  1209. // Else put this one at the front of the request stack; we do this because
  1210. // we want the most-recently-used curl handle to be re-used on the next
  1211. // request, to maximize our chances of re-using a TCP connection before it
  1212. // times out
  1213. else {
  1214. requestStackG[requestStackCountG++] = request;
  1215. pthread_mutex_unlock(&requestStackMutexG);
  1216. }
  1217. #endif
  1218. }
  1219. S3Status request_api_initialize(const char *userAgentInfo, int flags,
  1220. const char *defaultHostName)
  1221. {
  1222. // WINSCP (winsock must be initialized by caller)
  1223. if (!defaultHostName) {
  1224. defaultHostName = S3_DEFAULT_HOSTNAME;
  1225. }
  1226. if (snprintf(defaultHostNameG, S3_MAX_HOSTNAME_SIZE,
  1227. "%s", defaultHostName) >= S3_MAX_HOSTNAME_SIZE) {
  1228. return S3StatusUriTooLong;
  1229. }
  1230. #ifndef WINSCP
  1231. pthread_mutex_init(&requestStackMutexG, 0);
  1232. requestStackCountG = 0;
  1233. #endif
  1234. if (!userAgentInfo || !*userAgentInfo) {
  1235. userAgentInfo = "Unknown";
  1236. }
  1237. struct utsname utsn;
  1238. char platform[sizeof(utsn.sysname) + 1 + sizeof(utsn.machine) + 1];
  1239. if (uname(&utsn)) {
  1240. snprintf(platform, sizeof(platform), "Unknown");
  1241. }
  1242. else {
  1243. snprintf(platform, sizeof(platform), "%s%s%s", utsn.sysname,
  1244. utsn.machine[0] ? " " : "", utsn.machine);
  1245. }
  1246. snprintf(userAgentG, sizeof(userAgentG),
  1247. "Mozilla/4.0 (Compatible; %s; libs3 %s.%s; %s)",
  1248. userAgentInfo, LIBS3_VER_MAJOR, LIBS3_VER_MINOR, platform);
  1249. // WINSCP (Expat does not need global initialization)
  1250. return S3StatusOK;
  1251. }
  1252. void request_api_deinitialize()
  1253. {
  1254. #ifndef WINSCP
  1255. pthread_mutex_destroy(&requestStackMutexG);
  1256. // WINSCP (Expat does not need global initialization)
  1257. while (requestStackCountG--) {
  1258. request_destroy(requestStackG[requestStackCountG]);
  1259. }
  1260. #endif
  1261. }
  1262. static S3Status setup_request(const RequestParams *params,
  1263. RequestComputedValues *computed,
  1264. int forceUnsignedPayload)
  1265. {
  1266. S3Status status;
  1267. // Validate the bucket name
  1268. if (params->bucketContext.bucketName
  1269. && ((status = S3_validate_bucket_name(params->bucketContext.bucketName,
  1270. params->bucketContext.uriStyle))
  1271. != S3StatusOK)) {
  1272. return status;
  1273. }
  1274. // WINSCP (inspired by PuTTY ltime())
  1275. // Original time()/gmtime() combination did not work correctly in winter time
  1276. SYSTEMTIME st;
  1277. GetSystemTime(&st);
  1278. struct tm gmt;
  1279. memset(&gmt, 0, sizeof(gmt));
  1280. gmt.tm_sec=st.wSecond;
  1281. gmt.tm_min=st.wMinute;
  1282. gmt.tm_hour=st.wHour;
  1283. gmt.tm_mday=st.wDay;
  1284. gmt.tm_mon=st.wMonth-1;
  1285. gmt.tm_year=(st.wYear>=1900?st.wYear-1900:0);
  1286. gmt.tm_wday=st.wDayOfWeek;
  1287. gmt.tm_yday=-1; /* GetSystemTime doesn't tell us */
  1288. gmt.tm_isdst=0; /* GetSystemTime doesn't tell us */
  1289. strftime(computed->requestDateISO8601, sizeof(computed->requestDateISO8601),
  1290. "%Y%m%dT%H%M%SZ", &gmt);
  1291. // Compose the amz headers
  1292. if ((status = compose_amz_headers(params, forceUnsignedPayload, computed))
  1293. != S3StatusOK) {
  1294. return status;
  1295. }
  1296. // Compose standard headers
  1297. if ((status = compose_standard_headers(params, computed)) != S3StatusOK) {
  1298. return status;
  1299. }
  1300. // URL encode the key
  1301. if ((status = encode_key(params, computed)) != S3StatusOK) {
  1302. return status;
  1303. }
  1304. // Compute the canonicalized amz headers
  1305. canonicalize_signature_headers(computed);
  1306. // Compute the canonicalized resource
  1307. canonicalize_resource(&params->bucketContext, computed->urlEncodedKey,
  1308. computed->canonicalURI,
  1309. sizeof(computed->canonicalURI));
  1310. canonicalize_query_string(params->queryParams, params->subResource,
  1311. computed->canonicalQueryString,
  1312. sizeof(computed->canonicalQueryString));
  1313. // Compose Authorization header
  1314. if ((status = compose_auth_header(params, computed)) != S3StatusOK) {
  1315. return status;
  1316. }
  1317. #ifdef SIGNATURE_DEBUG
  1318. int i = 0;
  1319. ne_debug(NULL, NE_DBG_HTTPBODY, "\n--\nAMZ Headers:\n");
  1320. for (; i < computed->amzHeadersCount; i++) {
  1321. ne_debug(NULL, NE_DBG_HTTPBODY, "%s\n", computed->amzHeaders[i]);
  1322. }
  1323. #endif
  1324. return status;
  1325. }
  1326. void request_perform(const RequestParams *params, S3RequestContext *context)
  1327. {
  1328. Request *request;
  1329. S3Status status;
  1330. #define return_status(status) \
  1331. (*(params->completeCallback))(status, 0, params->callbackData); \
  1332. return
  1333. // These will hold the computed values
  1334. RequestComputedValues computed;
  1335. if ((status = setup_request(params, &computed, 0)) != S3StatusOK) {
  1336. return_status(status);
  1337. }
  1338. // Get an initialized Request structure now
  1339. if ((status = request_get(params, &computed, context, &request)) != S3StatusOK) {
  1340. return_status(status);
  1341. }
  1342. // WINSCP (we should always verify the peer)
  1343. #ifndef WINSCP
  1344. // If a RequestContext was provided, add the request to the curl multi
  1345. if (context) {
  1346. CURLMcode code = curl_multi_add_handle(context->curlm, request->curl);
  1347. if (code == CURLM_OK) {
  1348. if (context->requests) {
  1349. request->prev = context->requests->prev;
  1350. request->next = context->requests;
  1351. context->requests->prev->next = request;
  1352. context->requests->prev = request;
  1353. }
  1354. else {
  1355. context->requests = request->next = request->prev = request;
  1356. }
  1357. }
  1358. else {
  1359. if (request->status == S3StatusOK) {
  1360. request->status = (code == CURLM_OUT_OF_MEMORY) ?
  1361. S3StatusOutOfMemory : S3StatusInternalError;
  1362. }
  1363. request_finish(request);
  1364. }
  1365. }
  1366. // Else, perform the request immediately
  1367. else
  1368. #endif
  1369. {
  1370. NeonCode code = ne_request_dispatch(request->NeonRequest);
  1371. // Finish the request, ensuring that all callbacks have been made, and
  1372. // also releases the request
  1373. request_finish(request, code);
  1374. }
  1375. }
  1376. void request_finish(Request *request, NeonCode code)
  1377. {
  1378. // If we haven't detected this already, we now know that the headers are
  1379. // definitely done being read in
  1380. request_headers_done(request);
  1381. // If there was no error processing the request, then possibly there was
  1382. // an S3 error parsed, which should be converted into the request status
  1383. // WINSCP: We get "OK", even if there's TCP or HTTP error
  1384. if (request->status == S3StatusOK) {
  1385. // First handle S3 errors
  1386. // TemporaryRedirect S3 error has a precedence over HTTP 3xx error that carries it.
  1387. error_parser_convert_status(&(request->errorParser),
  1388. &(request->status));
  1389. #ifdef WINSCP
  1390. // This handles TCP and HTTP errors
  1391. if (request->status == S3StatusOK) {
  1392. if (code != NE_OK) {
  1393. request->status = request_neon_code_to_status(code);
  1394. if (request->errorParser.s3ErrorDetails.message == NULL) {
  1395. const char * neonError = ne_get_error(request->NeonSession);
  1396. int allFit;
  1397. string_buffer_append(request->statusMessage, neonError, strlen(neonError), allFit);
  1398. request->errorParser.s3ErrorDetails.message = request->statusMessage;
  1399. }
  1400. }
  1401. }
  1402. #endif
  1403. // If there still was no error recorded, then it is possible that
  1404. // there was in fact an error but that there was no error XML
  1405. // detailing the error
  1406. // WINSCP: We possibly never get here with neon
  1407. if ((request->status == S3StatusOK) &&
  1408. ((request->httpResponseCode < 200) ||
  1409. (request->httpResponseCode > 299))) {
  1410. switch (request->httpResponseCode) {
  1411. case 0:
  1412. // This happens if the request never got any HTTP response
  1413. // headers at all, we call this a ConnectionFailed error
  1414. request->status = S3StatusConnectionFailed;
  1415. break;
  1416. case 100: // Some versions of libcurl erroneously set HTTP
  1417. // status to this
  1418. break;
  1419. case 301:
  1420. request->status = S3StatusErrorPermanentRedirect;
  1421. break;
  1422. case 307:
  1423. request->status = S3StatusHttpErrorMovedTemporarily;
  1424. break;
  1425. case 400:
  1426. request->status = S3StatusHttpErrorBadRequest;
  1427. break;
  1428. case 403:
  1429. request->status = S3StatusHttpErrorForbidden;
  1430. break;
  1431. case 404:
  1432. request->status = S3StatusHttpErrorNotFound;
  1433. break;
  1434. case 405:
  1435. request->status = S3StatusErrorMethodNotAllowed;
  1436. break;
  1437. case 409:
  1438. request->status = S3StatusHttpErrorConflict;
  1439. break;
  1440. case 411:
  1441. request->status = S3StatusErrorMissingContentLength;
  1442. break;
  1443. case 412:
  1444. request->status = S3StatusErrorPreconditionFailed;
  1445. break;
  1446. case 416:
  1447. request->status = S3StatusErrorInvalidRange;
  1448. break;
  1449. case 500:
  1450. request->status = S3StatusErrorInternalError;
  1451. break;
  1452. case 501:
  1453. request->status = S3StatusErrorNotImplemented;
  1454. break;
  1455. case 503:
  1456. request->status = S3StatusErrorSlowDown;
  1457. break;
  1458. default:
  1459. request->status = S3StatusHttpErrorUnknown;
  1460. break;
  1461. }
  1462. }
  1463. }
  1464. (*(request->completeCallback))
  1465. (request->status, &(request->errorParser.s3ErrorDetails),
  1466. request->callbackData);
  1467. request_release(request);
  1468. }
  1469. S3Status request_neon_code_to_status(NeonCode code)
  1470. {
  1471. switch (code) {
  1472. case NE_LOOKUP:
  1473. return S3StatusNameLookupError;
  1474. case NE_CONNECT:
  1475. return S3StatusFailedToConnect;
  1476. case NE_TIMEOUT:
  1477. case NE_SOCKET:
  1478. return S3StatusConnectionFailed;
  1479. default:
  1480. return S3StatusInternalError;
  1481. }
  1482. }
  1483. #ifndef WINSCP
  1484. S3Status S3_generate_authenticated_query_string
  1485. (char *buffer, const S3BucketContext *bucketContext,
  1486. const char *key, int expires, const char *resource,
  1487. const char *httpMethod)
  1488. {
  1489. // maximum expiration period is seven days (in seconds)
  1490. #define MAX_EXPIRES 604800
  1491. if (expires < 0) {
  1492. expires = MAX_EXPIRES;
  1493. }
  1494. else if (expires > MAX_EXPIRES) {
  1495. expires = MAX_EXPIRES;
  1496. }
  1497. // WinSCP
  1498. RequestParams params =
  1499. { http_request_method_to_type(httpMethod),
  1500. { bucketContext->hostName, bucketContext->bucketName, bucketContext->protocol, bucketContext->uriStyle, bucketContext->accessKeyId, bucketContext->secretAccessKey, bucketContext->securityToken, bucketContext->authRegion },
  1501. key, NULL,
  1502. resource,
  1503. NULL, NULL, NULL, 0, 0, NULL, NULL, NULL, 0, NULL, NULL, NULL, 0};
  1504. RequestComputedValues computed;
  1505. S3Status status = setup_request(&params, &computed, 1);
  1506. if (status != S3StatusOK) {
  1507. return status;
  1508. }
  1509. // Finally, compose the URI, with params
  1510. char queryParams[sizeof("X-Amz-Algorithm=AWS4-HMAC-SHA256") +
  1511. sizeof("&X-Amz-Credential=") +
  1512. sizeof(computed.authCredential) +
  1513. sizeof("&X-Amz-Date=") +
  1514. sizeof(computed.requestDateISO8601) +
  1515. sizeof("&X-Amz-Expires=") + 64 +
  1516. sizeof("&X-Amz-SignedHeaders=") +
  1517. sizeof(computed.signedHeaders) +
  1518. sizeof("&X-Amz-Signature=") +
  1519. sizeof(computed.requestSignatureHex) + 1];
  1520. snprintf(queryParams, sizeof(queryParams),
  1521. "X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=%s"
  1522. "&X-Amz-Date=%s&X-Amz-Expires=%d"
  1523. "&X-Amz-SignedHeaders=%s&X-Amz-Signature=%s",
  1524. computed.authCredential, computed.requestDateISO8601, expires,
  1525. computed.signedHeaders, computed.requestSignatureHex);
  1526. return compose_uri(buffer, S3_MAX_AUTHENTICATED_QUERY_STRING_SIZE,
  1527. bucketContext, computed.urlEncodedKey, resource,
  1528. queryParams);
  1529. }
  1530. #endif