1
0

request.c 58 KB

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