request.c 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827
  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. else if (params->httpRequestType == HttpRequestTypeCOPY)
  1049. {
  1050. // Google cloud needs "Content-Length: 0" header
  1051. ne_set_request_body_buffer(request->NeonRequest, "", 0);
  1052. }
  1053. // WINSCP (Last-Modified parsed in response_headers_handler_done)
  1054. // xxx todo - support setting the proxy for Curl to use (can't use https
  1055. // for proxies though)
  1056. // xxx todo - support setting the network interface for Curl to use
  1057. // WINSCP (neon sets "nodelay" unconditionally)
  1058. // WINSCP (we should verify peer always)
  1059. ne_ssl_set_verify(request->NeonSession, neon_ssl_callback, request);
  1060. ne_ssl_trust_default_ca(request->NeonSession);
  1061. // Follow any redirection directives that S3 sends
  1062. // TODO
  1063. // Set the User-Agent; maybe Amazon will track these?
  1064. ne_set_useragent(request->NeonSession, userAgentG);
  1065. if (params->timeoutMs > 0) {
  1066. ne_set_read_timeout(request->NeonSession, params->timeoutMs);
  1067. ne_set_connect_timeout(request->NeonSession, params->timeoutMs);
  1068. }
  1069. #define do_add_header(header) \
  1070. { \
  1071. char * buf = new char[strlen(header) + 1]; \
  1072. strcpy(buf, header); \
  1073. char * p = strchr(buf, ':'); \
  1074. if (p != NULL) \
  1075. { \
  1076. *p = '\0'; \
  1077. p++; \
  1078. while (is_blank(p[0])) p++; \
  1079. ne_add_request_header(request->NeonRequest, buf, p); \
  1080. } \
  1081. delete[] buf; \
  1082. }
  1083. // Append standard headers
  1084. #define append_standard_header(fieldName) \
  1085. if (values-> fieldName [0]) { \
  1086. do_add_header(values-> fieldName); \
  1087. }
  1088. // WINSCP (hostHeader is added implicitly by neon based on uri, but for certificate check, we use base hostname
  1089. // as the bucket name can contain dots, for which the certificate check would fail)
  1090. char * hostName = strdup(params->bucketContext.hostName ? params->bucketContext.hostName : defaultHostNameG);
  1091. char * colon = strchr(hostName, ':');
  1092. if (colon != NULL)
  1093. {
  1094. *colon = '\0';
  1095. }
  1096. ne_set_realhost(request->NeonSession, hostName);
  1097. free(hostName);
  1098. append_standard_header(cacheControlHeader);
  1099. append_standard_header(contentTypeHeader);
  1100. append_standard_header(md5Header);
  1101. append_standard_header(contentDispositionHeader);
  1102. append_standard_header(contentEncodingHeader);
  1103. append_standard_header(expiresHeader);
  1104. append_standard_header(ifModifiedSinceHeader);
  1105. append_standard_header(ifUnmodifiedSinceHeader);
  1106. append_standard_header(ifMatchHeader);
  1107. append_standard_header(ifNoneMatchHeader);
  1108. append_standard_header(rangeHeader);
  1109. append_standard_header(authorizationHeader);
  1110. // Append x-amz- headers
  1111. int i;
  1112. for (i = 0; i < values->amzHeadersCount; i++) {
  1113. do_add_header(values->amzHeaders[i]);
  1114. }
  1115. return S3StatusOK;
  1116. }
  1117. static void request_deinitialize(Request *request)
  1118. {
  1119. ne_request_destroy(request->NeonRequest);
  1120. ne_session_destroy(request->NeonSession);
  1121. error_parser_deinitialize(&(request->errorParser));
  1122. }
  1123. static S3Status request_get(const RequestParams *params,
  1124. const RequestComputedValues *values,
  1125. S3RequestContext *context, // WINSCP (non-const)
  1126. Request **reqReturn)
  1127. {
  1128. Request *request = 0;
  1129. #ifndef WINSCP
  1130. // Try to get one from the request stack. We hold the lock for the
  1131. // shortest time possible here.
  1132. pthread_mutex_lock(&requestStackMutexG);
  1133. if (requestStackCountG) {
  1134. request = requestStackG[--requestStackCountG];
  1135. }
  1136. pthread_mutex_unlock(&requestStackMutexG);
  1137. // If we got one, deinitialize it for re-use
  1138. if (request) {
  1139. request_deinitialize(request);
  1140. }
  1141. // Else there wasn't one available in the request stack, so create one
  1142. else {
  1143. #endif
  1144. if ((request = (Request *) malloc(sizeof(Request))) == NULL) {
  1145. return S3StatusOutOfMemory;
  1146. }
  1147. request->NeonSession = NULL;
  1148. #ifndef WINSCP
  1149. }
  1150. #endif
  1151. // Initialize the request
  1152. #ifndef WINSCP
  1153. request->prev = 0;
  1154. request->next = 0;
  1155. #else
  1156. request->requestContext = context;
  1157. string_buffer_initialize(request->statusMessage);
  1158. #endif
  1159. // Request status is initialized to no error, will be updated whenever
  1160. // an error occurs
  1161. request->status = S3StatusOK;
  1162. S3Status status;
  1163. // Compute the URL
  1164. if ((status = compose_uri
  1165. (request->uri, sizeof(request->uri),
  1166. &(params->bucketContext), values->urlEncodedKey,
  1167. params->subResource, params->queryParams)) != S3StatusOK) {
  1168. free(request);
  1169. return status;
  1170. }
  1171. // Set all of the handle options
  1172. if ((status = setup_neon(request, params, values)) != S3StatusOK) {
  1173. free(request);
  1174. return status;
  1175. }
  1176. #ifndef WINSCP
  1177. if (context && context->setupCurlCallback &&
  1178. (status = context->setupCurlCallback(
  1179. context->curlm, request->curl,
  1180. context->setupCurlCallbackData)) != S3StatusOK) {
  1181. curl_easy_cleanup(request->curl);
  1182. free(request);
  1183. return status;
  1184. }
  1185. #endif
  1186. request->propertiesCallback = params->propertiesCallback;
  1187. request->toS3Callback = params->toS3Callback;
  1188. request->toS3CallbackBytesRemaining = params->toS3CallbackTotalSize;
  1189. request->fromS3Callback = params->fromS3Callback;
  1190. request->completeCallback = params->completeCallback;
  1191. request->callbackData = params->callbackData;
  1192. response_headers_handler_initialize(&(request->responseHeadersHandler));
  1193. request->propertiesCallbackMade = 0;
  1194. error_parser_initialize(&(request->errorParser));
  1195. *reqReturn = request;
  1196. return S3StatusOK;
  1197. }
  1198. static void request_destroy(Request *request)
  1199. {
  1200. request_deinitialize(request);
  1201. free(request);
  1202. }
  1203. static void request_release(Request *request)
  1204. {
  1205. #ifndef WINSCP
  1206. pthread_mutex_lock(&requestStackMutexG);
  1207. // If the request stack is full, destroy this one
  1208. if (requestStackCountG == REQUEST_STACK_SIZE) {
  1209. pthread_mutex_unlock(&requestStackMutexG);
  1210. #endif
  1211. request_destroy(request);
  1212. #ifndef WINSCP
  1213. }
  1214. // Else put this one at the front of the request stack; we do this because
  1215. // we want the most-recently-used curl handle to be re-used on the next
  1216. // request, to maximize our chances of re-using a TCP connection before it
  1217. // times out
  1218. else {
  1219. requestStackG[requestStackCountG++] = request;
  1220. pthread_mutex_unlock(&requestStackMutexG);
  1221. }
  1222. #endif
  1223. }
  1224. S3Status request_api_initialize(const char *userAgentInfo, int flags,
  1225. const char *defaultHostName)
  1226. {
  1227. // WINSCP (winsock must be initialized by caller)
  1228. if (!defaultHostName) {
  1229. defaultHostName = S3_DEFAULT_HOSTNAME;
  1230. }
  1231. if (snprintf(defaultHostNameG, S3_MAX_HOSTNAME_SIZE,
  1232. "%s", defaultHostName) >= S3_MAX_HOSTNAME_SIZE) {
  1233. return S3StatusUriTooLong;
  1234. }
  1235. #ifndef WINSCP
  1236. pthread_mutex_init(&requestStackMutexG, 0);
  1237. requestStackCountG = 0;
  1238. #endif
  1239. if (!userAgentInfo || !*userAgentInfo) {
  1240. userAgentInfo = "Unknown";
  1241. }
  1242. struct utsname utsn;
  1243. char platform[sizeof(utsn.sysname) + 1 + sizeof(utsn.machine) + 1];
  1244. if (uname(&utsn)) {
  1245. snprintf(platform, sizeof(platform), "Unknown");
  1246. }
  1247. else {
  1248. snprintf(platform, sizeof(platform), "%s%s%s", utsn.sysname,
  1249. utsn.machine[0] ? " " : "", utsn.machine);
  1250. }
  1251. snprintf(userAgentG, sizeof(userAgentG),
  1252. "Mozilla/4.0 (Compatible; %s; libs3 %s.%s; %s)",
  1253. userAgentInfo, LIBS3_VER_MAJOR, LIBS3_VER_MINOR, platform);
  1254. // WINSCP (Expat does not need global initialization)
  1255. return S3StatusOK;
  1256. }
  1257. void request_api_deinitialize()
  1258. {
  1259. #ifndef WINSCP
  1260. pthread_mutex_destroy(&requestStackMutexG);
  1261. // WINSCP (Expat does not need global initialization)
  1262. while (requestStackCountG--) {
  1263. request_destroy(requestStackG[requestStackCountG]);
  1264. }
  1265. #endif
  1266. }
  1267. static S3Status setup_request(const RequestParams *params,
  1268. RequestComputedValues *computed,
  1269. int forceUnsignedPayload)
  1270. {
  1271. S3Status status;
  1272. // Validate the bucket name
  1273. if (params->bucketContext.bucketName
  1274. && ((status = S3_validate_bucket_name(params->bucketContext.bucketName,
  1275. params->bucketContext.uriStyle))
  1276. != S3StatusOK)) {
  1277. return status;
  1278. }
  1279. // WINSCP (inspired by PuTTY ltime())
  1280. // Original time()/gmtime() combination did not work correctly in winter time
  1281. SYSTEMTIME st;
  1282. GetSystemTime(&st);
  1283. struct tm gmt;
  1284. memset(&gmt, 0, sizeof(gmt));
  1285. gmt.tm_sec=st.wSecond;
  1286. gmt.tm_min=st.wMinute;
  1287. gmt.tm_hour=st.wHour;
  1288. gmt.tm_mday=st.wDay;
  1289. gmt.tm_mon=st.wMonth-1;
  1290. gmt.tm_year=(st.wYear>=1900?st.wYear-1900:0);
  1291. gmt.tm_wday=st.wDayOfWeek;
  1292. gmt.tm_yday=-1; /* GetSystemTime doesn't tell us */
  1293. gmt.tm_isdst=0; /* GetSystemTime doesn't tell us */
  1294. strftime(computed->requestDateISO8601, sizeof(computed->requestDateISO8601),
  1295. "%Y%m%dT%H%M%SZ", &gmt);
  1296. // Compose the amz headers
  1297. if ((status = compose_amz_headers(params, forceUnsignedPayload, computed))
  1298. != S3StatusOK) {
  1299. return status;
  1300. }
  1301. // Compose standard headers
  1302. if ((status = compose_standard_headers(params, computed)) != S3StatusOK) {
  1303. return status;
  1304. }
  1305. // URL encode the key
  1306. if ((status = encode_key(params, computed)) != S3StatusOK) {
  1307. return status;
  1308. }
  1309. // Compute the canonicalized amz headers
  1310. canonicalize_signature_headers(computed);
  1311. // Compute the canonicalized resource
  1312. canonicalize_resource(&params->bucketContext, computed->urlEncodedKey,
  1313. computed->canonicalURI,
  1314. sizeof(computed->canonicalURI));
  1315. canonicalize_query_string(params->queryParams, params->subResource,
  1316. computed->canonicalQueryString,
  1317. sizeof(computed->canonicalQueryString));
  1318. // Compose Authorization header
  1319. if ((status = compose_auth_header(params, computed)) != S3StatusOK) {
  1320. return status;
  1321. }
  1322. #ifdef SIGNATURE_DEBUG
  1323. int i = 0;
  1324. ne_debug(NULL, NE_DBG_HTTPBODY, "\n--\nAMZ Headers:\n");
  1325. for (; i < computed->amzHeadersCount; i++) {
  1326. ne_debug(NULL, NE_DBG_HTTPBODY, "%s\n", computed->amzHeaders[i]);
  1327. }
  1328. #endif
  1329. return status;
  1330. }
  1331. void request_perform(const RequestParams *params, S3RequestContext *context)
  1332. {
  1333. Request *request;
  1334. S3Status status;
  1335. #define return_status(status) \
  1336. (*(params->completeCallback))(status, 0, params->callbackData); \
  1337. return
  1338. // These will hold the computed values
  1339. RequestComputedValues computed;
  1340. if ((status = setup_request(params, &computed, 0)) != S3StatusOK) {
  1341. return_status(status);
  1342. }
  1343. // Get an initialized Request structure now
  1344. if ((status = request_get(params, &computed, context, &request)) != S3StatusOK) {
  1345. return_status(status);
  1346. }
  1347. // WINSCP (we should always verify the peer)
  1348. #ifndef WINSCP
  1349. // If a RequestContext was provided, add the request to the curl multi
  1350. if (context) {
  1351. CURLMcode code = curl_multi_add_handle(context->curlm, request->curl);
  1352. if (code == CURLM_OK) {
  1353. if (context->requests) {
  1354. request->prev = context->requests->prev;
  1355. request->next = context->requests;
  1356. context->requests->prev->next = request;
  1357. context->requests->prev = request;
  1358. }
  1359. else {
  1360. context->requests = request->next = request->prev = request;
  1361. }
  1362. }
  1363. else {
  1364. if (request->status == S3StatusOK) {
  1365. request->status = (code == CURLM_OUT_OF_MEMORY) ?
  1366. S3StatusOutOfMemory : S3StatusInternalError;
  1367. }
  1368. request_finish(request);
  1369. }
  1370. }
  1371. // Else, perform the request immediately
  1372. else
  1373. #endif
  1374. {
  1375. NeonCode code = ne_request_dispatch(request->NeonRequest);
  1376. // Finish the request, ensuring that all callbacks have been made, and
  1377. // also releases the request
  1378. request_finish(request, code);
  1379. }
  1380. }
  1381. void request_finish(Request *request, NeonCode code)
  1382. {
  1383. const char * httpMessage = NULL;
  1384. // If we haven't detected this already, we now know that the headers are
  1385. // definitely done being read in
  1386. request_headers_done(request);
  1387. // If there was no error processing the request, then possibly there was
  1388. // an S3 error parsed, which should be converted into the request status
  1389. // WINSCP: We get "OK", even if there's TCP or HTTP error
  1390. if (request->status == S3StatusOK) {
  1391. // First handle S3 errors
  1392. // TemporaryRedirect S3 error has a precedence over HTTP 3xx error that carries it.
  1393. error_parser_convert_status(&(request->errorParser),
  1394. &(request->status));
  1395. #ifdef WINSCP
  1396. // This handles TCP and HTTP errors
  1397. if (request->status == S3StatusOK) {
  1398. if (code != NE_OK) {
  1399. request->status = request_neon_code_to_status(code);
  1400. if (request->errorParser.s3ErrorDetails.message == NULL) {
  1401. const char * neonError = ne_get_error(request->NeonSession);
  1402. int allFit;
  1403. string_buffer_append(request->statusMessage, neonError, strlen(neonError), allFit);
  1404. request->errorParser.s3ErrorDetails.message = request->statusMessage;
  1405. }
  1406. }
  1407. }
  1408. #endif
  1409. // If there still was no error recorded, then it is possible that
  1410. // there was in fact an error but that there was no error XML
  1411. // detailing the error
  1412. // WINSCP: We possibly never get here with neon
  1413. if ((request->status == S3StatusOK) &&
  1414. ((request->httpResponseCode < 200) ||
  1415. (request->httpResponseCode > 299))) {
  1416. switch (request->httpResponseCode) {
  1417. case 0:
  1418. // This happens if the request never got any HTTP response
  1419. // headers at all, we call this a ConnectionFailed error
  1420. request->status = S3StatusConnectionFailed;
  1421. break;
  1422. case 100: // Some versions of libcurl erroneously set HTTP
  1423. // status to this
  1424. break;
  1425. case 301:
  1426. request->status = S3StatusErrorPermanentRedirect;
  1427. break;
  1428. case 307:
  1429. request->status = S3StatusHttpErrorMovedTemporarily;
  1430. break;
  1431. case 400:
  1432. request->status = S3StatusHttpErrorBadRequest;
  1433. break;
  1434. case 403:
  1435. request->status = S3StatusHttpErrorForbidden;
  1436. break;
  1437. case 404:
  1438. request->status = S3StatusHttpErrorNotFound;
  1439. break;
  1440. case 405:
  1441. request->status = S3StatusErrorMethodNotAllowed;
  1442. break;
  1443. case 409:
  1444. request->status = S3StatusHttpErrorConflict;
  1445. break;
  1446. case 411:
  1447. request->status = S3StatusErrorMissingContentLength;
  1448. break;
  1449. case 412:
  1450. request->status = S3StatusErrorPreconditionFailed;
  1451. break;
  1452. case 416:
  1453. request->status = S3StatusErrorInvalidRange;
  1454. break;
  1455. case 500:
  1456. request->status = S3StatusErrorInternalError;
  1457. break;
  1458. case 501:
  1459. request->status = S3StatusErrorNotImplemented;
  1460. break;
  1461. case 503:
  1462. request->status = S3StatusErrorSlowDown;
  1463. break;
  1464. default:
  1465. request->status = S3StatusHttpErrorUnknown;
  1466. break;
  1467. }
  1468. httpMessage = ne_get_status(request->NeonRequest)->reason_phrase;
  1469. }
  1470. }
  1471. { // WINSCP
  1472. // WINSCP
  1473. S3ErrorDetails errorDetails = request->errorParser.s3ErrorDetails;
  1474. if (errorDetails.furtherDetails == NULL)
  1475. {
  1476. errorDetails.furtherDetails = httpMessage;
  1477. }
  1478. (*(request->completeCallback))
  1479. (request->status, &errorDetails, // WINSCP
  1480. request->callbackData);
  1481. request_release(request);
  1482. } // WINSCP
  1483. }
  1484. S3Status request_neon_code_to_status(NeonCode code)
  1485. {
  1486. switch (code) {
  1487. case NE_LOOKUP:
  1488. return S3StatusNameLookupError;
  1489. case NE_CONNECT:
  1490. return S3StatusFailedToConnect;
  1491. case NE_TIMEOUT:
  1492. case NE_SOCKET:
  1493. return S3StatusConnectionFailed;
  1494. default:
  1495. return S3StatusInternalError;
  1496. }
  1497. }
  1498. #ifndef WINSCP
  1499. S3Status S3_generate_authenticated_query_string
  1500. (char *buffer, const S3BucketContext *bucketContext,
  1501. const char *key, int expires, const char *resource,
  1502. const char *httpMethod)
  1503. {
  1504. // maximum expiration period is seven days (in seconds)
  1505. #define MAX_EXPIRES 604800
  1506. if (expires < 0) {
  1507. expires = MAX_EXPIRES;
  1508. }
  1509. else if (expires > MAX_EXPIRES) {
  1510. expires = MAX_EXPIRES;
  1511. }
  1512. // WinSCP
  1513. RequestParams params =
  1514. { http_request_method_to_type(httpMethod),
  1515. { bucketContext->hostName, bucketContext->bucketName, bucketContext->protocol, bucketContext->uriStyle, bucketContext->accessKeyId, bucketContext->secretAccessKey, bucketContext->securityToken, bucketContext->authRegion },
  1516. key, NULL,
  1517. resource,
  1518. NULL, NULL, NULL, 0, 0, NULL, NULL, NULL, 0, NULL, NULL, NULL, 0};
  1519. RequestComputedValues computed;
  1520. S3Status status = setup_request(&params, &computed, 1);
  1521. if (status != S3StatusOK) {
  1522. return status;
  1523. }
  1524. // Finally, compose the URI, with params
  1525. char queryParams[sizeof("X-Amz-Algorithm=AWS4-HMAC-SHA256") +
  1526. sizeof("&X-Amz-Credential=") +
  1527. sizeof(computed.authCredential) +
  1528. sizeof("&X-Amz-Date=") +
  1529. sizeof(computed.requestDateISO8601) +
  1530. sizeof("&X-Amz-Expires=") + 64 +
  1531. sizeof("&X-Amz-SignedHeaders=") +
  1532. sizeof(computed.signedHeaders) +
  1533. sizeof("&X-Amz-Signature=") +
  1534. sizeof(computed.requestSignatureHex) + 1];
  1535. snprintf(queryParams, sizeof(queryParams),
  1536. "X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=%s"
  1537. "&X-Amz-Date=%s&X-Amz-Expires=%d"
  1538. "&X-Amz-SignedHeaders=%s&X-Amz-Signature=%s",
  1539. computed.authCredential, computed.requestDateISO8601, expires,
  1540. computed.signedHeaders, computed.requestSignatureHex);
  1541. return compose_uri(buffer, S3_MAX_AUTHENTICATED_QUERY_STRING_SIZE,
  1542. bucketContext, computed.urlEncodedKey, resource,
  1543. queryParams);
  1544. }
  1545. #endif