PageRenderTime 69ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 1ms

/amanda/tags/3_3_0_qa09/device-src/s3.c

#
C | 2103 lines | 1488 code | 295 blank | 320 comment | 319 complexity | c5a9ec72fa913f2175fe3fd9fff0cc03 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. /*
  2. * Copyright (c) 2008, 2009, 2010 Zmanda, Inc. All Rights Reserved.
  3. *
  4. * This program is free software; you can redistribute it and/or modify it
  5. * under the terms of the GNU General Public License version 2 as published
  6. * by the Free Software Foundation.
  7. *
  8. * This program is distributed in the hope that it will be useful, but
  9. * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  10. * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
  11. * for more details.
  12. *
  13. * You should have received a copy of the GNU General Public License along
  14. * with this program; if not, write to the Free Software Foundation, Inc.,
  15. * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. *
  17. * Contact information: Zmanda Inc., 465 S. Mathilda Ave., Suite 300
  18. * Sunnyvale, CA 94085, USA, or: http://www.zmanda.com
  19. */
  20. /* TODO
  21. * - collect speed statistics
  22. * - debugging mode
  23. */
  24. #ifdef HAVE_CONFIG_H
  25. /* use a relative path here to avoid conflicting with Perl's config.h. */
  26. #include "../config/config.h"
  27. #endif
  28. #include <string.h>
  29. #include "s3.h"
  30. #include "s3-util.h"
  31. #ifdef HAVE_REGEX_H
  32. #include <regex.h>
  33. #endif
  34. #ifdef HAVE_SYS_TYPES_H
  35. #include <sys/types.h>
  36. #endif
  37. #ifdef HAVE_SYS_STAT_H
  38. #include <sys/stat.h>
  39. #endif
  40. #ifdef HAVE_UNISTD_H
  41. #include <unistd.h>
  42. #endif
  43. #ifdef HAVE_DIRENT_H
  44. #include <dirent.h>
  45. #endif
  46. #ifdef HAVE_TIME_H
  47. #include <time.h>
  48. #endif
  49. #ifdef HAVE_UTIL_H
  50. #include "util.h"
  51. #endif
  52. #ifdef HAVE_AMANDA_H
  53. #include "amanda.h"
  54. #endif
  55. #include <curl/curl.h>
  56. /* Constant renamed after version 7.10.7 */
  57. #ifndef CURLINFO_RESPONSE_CODE
  58. #define CURLINFO_RESPONSE_CODE CURLINFO_HTTP_CODE
  59. #endif
  60. /* We don't need OpenSSL's kerberos support, and it's broken in
  61. * RHEL 3 anyway. */
  62. #define OPENSSL_NO_KRB5
  63. #ifdef HAVE_OPENSSL_HMAC_H
  64. # include <openssl/hmac.h>
  65. #else
  66. # ifdef HAVE_CRYPTO_HMAC_H
  67. # include <crypto/hmac.h>
  68. # else
  69. # ifdef HAVE_HMAC_H
  70. # include <hmac.h>
  71. # endif
  72. # endif
  73. #endif
  74. #include <openssl/err.h>
  75. #include <openssl/ssl.h>
  76. #include <openssl/md5.h>
  77. /* Maximum key length as specified in the S3 documentation
  78. * (*excluding* null terminator) */
  79. #define S3_MAX_KEY_LENGTH 1024
  80. #define AMAZON_SECURITY_HEADER "x-amz-security-token"
  81. #define AMAZON_BUCKET_CONF_TEMPLATE "\
  82. <CreateBucketConfiguration>\n\
  83. <LocationConstraint>%s</LocationConstraint>\n\
  84. </CreateBucketConfiguration>"
  85. #define AMAZON_STORAGE_CLASS_HEADER "x-amz-storage-class"
  86. #define AMAZON_SERVER_SIDE_ENCRYPTION_HEADER "x-amz-server-side-encryption"
  87. #define AMAZON_WILDCARD_LOCATION "*"
  88. /* parameters for exponential backoff in the face of retriable errors */
  89. /* start at 0.01s */
  90. #define EXPONENTIAL_BACKOFF_START_USEC G_USEC_PER_SEC/100
  91. /* double at each retry */
  92. #define EXPONENTIAL_BACKOFF_BASE 2
  93. /* retry 14 times (for a total of about 3 minutes spent waiting) */
  94. #define EXPONENTIAL_BACKOFF_MAX_RETRIES 14
  95. /* general "reasonable size" parameters */
  96. #define MAX_ERROR_RESPONSE_LEN (100*1024)
  97. /* Results which should always be retried */
  98. #define RESULT_HANDLING_ALWAYS_RETRY \
  99. { 400, S3_ERROR_RequestTimeout, 0, S3_RESULT_RETRY }, \
  100. { 403, S3_ERROR_RequestTimeTooSkewed,0, S3_RESULT_RETRY }, \
  101. { 409, S3_ERROR_OperationAborted, 0, S3_RESULT_RETRY }, \
  102. { 412, S3_ERROR_PreconditionFailed, 0, S3_RESULT_RETRY }, \
  103. { 500, S3_ERROR_InternalError, 0, S3_RESULT_RETRY }, \
  104. { 501, S3_ERROR_NotImplemented, 0, S3_RESULT_RETRY }, \
  105. { 0, 0, CURLE_COULDNT_CONNECT, S3_RESULT_RETRY }, \
  106. { 0, 0, CURLE_COULDNT_RESOLVE_HOST, S3_RESULT_RETRY }, \
  107. { 0, 0, CURLE_PARTIAL_FILE, S3_RESULT_RETRY }, \
  108. { 0, 0, CURLE_OPERATION_TIMEOUTED, S3_RESULT_RETRY }, \
  109. { 0, 0, CURLE_SSL_CONNECT_ERROR, S3_RESULT_RETRY }, \
  110. { 0, 0, CURLE_SEND_ERROR, S3_RESULT_RETRY }, \
  111. { 0, 0, CURLE_RECV_ERROR, S3_RESULT_RETRY }, \
  112. { 0, 0, CURLE_GOT_NOTHING, S3_RESULT_RETRY }
  113. /*
  114. * Data structures and associated functions
  115. */
  116. struct S3Handle {
  117. /* (all strings in this struct are freed by s3_free()) */
  118. char *access_key;
  119. char *secret_key;
  120. char *user_token;
  121. /* attributes for new objects */
  122. char *bucket_location;
  123. char *storage_class;
  124. char *server_side_encryption;
  125. char *host;
  126. char *service_path;
  127. gboolean use_subdomain;
  128. char *ca_info;
  129. CURL *curl;
  130. gboolean verbose;
  131. gboolean use_ssl;
  132. guint64 max_send_speed;
  133. guint64 max_recv_speed;
  134. /* information from the last request */
  135. char *last_message;
  136. guint last_response_code;
  137. s3_error_code_t last_s3_error_code;
  138. CURLcode last_curl_code;
  139. guint last_num_retries;
  140. void *last_response_body;
  141. guint last_response_body_size;
  142. /* offset with s3 */
  143. time_t time_offset_with_s3;
  144. };
  145. typedef struct {
  146. CurlBuffer resp_buf;
  147. s3_write_func write_func;
  148. s3_reset_func reset_func;
  149. gpointer write_data;
  150. gboolean headers_done;
  151. gboolean int_write_done;
  152. char *etag;
  153. /* Points to current handle: Added to get hold of s3 offset */
  154. struct S3Handle *hdl;
  155. } S3InternalData;
  156. /* Callback function to examine headers one-at-a-time
  157. *
  158. * @note this is the same as CURLOPT_HEADERFUNCTION
  159. *
  160. * @param data: The pointer to read data from
  161. * @param size: The size of each "element" of the data buffer in bytes
  162. * @param nmemb: The number of elements in the data buffer.
  163. * So, the buffer's size is size*nmemb bytes.
  164. * @param stream: the header_data (an opaque pointer)
  165. *
  166. * @return The number of bytes written to the buffer or
  167. * CURL_WRITEFUNC_PAUSE to pause.
  168. * If it's the number of bytes written, it should match the buffer size
  169. */
  170. typedef size_t (*s3_header_func)(void *data, size_t size, size_t nmemb, void *stream);
  171. /*
  172. * S3 errors */
  173. /* (see preprocessor magic in s3.h) */
  174. static char * s3_error_code_names[] = {
  175. #define S3_ERROR(NAME) #NAME
  176. S3_ERROR_LIST
  177. #undef S3_ERROR
  178. };
  179. /* Convert an s3 error name to an error code. This function
  180. * matches strings case-insensitively, and is appropriate for use
  181. * on data from the network.
  182. *
  183. * @param s3_error_code: the error name
  184. * @returns: the error code (see constants in s3.h)
  185. */
  186. static s3_error_code_t
  187. s3_error_code_from_name(char *s3_error_name);
  188. /* Convert an s3 error code to a string
  189. *
  190. * @param s3_error_code: the error code to convert
  191. * @returns: statically allocated string
  192. */
  193. static const char *
  194. s3_error_name_from_code(s3_error_code_t s3_error_code);
  195. /*
  196. * result handling */
  197. /* result handling is specified by a static array of result_handling structs,
  198. * which match based on response_code (from HTTP) and S3 error code. The result
  199. * given for the first match is used. 0 acts as a wildcard for both response_code
  200. * and s3_error_code. The list is terminated with a struct containing 0 for both
  201. * response_code and s3_error_code; the result for that struct is the default
  202. * result.
  203. *
  204. * See RESULT_HANDLING_ALWAYS_RETRY for an example.
  205. */
  206. typedef enum {
  207. S3_RESULT_RETRY = -1,
  208. S3_RESULT_FAIL = 0,
  209. S3_RESULT_OK = 1
  210. } s3_result_t;
  211. typedef struct result_handling {
  212. guint response_code;
  213. s3_error_code_t s3_error_code;
  214. CURLcode curl_code;
  215. s3_result_t result;
  216. } result_handling_t;
  217. /* Lookup a result in C{result_handling}.
  218. *
  219. * @param result_handling: array of handling specifications
  220. * @param response_code: response code from operation
  221. * @param s3_error_code: s3 error code from operation, if any
  222. * @param curl_code: the CURL error, if any
  223. * @returns: the matching result
  224. */
  225. static s3_result_t
  226. lookup_result(const result_handling_t *result_handling,
  227. guint response_code,
  228. s3_error_code_t s3_error_code,
  229. CURLcode curl_code);
  230. /*
  231. * Precompiled regular expressions */
  232. static regex_t etag_regex, error_name_regex, message_regex, subdomain_regex,
  233. location_con_regex, date_sync_regex;
  234. /*
  235. * Utility functions
  236. */
  237. /* Check if a string is non-empty
  238. *
  239. * @param str: string to check
  240. * @returns: true iff str is non-NULL and not "\0"
  241. */
  242. static gboolean is_non_empty_string(const char *str);
  243. /* Construct the URL for an Amazon S3 REST request.
  244. *
  245. * A new string is allocated and returned; it is the responsiblity of the caller.
  246. *
  247. * @param hdl: the S3Handle object
  248. * @param verb: capitalized verb for this request ('PUT', 'GET', etc.)
  249. * @param host: the host name to connect to, 's3.amazonaws.com'
  250. * @param service_path: A path to add in the URL, or NULL for none.
  251. * @param bucket: the bucket being accessed, or NULL for none
  252. * @param key: the key being accessed, or NULL for none
  253. * @param subresource: the sub-resource being accessed (e.g. "acl"), or NULL for none
  254. * @param use_subdomain: if TRUE, a subdomain of 'host' will be used
  255. * @param use_ssl: if TRUE, use 'https'
  256. *
  257. * !use_subdomain: http://host/service_path/bucket/key
  258. * use_subdomain : http://bucket.host/service_path/key
  259. *
  260. */
  261. static char *
  262. build_url(
  263. CURL *curl,
  264. const char *host,
  265. const char *service_path,
  266. const char *bucket,
  267. const char *key,
  268. const char *subresource,
  269. const char *query,
  270. gboolean use_subdomain,
  271. gboolean use_ssl);
  272. /* Create proper authorization headers for an Amazon S3 REST
  273. * request to C{headers}.
  274. *
  275. * @note: C{X-Amz} headers (in C{headers}) must
  276. * - be in lower-case
  277. * - be in alphabetical order
  278. * - have no spaces around the colon
  279. * (don't yell at me -- see the Amazon Developer Guide)
  280. *
  281. * @param hdl: the S3Handle object
  282. * @param verb: capitalized verb for this request ('PUT', 'GET', etc.)
  283. * @param bucket: the bucket being accessed, or NULL for none
  284. * @param key: the key being accessed, or NULL for none
  285. * @param subresource: the sub-resource being accessed (e.g. "acl"), or NULL for none
  286. * @param md5_hash: the MD5 hash of the request body, or NULL for none
  287. */
  288. static struct curl_slist *
  289. authenticate_request(S3Handle *hdl,
  290. const char *verb,
  291. const char *bucket,
  292. const char *key,
  293. const char *subresource,
  294. const char *md5_hash);
  295. /* Interpret the response to an S3 operation, assuming CURL completed its request
  296. * successfully. This function fills in the relevant C{hdl->last*} members.
  297. *
  298. * @param hdl: The S3Handle object
  299. * @param body: the response body
  300. * @param body_len: the length of the response body
  301. * @param etag: The response's ETag header
  302. * @param content_md5: The hex-encoded MD5 hash of the request body,
  303. * which will be checked against the response's ETag header.
  304. * If NULL, the header is not checked.
  305. * If non-NULL, then the body should have the response headers at its beginnning.
  306. * @returns: TRUE if the response should be retried (e.g., network error)
  307. */
  308. static gboolean
  309. interpret_response(S3Handle *hdl,
  310. CURLcode curl_code,
  311. char *curl_error_buffer,
  312. gchar *body,
  313. guint body_len,
  314. const char *etag,
  315. const char *content_md5);
  316. /* Perform an S3 operation. This function handles all of the details
  317. * of retryig requests and so on.
  318. *
  319. * The concepts of bucket and keys are defined by the Amazon S3 API.
  320. * See: "Components of Amazon S3" - API Version 2006-03-01 pg. 8
  321. *
  322. * Individual sub-resources are defined in several places. In the REST API,
  323. * they they are represented by a "flag" in the "query string".
  324. * See: "Constructing the CanonicalizedResource Element" - API Version 2006-03-01 pg. 60
  325. *
  326. * @param hdl: the S3Handle object
  327. * @param verb: the HTTP request method
  328. * @param bucket: the bucket to access, or NULL for none
  329. * @param key: the key to access, or NULL for none
  330. * @param subresource: the "sub-resource" to request (e.g. "acl") or NULL for none
  331. * @param query: the query string to send (not including th initial '?'),
  332. * or NULL for none
  333. * @param read_func: the callback for reading data
  334. * Will use s3_empty_read_func if NULL is passed in.
  335. * @param read_reset_func: the callback for to reset reading data
  336. * @param size_func: the callback to get the number of bytes to upload
  337. * @param md5_func: the callback to get the MD5 hash of the data to upload
  338. * @param read_data: pointer to pass to the above functions
  339. * @param write_func: the callback for writing data.
  340. * Will use s3_counter_write_func if NULL is passed in.
  341. * @param write_reset_func: the callback for to reset writing data
  342. * @param write_data: pointer to pass to C{write_func}
  343. * @param progress_func: the callback for progress information
  344. * @param progress_data: pointer to pass to C{progress_func}
  345. * @param result_handling: instructions for handling the results; see above.
  346. * @returns: the result specified by result_handling; details of the response
  347. * are then available in C{hdl->last*}
  348. */
  349. static s3_result_t
  350. perform_request(S3Handle *hdl,
  351. const char *verb,
  352. const char *bucket,
  353. const char *key,
  354. const char *subresource,
  355. const char *query,
  356. s3_read_func read_func,
  357. s3_reset_func read_reset_func,
  358. s3_size_func size_func,
  359. s3_md5_func md5_func,
  360. gpointer read_data,
  361. s3_write_func write_func,
  362. s3_reset_func write_reset_func,
  363. gpointer write_data,
  364. s3_progress_func progress_func,
  365. gpointer progress_data,
  366. const result_handling_t *result_handling);
  367. /*
  368. * a CURLOPT_WRITEFUNCTION to save part of the response in memory and
  369. * call an external function if one was provided.
  370. */
  371. static size_t
  372. s3_internal_write_func(void *ptr, size_t size, size_t nmemb, void * stream);
  373. /*
  374. * a function to reset to our internal buffer
  375. */
  376. static void
  377. s3_internal_reset_func(void * stream);
  378. /*
  379. * a CURLOPT_HEADERFUNCTION to save the ETag header only.
  380. */
  381. static size_t
  382. s3_internal_header_func(void *ptr, size_t size, size_t nmemb, void * stream);
  383. static gboolean
  384. compile_regexes(void);
  385. /*
  386. * Static function implementations
  387. */
  388. static s3_error_code_t
  389. s3_error_code_from_name(char *s3_error_name)
  390. {
  391. int i;
  392. if (!s3_error_name) return S3_ERROR_Unknown;
  393. /* do a brute-force search through the list, since it's not sorted */
  394. for (i = 0; i < S3_ERROR_END; i++) {
  395. if (g_ascii_strcasecmp(s3_error_name, s3_error_code_names[i]) == 0)
  396. return i;
  397. }
  398. return S3_ERROR_Unknown;
  399. }
  400. static const char *
  401. s3_error_name_from_code(s3_error_code_t s3_error_code)
  402. {
  403. if (s3_error_code >= S3_ERROR_END)
  404. s3_error_code = S3_ERROR_Unknown;
  405. return s3_error_code_names[s3_error_code];
  406. }
  407. gboolean
  408. s3_curl_supports_ssl(void)
  409. {
  410. static int supported = -1;
  411. if (supported == -1) {
  412. #if defined(CURL_VERSION_SSL)
  413. curl_version_info_data *info = curl_version_info(CURLVERSION_NOW);
  414. if (info->features & CURL_VERSION_SSL)
  415. supported = 1;
  416. else
  417. supported = 0;
  418. #else
  419. supported = 0;
  420. #endif
  421. }
  422. return supported;
  423. }
  424. static gboolean
  425. s3_curl_throttling_compat(void)
  426. {
  427. /* CURLOPT_MAX_SEND_SPEED_LARGE added in 7.15.5 */
  428. #if LIBCURL_VERSION_NUM >= 0x070f05
  429. curl_version_info_data *info;
  430. /* check the runtime version too */
  431. info = curl_version_info(CURLVERSION_NOW);
  432. return info->version_num >= 0x070f05;
  433. #else
  434. return FALSE;
  435. #endif
  436. }
  437. static s3_result_t
  438. lookup_result(const result_handling_t *result_handling,
  439. guint response_code,
  440. s3_error_code_t s3_error_code,
  441. CURLcode curl_code)
  442. {
  443. while (result_handling->response_code
  444. || result_handling->s3_error_code
  445. || result_handling->curl_code) {
  446. if ((result_handling->response_code && result_handling->response_code != response_code)
  447. || (result_handling->s3_error_code && result_handling->s3_error_code != s3_error_code)
  448. || (result_handling->curl_code && result_handling->curl_code != curl_code)) {
  449. result_handling++;
  450. continue;
  451. }
  452. return result_handling->result;
  453. }
  454. /* return the result for the terminator, as the default */
  455. return result_handling->result;
  456. }
  457. static gboolean
  458. is_non_empty_string(const char *str)
  459. {
  460. return str && str[0] != '\0';
  461. }
  462. static char *
  463. build_url(
  464. CURL *curl G_GNUC_UNUSED,
  465. const char *host,
  466. const char *service_path,
  467. const char *bucket,
  468. const char *key,
  469. const char *subresource,
  470. const char *query,
  471. gboolean use_subdomain,
  472. gboolean use_ssl)
  473. {
  474. GString *url = NULL;
  475. char *esc_bucket = NULL, *esc_key = NULL;
  476. /* scheme */
  477. url = g_string_new("http");
  478. if (use_ssl)
  479. g_string_append(url, "s");
  480. g_string_append(url, "://");
  481. /* domain */
  482. if (use_subdomain && bucket)
  483. g_string_append_printf(url, "%s.%s", bucket, host);
  484. else
  485. g_string_append_printf(url, "%s", host);
  486. if (service_path) {
  487. g_string_append_printf(url, "%s/", service_path);
  488. } else {
  489. g_string_append(url, "/");
  490. }
  491. /* path */
  492. if (!use_subdomain && bucket) {
  493. /* curl_easy_escape addeded in 7.15.4 */
  494. #if LIBCURL_VERSION_NUM >= 0x070f04
  495. curl_version_info_data *info;
  496. /* check the runtime version too */
  497. info = curl_version_info(CURLVERSION_NOW);
  498. if (info->version_num >= 0x070f04)
  499. esc_bucket = curl_easy_escape(curl, bucket, 0);
  500. else
  501. esc_bucket = curl_escape(bucket, 0);
  502. #else
  503. esc_bucket = curl_escape(bucket, 0);
  504. #endif
  505. if (!esc_bucket) goto cleanup;
  506. g_string_append_printf(url, "%s", esc_bucket);
  507. if (key)
  508. g_string_append(url, "/");
  509. curl_free(esc_bucket);
  510. }
  511. if (key) {
  512. /* curl_easy_escape addeded in 7.15.4 */
  513. #if LIBCURL_VERSION_NUM >= 0x070f04
  514. curl_version_info_data *info;
  515. /* check the runtime version too */
  516. info = curl_version_info(CURLVERSION_NOW);
  517. if (info->version_num >= 0x070f04)
  518. esc_key = curl_easy_escape(curl, key, 0);
  519. else
  520. esc_key = curl_escape(key, 0);
  521. #else
  522. esc_key = curl_escape(key, 0);
  523. #endif
  524. if (!esc_key) goto cleanup;
  525. g_string_append_printf(url, "%s", esc_key);
  526. curl_free(esc_key);
  527. }
  528. /* query string */
  529. if (subresource || query)
  530. g_string_append(url, "?");
  531. if (subresource)
  532. g_string_append(url, subresource);
  533. if (subresource && query)
  534. g_string_append(url, "&");
  535. if (query)
  536. g_string_append(url, query);
  537. cleanup:
  538. return g_string_free(url, FALSE);
  539. }
  540. static struct curl_slist *
  541. authenticate_request(S3Handle *hdl,
  542. const char *verb,
  543. const char *bucket,
  544. const char *key,
  545. const char *subresource,
  546. const char *md5_hash)
  547. {
  548. time_t t;
  549. struct tm tmp;
  550. char *date = NULL;
  551. char *buf = NULL;
  552. HMAC_CTX ctx;
  553. GByteArray *md = NULL;
  554. char *auth_base64 = NULL;
  555. struct curl_slist *headers = NULL;
  556. char *esc_bucket = NULL, *esc_key = NULL;
  557. GString *auth_string = NULL;
  558. /* From RFC 2616 */
  559. static const char *wkday[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
  560. static const char *month[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  561. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  562. /* Build the string to sign, per the S3 spec.
  563. * See: "Authenticating REST Requests" - API Version 2006-03-01 pg 58
  564. */
  565. /* verb */
  566. auth_string = g_string_new(verb);
  567. g_string_append(auth_string, "\n");
  568. /* Content-MD5 header */
  569. if (md5_hash)
  570. g_string_append(auth_string, md5_hash);
  571. g_string_append(auth_string, "\n");
  572. /* Content-Type is empty*/
  573. g_string_append(auth_string, "\n");
  574. /* calculate the date */
  575. t = time(NULL);
  576. /* sync clock with amazon s3 */
  577. t = t + hdl->time_offset_with_s3;
  578. #ifdef _WIN32
  579. if (!gmtime_s(&tmp, &t)) g_debug("localtime error");
  580. #else
  581. if (!gmtime_r(&t, &tmp)) perror("localtime");
  582. #endif
  583. date = g_strdup_printf("%s, %02d %s %04d %02d:%02d:%02d GMT",
  584. wkday[tmp.tm_wday], tmp.tm_mday, month[tmp.tm_mon], 1900+tmp.tm_year,
  585. tmp.tm_hour, tmp.tm_min, tmp.tm_sec);
  586. g_string_append(auth_string, date);
  587. g_string_append(auth_string, "\n");
  588. /* CanonicalizedAmzHeaders, sorted lexicographically */
  589. if (is_non_empty_string(hdl->user_token)) {
  590. g_string_append(auth_string, AMAZON_SECURITY_HEADER);
  591. g_string_append(auth_string, ":");
  592. g_string_append(auth_string, hdl->user_token);
  593. g_string_append(auth_string, ",");
  594. g_string_append(auth_string, STS_PRODUCT_TOKEN);
  595. g_string_append(auth_string, "\n");
  596. }
  597. if (g_str_equal(verb,"PUT") &&
  598. is_non_empty_string(hdl->server_side_encryption)) {
  599. g_string_append(auth_string, AMAZON_SERVER_SIDE_ENCRYPTION_HEADER);
  600. g_string_append(auth_string, ":");
  601. g_string_append(auth_string, hdl->server_side_encryption);
  602. g_string_append(auth_string, "\n");
  603. }
  604. if (is_non_empty_string(hdl->storage_class)) {
  605. g_string_append(auth_string, AMAZON_STORAGE_CLASS_HEADER);
  606. g_string_append(auth_string, ":");
  607. g_string_append(auth_string, hdl->storage_class);
  608. g_string_append(auth_string, "\n");
  609. }
  610. /* CanonicalizedResource */
  611. if (hdl->service_path) {
  612. g_string_append(auth_string, hdl->service_path);
  613. }
  614. g_string_append(auth_string, "/");
  615. if (bucket) {
  616. if (hdl->use_subdomain)
  617. g_string_append(auth_string, bucket);
  618. else {
  619. esc_bucket = curl_escape(bucket, 0);
  620. if (!esc_bucket) goto cleanup;
  621. g_string_append(auth_string, esc_bucket);
  622. }
  623. }
  624. if (bucket && (hdl->use_subdomain || key))
  625. g_string_append(auth_string, "/");
  626. if (key) {
  627. esc_key = curl_escape(key, 0);
  628. if (!esc_key) goto cleanup;
  629. g_string_append(auth_string, esc_key);
  630. }
  631. if (subresource) {
  632. g_string_append(auth_string, "?");
  633. g_string_append(auth_string, subresource);
  634. }
  635. /* run HMAC-SHA1 on the canonicalized string */
  636. md = g_byte_array_sized_new(EVP_MAX_MD_SIZE+1);
  637. HMAC_CTX_init(&ctx);
  638. HMAC_Init_ex(&ctx, hdl->secret_key, (int) strlen(hdl->secret_key), EVP_sha1(), NULL);
  639. HMAC_Update(&ctx, (unsigned char*) auth_string->str, auth_string->len);
  640. HMAC_Final(&ctx, md->data, &md->len);
  641. HMAC_CTX_cleanup(&ctx);
  642. auth_base64 = s3_base64_encode(md);
  643. /* append the new headers */
  644. if (is_non_empty_string(hdl->user_token)) {
  645. /* Devpay headers are included in hash. */
  646. buf = g_strdup_printf(AMAZON_SECURITY_HEADER ": %s", hdl->user_token);
  647. headers = curl_slist_append(headers, buf);
  648. g_free(buf);
  649. buf = g_strdup_printf(AMAZON_SECURITY_HEADER ": %s", STS_PRODUCT_TOKEN);
  650. headers = curl_slist_append(headers, buf);
  651. g_free(buf);
  652. }
  653. if (g_str_equal(verb,"PUT") &&
  654. is_non_empty_string(hdl->server_side_encryption)) {
  655. buf = g_strdup_printf(AMAZON_SERVER_SIDE_ENCRYPTION_HEADER ": %s", hdl->server_side_encryption);
  656. headers = curl_slist_append(headers, buf);
  657. g_free(buf);
  658. }
  659. if (is_non_empty_string(hdl->storage_class)) {
  660. buf = g_strdup_printf(AMAZON_STORAGE_CLASS_HEADER ": %s", hdl->storage_class);
  661. headers = curl_slist_append(headers, buf);
  662. g_free(buf);
  663. }
  664. buf = g_strdup_printf("Authorization: AWS %s:%s",
  665. hdl->access_key, auth_base64);
  666. headers = curl_slist_append(headers, buf);
  667. g_free(buf);
  668. if (md5_hash && '\0' != md5_hash[0]) {
  669. buf = g_strdup_printf("Content-MD5: %s", md5_hash);
  670. headers = curl_slist_append(headers, buf);
  671. g_free(buf);
  672. }
  673. buf = g_strdup_printf("Date: %s", date);
  674. headers = curl_slist_append(headers, buf);
  675. g_free(buf);
  676. cleanup:
  677. g_free(date);
  678. g_free(esc_bucket);
  679. g_free(esc_key);
  680. g_byte_array_free(md, TRUE);
  681. g_free(auth_base64);
  682. g_string_free(auth_string, TRUE);
  683. return headers;
  684. }
  685. static gboolean
  686. interpret_response(S3Handle *hdl,
  687. CURLcode curl_code,
  688. char *curl_error_buffer,
  689. gchar *body,
  690. guint body_len,
  691. const char *etag,
  692. const char *content_md5)
  693. {
  694. long response_code = 0;
  695. regmatch_t pmatch[2];
  696. char *error_name = NULL, *message = NULL;
  697. char *body_copy = NULL;
  698. gboolean ret = TRUE;
  699. if (!hdl) return FALSE;
  700. if (hdl->last_message) g_free(hdl->last_message);
  701. hdl->last_message = NULL;
  702. /* bail out from a CURL error */
  703. if (curl_code != CURLE_OK) {
  704. hdl->last_curl_code = curl_code;
  705. hdl->last_message = g_strdup_printf("CURL error: %s", curl_error_buffer);
  706. return FALSE;
  707. }
  708. /* CURL seems to think things were OK, so get its response code */
  709. curl_easy_getinfo(hdl->curl, CURLINFO_RESPONSE_CODE, &response_code);
  710. hdl->last_response_code = response_code;
  711. /* check ETag, if present */
  712. if (etag && content_md5 && 200 == response_code) {
  713. if (etag && g_ascii_strcasecmp(etag, content_md5))
  714. hdl->last_message = g_strdup("S3 Error: Possible data corruption (ETag returned by Amazon did not match the MD5 hash of the data sent)");
  715. else
  716. ret = FALSE;
  717. return ret;
  718. }
  719. if (200 <= response_code && response_code < 400) {
  720. /* 2xx and 3xx codes won't have a response body we care about */
  721. hdl->last_s3_error_code = S3_ERROR_None;
  722. return FALSE;
  723. }
  724. /* Now look at the body to try to get the actual Amazon error message. Rather
  725. * than parse out the XML, just use some regexes. */
  726. /* impose a reasonable limit on body size */
  727. if (body_len > MAX_ERROR_RESPONSE_LEN) {
  728. hdl->last_message = g_strdup("S3 Error: Unknown (response body too large to parse)");
  729. return FALSE;
  730. } else if (!body || body_len == 0) {
  731. hdl->last_message = g_strdup("S3 Error: Unknown (empty response body)");
  732. return TRUE; /* perhaps a network error; retry the request */
  733. }
  734. /* use strndup to get a zero-terminated string */
  735. body_copy = g_strndup(body, body_len);
  736. if (!body_copy) goto cleanup;
  737. if (!s3_regexec_wrap(&error_name_regex, body_copy, 2, pmatch, 0))
  738. error_name = find_regex_substring(body_copy, pmatch[1]);
  739. if (!s3_regexec_wrap(&message_regex, body_copy, 2, pmatch, 0))
  740. message = find_regex_substring(body_copy, pmatch[1]);
  741. if (error_name) {
  742. hdl->last_s3_error_code = s3_error_code_from_name(error_name);
  743. }
  744. if (message) {
  745. hdl->last_message = message;
  746. message = NULL; /* steal the reference to the string */
  747. }
  748. cleanup:
  749. g_free(body_copy);
  750. g_free(message);
  751. g_free(error_name);
  752. return FALSE;
  753. }
  754. /* a CURLOPT_READFUNCTION to read data from a buffer. */
  755. size_t
  756. s3_buffer_read_func(void *ptr, size_t size, size_t nmemb, void * stream)
  757. {
  758. CurlBuffer *data = stream;
  759. guint bytes_desired = (guint) size * nmemb;
  760. /* check the number of bytes remaining, just to be safe */
  761. if (bytes_desired > data->buffer_len - data->buffer_pos)
  762. bytes_desired = data->buffer_len - data->buffer_pos;
  763. memcpy((char *)ptr, data->buffer + data->buffer_pos, bytes_desired);
  764. data->buffer_pos += bytes_desired;
  765. return bytes_desired;
  766. }
  767. size_t
  768. s3_buffer_size_func(void *stream)
  769. {
  770. CurlBuffer *data = stream;
  771. return data->buffer_len;
  772. }
  773. GByteArray*
  774. s3_buffer_md5_func(void *stream)
  775. {
  776. CurlBuffer *data = stream;
  777. GByteArray req_body_gba = {(guint8 *)data->buffer, data->buffer_len};
  778. return s3_compute_md5_hash(&req_body_gba);
  779. }
  780. void
  781. s3_buffer_reset_func(void *stream)
  782. {
  783. CurlBuffer *data = stream;
  784. data->buffer_pos = 0;
  785. }
  786. /* a CURLOPT_WRITEFUNCTION to write data to a buffer. */
  787. size_t
  788. s3_buffer_write_func(void *ptr, size_t size, size_t nmemb, void *stream)
  789. {
  790. CurlBuffer * data = stream;
  791. guint new_bytes = (guint) size * nmemb;
  792. guint bytes_needed = data->buffer_pos + new_bytes;
  793. /* error out if the new size is greater than the maximum allowed */
  794. if (data->max_buffer_size && bytes_needed > data->max_buffer_size)
  795. return 0;
  796. /* reallocate if necessary. We use exponential sizing to make this
  797. * happen less often. */
  798. if (bytes_needed > data->buffer_len) {
  799. guint new_size = MAX(bytes_needed, data->buffer_len * 2);
  800. if (data->max_buffer_size) {
  801. new_size = MIN(new_size, data->max_buffer_size);
  802. }
  803. data->buffer = g_realloc(data->buffer, new_size);
  804. data->buffer_len = new_size;
  805. }
  806. if (!data->buffer)
  807. return 0; /* returning zero signals an error to libcurl */
  808. /* actually copy the data to the buffer */
  809. memcpy(data->buffer + data->buffer_pos, ptr, new_bytes);
  810. data->buffer_pos += new_bytes;
  811. /* signal success to curl */
  812. return new_bytes;
  813. }
  814. /* a CURLOPT_READFUNCTION that writes nothing. */
  815. size_t
  816. s3_empty_read_func(G_GNUC_UNUSED void *ptr, G_GNUC_UNUSED size_t size, G_GNUC_UNUSED size_t nmemb, G_GNUC_UNUSED void * stream)
  817. {
  818. return 0;
  819. }
  820. size_t
  821. s3_empty_size_func(G_GNUC_UNUSED void *stream)
  822. {
  823. return 0;
  824. }
  825. GByteArray*
  826. s3_empty_md5_func(G_GNUC_UNUSED void *stream)
  827. {
  828. static const GByteArray empty = {(guint8 *) "", 0};
  829. return s3_compute_md5_hash(&empty);
  830. }
  831. /* a CURLOPT_WRITEFUNCTION to write data that just counts data.
  832. * s3_write_data should be NULL or a pointer to an gint64.
  833. */
  834. size_t
  835. s3_counter_write_func(G_GNUC_UNUSED void *ptr, size_t size, size_t nmemb, void *stream)
  836. {
  837. gint64 *count = (gint64*) stream, inc = nmemb*size;
  838. if (count) *count += inc;
  839. return inc;
  840. }
  841. void
  842. s3_counter_reset_func(void *stream)
  843. {
  844. gint64 *count = (gint64*) stream;
  845. if (count) *count = 0;
  846. }
  847. #ifdef _WIN32
  848. /* a CURLOPT_READFUNCTION to read data from a file. */
  849. size_t
  850. s3_file_read_func(void *ptr, size_t size, size_t nmemb, void * stream)
  851. {
  852. HANDLE *hFile = (HANDLE *) stream;
  853. DWORD bytes_read;
  854. ReadFile(hFile, ptr, (DWORD) size*nmemb, &bytes_read, NULL);
  855. return bytes_read;
  856. }
  857. size_t
  858. s3_file_size_func(void *stream)
  859. {
  860. HANDLE *hFile = (HANDLE *) stream;
  861. DWORD size = GetFileSize(hFile, NULL);
  862. if (INVALID_FILE_SIZE == size) {
  863. return -1;
  864. } else {
  865. return size;
  866. }
  867. }
  868. GByteArray*
  869. s3_file_md5_func(void *stream)
  870. {
  871. #define S3_MD5_BUF_SIZE (10*1024)
  872. HANDLE *hFile = (HANDLE *) stream;
  873. guint8 buf[S3_MD5_BUF_SIZE];
  874. DWORD bytes_read;
  875. MD5_CTX md5_ctx;
  876. GByteArray *ret = NULL;
  877. g_assert(INVALID_SET_FILE_POINTER != SetFilePointer(hFile, 0, NULL, FILE_BEGIN));
  878. ret = g_byte_array_sized_new(S3_MD5_HASH_BYTE_LEN);
  879. g_byte_array_set_size(ret, S3_MD5_HASH_BYTE_LEN);
  880. MD5_Init(&md5_ctx);
  881. while (ReadFile(hFile, buf, S3_MD5_BUF_SIZE, &bytes_read, NULL)) {
  882. MD5_Update(&md5_ctx, buf, bytes_read);
  883. }
  884. MD5_Final(ret->data, &md5_ctx);
  885. g_assert(INVALID_SET_FILE_POINTER != SetFilePointer(hFile, 0, NULL, FILE_BEGIN));
  886. return ret;
  887. #undef S3_MD5_BUF_SIZE
  888. }
  889. GByteArray*
  890. s3_file_reset_func(void *stream)
  891. {
  892. g_assert(INVALID_SET_FILE_POINTER != SetFilePointer(hFile, 0, NULL, FILE_BEGIN));
  893. }
  894. /* a CURLOPT_WRITEFUNCTION to write data to a file. */
  895. size_t
  896. s3_file_write_func(void *ptr, size_t size, size_t nmemb, void *stream)
  897. {
  898. HANDLE *hFile = (HANDLE *) stream;
  899. DWORD bytes_written;
  900. WriteFile(hFile, ptr, (DWORD) size*nmemb, &bytes_written, NULL);
  901. return bytes_written;
  902. }
  903. #endif
  904. static int
  905. curl_debug_message(CURL *curl G_GNUC_UNUSED,
  906. curl_infotype type,
  907. char *s,
  908. size_t len,
  909. void *unused G_GNUC_UNUSED)
  910. {
  911. char *lineprefix;
  912. char *message;
  913. char **lines, **line;
  914. switch (type) {
  915. case CURLINFO_TEXT:
  916. lineprefix="";
  917. break;
  918. case CURLINFO_HEADER_IN:
  919. lineprefix="Hdr In: ";
  920. break;
  921. case CURLINFO_HEADER_OUT:
  922. lineprefix="Hdr Out: ";
  923. break;
  924. default:
  925. /* ignore data in/out -- nobody wants to see that in the
  926. * debug logs! */
  927. return 0;
  928. }
  929. /* split the input into lines */
  930. message = g_strndup(s, (gsize) len);
  931. lines = g_strsplit(message, "\n", -1);
  932. g_free(message);
  933. for (line = lines; *line; line++) {
  934. if (**line == '\0') continue; /* skip blank lines */
  935. g_debug("%s%s", lineprefix, *line);
  936. }
  937. g_strfreev(lines);
  938. return 0;
  939. }
  940. static s3_result_t
  941. perform_request(S3Handle *hdl,
  942. const char *verb,
  943. const char *bucket,
  944. const char *key,
  945. const char *subresource,
  946. const char *query,
  947. s3_read_func read_func,
  948. s3_reset_func read_reset_func,
  949. s3_size_func size_func,
  950. s3_md5_func md5_func,
  951. gpointer read_data,
  952. s3_write_func write_func,
  953. s3_reset_func write_reset_func,
  954. gpointer write_data,
  955. s3_progress_func progress_func,
  956. gpointer progress_data,
  957. const result_handling_t *result_handling)
  958. {
  959. char *url = NULL;
  960. s3_result_t result = S3_RESULT_FAIL; /* assume the worst.. */
  961. CURLcode curl_code = CURLE_OK;
  962. char curl_error_buffer[CURL_ERROR_SIZE] = "";
  963. struct curl_slist *headers = NULL;
  964. /* Set S3Internal Data */
  965. S3InternalData int_writedata = {{NULL, 0, 0, MAX_ERROR_RESPONSE_LEN}, NULL, NULL, NULL, FALSE, FALSE, NULL, hdl};
  966. gboolean should_retry;
  967. guint retries = 0;
  968. gulong backoff = EXPONENTIAL_BACKOFF_START_USEC;
  969. /* corresponds to PUT, HEAD, GET, and POST */
  970. int curlopt_upload = 0, curlopt_nobody = 0, curlopt_httpget = 0, curlopt_post = 0;
  971. /* do we want to examine the headers */
  972. const char *curlopt_customrequest = NULL;
  973. /* for MD5 calculation */
  974. GByteArray *md5_hash = NULL;
  975. gchar *md5_hash_hex = NULL, *md5_hash_b64 = NULL;
  976. size_t request_body_size = 0;
  977. g_assert(hdl != NULL && hdl->curl != NULL);
  978. s3_reset(hdl);
  979. url = build_url(hdl->curl, hdl->host, hdl->service_path, bucket, key,
  980. subresource, query, hdl->use_subdomain, hdl->use_ssl);
  981. if (!url) goto cleanup;
  982. /* libcurl may behave strangely if these are not set correctly */
  983. if (!strncmp(verb, "PUT", 4)) {
  984. curlopt_upload = 1;
  985. } else if (!strncmp(verb, "GET", 4)) {
  986. curlopt_httpget = 1;
  987. } else if (!strncmp(verb, "POST", 5)) {
  988. curlopt_post = 1;
  989. } else if (!strncmp(verb, "HEAD", 5)) {
  990. curlopt_nobody = 1;
  991. } else {
  992. curlopt_customrequest = verb;
  993. }
  994. if (size_func) {
  995. request_body_size = size_func(read_data);
  996. }
  997. if (md5_func) {
  998. md5_hash = md5_func(read_data);
  999. if (md5_hash) {
  1000. md5_hash_b64 = s3_base64_encode(md5_hash);
  1001. md5_hash_hex = s3_hex_encode(md5_hash);
  1002. g_byte_array_free(md5_hash, TRUE);
  1003. }
  1004. }
  1005. if (!read_func) {
  1006. /* Curl will use fread() otherwise */
  1007. read_func = s3_empty_read_func;
  1008. }
  1009. if (write_func) {
  1010. int_writedata.write_func = write_func;
  1011. int_writedata.reset_func = write_reset_func;
  1012. int_writedata.write_data = write_data;
  1013. } else {
  1014. /* Curl will use fwrite() otherwise */
  1015. int_writedata.write_func = s3_counter_write_func;
  1016. int_writedata.reset_func = s3_counter_reset_func;
  1017. int_writedata.write_data = NULL;
  1018. }
  1019. while (1) {
  1020. /* reset things */
  1021. if (headers) {
  1022. curl_slist_free_all(headers);
  1023. }
  1024. curl_error_buffer[0] = '\0';
  1025. if (read_reset_func) {
  1026. read_reset_func(read_data);
  1027. }
  1028. /* calls write_reset_func */
  1029. s3_internal_reset_func(&int_writedata);
  1030. /* set up the request */
  1031. headers = authenticate_request(hdl, verb, bucket, key, subresource,
  1032. md5_hash_b64);
  1033. if (hdl->use_ssl && hdl->ca_info) {
  1034. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_CAINFO, hdl->ca_info)))
  1035. goto curl_error;
  1036. }
  1037. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_VERBOSE, hdl->verbose)))
  1038. goto curl_error;
  1039. if (hdl->verbose) {
  1040. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_DEBUGFUNCTION,
  1041. curl_debug_message)))
  1042. goto curl_error;
  1043. }
  1044. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_ERRORBUFFER,
  1045. curl_error_buffer)))
  1046. goto curl_error;
  1047. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_NOPROGRESS, 1)))
  1048. goto curl_error;
  1049. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_FOLLOWLOCATION, 1)))
  1050. goto curl_error;
  1051. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_URL, url)))
  1052. goto curl_error;
  1053. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_HTTPHEADER,
  1054. headers)))
  1055. goto curl_error;
  1056. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_WRITEFUNCTION, s3_internal_write_func)))
  1057. goto curl_error;
  1058. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_WRITEDATA, &int_writedata)))
  1059. goto curl_error;
  1060. /* Note: we always have to set this apparently, for consistent "end of header" detection */
  1061. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_HEADERFUNCTION, s3_internal_header_func)))
  1062. goto curl_error;
  1063. /* Note: if set, CURLOPT_HEADERDATA seems to also be used for CURLOPT_WRITEDATA ? */
  1064. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_HEADERDATA, &int_writedata)))
  1065. goto curl_error;
  1066. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_PROGRESSFUNCTION, progress_func)))
  1067. goto curl_error;
  1068. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_PROGRESSDATA, progress_data)))
  1069. goto curl_error;
  1070. /* CURLOPT_INFILESIZE_LARGE added in 7.11.0 */
  1071. #if LIBCURL_VERSION_NUM >= 0x070b00
  1072. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_INFILESIZE_LARGE, (curl_off_t)request_body_size)))
  1073. goto curl_error;
  1074. #else
  1075. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_INFILESIZE, (long)request_body_size)))
  1076. goto curl_error;
  1077. #endif
  1078. /* CURLOPT_MAX_{RECV,SEND}_SPEED_LARGE added in 7.15.5 */
  1079. #if LIBCURL_VERSION_NUM >= 0x070f05
  1080. if (s3_curl_throttling_compat()) {
  1081. if (hdl->max_send_speed)
  1082. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_MAX_SEND_SPEED_LARGE, (curl_off_t)hdl->max_send_speed)))
  1083. goto curl_error;
  1084. if (hdl->max_recv_speed)
  1085. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_MAX_RECV_SPEED_LARGE, (curl_off_t)hdl->max_recv_speed)))
  1086. goto curl_error;
  1087. }
  1088. #endif
  1089. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_HTTPGET, curlopt_httpget)))
  1090. goto curl_error;
  1091. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_UPLOAD, curlopt_upload)))
  1092. goto curl_error;
  1093. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_POST, curlopt_post)))
  1094. goto curl_error;
  1095. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_NOBODY, curlopt_nobody)))
  1096. goto curl_error;
  1097. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_CUSTOMREQUEST,
  1098. curlopt_customrequest)))
  1099. goto curl_error;
  1100. if (curlopt_upload) {
  1101. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_READFUNCTION, read_func)))
  1102. goto curl_error;
  1103. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_READDATA, read_data)))
  1104. goto curl_error;
  1105. } else {
  1106. /* Clear request_body options. */
  1107. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_READFUNCTION,
  1108. NULL)))
  1109. goto curl_error;
  1110. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_READDATA,
  1111. NULL)))
  1112. goto curl_error;
  1113. }
  1114. /* Perform the request */
  1115. curl_code = curl_easy_perform(hdl->curl);
  1116. /* interpret the response into hdl->last* */
  1117. curl_error: /* (label for short-circuiting the curl_easy_perform call) */
  1118. should_retry = interpret_response(hdl, curl_code, curl_error_buffer,
  1119. int_writedata.resp_buf.buffer, int_writedata.resp_buf.buffer_pos, int_writedata.etag, md5_hash_hex);
  1120. /* and, unless we know we need to retry, see what we're to do now */
  1121. if (!should_retry) {
  1122. result = lookup_result(result_handling, hdl->last_response_code,
  1123. hdl->last_s3_error_code, hdl->last_curl_code);
  1124. /* break out of the while(1) unless we're retrying */
  1125. if (result != S3_RESULT_RETRY)
  1126. break;
  1127. }
  1128. if (retries >= EXPONENTIAL_BACKOFF_MAX_RETRIES) {
  1129. /* we're out of retries, so annotate hdl->last_message appropriately and bail
  1130. * out. */
  1131. char *m = g_strdup_printf("Too many retries; last message was '%s'", hdl->last_message);
  1132. if (hdl->last_message) g_free(hdl->last_message);
  1133. hdl->last_message = m;
  1134. result = S3_RESULT_FAIL;
  1135. break;
  1136. }
  1137. g_usleep(backoff);
  1138. retries++;
  1139. backoff *= EXPONENTIAL_BACKOFF_BASE;
  1140. }
  1141. if (result != S3_RESULT_OK) {
  1142. g_debug(_("%s %s failed with %d/%s"), verb, url,
  1143. hdl->last_response_code,
  1144. s3_error_name_from_code(hdl->last_s3_error_code));
  1145. }
  1146. cleanup:
  1147. g_free(url);
  1148. if (headers) curl_slist_free_all(headers);
  1149. g_free(md5_hash_b64);
  1150. g_free(md5_hash_hex);
  1151. /* we don't deallocate the response body -- we keep it for later */
  1152. hdl->last_response_body = int_writedata.resp_buf.buffer;
  1153. hdl->last_response_body_size = int_writedata.resp_buf.buffer_pos;
  1154. hdl->last_num_retries = retries;
  1155. return result;
  1156. }
  1157. static size_t
  1158. s3_internal_write_func(void *ptr, size_t size, size_t nmemb, void * stream)
  1159. {
  1160. S3InternalData *data = (S3InternalData *) stream;
  1161. size_t bytes_saved;
  1162. if (!data->headers_done)
  1163. return size*nmemb;
  1164. /* call write on internal buffer (if not full) */
  1165. if (data->int_write_done) {
  1166. bytes_saved = 0;
  1167. } else {
  1168. bytes_saved = s3_buffer_write_func(ptr, size, nmemb, &data->resp_buf);
  1169. if (!bytes_saved) {
  1170. data->int_write_done = TRUE;
  1171. }
  1172. }
  1173. /* call write on user buffer */
  1174. if (data->write_func) {
  1175. return data->write_func(ptr, size, nmemb, data->write_data);
  1176. } else {
  1177. return bytes_saved;
  1178. }
  1179. }
  1180. static void
  1181. s3_internal_reset_func(void * stream)
  1182. {
  1183. S3InternalData *data = (S3InternalData *) stream;
  1184. s3_buffer_reset_func(&data->resp_buf);
  1185. data->headers_done = FALSE;
  1186. data->int_write_done = FALSE;
  1187. data->etag = NULL;
  1188. if (data->reset_func) {
  1189. data->reset_func(data->write_data);
  1190. }
  1191. }
  1192. static size_t
  1193. s3_internal_header_func(void *ptr, size_t size, size_t nmemb, void * stream)
  1194. {
  1195. static const char *final_header = "\r\n";
  1196. time_t remote_time_in_sec,local_time;
  1197. char *header;
  1198. regmatch_t pmatch[2];
  1199. S3InternalData *data = (S3InternalData *) stream;
  1200. header = g_strndup((gchar *) ptr, (gsize) size*nmemb);
  1201. if (!s3_regexec_wrap(&etag_regex, header, 2, pmatch, 0))
  1202. data->etag = find_regex_substring(header, pmatch[1]);
  1203. if (!strcmp(final_header, header))
  1204. data->headers_done = TRUE;
  1205. /* If date header is found */
  1206. if (!s3_regexec_wrap(&date_sync_regex, header, 2, pmatch, 0)){
  1207. char *date = find_regex_substring(header, pmatch[1]);
  1208. /* Remote time is always in GMT: RFC 2616 */
  1209. /* both curl_getdate and time operate in UTC, so no timezone math is necessary */
  1210. if ( (remote_time_in_sec = curl_getdate(date, NULL)) < 0 ){
  1211. g_debug("Error: Conversion of remote time to seconds failed.");
  1212. data->hdl->time_offset_with_s3 = 0;
  1213. }else{
  1214. local_time = time(NULL);
  1215. /* Offset time */
  1216. data->hdl->time_offset_with_s3 = remote_time_in_sec - local_time;
  1217. if (data->hdl->verbose)
  1218. g_debug("Time Offset (remote - local) :%ld",(long)data->hdl->time_offset_with_s3);
  1219. }
  1220. g_free(date);
  1221. }
  1222. g_free(header);
  1223. return size*nmemb;
  1224. }
  1225. static gboolean
  1226. compile_regexes(void)
  1227. {
  1228. #ifdef HAVE_REGEX_H
  1229. /* using POSIX regular expressions */
  1230. struct {const char * str; int flags; regex_t *regex;} regexes[] = {
  1231. {"<Code>[[:space:]]*([^<]*)[[:space:]]*</Code>", REG_EXTENDED | REG_ICASE, &error_name_regex},
  1232. {"^ETag:[[:space:]]*\"([^\"]+)\"[[:space:]]*$", REG_EXTENDED | REG_ICASE | REG_NEWLINE, &etag_regex},
  1233. {"<Message>[[:space:]]*([^<]*)[[:space:]]*</Message>", REG_EXTENDED | REG_ICASE, &message_regex},
  1234. {"^[a-z0-9](-*[a-z0-9]){2,62}$", REG_EXTENDED | REG_NOSUB, &subdomain_regex},
  1235. {"(/>)|(>([^<]*)</LocationConstraint>)", REG_EXTENDED | REG_ICASE, &location_con_regex},
  1236. {"^Date:(.*)\r",REG_EXTENDED | REG_ICASE | REG_NEWLINE, &date_sync_regex},
  1237. {NULL, 0, NULL}
  1238. };
  1239. char regmessage[1024];
  1240. int i;
  1241. int reg_result;
  1242. for (i = 0; regexes[i].str; i++) {
  1243. reg_result = regcomp(regexes[i].regex, regexes[i].str, regexes[i].flags);
  1244. if (reg_result != 0) {
  1245. regerror(reg_result, regexes[i].regex, regmessage, sizeof(regmessage));
  1246. g_error(_("Regex error: %s"), regmessage);
  1247. return FALSE;
  1248. }
  1249. }
  1250. #else /* ! HAVE_REGEX_H */
  1251. /* using PCRE via GLib */
  1252. struct {const char * str; int flags; regex_t *regex;} regexes[] = {
  1253. {"<Code>\\s*([^<]*)\\s*</Code>",
  1254. G_REGEX_OPTIMIZE | G_REGEX_CASELESS,
  1255. &error_name_regex},
  1256. {"^ETag:\\s*\"([^\"]+)\"\\s*$",
  1257. G_REGEX_OPTIMIZE | G_REGEX_CASELESS,
  1258. &etag_regex},
  1259. {"<Message>\\s*([^<]*)\\s*</Message>",
  1260. G_REGEX_OPTIMIZE | G_REGEX_CASELESS,
  1261. &message_regex},
  1262. {"^[a-z0-9]((-*[a-z0-9])|(\\.[a-z0-9])){2,62}$",
  1263. G_REGEX_OPTIMIZE | G_REGEX_NO_AUTO_CAPTURE,
  1264. &subdomain_regex},
  1265. {"(/>)|(>([^<]*)</LocationConstraint>)",
  1266. G_REGEX_CASELESS,
  1267. &location_con_regex},
  1268. {"^Date:(.*)\\r",
  1269. G_REGEX_OPTIMIZE | G_REGEX_CASELESS,
  1270. &date_sync_regex},
  1271. {NULL, 0, NULL}
  1272. };
  1273. int i;
  1274. GError *err = NULL;
  1275. for (i = 0; regexes[i].str; i++) {
  1276. *(regexes[i].regex) = g_regex_new(regexes[i].str, regexes[i].flags, 0, &err);
  1277. if (err) {
  1278. g_error(_("Regex error: %s"), err->message);
  1279. g_error_free(err);
  1280. return FALSE;
  1281. }
  1282. }
  1283. #endif
  1284. return TRUE;
  1285. }
  1286. /*
  1287. * Public function implementations
  1288. */
  1289. gboolean s3_init(void)
  1290. {
  1291. static GStaticMutex mutex = G_STATIC_MUTEX_INIT;
  1292. static gboolean init = FALSE, ret;
  1293. /* n.b. curl_global_init is called in common-src/glib-util.c:glib_init() */
  1294. g_static_mutex_lock (&mutex);
  1295. if (!init) {
  1296. ret = compile_regexes();
  1297. init = TRUE;
  1298. }
  1299. g_static_mutex_unlock(&mutex);
  1300. return ret;
  1301. }
  1302. gboolean
  1303. s3_curl_location_compat(void)
  1304. {
  1305. curl_version_info_data *info;
  1306. info = curl_version_info(CURLVERSION_NOW);
  1307. return info->version_num > 0x070a02;
  1308. }
  1309. gboolean
  1310. s3_bucket_location_compat(const char *bucket)
  1311. {
  1312. return !s3_regexec_wrap(&subdomain_regex, bucket, 0, NULL, 0);
  1313. }
  1314. S3Handle *
  1315. s3_open(const char *access_key,
  1316. const char *secret_key,
  1317. const char *host,
  1318. const char *service_path,
  1319. const gboolean use_subdomain,
  1320. const char *user_token,
  1321. const char *bucket_location,
  1322. const char *storage_class,
  1323. const char *ca_info,
  1324. const char *server_side_encryption
  1325. )
  1326. {
  1327. S3Handle *hdl;
  1328. hdl = g_new0(S3Handle, 1);
  1329. if (!hdl) goto error;
  1330. hdl->verbose = FALSE;
  1331. hdl->use_ssl = s3_curl_supports_ssl();
  1332. g_assert(access_key);
  1333. hdl->access_key = g_strdup(access_key);
  1334. g_assert(secret_key);
  1335. hdl->secret_key = g_strdup(secret_key);
  1336. /* NULL is okay */
  1337. hdl->user_token = g_strdup(user_token);
  1338. /* NULL is okay */
  1339. hdl->bucket_location = g_strdup(bucket_location);
  1340. /* NULL is ok */
  1341. hdl->storage_class = g_strdup(storage_class);
  1342. /* NULL is ok */
  1343. hdl->server_side_encryption = g_strdup(server_side_encryption);
  1344. /* NULL is okay */
  1345. hdl->ca_info = g_strdup(ca_info);
  1346. if (!is_non_empty_string(host))
  1347. host = "s3.amazonaws.com";
  1348. hdl->host = g_strdup(host);
  1349. hdl->use_subdomain = use_subdomain ||
  1350. (strcmp(host, "s3.amazonaws.com") == 0 &&
  1351. is_non_empty_string(hdl->bucket_location));
  1352. if (service_path) {
  1353. if (strlen(service_path) == 0 ||
  1354. (strlen(service_path) == 1 && service_path[0] == '/')) {
  1355. hdl->service_path = NULL;
  1356. } else if (service_path[0] != '/') {
  1357. hdl->service_path = g_strdup_printf("/%s", service_path);
  1358. } else {
  1359. hdl->service_path = g_strdup(service_path);
  1360. }
  1361. if (hdl->service_path) {
  1362. /* remove trailling / */
  1363. size_t len = strlen(hdl->service_path) - 1;
  1364. if (hdl->service_path[len] == '/')
  1365. hdl->service_path[len] = '\0';
  1366. }
  1367. } else {
  1368. hdl->service_path = NULL;
  1369. }
  1370. hdl->curl = curl_easy_init();
  1371. if (!hdl->curl) goto error;
  1372. return hdl;
  1373. error:
  1374. s3_free(hdl);
  1375. return NULL;
  1376. }
  1377. void
  1378. s3_free(S3Handle *hdl)
  1379. {
  1380. s3_reset(hdl);
  1381. if (hdl) {
  1382. g_free(hdl

Large files files are truncated, but you can click here to view the full file