request.c 61 KB

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