1
0

request.c 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745
  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. #ifndef WINSCP
  907. // We cannot change Host: header with neon.
  908. // Instead we tweak host name validation
  909. if (strchr(bucketContext->bucketName, '.') == NULL) {
  910. #endif
  911. uri_append("%s.%s", bucketContext->bucketName, hostName);
  912. #ifndef WINSCP
  913. }
  914. else {
  915. // We'll use the hostName in the URL, and then explicitly set
  916. // the Host header to match bucket.host so that host validation
  917. // works.
  918. uri_append("%s", hostName);
  919. }
  920. #endif
  921. }
  922. else {
  923. uri_append("%s/%s", hostName, bucketContext->bucketName);
  924. }
  925. }
  926. else {
  927. uri_append("%s", hostName);
  928. }
  929. uri_append("%s", "/");
  930. uri_append("%s", urlEncodedKey);
  931. if (subResource && subResource[0]) {
  932. uri_append("?%s", subResource);
  933. }
  934. if (queryParams) {
  935. uri_append("%s%s", (subResource && subResource[0]) ? "&" : "?",
  936. queryParams);
  937. }
  938. return S3StatusOK;
  939. }
  940. #ifdef WINSCP
  941. int neon_ssl_callback(void * user_data, int failures, const ne_ssl_certificate * certificate)
  942. {
  943. Request *request = (Request *) user_data;
  944. int result = NE_ERROR;
  945. if (request->requestContext->sslCallback != NULL)
  946. {
  947. result = request->requestContext->sslCallback(failures, certificate, request->requestContext->sslCallbackData);
  948. }
  949. return result;
  950. }
  951. #endif
  952. // WINSCP (neon)
  953. // Sets up the neon handle given the completely computed RequestParams
  954. static S3Status setup_neon(Request *request,
  955. const RequestParams *params,
  956. const RequestComputedValues *values)
  957. {
  958. NeonCode status;
  959. ne_uri uri;
  960. if (ne_uri_parse(request->uri, &uri) != 0)
  961. {
  962. return S3StatusFailedToInitializeRequest;
  963. }
  964. int port = uri.port;
  965. if (port == 0)
  966. {
  967. port = ne_uri_defaultport(uri.scheme);
  968. }
  969. request->NeonSession = ne_session_create(uri.scheme, uri.host, port);
  970. if (request->requestContext->sessionCallback != NULL)
  971. {
  972. request->requestContext->sessionCallback(request->NeonSession, request->requestContext->sessionCallbackData);
  973. }
  974. char method[64];
  975. strcpy(method, "GET");
  976. switch (params->httpRequestType) {
  977. case HttpRequestTypeHEAD:
  978. strcpy(method, "HEAD");
  979. break;
  980. case HttpRequestTypePOST:
  981. strcpy(method, "POST");
  982. break;
  983. case HttpRequestTypePUT:
  984. case HttpRequestTypeCOPY:
  985. strcpy(method, "PUT");
  986. break;
  987. case HttpRequestTypeDELETE:
  988. strcpy(method, "DELETE");
  989. break;
  990. default: // HttpRequestTypeGET
  991. break;
  992. }
  993. ne_buffer * buf = ne_buffer_create();
  994. ne_buffer_zappend(buf, uri.path);
  995. if (uri.query != NULL)
  996. {
  997. ne_buffer_concat(buf, "?", uri.query, NULL);
  998. }
  999. request->NeonRequest = ne_request_create(request->NeonSession, method, buf->data);
  1000. ne_buffer_destroy(buf);
  1001. ne_uri_free(&uri);
  1002. // Set header callback and data
  1003. // Set read callback, data, and readSize
  1004. ne_add_response_body_reader(request->NeonRequest, neon_header_func, neon_write_func, request);
  1005. // Set write callback and data
  1006. if ((params->httpRequestType == HttpRequestTypePUT) ||
  1007. (params->httpRequestType == HttpRequestTypePOST))
  1008. {
  1009. ne_set_request_body_provider(request->NeonRequest, (ne_off_t)params->toS3CallbackTotalSize, neon_read_func, request);
  1010. }
  1011. // WINSCP (Last-Modified parsed in response_headers_handler_done)
  1012. // xxx todo - support setting the proxy for Curl to use (can't use https
  1013. // for proxies though)
  1014. // xxx todo - support setting the network interface for Curl to use
  1015. // WINSCP (neon sets "nodelay" unconditionally)
  1016. // WINSCP (we should verify peer always)
  1017. ne_ssl_set_verify(request->NeonSession, neon_ssl_callback, request);
  1018. ne_ssl_trust_default_ca(request->NeonSession);
  1019. // Follow any redirection directives that S3 sends
  1020. // TODO
  1021. // Set the User-Agent; maybe Amazon will track these?
  1022. ne_set_useragent(request->NeonSession, userAgentG);
  1023. if (params->timeoutMs > 0) {
  1024. ne_set_read_timeout(request->NeonSession, params->timeoutMs);
  1025. ne_set_connect_timeout(request->NeonSession, params->timeoutMs);
  1026. }
  1027. #define do_add_header(header) \
  1028. { \
  1029. char * buf = new char[strlen(header) + 1]; \
  1030. strcpy(buf, header); \
  1031. char * p = strchr(buf, ':'); \
  1032. if (p != NULL) \
  1033. { \
  1034. *p = '\0'; \
  1035. p++; \
  1036. while (is_blank(p[0])) p++; \
  1037. ne_add_request_header(request->NeonRequest, buf, p); \
  1038. } \
  1039. delete[] buf; \
  1040. }
  1041. // Append standard headers
  1042. #define append_standard_header(fieldName) \
  1043. if (values-> fieldName [0]) { \
  1044. do_add_header(values-> fieldName); \
  1045. }
  1046. // WINSCP (hostHeader is added implicitly by neon based on uri, but for certificate check, we use base hostname
  1047. // as the bucket name can contain dots, for which the certificate check would fail)
  1048. ne_set_realhost(request->NeonSession, params->bucketContext.hostName ? params->bucketContext.hostName : defaultHostNameG);
  1049. append_standard_header(cacheControlHeader);
  1050. append_standard_header(contentTypeHeader);
  1051. append_standard_header(md5Header);
  1052. append_standard_header(contentDispositionHeader);
  1053. append_standard_header(contentEncodingHeader);
  1054. append_standard_header(expiresHeader);
  1055. append_standard_header(ifModifiedSinceHeader);
  1056. append_standard_header(ifUnmodifiedSinceHeader);
  1057. append_standard_header(ifMatchHeader);
  1058. append_standard_header(ifNoneMatchHeader);
  1059. append_standard_header(rangeHeader);
  1060. append_standard_header(authorizationHeader);
  1061. // Append x-amz- headers
  1062. int i;
  1063. for (i = 0; i < values->amzHeadersCount; i++) {
  1064. do_add_header(values->amzHeaders[i]);
  1065. }
  1066. return S3StatusOK;
  1067. }
  1068. static void request_deinitialize(Request *request)
  1069. {
  1070. ne_request_destroy(request->NeonRequest);
  1071. ne_session_destroy(request->NeonSession);
  1072. error_parser_deinitialize(&(request->errorParser));
  1073. }
  1074. static S3Status request_get(const RequestParams *params,
  1075. S3RequestContext *context,
  1076. const RequestComputedValues *values,
  1077. Request **reqReturn)
  1078. {
  1079. Request *request = 0;
  1080. #ifndef WINSCP
  1081. // Try to get one from the request stack. We hold the lock for the
  1082. // shortest time possible here.
  1083. pthread_mutex_lock(&requestStackMutexG);
  1084. if (requestStackCountG) {
  1085. request = requestStackG[--requestStackCountG];
  1086. }
  1087. pthread_mutex_unlock(&requestStackMutexG);
  1088. // If we got one, deinitialize it for re-use
  1089. if (request) {
  1090. request_deinitialize(request);
  1091. }
  1092. // Else there wasn't one available in the request stack, so create one
  1093. else {
  1094. #endif
  1095. if ((request = (Request *) malloc(sizeof(Request))) == NULL) {
  1096. return S3StatusOutOfMemory;
  1097. }
  1098. request->NeonSession = NULL;
  1099. #ifndef WINSCP
  1100. }
  1101. #endif
  1102. // Initialize the request
  1103. #ifndef WINSCP
  1104. request->prev = 0;
  1105. request->next = 0;
  1106. #else
  1107. request->requestContext = context;
  1108. string_buffer_initialize(request->statusMessage);
  1109. #endif
  1110. // Request status is initialized to no error, will be updated whenever
  1111. // an error occurs
  1112. request->status = S3StatusOK;
  1113. S3Status status;
  1114. // Compute the URL
  1115. if ((status = compose_uri
  1116. (request->uri, sizeof(request->uri),
  1117. &(params->bucketContext), values->urlEncodedKey,
  1118. params->subResource, params->queryParams)) != S3StatusOK) {
  1119. free(request);
  1120. return status;
  1121. }
  1122. // Set all of the handle options
  1123. if ((status = setup_neon(request, params, values)) != S3StatusOK) {
  1124. free(request);
  1125. return status;
  1126. }
  1127. request->propertiesCallback = params->propertiesCallback;
  1128. request->toS3Callback = params->toS3Callback;
  1129. request->toS3CallbackBytesRemaining = params->toS3CallbackTotalSize;
  1130. request->fromS3Callback = params->fromS3Callback;
  1131. request->completeCallback = params->completeCallback;
  1132. request->callbackData = params->callbackData;
  1133. response_headers_handler_initialize(&(request->responseHeadersHandler));
  1134. request->propertiesCallbackMade = 0;
  1135. error_parser_initialize(&(request->errorParser));
  1136. *reqReturn = request;
  1137. return S3StatusOK;
  1138. }
  1139. static void request_destroy(Request *request)
  1140. {
  1141. request_deinitialize(request);
  1142. free(request);
  1143. }
  1144. static void request_release(Request *request)
  1145. {
  1146. #ifndef WINSCP
  1147. pthread_mutex_lock(&requestStackMutexG);
  1148. // If the request stack is full, destroy this one
  1149. if (requestStackCountG == REQUEST_STACK_SIZE) {
  1150. pthread_mutex_unlock(&requestStackMutexG);
  1151. #endif
  1152. request_destroy(request);
  1153. #ifndef WINSCP
  1154. }
  1155. // Else put this one at the front of the request stack; we do this because
  1156. // we want the most-recently-used curl handle to be re-used on the next
  1157. // request, to maximize our chances of re-using a TCP connection before it
  1158. // times out
  1159. else {
  1160. requestStackG[requestStackCountG++] = request;
  1161. pthread_mutex_unlock(&requestStackMutexG);
  1162. }
  1163. #endif
  1164. }
  1165. S3Status request_api_initialize(const char *userAgentInfo, int flags,
  1166. const char *defaultHostName)
  1167. {
  1168. // WINSCP (winsock must be initialized by caller)
  1169. if (!defaultHostName) {
  1170. defaultHostName = S3_DEFAULT_HOSTNAME;
  1171. }
  1172. if (snprintf(defaultHostNameG, S3_MAX_HOSTNAME_SIZE,
  1173. "%s", defaultHostName) >= S3_MAX_HOSTNAME_SIZE) {
  1174. return S3StatusUriTooLong;
  1175. }
  1176. #ifndef WINSCP
  1177. pthread_mutex_init(&requestStackMutexG, 0);
  1178. requestStackCountG = 0;
  1179. #endif
  1180. if (!userAgentInfo || !*userAgentInfo) {
  1181. userAgentInfo = "Unknown";
  1182. }
  1183. char platform[96];
  1184. struct utsname utsn;
  1185. if (uname(&utsn)) {
  1186. snprintf(platform, sizeof(platform), "Unknown");
  1187. }
  1188. else {
  1189. snprintf(platform, sizeof(platform), "%s%s%s", utsn.sysname,
  1190. utsn.machine[0] ? " " : "", utsn.machine);
  1191. }
  1192. snprintf(userAgentG, sizeof(userAgentG),
  1193. "Mozilla/4.0 (Compatible; %s; libs3 %s.%s; %s)",
  1194. userAgentInfo, LIBS3_VER_MAJOR, LIBS3_VER_MINOR, platform);
  1195. // WINSCP (Expat does not need global initialization)
  1196. return S3StatusOK;
  1197. }
  1198. void request_api_deinitialize()
  1199. {
  1200. #ifndef WINSCP
  1201. pthread_mutex_destroy(&requestStackMutexG);
  1202. // WINSCP (Expat does not need global initialization)
  1203. while (requestStackCountG--) {
  1204. request_destroy(requestStackG[requestStackCountG]);
  1205. }
  1206. #endif
  1207. }
  1208. static S3Status setup_request(const RequestParams *params,
  1209. RequestComputedValues *computed,
  1210. int forceUnsignedPayload)
  1211. {
  1212. S3Status status;
  1213. // Validate the bucket name
  1214. if (params->bucketContext.bucketName
  1215. && ((status = S3_validate_bucket_name(params->bucketContext.bucketName,
  1216. params->bucketContext.uriStyle))
  1217. != S3StatusOK)) {
  1218. return status;
  1219. }
  1220. // WINSCP (inspired by PuTTY ltime())
  1221. // Original time()/gmtime() combination did not work correctly in winter time
  1222. SYSTEMTIME st;
  1223. GetSystemTime(&st);
  1224. struct tm gmt;
  1225. memset(&gmt, 0, sizeof(gmt));
  1226. gmt.tm_sec=st.wSecond;
  1227. gmt.tm_min=st.wMinute;
  1228. gmt.tm_hour=st.wHour;
  1229. gmt.tm_mday=st.wDay;
  1230. gmt.tm_mon=st.wMonth-1;
  1231. gmt.tm_year=(st.wYear>=1900?st.wYear-1900:0);
  1232. gmt.tm_wday=st.wDayOfWeek;
  1233. gmt.tm_yday=-1; /* GetSystemTime doesn't tell us */
  1234. gmt.tm_isdst=0; /* GetSystemTime doesn't tell us */
  1235. strftime(computed->requestDateISO8601, sizeof(computed->requestDateISO8601),
  1236. "%Y%m%dT%H%M%SZ", &gmt);
  1237. // Compose the amz headers
  1238. if ((status = compose_amz_headers(params, forceUnsignedPayload, computed))
  1239. != S3StatusOK) {
  1240. return status;
  1241. }
  1242. // Compose standard headers
  1243. if ((status = compose_standard_headers(params, computed)) != S3StatusOK) {
  1244. return status;
  1245. }
  1246. // URL encode the key
  1247. if ((status = encode_key(params, computed)) != S3StatusOK) {
  1248. return status;
  1249. }
  1250. // Compute the canonicalized amz headers
  1251. canonicalize_signature_headers(computed);
  1252. // Compute the canonicalized resource
  1253. canonicalize_resource(&params->bucketContext, computed->urlEncodedKey,
  1254. computed->canonicalURI);
  1255. canonicalize_query_string(params->queryParams, params->subResource,
  1256. computed->canonicalQueryString);
  1257. // Compose Authorization header
  1258. if ((status = compose_auth_header(params, computed)) != S3StatusOK) {
  1259. return status;
  1260. }
  1261. int i = 0;
  1262. ne_debug(NULL, NE_DBG_HTTPBODY, "\n--\nAMZ Headers:\n");
  1263. for (; i < computed->amzHeadersCount; i++) {
  1264. ne_debug(NULL, NE_DBG_HTTPBODY, "%s\n", computed->amzHeaders[i]);
  1265. }
  1266. return status;
  1267. }
  1268. void request_perform(const RequestParams *params, S3RequestContext *context)
  1269. {
  1270. Request *request;
  1271. S3Status status;
  1272. #define return_status(status) \
  1273. (*(params->completeCallback))(status, 0, params->callbackData); \
  1274. return
  1275. // These will hold the computed values
  1276. RequestComputedValues computed;
  1277. if ((status = setup_request(params, &computed, 0)) != S3StatusOK) {
  1278. return_status(status);
  1279. }
  1280. // Get an initialized Request structure now
  1281. if ((status = request_get(params, context /*WINSCP*/, &computed, &request)) != S3StatusOK) {
  1282. return_status(status);
  1283. }
  1284. // WINSCP (we should always verify the peer)
  1285. #ifndef WINSCP
  1286. // If a RequestContext was provided, add the request to the curl multi
  1287. if (context) {
  1288. CURLMcode code = curl_multi_add_handle(context->curlm, request->curl);
  1289. if (code == CURLM_OK) {
  1290. if (context->requests) {
  1291. request->prev = context->requests->prev;
  1292. request->next = context->requests;
  1293. context->requests->prev->next = request;
  1294. context->requests->prev = request;
  1295. }
  1296. else {
  1297. context->requests = request->next = request->prev = request;
  1298. }
  1299. }
  1300. else {
  1301. if (request->status == S3StatusOK) {
  1302. request->status = (code == CURLM_OUT_OF_MEMORY) ?
  1303. S3StatusOutOfMemory : S3StatusInternalError;
  1304. }
  1305. request_finish(request);
  1306. }
  1307. }
  1308. // Else, perform the request immediately
  1309. else
  1310. #endif
  1311. {
  1312. NeonCode code = ne_request_dispatch(request->NeonRequest);
  1313. // Finish the request, ensuring that all callbacks have been made, and
  1314. // also releases the request
  1315. request_finish(request, code);
  1316. }
  1317. }
  1318. void request_finish(Request *request, NeonCode code)
  1319. {
  1320. // If we haven't detected this already, we now know that the headers are
  1321. // definitely done being read in
  1322. request_headers_done(request);
  1323. // If there was no error processing the request, then possibly there was
  1324. // an S3 error parsed, which should be converted into the request status
  1325. // WINSCP: We get "OK", even if there's TCP or HTTP error
  1326. if (request->status == S3StatusOK) {
  1327. // First handle S3 errors
  1328. // TemporaryRedirect S3 error has a precedence over HTTP 3xx error that carries it.
  1329. error_parser_convert_status(&(request->errorParser),
  1330. &(request->status));
  1331. #ifdef WINSCP
  1332. // This handles TCP and HTTP errors
  1333. if (request->status == S3StatusOK) {
  1334. if (code != NE_OK) {
  1335. request->status = request_neon_code_to_status(code);
  1336. if (request->errorParser.s3ErrorDetails.message == NULL) {
  1337. const char * neonError = ne_get_error(request->NeonSession);
  1338. int allFit;
  1339. string_buffer_append(request->statusMessage, neonError, strlen(neonError), allFit);
  1340. request->errorParser.s3ErrorDetails.message = request->statusMessage;
  1341. }
  1342. }
  1343. }
  1344. #endif
  1345. // If there still was no error recorded, then it is possible that
  1346. // there was in fact an error but that there was no error XML
  1347. // detailing the error
  1348. // WINSCP: We possibly never get here with neon
  1349. if ((request->status == S3StatusOK) &&
  1350. ((request->httpResponseCode < 200) ||
  1351. (request->httpResponseCode > 299))) {
  1352. switch (request->httpResponseCode) {
  1353. case 0:
  1354. // This happens if the request never got any HTTP response
  1355. // headers at all, we call this a ConnectionFailed error
  1356. request->status = S3StatusConnectionFailed;
  1357. break;
  1358. case 100: // Some versions of libcurl erroneously set HTTP
  1359. // status to this
  1360. break;
  1361. case 301:
  1362. request->status = S3StatusErrorPermanentRedirect;
  1363. break;
  1364. case 307:
  1365. request->status = S3StatusHttpErrorMovedTemporarily;
  1366. break;
  1367. case 400:
  1368. request->status = S3StatusHttpErrorBadRequest;
  1369. break;
  1370. case 403:
  1371. request->status = S3StatusHttpErrorForbidden;
  1372. break;
  1373. case 404:
  1374. request->status = S3StatusHttpErrorNotFound;
  1375. break;
  1376. case 405:
  1377. request->status = S3StatusErrorMethodNotAllowed;
  1378. break;
  1379. case 409:
  1380. request->status = S3StatusHttpErrorConflict;
  1381. break;
  1382. case 411:
  1383. request->status = S3StatusErrorMissingContentLength;
  1384. break;
  1385. case 412:
  1386. request->status = S3StatusErrorPreconditionFailed;
  1387. break;
  1388. case 416:
  1389. request->status = S3StatusErrorInvalidRange;
  1390. break;
  1391. case 500:
  1392. request->status = S3StatusErrorInternalError;
  1393. break;
  1394. case 501:
  1395. request->status = S3StatusErrorNotImplemented;
  1396. break;
  1397. case 503:
  1398. request->status = S3StatusErrorSlowDown;
  1399. break;
  1400. default:
  1401. request->status = S3StatusHttpErrorUnknown;
  1402. break;
  1403. }
  1404. }
  1405. }
  1406. (*(request->completeCallback))
  1407. (request->status, &(request->errorParser.s3ErrorDetails),
  1408. request->callbackData);
  1409. request_release(request);
  1410. }
  1411. S3Status request_neon_code_to_status(NeonCode code)
  1412. {
  1413. switch (code) {
  1414. case NE_LOOKUP:
  1415. return S3StatusNameLookupError;
  1416. case NE_CONNECT:
  1417. return S3StatusFailedToConnect;
  1418. case NE_TIMEOUT:
  1419. case NE_SOCKET:
  1420. return S3StatusConnectionFailed;
  1421. default:
  1422. return S3StatusInternalError;
  1423. }
  1424. }
  1425. S3Status S3_generate_authenticated_query_string
  1426. (char *buffer, const S3BucketContext *bucketContext,
  1427. const char *key, int expires, const char *resource,
  1428. const char *httpMethod)
  1429. {
  1430. // maximum expiration period is seven days (in seconds)
  1431. #define MAX_EXPIRES 604800
  1432. if (expires < 0) {
  1433. expires = MAX_EXPIRES;
  1434. }
  1435. else if (expires > MAX_EXPIRES) {
  1436. expires = MAX_EXPIRES;
  1437. }
  1438. // WinSCP
  1439. RequestParams params =
  1440. { http_request_method_to_type(httpMethod),
  1441. { bucketContext->hostName, bucketContext->bucketName, bucketContext->protocol, bucketContext->uriStyle, bucketContext->accessKeyId, bucketContext->secretAccessKey, bucketContext->securityToken, bucketContext->authRegion },
  1442. key, NULL,
  1443. resource,
  1444. NULL, NULL, NULL, 0, 0, NULL, NULL, NULL, 0, NULL, NULL, NULL, 0};
  1445. RequestComputedValues computed;
  1446. S3Status status = setup_request(&params, &computed, 1);
  1447. if (status != S3StatusOK) {
  1448. return status;
  1449. }
  1450. // Finally, compose the URI, with params
  1451. char queryParams[sizeof("X-Amz-Algorithm=AWS4-HMAC-SHA256")
  1452. + sizeof("&X-Amz-Credential=") + MAX_CREDENTIAL_SIZE
  1453. + sizeof("&X-Amz-Date=") + 16 + sizeof("&X-Amz-Expires=") + 6
  1454. + sizeof("&X-Amz-SignedHeaders=") + 128 + sizeof("&X-Amz-Signature=")
  1455. + sizeof(computed.requestSignatureHex) + 1];
  1456. snprintf(queryParams, sizeof(queryParams),
  1457. "X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=%s"
  1458. "&X-Amz-Date=%s&X-Amz-Expires=%d"
  1459. "&X-Amz-SignedHeaders=%s&X-Amz-Signature=%s",
  1460. computed.authCredential, computed.requestDateISO8601, expires,
  1461. computed.signedHeaders, computed.requestSignatureHex);
  1462. return compose_uri(buffer, S3_MAX_AUTHENTICATED_QUERY_STRING_SIZE,
  1463. bucketContext, computed.urlEncodedKey, resource,
  1464. queryParams);
  1465. }