request.c 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799
  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. char bucketKey[S3_MAX_METADATA_SIZE];
  324. snprintf(bucketKey, sizeof(bucketKey), "/%s/%s",
  325. params->copySourceBucketName, params->copySourceKey);
  326. append_amz_header(values, 0, "x-amz-copy-source", bucketKey);
  327. }
  328. // If byteCount != 0 then we're just copying a range, add header
  329. if (params->byteCount > 0) {
  330. char byteRange[S3_MAX_METADATA_SIZE];
  331. snprintf(byteRange, sizeof(byteRange), "bytes=%zd-%zd",
  332. params->startByte, params->startByte + params->byteCount);
  333. append_amz_header(values, 0, "x-amz-copy-source-range", byteRange);
  334. }
  335. // And the x-amz-metadata-directive header
  336. if (properties) {
  337. append_amz_header(values, 0, "x-amz-metadata-directive", "REPLACE");
  338. }
  339. }
  340. // Add the x-amz-security-token header if necessary
  341. if (params->bucketContext.securityToken) {
  342. append_amz_header(values, 0, "x-amz-security-token",
  343. params->bucketContext.securityToken);
  344. }
  345. if (!forceUnsignedPayload
  346. && (params->httpRequestType == HttpRequestTypeGET
  347. || params->httpRequestType == HttpRequestTypeCOPY
  348. || params->httpRequestType == HttpRequestTypeDELETE
  349. || params->httpRequestType == HttpRequestTypeHEAD)) {
  350. // empty payload
  351. unsigned char md[S3_SHA256_DIGEST_LENGTH];
  352. #ifdef __APPLE__
  353. CC_SHA256("", 0, md);
  354. #else
  355. SHA256((const unsigned char*) "", 0, md);
  356. #endif
  357. values->payloadHash[0] = '\0';
  358. int i = 0;
  359. for (; i < S3_SHA256_DIGEST_LENGTH; i++) {
  360. snprintf(&(values->payloadHash[i * 2]), 3, "%02x", md[i]);
  361. }
  362. }
  363. else {
  364. // TODO: figure out how to manage signed payloads
  365. strcpy(values->payloadHash, "UNSIGNED-PAYLOAD");
  366. }
  367. append_amz_header(values, 0, "x-amz-content-sha256",
  368. values->payloadHash);
  369. return S3StatusOK;
  370. }
  371. // Composes the other headers
  372. static S3Status compose_standard_headers(const RequestParams *params,
  373. RequestComputedValues *values)
  374. {
  375. #define do_put_header(fmt, sourceField, destField, badError, tooLongError) \
  376. do { \
  377. if (params->putProperties && \
  378. params->putProperties-> sourceField && \
  379. params->putProperties-> sourceField[0]) { \
  380. /* Skip whitespace at beginning of val */ \
  381. const char *val = params->putProperties-> sourceField; \
  382. while (*val && is_blank(*val)) { \
  383. val++; \
  384. } \
  385. if (!*val) { \
  386. return badError; \
  387. } \
  388. /* Compose header, make sure it all fit */ \
  389. int len = snprintf(values-> destField, \
  390. sizeof(values-> destField), fmt, val); \
  391. if (len >= (int) sizeof(values-> destField)) { \
  392. return tooLongError; \
  393. } \
  394. /* Now remove the whitespace at the end */ \
  395. while (is_blank(values-> destField[len])) { \
  396. len--; \
  397. } \
  398. values-> destField[len] = 0; \
  399. } \
  400. else { \
  401. values-> destField[0] = 0; \
  402. } \
  403. } while (0)
  404. #define do_get_header(fmt, sourceField, destField, badError, tooLongError) \
  405. do { \
  406. if (params->getConditions && \
  407. params->getConditions-> sourceField && \
  408. params->getConditions-> sourceField[0]) { \
  409. /* Skip whitespace at beginning of val */ \
  410. const char *val = params->getConditions-> sourceField; \
  411. while (*val && is_blank(*val)) { \
  412. val++; \
  413. } \
  414. if (!*val) { \
  415. return badError; \
  416. } \
  417. /* Compose header, make sure it all fit */ \
  418. int len = snprintf(values-> destField, \
  419. sizeof(values-> destField), fmt, val); \
  420. if (len >= (int) sizeof(values-> destField)) { \
  421. return tooLongError; \
  422. } \
  423. /* Now remove the whitespace at the end */ \
  424. while (is_blank(values-> destField[len])) { \
  425. len--; \
  426. } \
  427. values-> destField[len] = 0; \
  428. } \
  429. else { \
  430. values-> destField[0] = 0; \
  431. } \
  432. } while (0)
  433. // Host
  434. if (params->bucketContext.uriStyle == S3UriStyleVirtualHost) {
  435. const char *requestHostName = params->bucketContext.hostName
  436. ? params->bucketContext.hostName : defaultHostNameG;
  437. size_t len = snprintf(values->hostHeader, sizeof(values->hostHeader),
  438. "Host: %s.%s", params->bucketContext.bucketName,
  439. requestHostName);
  440. if (len >= sizeof(values->hostHeader)) {
  441. return S3StatusUriTooLong;
  442. }
  443. while (is_blank(values->hostHeader[len])) {
  444. len--;
  445. }
  446. values->hostHeader[len] = 0;
  447. }
  448. else {
  449. size_t len = snprintf(
  450. values->hostHeader,
  451. sizeof(values->hostHeader),
  452. "Host: %s",
  453. params->bucketContext.hostName ?
  454. params->bucketContext.hostName : defaultHostNameG);
  455. if (len >= sizeof(values->hostHeader)) {
  456. return S3StatusUriTooLong;
  457. }
  458. while (is_blank(values->hostHeader[len])) {
  459. len--;
  460. }
  461. values->hostHeader[len] = 0;
  462. }
  463. // Cache-Control
  464. do_put_header("Cache-Control: %s", cacheControl, cacheControlHeader,
  465. S3StatusBadCacheControl, S3StatusCacheControlTooLong);
  466. // ContentType
  467. do_put_header("Content-Type: %s", contentType, contentTypeHeader,
  468. S3StatusBadContentType, S3StatusContentTypeTooLong);
  469. // MD5
  470. do_put_header("Content-MD5: %s", md5, md5Header, S3StatusBadMD5,
  471. S3StatusMD5TooLong);
  472. // Content-Disposition
  473. do_put_header("Content-Disposition: attachment; filename=\"%s\"",
  474. contentDispositionFilename, contentDispositionHeader,
  475. S3StatusBadContentDispositionFilename,
  476. S3StatusContentDispositionFilenameTooLong);
  477. // ContentEncoding
  478. do_put_header("Content-Encoding: %s", contentEncoding,
  479. contentEncodingHeader, S3StatusBadContentEncoding,
  480. S3StatusContentEncodingTooLong);
  481. // Expires
  482. // WINSCP (not implemented)
  483. values->expiresHeader[0] = 0;
  484. // If-Modified-Since
  485. // WINSCP (not implemented)
  486. values->ifModifiedSinceHeader[0] = 0;
  487. // If-Unmodified-Since header
  488. // WINSCP (not implemented)
  489. values->ifUnmodifiedSinceHeader[0] = 0;
  490. // If-Match header
  491. do_get_header("If-Match: %s", ifMatchETag, ifMatchHeader,
  492. S3StatusBadIfMatchETag, S3StatusIfMatchETagTooLong);
  493. // If-None-Match header
  494. do_get_header("If-None-Match: %s", ifNotMatchETag, ifNoneMatchHeader,
  495. S3StatusBadIfNotMatchETag,
  496. S3StatusIfNotMatchETagTooLong);
  497. // Range header
  498. if (params->startByte || params->byteCount) {
  499. if (params->byteCount) {
  500. snprintf(values->rangeHeader, sizeof(values->rangeHeader),
  501. "Range: bytes=%llu-%llu",
  502. (unsigned long long) params->startByte,
  503. (unsigned long long) (params->startByte +
  504. params->byteCount - 1));
  505. }
  506. else {
  507. snprintf(values->rangeHeader, sizeof(values->rangeHeader),
  508. "Range: bytes=%llu-",
  509. (unsigned long long) params->startByte);
  510. }
  511. }
  512. else {
  513. values->rangeHeader[0] = 0;
  514. }
  515. return S3StatusOK;
  516. }
  517. // URL encodes the params->key value into params->urlEncodedKey
  518. static S3Status encode_key(const RequestParams *params,
  519. RequestComputedValues *values)
  520. {
  521. return (urlEncode(values->urlEncodedKey, params->key, S3_MAX_KEY_SIZE, 0) ?
  522. S3StatusOK : S3StatusUriTooLong);
  523. }
  524. // Simple comparison function for comparing two "<key><delim><value>"
  525. // delimited strings, returning true if the key of s1 comes
  526. // before the key of s2 alphabetically, false if not
  527. static int headerle(const char *s1, const char *s2, char delim)
  528. {
  529. while (1) {
  530. if (*s1 == delim) {
  531. return (*s2 != delim);
  532. }
  533. else if (*s2 == delim) {
  534. return 0;
  535. }
  536. else if (*s2 < *s1) {
  537. return 0;
  538. }
  539. else if (*s2 > *s1) {
  540. return 1;
  541. }
  542. s1++, s2++;
  543. }
  544. #ifndef WINSCP
  545. return 0;
  546. #endif
  547. }
  548. // Replace this with merge sort eventually, it's the best stable sort. But
  549. // since typically the number of elements being sorted is small, it doesn't
  550. // matter that much which sort is used, and gnome sort is the world's simplest
  551. // stable sort. Added a slight twist to the standard gnome_sort - don't go
  552. // forward +1, go forward to the last highest index considered. This saves
  553. // all the string comparisons that would be done "going forward", and thus
  554. // only does the necessary string comparisons to move values back into their
  555. // sorted position.
  556. static void kv_gnome_sort(const char **values, int size, char delim)
  557. {
  558. int i = 0, last_highest = 0;
  559. while (i < size) {
  560. if ((i == 0) || headerle(values[i - 1], values[i], delim)) {
  561. i = ++last_highest;
  562. }
  563. else {
  564. const char *tmp = values[i];
  565. values[i] = values[i - 1];
  566. values[--i] = tmp;
  567. }
  568. }
  569. }
  570. // Canonicalizes the signature headers into the canonicalizedSignatureHeaders buffer
  571. static void canonicalize_signature_headers(RequestComputedValues *values)
  572. {
  573. // Make a copy of the headers that will be sorted
  574. const char *sortedHeaders[S3_MAX_METADATA_COUNT + 3];
  575. memcpy(sortedHeaders, values->amzHeaders,
  576. (values->amzHeadersCount * sizeof(sortedHeaders[0])));
  577. // add the content-type header and host header
  578. int headerCount = values->amzHeadersCount;
  579. if (values->contentTypeHeader[0]) {
  580. sortedHeaders[headerCount++] = values->contentTypeHeader;
  581. }
  582. if (values->hostHeader[0]) {
  583. sortedHeaders[headerCount++] = values->hostHeader;
  584. }
  585. if (values->rangeHeader[0]) {
  586. sortedHeaders[headerCount++] = values->rangeHeader;
  587. }
  588. if (values->md5Header[0]) {
  589. sortedHeaders[headerCount++] = values->md5Header;
  590. }
  591. // Now sort these
  592. kv_gnome_sort(sortedHeaders, headerCount, ':');
  593. // Now copy this sorted list into the buffer, all the while:
  594. // - folding repeated headers into single lines, and
  595. // - folding multiple lines
  596. // - removing the space after the colon
  597. int lastHeaderLen = 0;
  598. char *buffer = values->canonicalizedSignatureHeaders;
  599. char *hbuf = values->signedHeaders;
  600. int i = 0;
  601. for (; i < headerCount; i++) {
  602. const char *header = sortedHeaders[i];
  603. const char *c = header;
  604. char v;
  605. // If the header names are the same, append the next value
  606. if ((i > 0) &&
  607. !strncmp(header, sortedHeaders[i - 1], lastHeaderLen)) {
  608. // Replacing the previous newline with a comma
  609. *(buffer - 1) = ',';
  610. // Skip the header name and space
  611. c += (lastHeaderLen + 1);
  612. }
  613. // Else this is a new header
  614. else {
  615. // Copy in everything up to the space in the ": "
  616. while (*c != ' ') {
  617. v = tolower(*c++);
  618. *buffer++ = v;
  619. *hbuf++ = v;
  620. }
  621. // replace the ":" with a ";"
  622. *(hbuf - 1) = ';';
  623. // Save the header len since it's a new header
  624. lastHeaderLen = c - header;
  625. // Skip the space
  626. c++;
  627. }
  628. // Now copy in the value, folding the lines
  629. while (*c) {
  630. // If c points to a \r\n[whitespace] sequence, then fold
  631. // this newline out
  632. if ((*c == '\r') && (*(c + 1) == '\n') && is_blank(*(c + 2))) {
  633. c += 3;
  634. while (is_blank(*c)) {
  635. c++;
  636. }
  637. // Also, what has most recently been copied into buffer may
  638. // have been whitespace, and since we're folding whitespace
  639. // out around this newline sequence, back buffer up over
  640. // any whitespace it contains
  641. while (is_blank(*(buffer - 1))) {
  642. buffer--;
  643. }
  644. continue;
  645. }
  646. *buffer++ = *c++;
  647. }
  648. // Finally, add the newline
  649. *buffer++ = '\n';
  650. }
  651. // Remove the extra trailing semicolon from the header name list
  652. // and terminate the string.
  653. *(hbuf - 1) = '\0';
  654. // Terminate the buffer
  655. *buffer = 0;
  656. }
  657. // Canonicalizes the resource into params->canonicalizedResource
  658. static void canonicalize_resource(const S3BucketContext *context,
  659. const char *urlEncodedKey,
  660. char *buffer, unsigned int buffer_max)
  661. {
  662. int len = 0;
  663. *buffer = 0;
  664. #define append(str) len += snprintf(&(buffer[len]), buffer_max - len, "%s", str)
  665. if (context->uriStyle == S3UriStylePath) {
  666. if (context->bucketName && context->bucketName[0]) {
  667. buffer[len++] = '/';
  668. append(context->bucketName);
  669. }
  670. }
  671. append("/");
  672. if (urlEncodedKey && urlEncodedKey[0]) {
  673. append(urlEncodedKey);
  674. }
  675. #undef append
  676. }
  677. static void sort_query_string(const char *queryString, char *result,
  678. unsigned int result_size)
  679. {
  680. #ifdef SIGNATURE_DEBUG
  681. ne_debug(NULL, NE_DBG_HTTPBODY, "\n--\nsort_and_urlencode\nqueryString: %s\n", queryString);
  682. #endif
  683. unsigned int numParams = 1;
  684. const char *tmp = queryString;
  685. while ((tmp = strchr(tmp, '&')) != NULL) {
  686. numParams++;
  687. tmp++;
  688. }
  689. const char** params = new const char*[numParams]; // WINSCP (heap allocation)
  690. // Where did strdup go?!??
  691. int queryStringLen = strlen(queryString);
  692. char *buf = (char *) malloc(queryStringLen + 1);
  693. char *tok = buf;
  694. strcpy(tok, queryString);
  695. const char *token = NULL;
  696. char *save = NULL;
  697. unsigned int i = 0;
  698. while ((token = strtok_r(tok, "&", &save)) != NULL) {
  699. tok = NULL;
  700. params[i++] = token;
  701. }
  702. kv_gnome_sort(params, numParams, '=');
  703. #ifdef SIGNATURE_DEBUG
  704. for (i = 0; i < numParams; i++) {
  705. ne_debug(NULL, NE_DBG_HTTPBODY, "%d: %s\n", i, params[i]);
  706. }
  707. #endif
  708. // All params are urlEncoded
  709. #define append(str) len += snprintf(&(result[len]), result_size - len, "%s", str)
  710. unsigned int pi = 0;
  711. unsigned int len = 0;
  712. for (; pi < numParams; pi++) {
  713. append(params[pi]);
  714. append("&");
  715. }
  716. // Take off the extra '&'
  717. if (len > 0) {
  718. result[len - 1] = 0;
  719. }
  720. #undef append
  721. delete[] params; // WINSCP (heap allocation)
  722. free(buf);
  723. }
  724. // Canonicalize the query string part of the request into a buffer
  725. static void canonicalize_query_string(const char *queryParams,
  726. const char *subResource,
  727. char *buffer, unsigned int buffer_size)
  728. {
  729. int len = 0;
  730. *buffer = 0;
  731. #define append(str) len += snprintf(&(buffer[len]), buffer_size - len, "%s", str)
  732. if (queryParams && queryParams[0]) {
  733. int sortedLen = strlen(queryParams) * 2;
  734. char * sorted = new char[sortedLen]; // WINSCP (heap allocation)
  735. sorted[0] = '\0';
  736. sort_query_string(queryParams, sorted, sortedLen);
  737. append(sorted);
  738. delete[] sorted; // WINSCP (heap allocation)
  739. }
  740. if (subResource && subResource[0]) {
  741. if (queryParams && queryParams[0]) {
  742. append("&");
  743. }
  744. append(subResource);
  745. if (!strchr(subResource, '=')) {
  746. append("=");
  747. }
  748. }
  749. #undef append
  750. }
  751. static HttpRequestType http_request_method_to_type(const char *method)
  752. {
  753. if (!method) {
  754. return HttpRequestTypeInvalid;
  755. }
  756. if (strcmp(method, "POST") == 0) {
  757. return HttpRequestTypePOST;
  758. }
  759. else if (strcmp(method, "GET") == 0) {
  760. return HttpRequestTypeGET;
  761. }
  762. else if (strcmp(method, "HEAD") == 0) {
  763. return HttpRequestTypeHEAD;
  764. }
  765. else if (strcmp(method, "PUT") == 0) {
  766. return HttpRequestTypePUT;
  767. }
  768. else if (strcmp(method, "COPY") == 0) {
  769. return HttpRequestTypeCOPY;
  770. }
  771. else if (strcmp(method, "DELETE") == 0) {
  772. return HttpRequestTypeDELETE;
  773. }
  774. return HttpRequestTypeInvalid;
  775. }
  776. // Convert an HttpRequestType to an HTTP Verb string
  777. static const char *http_request_type_to_verb(HttpRequestType requestType)
  778. {
  779. switch (requestType) {
  780. case HttpRequestTypePOST:
  781. return "POST";
  782. case HttpRequestTypeGET:
  783. return "GET";
  784. case HttpRequestTypeHEAD:
  785. return "HEAD";
  786. case HttpRequestTypePUT:
  787. case HttpRequestTypeCOPY:
  788. return "PUT";
  789. default: // HttpRequestTypeDELETE
  790. return "DELETE";
  791. }
  792. }
  793. // Composes the Authorization header for the request
  794. static S3Status compose_auth_header(const RequestParams *params,
  795. RequestComputedValues *values)
  796. {
  797. const char *httpMethod = http_request_type_to_verb(params->httpRequestType);
  798. int canonicalRequestLen = strlen(httpMethod) + 1 +
  799. strlen(values->canonicalURI) + 1 +
  800. strlen(values->canonicalQueryString) + 1 +
  801. strlen(values->canonicalizedSignatureHeaders) + 1 +
  802. strlen(values->signedHeaders) + 1 +
  803. 2 * S3_SHA256_DIGEST_LENGTH + 1; // 2 hex digits for each byte
  804. int len = 0;
  805. char * canonicalRequest = new char[canonicalRequestLen]; // WINSCP (heap allocation)
  806. // WINSCP (heap allocation)
  807. #define buf_append(buf, format, ...) \
  808. len += snprintf(&(buf[len]), size - len, \
  809. format, __VA_ARGS__)
  810. canonicalRequest[0] = '\0';
  811. int size = canonicalRequestLen; // WINSCP
  812. buf_append(canonicalRequest, "%s\n", httpMethod);
  813. buf_append(canonicalRequest, "%s\n", values->canonicalURI);
  814. buf_append(canonicalRequest, "%s\n", values->canonicalQueryString);
  815. buf_append(canonicalRequest, "%s\n", values->canonicalizedSignatureHeaders);
  816. buf_append(canonicalRequest, "%s\n", values->signedHeaders);
  817. buf_append(canonicalRequest, "%s", values->payloadHash);
  818. #ifdef SIGNATURE_DEBUG
  819. ne_debug(NULL, NE_DBG_HTTPBODY, "--\nCanonical Request:\n%s\n", canonicalRequest);
  820. #endif
  821. len = 0;
  822. unsigned char canonicalRequestHash[S3_SHA256_DIGEST_LENGTH];
  823. #ifdef __APPLE__
  824. CC_SHA256(canonicalRequest, strlen(canonicalRequest), canonicalRequestHash);
  825. #else
  826. const unsigned char *rqstData = (const unsigned char*) canonicalRequest;
  827. SHA256(rqstData, strlen(canonicalRequest), canonicalRequestHash);
  828. #endif
  829. delete[] canonicalRequest; // WINSCP
  830. char canonicalRequestHashHex[2 * S3_SHA256_DIGEST_LENGTH + 1];
  831. size = sizeof(canonicalRequestHashHex); // WINSCP
  832. canonicalRequestHashHex[0] = '\0';
  833. int i = 0;
  834. for (; i < S3_SHA256_DIGEST_LENGTH; i++) {
  835. buf_append(canonicalRequestHashHex, "%02x", canonicalRequestHash[i]);
  836. }
  837. const char *awsRegion = S3_DEFAULT_REGION;
  838. if (params->bucketContext.authRegion) {
  839. awsRegion = params->bucketContext.authRegion;
  840. }
  841. char scope[sizeof(values->requestDateISO8601) + sizeof(awsRegion) +
  842. sizeof("//s3/aws4_request") + 1];
  843. snprintf(scope, sizeof(scope), "%.8s/%s/s3/aws4_request",
  844. values->requestDateISO8601, awsRegion);
  845. const int stringToSignLen = 17 + 17 + sizeof(values->requestDateISO8601) +
  846. sizeof(scope) + sizeof(canonicalRequestHashHex) + 1; // WINSCP (heap allocation)
  847. char * stringToSign = new char[stringToSignLen];
  848. snprintf(stringToSign, stringToSignLen, "AWS4-HMAC-SHA256\n%s\n%s\n%s",
  849. values->requestDateISO8601, scope, canonicalRequestHashHex);
  850. #ifdef SIGNATURE_DEBUG
  851. ne_debug(NULL, NE_DBG_HTTPBODY, "--\nString to Sign:\n%s\n", stringToSign);
  852. #endif
  853. const char *secretAccessKey = params->bucketContext.secretAccessKey;
  854. const int accessKeyLen = strlen(secretAccessKey) + 5; // WINSCP (heap allocation)
  855. char * accessKey = new char[accessKeyLen];
  856. snprintf(accessKey, accessKeyLen, "AWS4%s", secretAccessKey);
  857. #ifdef __APPLE__
  858. unsigned char dateKey[S3_SHA256_DIGEST_LENGTH];
  859. CCHmac(kCCHmacAlgSHA256, accessKey, strlen(accessKey),
  860. values->requestDateISO8601, 8, dateKey);
  861. unsigned char dateRegionKey[S3_SHA256_DIGEST_LENGTH];
  862. CCHmac(kCCHmacAlgSHA256, dateKey, S3_SHA256_DIGEST_LENGTH, awsRegion,
  863. strlen(awsRegion), dateRegionKey);
  864. unsigned char dateRegionServiceKey[S3_SHA256_DIGEST_LENGTH];
  865. CCHmac(kCCHmacAlgSHA256, dateRegionKey, S3_SHA256_DIGEST_LENGTH, "s3", 2,
  866. dateRegionServiceKey);
  867. unsigned char signingKey[S3_SHA256_DIGEST_LENGTH];
  868. CCHmac(kCCHmacAlgSHA256, dateRegionServiceKey, S3_SHA256_DIGEST_LENGTH,
  869. "aws4_request", strlen("aws4_request"), signingKey);
  870. unsigned char finalSignature[S3_SHA256_DIGEST_LENGTH];
  871. CCHmac(kCCHmacAlgSHA256, signingKey, S3_SHA256_DIGEST_LENGTH, stringToSign,
  872. strlen(stringToSign), finalSignature);
  873. #else
  874. const EVP_MD *sha256evp = EVP_sha256();
  875. unsigned char dateKey[S3_SHA256_DIGEST_LENGTH];
  876. HMAC(sha256evp, accessKey, strlen(accessKey),
  877. (const unsigned char*) values->requestDateISO8601, 8, dateKey,
  878. NULL);
  879. unsigned char dateRegionKey[S3_SHA256_DIGEST_LENGTH];
  880. HMAC(sha256evp, dateKey, S3_SHA256_DIGEST_LENGTH,
  881. (const unsigned char*) awsRegion, strlen(awsRegion), dateRegionKey,
  882. NULL);
  883. unsigned char dateRegionServiceKey[S3_SHA256_DIGEST_LENGTH];
  884. HMAC(sha256evp, dateRegionKey, S3_SHA256_DIGEST_LENGTH,
  885. (const unsigned char*) "s3", 2, dateRegionServiceKey, NULL);
  886. unsigned char signingKey[S3_SHA256_DIGEST_LENGTH];
  887. HMAC(sha256evp, dateRegionServiceKey, S3_SHA256_DIGEST_LENGTH,
  888. (const unsigned char*) "aws4_request", strlen("aws4_request"),
  889. signingKey,
  890. NULL);
  891. unsigned char finalSignature[S3_SHA256_DIGEST_LENGTH];
  892. HMAC(sha256evp, signingKey, S3_SHA256_DIGEST_LENGTH,
  893. (const unsigned char*) stringToSign, strlen(stringToSign),
  894. finalSignature, NULL);
  895. #endif
  896. delete[] accessKey; // WINSCP
  897. delete[] stringToSign; // WINSCP
  898. len = 0;
  899. size = sizeof(values->requestSignatureHex); // WINSCP
  900. values->requestSignatureHex[0] = '\0';
  901. for (i = 0; i < S3_SHA256_DIGEST_LENGTH; i++) {
  902. buf_append(values->requestSignatureHex, "%02x", finalSignature[i]);
  903. }
  904. snprintf(values->authCredential, sizeof(values->authCredential),
  905. "%s/%.8s/%s/s3/aws4_request", params->bucketContext.accessKeyId,
  906. values->requestDateISO8601, awsRegion);
  907. snprintf(values->authorizationHeader,
  908. sizeof(values->authorizationHeader),
  909. "Authorization: AWS4-HMAC-SHA256 Credential=%s,SignedHeaders=%s,Signature=%s",
  910. values->authCredential, values->signedHeaders,
  911. values->requestSignatureHex);
  912. #ifdef SIGNATURE_DEBUG
  913. ne_debug(NULL, NE_DBG_HTTPBODY, "--\nAuthorization Header:\n%s\n", values->authorizationHeader);
  914. #endif
  915. return S3StatusOK;
  916. #undef buf_append
  917. }
  918. // Compose the URI to use for the request given the request parameters
  919. static S3Status compose_uri(char *buffer, int bufferSize,
  920. const S3BucketContext *bucketContext,
  921. const char *urlEncodedKey,
  922. const char *subResource, const char *queryParams)
  923. {
  924. int len = 0;
  925. #define uri_append(fmt, ...) \
  926. do { \
  927. len += snprintf(&(buffer[len]), bufferSize - len, fmt, __VA_ARGS__); \
  928. if (len >= bufferSize) { \
  929. return S3StatusUriTooLong; \
  930. } \
  931. } while (0)
  932. uri_append("http%s://",
  933. (bucketContext->protocol == S3ProtocolHTTP) ? "" : "s");
  934. const char *hostName =
  935. bucketContext->hostName ? bucketContext->hostName : defaultHostNameG;
  936. if (bucketContext->bucketName &&
  937. bucketContext->bucketName[0]) {
  938. if (bucketContext->uriStyle == S3UriStyleVirtualHost) {
  939. #ifndef WINSCP
  940. // We cannot change Host: header with neon.
  941. // Instead we tweak host name validation
  942. if (strchr(bucketContext->bucketName, '.') == NULL) {
  943. #endif
  944. uri_append("%s.%s", bucketContext->bucketName, hostName);
  945. #ifndef WINSCP
  946. }
  947. else {
  948. // We'll use the hostName in the URL, and then explicitly set
  949. // the Host header to match bucket.host so that host validation
  950. // works.
  951. uri_append("%s", hostName);
  952. }
  953. #endif
  954. }
  955. else {
  956. uri_append("%s/%s", hostName, bucketContext->bucketName);
  957. }
  958. }
  959. else {
  960. uri_append("%s", hostName);
  961. }
  962. uri_append("%s", "/");
  963. uri_append("%s", urlEncodedKey);
  964. if (subResource && subResource[0]) {
  965. uri_append("?%s", subResource);
  966. }
  967. if (queryParams) {
  968. uri_append("%s%s", (subResource && subResource[0]) ? "&" : "?",
  969. queryParams);
  970. }
  971. return S3StatusOK;
  972. }
  973. #ifdef WINSCP
  974. int neon_ssl_callback(void * user_data, int failures, const ne_ssl_certificate * certificate)
  975. {
  976. Request *request = (Request *) user_data;
  977. int result = NE_ERROR;
  978. if (request->requestContext->sslCallback != NULL)
  979. {
  980. result = request->requestContext->sslCallback(failures, certificate, request->requestContext->sslCallbackData);
  981. }
  982. return result;
  983. }
  984. #endif
  985. // WINSCP (neon)
  986. // Sets up the neon handle given the completely computed RequestParams
  987. static S3Status setup_neon(Request *request,
  988. const RequestParams *params,
  989. const RequestComputedValues *values)
  990. {
  991. NeonCode status;
  992. ne_uri uri;
  993. if (ne_uri_parse(request->uri, &uri) != 0)
  994. {
  995. return S3StatusFailedToInitializeRequest;
  996. }
  997. int port = uri.port;
  998. if (port == 0)
  999. {
  1000. port = ne_uri_defaultport(uri.scheme);
  1001. }
  1002. request->NeonSession = ne_session_create(uri.scheme, uri.host, port);
  1003. if (request->requestContext->sessionCallback != NULL)
  1004. {
  1005. request->requestContext->sessionCallback(request->NeonSession, request->requestContext->sessionCallbackData);
  1006. }
  1007. char method[64];
  1008. strcpy(method, "GET");
  1009. switch (params->httpRequestType) {
  1010. case HttpRequestTypeHEAD:
  1011. strcpy(method, "HEAD");
  1012. break;
  1013. case HttpRequestTypePOST:
  1014. strcpy(method, "POST");
  1015. break;
  1016. case HttpRequestTypePUT:
  1017. case HttpRequestTypeCOPY:
  1018. strcpy(method, "PUT");
  1019. break;
  1020. case HttpRequestTypeDELETE:
  1021. strcpy(method, "DELETE");
  1022. break;
  1023. default: // HttpRequestTypeGET
  1024. break;
  1025. }
  1026. ne_buffer * buf = ne_buffer_create();
  1027. ne_buffer_zappend(buf, uri.path);
  1028. if (uri.query != NULL)
  1029. {
  1030. ne_buffer_concat(buf, "?", uri.query, NULL);
  1031. }
  1032. request->NeonRequest = ne_request_create(request->NeonSession, method, buf->data);
  1033. ne_buffer_destroy(buf);
  1034. ne_uri_free(&uri);
  1035. // Set header callback and data
  1036. // Set read callback, data, and readSize
  1037. ne_add_response_body_reader(request->NeonRequest, neon_header_func, neon_write_func, request);
  1038. // Set write callback and data
  1039. if ((params->httpRequestType == HttpRequestTypePUT) ||
  1040. (params->httpRequestType == HttpRequestTypePOST))
  1041. {
  1042. ne_set_request_body_provider(request->NeonRequest, (ne_off_t)params->toS3CallbackTotalSize, neon_read_func, request);
  1043. }
  1044. // WINSCP (Last-Modified parsed in response_headers_handler_done)
  1045. // xxx todo - support setting the proxy for Curl to use (can't use https
  1046. // for proxies though)
  1047. // xxx todo - support setting the network interface for Curl to use
  1048. // WINSCP (neon sets "nodelay" unconditionally)
  1049. // WINSCP (we should verify peer always)
  1050. ne_ssl_set_verify(request->NeonSession, neon_ssl_callback, request);
  1051. ne_ssl_trust_default_ca(request->NeonSession);
  1052. // Follow any redirection directives that S3 sends
  1053. // TODO
  1054. // Set the User-Agent; maybe Amazon will track these?
  1055. ne_set_useragent(request->NeonSession, userAgentG);
  1056. if (params->timeoutMs > 0) {
  1057. ne_set_read_timeout(request->NeonSession, params->timeoutMs);
  1058. ne_set_connect_timeout(request->NeonSession, params->timeoutMs);
  1059. }
  1060. #define do_add_header(header) \
  1061. { \
  1062. char * buf = new char[strlen(header) + 1]; \
  1063. strcpy(buf, header); \
  1064. char * p = strchr(buf, ':'); \
  1065. if (p != NULL) \
  1066. { \
  1067. *p = '\0'; \
  1068. p++; \
  1069. while (is_blank(p[0])) p++; \
  1070. ne_add_request_header(request->NeonRequest, buf, p); \
  1071. } \
  1072. delete[] buf; \
  1073. }
  1074. // Append standard headers
  1075. #define append_standard_header(fieldName) \
  1076. if (values-> fieldName [0]) { \
  1077. do_add_header(values-> fieldName); \
  1078. }
  1079. // WINSCP (hostHeader is added implicitly by neon based on uri, but for certificate check, we use base hostname
  1080. // as the bucket name can contain dots, for which the certificate check would fail)
  1081. ne_set_realhost(request->NeonSession, params->bucketContext.hostName ? params->bucketContext.hostName : defaultHostNameG);
  1082. append_standard_header(cacheControlHeader);
  1083. append_standard_header(contentTypeHeader);
  1084. append_standard_header(md5Header);
  1085. append_standard_header(contentDispositionHeader);
  1086. append_standard_header(contentEncodingHeader);
  1087. append_standard_header(expiresHeader);
  1088. append_standard_header(ifModifiedSinceHeader);
  1089. append_standard_header(ifUnmodifiedSinceHeader);
  1090. append_standard_header(ifMatchHeader);
  1091. append_standard_header(ifNoneMatchHeader);
  1092. append_standard_header(rangeHeader);
  1093. append_standard_header(authorizationHeader);
  1094. // Append x-amz- headers
  1095. int i;
  1096. for (i = 0; i < values->amzHeadersCount; i++) {
  1097. do_add_header(values->amzHeaders[i]);
  1098. }
  1099. return S3StatusOK;
  1100. }
  1101. static void request_deinitialize(Request *request)
  1102. {
  1103. ne_request_destroy(request->NeonRequest);
  1104. ne_session_destroy(request->NeonSession);
  1105. error_parser_deinitialize(&(request->errorParser));
  1106. }
  1107. static S3Status request_get(const RequestParams *params,
  1108. const RequestComputedValues *values,
  1109. S3RequestContext *context, // WINSCP (non-const)
  1110. Request **reqReturn)
  1111. {
  1112. Request *request = 0;
  1113. #ifndef WINSCP
  1114. // Try to get one from the request stack. We hold the lock for the
  1115. // shortest time possible here.
  1116. pthread_mutex_lock(&requestStackMutexG);
  1117. if (requestStackCountG) {
  1118. request = requestStackG[--requestStackCountG];
  1119. }
  1120. pthread_mutex_unlock(&requestStackMutexG);
  1121. // If we got one, deinitialize it for re-use
  1122. if (request) {
  1123. request_deinitialize(request);
  1124. }
  1125. // Else there wasn't one available in the request stack, so create one
  1126. else {
  1127. #endif
  1128. if ((request = (Request *) malloc(sizeof(Request))) == NULL) {
  1129. return S3StatusOutOfMemory;
  1130. }
  1131. request->NeonSession = NULL;
  1132. #ifndef WINSCP
  1133. }
  1134. #endif
  1135. // Initialize the request
  1136. #ifndef WINSCP
  1137. request->prev = 0;
  1138. request->next = 0;
  1139. #else
  1140. request->requestContext = context;
  1141. string_buffer_initialize(request->statusMessage);
  1142. #endif
  1143. // Request status is initialized to no error, will be updated whenever
  1144. // an error occurs
  1145. request->status = S3StatusOK;
  1146. S3Status status;
  1147. // Compute the URL
  1148. if ((status = compose_uri
  1149. (request->uri, sizeof(request->uri),
  1150. &(params->bucketContext), values->urlEncodedKey,
  1151. params->subResource, params->queryParams)) != S3StatusOK) {
  1152. free(request);
  1153. return status;
  1154. }
  1155. // Set all of the handle options
  1156. if ((status = setup_neon(request, params, values)) != S3StatusOK) {
  1157. free(request);
  1158. return status;
  1159. }
  1160. #ifndef WINSCP
  1161. if (context && context->setupCurlCallback &&
  1162. (status = context->setupCurlCallback(
  1163. context->curlm, request->curl,
  1164. context->setupCurlCallbackData)) != S3StatusOK) {
  1165. curl_easy_cleanup(request->curl);
  1166. free(request);
  1167. return status;
  1168. }
  1169. #endif
  1170. request->propertiesCallback = params->propertiesCallback;
  1171. request->toS3Callback = params->toS3Callback;
  1172. request->toS3CallbackBytesRemaining = params->toS3CallbackTotalSize;
  1173. request->fromS3Callback = params->fromS3Callback;
  1174. request->completeCallback = params->completeCallback;
  1175. request->callbackData = params->callbackData;
  1176. response_headers_handler_initialize(&(request->responseHeadersHandler));
  1177. request->propertiesCallbackMade = 0;
  1178. error_parser_initialize(&(request->errorParser));
  1179. *reqReturn = request;
  1180. return S3StatusOK;
  1181. }
  1182. static void request_destroy(Request *request)
  1183. {
  1184. request_deinitialize(request);
  1185. free(request);
  1186. }
  1187. static void request_release(Request *request)
  1188. {
  1189. #ifndef WINSCP
  1190. pthread_mutex_lock(&requestStackMutexG);
  1191. // If the request stack is full, destroy this one
  1192. if (requestStackCountG == REQUEST_STACK_SIZE) {
  1193. pthread_mutex_unlock(&requestStackMutexG);
  1194. #endif
  1195. request_destroy(request);
  1196. #ifndef WINSCP
  1197. }
  1198. // Else put this one at the front of the request stack; we do this because
  1199. // we want the most-recently-used curl handle to be re-used on the next
  1200. // request, to maximize our chances of re-using a TCP connection before it
  1201. // times out
  1202. else {
  1203. requestStackG[requestStackCountG++] = request;
  1204. pthread_mutex_unlock(&requestStackMutexG);
  1205. }
  1206. #endif
  1207. }
  1208. S3Status request_api_initialize(const char *userAgentInfo, int flags,
  1209. const char *defaultHostName)
  1210. {
  1211. // WINSCP (winsock must be initialized by caller)
  1212. if (!defaultHostName) {
  1213. defaultHostName = S3_DEFAULT_HOSTNAME;
  1214. }
  1215. if (snprintf(defaultHostNameG, S3_MAX_HOSTNAME_SIZE,
  1216. "%s", defaultHostName) >= S3_MAX_HOSTNAME_SIZE) {
  1217. return S3StatusUriTooLong;
  1218. }
  1219. #ifndef WINSCP
  1220. pthread_mutex_init(&requestStackMutexG, 0);
  1221. requestStackCountG = 0;
  1222. #endif
  1223. if (!userAgentInfo || !*userAgentInfo) {
  1224. userAgentInfo = "Unknown";
  1225. }
  1226. struct utsname utsn;
  1227. char platform[sizeof(utsn.sysname) + 1 + sizeof(utsn.machine) + 1];
  1228. if (uname(&utsn)) {
  1229. snprintf(platform, sizeof(platform), "Unknown");
  1230. }
  1231. else {
  1232. snprintf(platform, sizeof(platform), "%s%s%s", utsn.sysname,
  1233. utsn.machine[0] ? " " : "", utsn.machine);
  1234. }
  1235. snprintf(userAgentG, sizeof(userAgentG),
  1236. "Mozilla/4.0 (Compatible; %s; libs3 %s.%s; %s)",
  1237. userAgentInfo, LIBS3_VER_MAJOR, LIBS3_VER_MINOR, platform);
  1238. // WINSCP (Expat does not need global initialization)
  1239. return S3StatusOK;
  1240. }
  1241. void request_api_deinitialize()
  1242. {
  1243. #ifndef WINSCP
  1244. pthread_mutex_destroy(&requestStackMutexG);
  1245. // WINSCP (Expat does not need global initialization)
  1246. while (requestStackCountG--) {
  1247. request_destroy(requestStackG[requestStackCountG]);
  1248. }
  1249. #endif
  1250. }
  1251. static S3Status setup_request(const RequestParams *params,
  1252. RequestComputedValues *computed,
  1253. int forceUnsignedPayload)
  1254. {
  1255. S3Status status;
  1256. // Validate the bucket name
  1257. if (params->bucketContext.bucketName
  1258. && ((status = S3_validate_bucket_name(params->bucketContext.bucketName,
  1259. params->bucketContext.uriStyle))
  1260. != S3StatusOK)) {
  1261. return status;
  1262. }
  1263. // WINSCP (inspired by PuTTY ltime())
  1264. // Original time()/gmtime() combination did not work correctly in winter time
  1265. SYSTEMTIME st;
  1266. GetSystemTime(&st);
  1267. struct tm gmt;
  1268. memset(&gmt, 0, sizeof(gmt));
  1269. gmt.tm_sec=st.wSecond;
  1270. gmt.tm_min=st.wMinute;
  1271. gmt.tm_hour=st.wHour;
  1272. gmt.tm_mday=st.wDay;
  1273. gmt.tm_mon=st.wMonth-1;
  1274. gmt.tm_year=(st.wYear>=1900?st.wYear-1900:0);
  1275. gmt.tm_wday=st.wDayOfWeek;
  1276. gmt.tm_yday=-1; /* GetSystemTime doesn't tell us */
  1277. gmt.tm_isdst=0; /* GetSystemTime doesn't tell us */
  1278. strftime(computed->requestDateISO8601, sizeof(computed->requestDateISO8601),
  1279. "%Y%m%dT%H%M%SZ", &gmt);
  1280. // Compose the amz headers
  1281. if ((status = compose_amz_headers(params, forceUnsignedPayload, computed))
  1282. != S3StatusOK) {
  1283. return status;
  1284. }
  1285. // Compose standard headers
  1286. if ((status = compose_standard_headers(params, computed)) != S3StatusOK) {
  1287. return status;
  1288. }
  1289. // URL encode the key
  1290. if ((status = encode_key(params, computed)) != S3StatusOK) {
  1291. return status;
  1292. }
  1293. // Compute the canonicalized amz headers
  1294. canonicalize_signature_headers(computed);
  1295. // Compute the canonicalized resource
  1296. canonicalize_resource(&params->bucketContext, computed->urlEncodedKey,
  1297. computed->canonicalURI,
  1298. sizeof(computed->canonicalURI));
  1299. canonicalize_query_string(params->queryParams, params->subResource,
  1300. computed->canonicalQueryString,
  1301. sizeof(computed->canonicalQueryString));
  1302. // Compose Authorization header
  1303. if ((status = compose_auth_header(params, computed)) != S3StatusOK) {
  1304. return status;
  1305. }
  1306. #ifdef SIGNATURE_DEBUG
  1307. int i = 0;
  1308. ne_debug(NULL, NE_DBG_HTTPBODY, "\n--\nAMZ Headers:\n");
  1309. for (; i < computed->amzHeadersCount; i++) {
  1310. ne_debug(NULL, NE_DBG_HTTPBODY, "%s\n", computed->amzHeaders[i]);
  1311. }
  1312. #endif
  1313. return status;
  1314. }
  1315. void request_perform(const RequestParams *params, S3RequestContext *context)
  1316. {
  1317. Request *request;
  1318. S3Status status;
  1319. #define return_status(status) \
  1320. (*(params->completeCallback))(status, 0, params->callbackData); \
  1321. return
  1322. // These will hold the computed values
  1323. RequestComputedValues computed;
  1324. if ((status = setup_request(params, &computed, 0)) != S3StatusOK) {
  1325. return_status(status);
  1326. }
  1327. // Get an initialized Request structure now
  1328. if ((status = request_get(params, &computed, context, &request)) != S3StatusOK) {
  1329. return_status(status);
  1330. }
  1331. // WINSCP (we should always verify the peer)
  1332. #ifndef WINSCP
  1333. // If a RequestContext was provided, add the request to the curl multi
  1334. if (context) {
  1335. CURLMcode code = curl_multi_add_handle(context->curlm, request->curl);
  1336. if (code == CURLM_OK) {
  1337. if (context->requests) {
  1338. request->prev = context->requests->prev;
  1339. request->next = context->requests;
  1340. context->requests->prev->next = request;
  1341. context->requests->prev = request;
  1342. }
  1343. else {
  1344. context->requests = request->next = request->prev = request;
  1345. }
  1346. }
  1347. else {
  1348. if (request->status == S3StatusOK) {
  1349. request->status = (code == CURLM_OUT_OF_MEMORY) ?
  1350. S3StatusOutOfMemory : S3StatusInternalError;
  1351. }
  1352. request_finish(request);
  1353. }
  1354. }
  1355. // Else, perform the request immediately
  1356. else
  1357. #endif
  1358. {
  1359. NeonCode code = ne_request_dispatch(request->NeonRequest);
  1360. // Finish the request, ensuring that all callbacks have been made, and
  1361. // also releases the request
  1362. request_finish(request, code);
  1363. }
  1364. }
  1365. void request_finish(Request *request, NeonCode code)
  1366. {
  1367. // If we haven't detected this already, we now know that the headers are
  1368. // definitely done being read in
  1369. request_headers_done(request);
  1370. // If there was no error processing the request, then possibly there was
  1371. // an S3 error parsed, which should be converted into the request status
  1372. // WINSCP: We get "OK", even if there's TCP or HTTP error
  1373. if (request->status == S3StatusOK) {
  1374. // First handle S3 errors
  1375. // TemporaryRedirect S3 error has a precedence over HTTP 3xx error that carries it.
  1376. error_parser_convert_status(&(request->errorParser),
  1377. &(request->status));
  1378. #ifdef WINSCP
  1379. // This handles TCP and HTTP errors
  1380. if (request->status == S3StatusOK) {
  1381. if (code != NE_OK) {
  1382. request->status = request_neon_code_to_status(code);
  1383. if (request->errorParser.s3ErrorDetails.message == NULL) {
  1384. const char * neonError = ne_get_error(request->NeonSession);
  1385. int allFit;
  1386. string_buffer_append(request->statusMessage, neonError, strlen(neonError), allFit);
  1387. request->errorParser.s3ErrorDetails.message = request->statusMessage;
  1388. }
  1389. }
  1390. }
  1391. #endif
  1392. // If there still was no error recorded, then it is possible that
  1393. // there was in fact an error but that there was no error XML
  1394. // detailing the error
  1395. // WINSCP: We possibly never get here with neon
  1396. if ((request->status == S3StatusOK) &&
  1397. ((request->httpResponseCode < 200) ||
  1398. (request->httpResponseCode > 299))) {
  1399. switch (request->httpResponseCode) {
  1400. case 0:
  1401. // This happens if the request never got any HTTP response
  1402. // headers at all, we call this a ConnectionFailed error
  1403. request->status = S3StatusConnectionFailed;
  1404. break;
  1405. case 100: // Some versions of libcurl erroneously set HTTP
  1406. // status to this
  1407. break;
  1408. case 301:
  1409. request->status = S3StatusErrorPermanentRedirect;
  1410. break;
  1411. case 307:
  1412. request->status = S3StatusHttpErrorMovedTemporarily;
  1413. break;
  1414. case 400:
  1415. request->status = S3StatusHttpErrorBadRequest;
  1416. break;
  1417. case 403:
  1418. request->status = S3StatusHttpErrorForbidden;
  1419. break;
  1420. case 404:
  1421. request->status = S3StatusHttpErrorNotFound;
  1422. break;
  1423. case 405:
  1424. request->status = S3StatusErrorMethodNotAllowed;
  1425. break;
  1426. case 409:
  1427. request->status = S3StatusHttpErrorConflict;
  1428. break;
  1429. case 411:
  1430. request->status = S3StatusErrorMissingContentLength;
  1431. break;
  1432. case 412:
  1433. request->status = S3StatusErrorPreconditionFailed;
  1434. break;
  1435. case 416:
  1436. request->status = S3StatusErrorInvalidRange;
  1437. break;
  1438. case 500:
  1439. request->status = S3StatusErrorInternalError;
  1440. break;
  1441. case 501:
  1442. request->status = S3StatusErrorNotImplemented;
  1443. break;
  1444. case 503:
  1445. request->status = S3StatusErrorSlowDown;
  1446. break;
  1447. default:
  1448. request->status = S3StatusHttpErrorUnknown;
  1449. break;
  1450. }
  1451. }
  1452. }
  1453. (*(request->completeCallback))
  1454. (request->status, &(request->errorParser.s3ErrorDetails),
  1455. request->callbackData);
  1456. request_release(request);
  1457. }
  1458. S3Status request_neon_code_to_status(NeonCode code)
  1459. {
  1460. switch (code) {
  1461. case NE_LOOKUP:
  1462. return S3StatusNameLookupError;
  1463. case NE_CONNECT:
  1464. return S3StatusFailedToConnect;
  1465. case NE_TIMEOUT:
  1466. case NE_SOCKET:
  1467. return S3StatusConnectionFailed;
  1468. default:
  1469. return S3StatusInternalError;
  1470. }
  1471. }
  1472. #ifndef WINSCP
  1473. S3Status S3_generate_authenticated_query_string
  1474. (char *buffer, const S3BucketContext *bucketContext,
  1475. const char *key, int expires, const char *resource,
  1476. const char *httpMethod)
  1477. {
  1478. // maximum expiration period is seven days (in seconds)
  1479. #define MAX_EXPIRES 604800
  1480. if (expires < 0) {
  1481. expires = MAX_EXPIRES;
  1482. }
  1483. else if (expires > MAX_EXPIRES) {
  1484. expires = MAX_EXPIRES;
  1485. }
  1486. // WinSCP
  1487. RequestParams params =
  1488. { http_request_method_to_type(httpMethod),
  1489. { bucketContext->hostName, bucketContext->bucketName, bucketContext->protocol, bucketContext->uriStyle, bucketContext->accessKeyId, bucketContext->secretAccessKey, bucketContext->securityToken, bucketContext->authRegion },
  1490. key, NULL,
  1491. resource,
  1492. NULL, NULL, NULL, 0, 0, NULL, NULL, NULL, 0, NULL, NULL, NULL, 0};
  1493. RequestComputedValues computed;
  1494. S3Status status = setup_request(&params, &computed, 1);
  1495. if (status != S3StatusOK) {
  1496. return status;
  1497. }
  1498. // Finally, compose the URI, with params
  1499. char queryParams[sizeof("X-Amz-Algorithm=AWS4-HMAC-SHA256") +
  1500. sizeof("&X-Amz-Credential=") +
  1501. sizeof(computed.authCredential) +
  1502. sizeof("&X-Amz-Date=") +
  1503. sizeof(computed.requestDateISO8601) +
  1504. sizeof("&X-Amz-Expires=") + 64 +
  1505. sizeof("&X-Amz-SignedHeaders=") +
  1506. sizeof(computed.signedHeaders) +
  1507. sizeof("&X-Amz-Signature=") +
  1508. sizeof(computed.requestSignatureHex) + 1];
  1509. snprintf(queryParams, sizeof(queryParams),
  1510. "X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=%s"
  1511. "&X-Amz-Date=%s&X-Amz-Expires=%d"
  1512. "&X-Amz-SignedHeaders=%s&X-Amz-Signature=%s",
  1513. computed.authCredential, computed.requestDateISO8601, expires,
  1514. computed.signedHeaders, computed.requestSignatureHex);
  1515. return compose_uri(buffer, S3_MAX_AUTHENTICATED_QUERY_STRING_SIZE,
  1516. bucketContext, computed.urlEncodedKey, resource,
  1517. queryParams);
  1518. }
  1519. #endif