PageRenderTime 69ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 0ms

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

#
C | 2130 lines | 1531 code | 286 blank | 313 comment | 351 complexity | f6bc6152d69a85c99481e26c17306414 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%s>\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. char *swift_account_id;
  122. char *swift_access_key;
  123. /* attributes for new objects */
  124. char *bucket_location;
  125. char *storage_class;
  126. char *server_side_encryption;
  127. char *host;
  128. char *service_path;
  129. gboolean use_subdomain;
  130. gboolean openstack_swift_api;
  131. char *ca_info;
  132. char *x_auth_token;
  133. char *x_storage_url;
  134. CURL *curl;
  135. gboolean verbose;
  136. gboolean use_ssl;
  137. guint64 max_send_speed;
  138. guint64 max_recv_speed;
  139. /* information from the last request */
  140. char *last_message;
  141. guint last_response_code;
  142. s3_error_code_t last_s3_error_code;
  143. CURLcode last_curl_code;
  144. guint last_num_retries;
  145. void *last_response_body;
  146. guint last_response_body_size;
  147. /* offset with s3 */
  148. time_t time_offset_with_s3;
  149. };
  150. typedef struct {
  151. CurlBuffer resp_buf;
  152. s3_write_func write_func;
  153. s3_reset_func reset_func;
  154. gpointer write_data;
  155. gboolean headers_done;
  156. gboolean int_write_done;
  157. char *etag;
  158. /* Points to current handle: Added to get hold of s3 offset */
  159. struct S3Handle *hdl;
  160. } S3InternalData;
  161. /* Callback function to examine headers one-at-a-time
  162. *
  163. * @note this is the same as CURLOPT_HEADERFUNCTION
  164. *
  165. * @param data: The pointer to read data from
  166. * @param size: The size of each "element" of the data buffer in bytes
  167. * @param nmemb: The number of elements in the data buffer.
  168. * So, the buffer's size is size*nmemb bytes.
  169. * @param stream: the header_data (an opaque pointer)
  170. *
  171. * @return The number of bytes written to the buffer or
  172. * CURL_WRITEFUNC_PAUSE to pause.
  173. * If it's the number of bytes written, it should match the buffer size
  174. */
  175. typedef size_t (*s3_header_func)(void *data, size_t size, size_t nmemb, void *stream);
  176. /*
  177. * S3 errors */
  178. /* (see preprocessor magic in s3.h) */
  179. static char * s3_error_code_names[] = {
  180. #define S3_ERROR(NAME) #NAME
  181. S3_ERROR_LIST
  182. #undef S3_ERROR
  183. };
  184. /* Convert an s3 error name to an error code. This function
  185. * matches strings case-insensitively, and is appropriate for use
  186. * on data from the network.
  187. *
  188. * @param s3_error_code: the error name
  189. * @returns: the error code (see constants in s3.h)
  190. */
  191. static s3_error_code_t
  192. s3_error_code_from_name(char *s3_error_name);
  193. /* Convert an s3 error code to a string
  194. *
  195. * @param s3_error_code: the error code to convert
  196. * @returns: statically allocated string
  197. */
  198. static const char *
  199. s3_error_name_from_code(s3_error_code_t s3_error_code);
  200. /*
  201. * result handling */
  202. /* result handling is specified by a static array of result_handling structs,
  203. * which match based on response_code (from HTTP) and S3 error code. The result
  204. * given for the first match is used. 0 acts as a wildcard for both response_code
  205. * and s3_error_code. The list is terminated with a struct containing 0 for both
  206. * response_code and s3_error_code; the result for that struct is the default
  207. * result.
  208. *
  209. * See RESULT_HANDLING_ALWAYS_RETRY for an example.
  210. */
  211. typedef enum {
  212. S3_RESULT_RETRY = -1,
  213. S3_RESULT_FAIL = 0,
  214. S3_RESULT_OK = 1
  215. } s3_result_t;
  216. typedef struct result_handling {
  217. guint response_code;
  218. s3_error_code_t s3_error_code;
  219. CURLcode curl_code;
  220. s3_result_t result;
  221. } result_handling_t;
  222. /* Lookup a result in C{result_handling}.
  223. *
  224. * @param result_handling: array of handling specifications
  225. * @param response_code: response code from operation
  226. * @param s3_error_code: s3 error code from operation, if any
  227. * @param curl_code: the CURL error, if any
  228. * @returns: the matching result
  229. */
  230. static s3_result_t
  231. lookup_result(const result_handling_t *result_handling,
  232. guint response_code,
  233. s3_error_code_t s3_error_code,
  234. CURLcode curl_code);
  235. /*
  236. * Precompiled regular expressions */
  237. static regex_t etag_regex, error_name_regex, message_regex, subdomain_regex,
  238. location_con_regex, date_sync_regex, x_auth_token_regex,
  239. x_storage_url_regex;
  240. /*
  241. * Utility functions
  242. */
  243. /* Check if a string is non-empty
  244. *
  245. * @param str: string to check
  246. * @returns: true iff str is non-NULL and not "\0"
  247. */
  248. static gboolean is_non_empty_string(const char *str);
  249. /* Construct the URL for an Amazon S3 REST request.
  250. *
  251. * A new string is allocated and returned; it is the responsiblity of the caller.
  252. *
  253. * @param hdl: the S3Handle object
  254. * @param service_path: A path to add in the URL, or NULL for none.
  255. * @param bucket: the bucket being accessed, or NULL for none
  256. * @param key: the key being accessed, or NULL for none
  257. * @param subresource: the sub-resource being accessed (e.g. "acl"), or NULL for none
  258. * @param query: the query being accessed (e.g. "acl"), or NULL for none
  259. *
  260. * !use_subdomain: http://host/service_path/bucket/key
  261. * use_subdomain : http://bucket.host/service_path/key
  262. *
  263. */
  264. static char *
  265. build_url(
  266. S3Handle *hdl,
  267. const char *bucket,
  268. const char *key,
  269. const char *subresource,
  270. const char *query);
  271. /* Create proper authorization headers for an Amazon S3 REST
  272. * request to C{headers}.
  273. *
  274. * @note: C{X-Amz} headers (in C{headers}) must
  275. * - be in lower-case
  276. * - be in alphabetical order
  277. * - have no spaces around the colon
  278. * (don't yell at me -- see the Amazon Developer Guide)
  279. *
  280. * @param hdl: the S3Handle object
  281. * @param verb: capitalized verb for this request ('PUT', 'GET', etc.)
  282. * @param bucket: the bucket being accessed, or NULL for none
  283. * @param key: the key being accessed, or NULL for none
  284. * @param subresource: the sub-resource being accessed (e.g. "acl"), or NULL for none
  285. * @param md5_hash: the MD5 hash of the request body, or NULL for none
  286. */
  287. static struct curl_slist *
  288. authenticate_request(S3Handle *hdl,
  289. const char *verb,
  290. const char *bucket,
  291. const char *key,
  292. const char *subresource,
  293. const char *md5_hash);
  294. /* Interpret the response to an S3 operation, assuming CURL completed its request
  295. * successfully. This function fills in the relevant C{hdl->last*} members.
  296. *
  297. * @param hdl: The S3Handle object
  298. * @param body: the response body
  299. * @param body_len: the length of the response body
  300. * @param etag: The response's ETag header
  301. * @param content_md5: The hex-encoded MD5 hash of the request body,
  302. * which will be checked against the response's ETag header.
  303. * If NULL, the header is not checked.
  304. * If non-NULL, then the body should have the response headers at its beginnning.
  305. * @returns: TRUE if the response should be retried (e.g., network error)
  306. */
  307. static gboolean
  308. interpret_response(S3Handle *hdl,
  309. CURLcode curl_code,
  310. char *curl_error_buffer,
  311. gchar *body,
  312. guint body_len,
  313. const char *etag,
  314. const char *content_md5);
  315. /* Perform an S3 operation. This function handles all of the details
  316. * of retryig requests and so on.
  317. *
  318. * The concepts of bucket and keys are defined by the Amazon S3 API.
  319. * See: "Components of Amazon S3" - API Version 2006-03-01 pg. 8
  320. *
  321. * Individual sub-resources are defined in several places. In the REST API,
  322. * they they are represented by a "flag" in the "query string".
  323. * See: "Constructing the CanonicalizedResource Element" - API Version 2006-03-01 pg. 60
  324. *
  325. * @param hdl: the S3Handle object
  326. * @param verb: the HTTP request method
  327. * @param bucket: the bucket to access, or NULL for none
  328. * @param key: the key to access, or NULL for none
  329. * @param subresource: the "sub-resource" to request (e.g. "acl") or NULL for none
  330. * @param query: the query string to send (not including th initial '?'),
  331. * or NULL for none
  332. * @param read_func: the callback for reading data
  333. * Will use s3_empty_read_func if NULL is passed in.
  334. * @param read_reset_func: the callback for to reset reading data
  335. * @param size_func: the callback to get the number of bytes to upload
  336. * @param md5_func: the callback to get the MD5 hash of the data to upload
  337. * @param read_data: pointer to pass to the above functions
  338. * @param write_func: the callback for writing data.
  339. * Will use s3_counter_write_func if NULL is passed in.
  340. * @param write_reset_func: the callback for to reset writing data
  341. * @param write_data: pointer to pass to C{write_func}
  342. * @param progress_func: the callback for progress information
  343. * @param progress_data: pointer to pass to C{progress_func}
  344. * @param result_handling: instructions for handling the results; see above.
  345. * @returns: the result specified by result_handling; details of the response
  346. * are then available in C{hdl->last*}
  347. */
  348. static s3_result_t
  349. perform_request(S3Handle *hdl,
  350. const char *verb,
  351. const char *bucket,
  352. const char *key,
  353. const char *subresource,
  354. const char *query,
  355. s3_read_func read_func,
  356. s3_reset_func read_reset_func,
  357. s3_size_func size_func,
  358. s3_md5_func md5_func,
  359. gpointer read_data,
  360. s3_write_func write_func,
  361. s3_reset_func write_reset_func,
  362. gpointer write_data,
  363. s3_progress_func progress_func,
  364. gpointer progress_data,
  365. const result_handling_t *result_handling);
  366. /*
  367. * a CURLOPT_WRITEFUNCTION to save part of the response in memory and
  368. * call an external function if one was provided.
  369. */
  370. static size_t
  371. s3_internal_write_func(void *ptr, size_t size, size_t nmemb, void * stream);
  372. /*
  373. * a function to reset to our internal buffer
  374. */
  375. static void
  376. s3_internal_reset_func(void * stream);
  377. /*
  378. * a CURLOPT_HEADERFUNCTION to save the ETag header only.
  379. */
  380. static size_t
  381. s3_internal_header_func(void *ptr, size_t size, size_t nmemb, void * stream);
  382. static gboolean
  383. compile_regexes(void);
  384. /*
  385. * Static function implementations
  386. */
  387. static s3_error_code_t
  388. s3_error_code_from_name(char *s3_error_name)
  389. {
  390. int i;
  391. if (!s3_error_name) return S3_ERROR_Unknown;
  392. /* do a brute-force search through the list, since it's not sorted */
  393. for (i = 0; i < S3_ERROR_END; i++) {
  394. if (g_ascii_strcasecmp(s3_error_name, s3_error_code_names[i]) == 0)
  395. return i;
  396. }
  397. return S3_ERROR_Unknown;
  398. }
  399. static const char *
  400. s3_error_name_from_code(s3_error_code_t s3_error_code)
  401. {
  402. if (s3_error_code >= S3_ERROR_END)
  403. s3_error_code = S3_ERROR_Unknown;
  404. return s3_error_code_names[s3_error_code];
  405. }
  406. gboolean
  407. s3_curl_supports_ssl(void)
  408. {
  409. static int supported = -1;
  410. if (supported == -1) {
  411. #if defined(CURL_VERSION_SSL)
  412. curl_version_info_data *info = curl_version_info(CURLVERSION_NOW);
  413. if (info->features & CURL_VERSION_SSL)
  414. supported = 1;
  415. else
  416. supported = 0;
  417. #else
  418. supported = 0;
  419. #endif
  420. }
  421. return supported;
  422. }
  423. static gboolean
  424. s3_curl_throttling_compat(void)
  425. {
  426. /* CURLOPT_MAX_SEND_SPEED_LARGE added in 7.15.5 */
  427. #if LIBCURL_VERSION_NUM >= 0x070f05
  428. curl_version_info_data *info;
  429. /* check the runtime version too */
  430. info = curl_version_info(CURLVERSION_NOW);
  431. return info->version_num >= 0x070f05;
  432. #else
  433. return FALSE;
  434. #endif
  435. }
  436. static s3_result_t
  437. lookup_result(const result_handling_t *result_handling,
  438. guint response_code,
  439. s3_error_code_t s3_error_code,
  440. CURLcode curl_code)
  441. {
  442. while (result_handling->response_code
  443. || result_handling->s3_error_code
  444. || result_handling->curl_code) {
  445. if ((result_handling->response_code && result_handling->response_code != response_code)
  446. || (result_handling->s3_error_code && result_handling->s3_error_code != s3_error_code)
  447. || (result_handling->curl_code && result_handling->curl_code != curl_code)) {
  448. result_handling++;
  449. continue;
  450. }
  451. return result_handling->result;
  452. }
  453. /* return the result for the terminator, as the default */
  454. return result_handling->result;
  455. }
  456. static gboolean
  457. is_non_empty_string(const char *str)
  458. {
  459. return str && str[0] != '\0';
  460. }
  461. static char *
  462. build_url(
  463. S3Handle *hdl,
  464. const char *bucket,
  465. const char *key,
  466. const char *subresource,
  467. const char *query)
  468. {
  469. GString *url = NULL;
  470. char *esc_bucket = NULL, *esc_key = NULL;
  471. if (hdl->openstack_swift_api && hdl->x_storage_url) {
  472. url = g_string_new(hdl->x_storage_url);
  473. g_string_append(url, "/");
  474. } else {
  475. /* scheme */
  476. url = g_string_new("http");
  477. if (hdl->use_ssl)
  478. g_string_append(url, "s");
  479. g_string_append(url, "://");
  480. /* domain */
  481. if (hdl->use_subdomain && bucket)
  482. g_string_append_printf(url, "%s.%s", bucket, hdl->host);
  483. else
  484. g_string_append_printf(url, "%s", hdl->host);
  485. if (hdl->service_path) {
  486. g_string_append_printf(url, "%s/", hdl->service_path);
  487. } else {
  488. g_string_append(url, "/");
  489. }
  490. }
  491. /* path */
  492. if (!hdl->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(hdl->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(hdl->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. /* calculate the date */
  563. t = time(NULL);
  564. /* sync clock with amazon s3 */
  565. t = t + hdl->time_offset_with_s3;
  566. #ifdef _WIN32
  567. if (!gmtime_s(&tmp, &t)) g_debug("localtime error");
  568. #else
  569. if (!gmtime_r(&t, &tmp)) perror("localtime");
  570. #endif
  571. date = g_strdup_printf("%s, %02d %s %04d %02d:%02d:%02d GMT",
  572. wkday[tmp.tm_wday], tmp.tm_mday, month[tmp.tm_mon], 1900+tmp.tm_year,
  573. tmp.tm_hour, tmp.tm_min, tmp.tm_sec);
  574. if (hdl->openstack_swift_api) {
  575. if (!bucket) {
  576. buf = g_strdup_printf("X-Auth-User: %s", hdl->swift_account_id);
  577. headers = curl_slist_append(headers, buf);
  578. g_free(buf);
  579. buf = g_strdup_printf("X-Auth-Key: %s", hdl->swift_access_key);
  580. headers = curl_slist_append(headers, buf);
  581. g_free(buf);
  582. } else {
  583. buf = g_strdup_printf("X-Auth-Token: %s", hdl->x_auth_token);
  584. headers = curl_slist_append(headers, buf);
  585. g_free(buf);
  586. }
  587. } else {
  588. /* Build the string to sign, per the S3 spec.
  589. * See: "Authenticating REST Requests" - API Version 2006-03-01 pg 58
  590. */
  591. /* verb */
  592. auth_string = g_string_new(verb);
  593. g_string_append(auth_string, "\n");
  594. /* Content-MD5 header */
  595. if (md5_hash)
  596. g_string_append(auth_string, md5_hash);
  597. g_string_append(auth_string, "\n");
  598. /* Content-Type is empty*/
  599. g_string_append(auth_string, "\n");
  600. /* Date */
  601. g_string_append(auth_string, date);
  602. g_string_append(auth_string, "\n");
  603. /* CanonicalizedAmzHeaders, sorted lexicographically */
  604. if (is_non_empty_string(hdl->user_token)) {
  605. g_string_append(auth_string, AMAZON_SECURITY_HEADER);
  606. g_string_append(auth_string, ":");
  607. g_string_append(auth_string, hdl->user_token);
  608. g_string_append(auth_string, ",");
  609. g_string_append(auth_string, STS_PRODUCT_TOKEN);
  610. g_string_append(auth_string, "\n");
  611. }
  612. if (g_str_equal(verb,"PUT") &&
  613. is_non_empty_string(hdl->server_side_encryption)) {
  614. g_string_append(auth_string, AMAZON_SERVER_SIDE_ENCRYPTION_HEADER);
  615. g_string_append(auth_string, ":");
  616. g_string_append(auth_string, hdl->server_side_encryption);
  617. g_string_append(auth_string, "\n");
  618. }
  619. if (is_non_empty_string(hdl->storage_class)) {
  620. g_string_append(auth_string, AMAZON_STORAGE_CLASS_HEADER);
  621. g_string_append(auth_string, ":");
  622. g_string_append(auth_string, hdl->storage_class);
  623. g_string_append(auth_string, "\n");
  624. }
  625. /* CanonicalizedResource */
  626. if (hdl->service_path) {
  627. g_string_append(auth_string, hdl->service_path);
  628. }
  629. g_string_append(auth_string, "/");
  630. if (bucket) {
  631. if (hdl->use_subdomain)
  632. g_string_append(auth_string, bucket);
  633. else {
  634. esc_bucket = curl_escape(bucket, 0);
  635. if (!esc_bucket) goto cleanup;
  636. g_string_append(auth_string, esc_bucket);
  637. }
  638. }
  639. if (bucket && (hdl->use_subdomain || key))
  640. g_string_append(auth_string, "/");
  641. if (key) {
  642. esc_key = curl_escape(key, 0);
  643. if (!esc_key) goto cleanup;
  644. g_string_append(auth_string, esc_key);
  645. }
  646. if (subresource) {
  647. g_string_append(auth_string, "?");
  648. g_string_append(auth_string, subresource);
  649. }
  650. /* run HMAC-SHA1 on the canonicalized string */
  651. md = g_byte_array_sized_new(EVP_MAX_MD_SIZE+1);
  652. HMAC_CTX_init(&ctx);
  653. HMAC_Init_ex(&ctx, hdl->secret_key, (int) strlen(hdl->secret_key),
  654. EVP_sha1(), NULL);
  655. HMAC_Update(&ctx, (unsigned char*) auth_string->str, auth_string->len);
  656. HMAC_Final(&ctx, md->data, &md->len);
  657. HMAC_CTX_cleanup(&ctx);
  658. auth_base64 = s3_base64_encode(md);
  659. /* append the new headers */
  660. if (is_non_empty_string(hdl->user_token)) {
  661. /* Devpay headers are included in hash. */
  662. buf = g_strdup_printf(AMAZON_SECURITY_HEADER ": %s",
  663. hdl->user_token);
  664. headers = curl_slist_append(headers, buf);
  665. g_free(buf);
  666. buf = g_strdup_printf(AMAZON_SECURITY_HEADER ": %s",
  667. STS_PRODUCT_TOKEN);
  668. headers = curl_slist_append(headers, buf);
  669. g_free(buf);
  670. }
  671. if (g_str_equal(verb,"PUT") &&
  672. is_non_empty_string(hdl->server_side_encryption)) {
  673. buf = g_strdup_printf(AMAZON_SERVER_SIDE_ENCRYPTION_HEADER ": %s",
  674. hdl->server_side_encryption);
  675. headers = curl_slist_append(headers, buf);
  676. g_free(buf);
  677. }
  678. if (is_non_empty_string(hdl->storage_class)) {
  679. buf = g_strdup_printf(AMAZON_STORAGE_CLASS_HEADER ": %s",
  680. hdl->storage_class);
  681. headers = curl_slist_append(headers, buf);
  682. g_free(buf);
  683. }
  684. buf = g_strdup_printf("Authorization: AWS %s:%s",
  685. hdl->access_key, auth_base64);
  686. headers = curl_slist_append(headers, buf);
  687. g_free(buf);
  688. }
  689. if (md5_hash && '\0' != md5_hash[0]) {
  690. buf = g_strdup_printf("Content-MD5: %s", md5_hash);
  691. headers = curl_slist_append(headers, buf);
  692. g_free(buf);
  693. }
  694. buf = g_strdup_printf("Date: %s", date);
  695. headers = curl_slist_append(headers, buf);
  696. g_free(buf);
  697. cleanup:
  698. g_free(date);
  699. g_free(esc_bucket);
  700. g_free(esc_key);
  701. if (md) g_byte_array_free(md, TRUE);
  702. g_free(auth_base64);
  703. if (auth_string) g_string_free(auth_string, TRUE);
  704. return headers;
  705. }
  706. /* Functions for a SAX parser to parse the XML failure from Amazon */
  707. /* Private structure for our "thunk", which tracks where the user is in the list
  708. * * of keys. */
  709. struct failure_thunk {
  710. gboolean want_text;
  711. gboolean in_title;
  712. gboolean in_body;
  713. gboolean in_code;
  714. gboolean in_message;
  715. gint in_others;
  716. gchar *text;
  717. gsize text_len;
  718. gchar *message;
  719. gchar *error_name;
  720. };
  721. static void
  722. failure_start_element(GMarkupParseContext *context G_GNUC_UNUSED,
  723. const gchar *element_name,
  724. const gchar **attribute_names G_GNUC_UNUSED,
  725. const gchar **attribute_values G_GNUC_UNUSED,
  726. gpointer user_data,
  727. GError **error G_GNUC_UNUSED)
  728. {
  729. struct failure_thunk *thunk = (struct failure_thunk *)user_data;
  730. if (g_ascii_strcasecmp(element_name, "title") == 0) {
  731. thunk->in_title = 1;
  732. thunk->in_others = 0;
  733. thunk->want_text = 1;
  734. } else if (g_ascii_strcasecmp(element_name, "body") == 0) {
  735. thunk->in_body = 1;
  736. thunk->in_others = 0;
  737. thunk->want_text = 1;
  738. } else if (g_ascii_strcasecmp(element_name, "code") == 0) {
  739. thunk->in_code = 1;
  740. thunk->in_others = 0;
  741. thunk->want_text = 1;
  742. } else if (g_ascii_strcasecmp(element_name, "message") == 0) {
  743. thunk->in_message = 1;
  744. thunk->in_others = 0;
  745. thunk->want_text = 1;
  746. } else {
  747. thunk->in_others++;
  748. }
  749. }
  750. static void
  751. failure_end_element(GMarkupParseContext *context G_GNUC_UNUSED,
  752. const gchar *element_name,
  753. gpointer user_data,
  754. GError **error G_GNUC_UNUSED)
  755. {
  756. struct failure_thunk *thunk = (struct failure_thunk *)user_data;
  757. if (g_ascii_strcasecmp(element_name, "title") == 0) {
  758. char *p = strchr(thunk->text, ' ');
  759. if (p) {
  760. p++;
  761. if (*p) {
  762. thunk->error_name = g_strdup(p);
  763. }
  764. }
  765. g_free(thunk->text);
  766. thunk->text = NULL;
  767. thunk->in_title = 0;
  768. } else if (g_ascii_strcasecmp(element_name, "body") == 0) {
  769. thunk->message = thunk->text;
  770. g_strstrip(thunk->message);
  771. thunk->text = NULL;
  772. thunk->in_body = 0;
  773. } else if (g_ascii_strcasecmp(element_name, "code") == 0) {
  774. thunk->error_name = thunk->text;
  775. thunk->text = NULL;
  776. thunk->in_code = 0;
  777. } else if (g_ascii_strcasecmp(element_name, "message") == 0) {
  778. thunk->message = thunk->text;
  779. thunk->text = NULL;
  780. thunk->in_message = 0;
  781. } else {
  782. thunk->in_others--;
  783. }
  784. }
  785. static void
  786. failure_text(GMarkupParseContext *context G_GNUC_UNUSED,
  787. const gchar *text,
  788. gsize text_len,
  789. gpointer user_data,
  790. GError **error G_GNUC_UNUSED)
  791. {
  792. struct failure_thunk *thunk = (struct failure_thunk *)user_data;
  793. if (thunk->want_text && thunk->in_others == 0) {
  794. char *new_text;
  795. new_text = g_strndup(text, text_len);
  796. if (thunk->text) {
  797. strappend(thunk->text, new_text);
  798. g_free(new_text);
  799. } else {
  800. thunk->text = new_text;
  801. }
  802. }
  803. }
  804. static gboolean
  805. interpret_response(S3Handle *hdl,
  806. CURLcode curl_code,
  807. char *curl_error_buffer,
  808. gchar *body,
  809. guint body_len,
  810. const char *etag,
  811. const char *content_md5)
  812. {
  813. long response_code = 0;
  814. gboolean ret = TRUE;
  815. struct failure_thunk thunk;
  816. GMarkupParseContext *ctxt = NULL;
  817. static GMarkupParser parser = { failure_start_element, failure_end_element, failure_text, NULL, NULL };
  818. GError *err = NULL;
  819. if (!hdl) return FALSE;
  820. if (hdl->last_message) g_free(hdl->last_message);
  821. hdl->last_message = NULL;
  822. /* bail out from a CURL error */
  823. if (curl_code != CURLE_OK) {
  824. hdl->last_curl_code = curl_code;
  825. hdl->last_message = g_strdup_printf("CURL error: %s", curl_error_buffer);
  826. return FALSE;
  827. }
  828. /* CURL seems to think things were OK, so get its response code */
  829. curl_easy_getinfo(hdl->curl, CURLINFO_RESPONSE_CODE, &response_code);
  830. hdl->last_response_code = response_code;
  831. /* check ETag, if present */
  832. if (etag && content_md5 && 200 == response_code) {
  833. if (etag && g_ascii_strcasecmp(etag, content_md5))
  834. hdl->last_message = g_strdup("S3 Error: Possible data corruption (ETag returned by Amazon did not match the MD5 hash of the data sent)");
  835. else
  836. ret = FALSE;
  837. return ret;
  838. }
  839. if (200 <= response_code && response_code < 400) {
  840. /* 2xx and 3xx codes won't have a response body we care about */
  841. hdl->last_s3_error_code = S3_ERROR_None;
  842. return FALSE;
  843. }
  844. /* Now look at the body to try to get the actual Amazon error message. */
  845. /* impose a reasonable limit on body size */
  846. if (body_len > MAX_ERROR_RESPONSE_LEN) {
  847. hdl->last_message = g_strdup("S3 Error: Unknown (response body too large to parse)");
  848. return FALSE;
  849. } else if (!body || body_len == 0) {
  850. hdl->last_message = g_strdup("S3 Error: Unknown (empty response body)");
  851. return TRUE; /* perhaps a network error; retry the request */
  852. }
  853. thunk.in_title = FALSE;
  854. thunk.in_body = FALSE;
  855. thunk.in_code = FALSE;
  856. thunk.in_message = FALSE;
  857. thunk.in_others = 0;
  858. thunk.text = NULL;
  859. thunk.want_text = FALSE;
  860. thunk.text_len = 0;
  861. thunk.message = NULL;
  862. thunk.error_name = NULL;
  863. if (hdl->openstack_swift_api &&
  864. !g_strstr_len(body, body_len, "xml version") &&
  865. !g_strstr_len(body, body_len, "<html>")) {
  866. char *body_copy = g_strndup(body, body_len);
  867. char *b = body_copy;
  868. char *p = strchr(b, '\n');
  869. char *p1;
  870. if (p) { /* first line: error code */
  871. *p = '\0';
  872. p++;
  873. p1 = strchr(b, ' ');
  874. if (p1) {
  875. p1++;
  876. if (*p1) {
  877. thunk.error_name = g_strdup(p1);
  878. }
  879. }
  880. b = p;
  881. }
  882. p = strchr(b, '\n');
  883. if (p) { /* second line: error message */
  884. *p = '\0';
  885. p++;
  886. thunk.message = g_strdup(p);
  887. g_strstrip(thunk.message);
  888. b = p;
  889. }
  890. goto parsing_done;
  891. }
  892. /* run the parser over it */
  893. ctxt = g_markup_parse_context_new(&parser, 0, (gpointer)&thunk, NULL);
  894. if (!g_markup_parse_context_parse(ctxt, body, body_len, &err)) {
  895. if (hdl->last_message) g_free(hdl->last_message);
  896. hdl->last_message = g_strdup(err->message);
  897. goto cleanup;
  898. }
  899. if (!g_markup_parse_context_end_parse(ctxt, &err)) {
  900. if (hdl->last_message) g_free(hdl->last_message);
  901. hdl->last_message = g_strdup(err->message);
  902. goto cleanup;
  903. }
  904. g_markup_parse_context_free(ctxt);
  905. ctxt = NULL;
  906. parsing_done:
  907. if (thunk.error_name) {
  908. hdl->last_s3_error_code = s3_error_code_from_name(thunk.error_name);
  909. g_free(thunk.error_name);
  910. thunk.error_name = NULL;
  911. }
  912. if (thunk.message) {
  913. g_free(hdl->last_message);
  914. hdl->last_message = thunk.message;
  915. thunk.message = NULL; /* steal the reference to the string */
  916. }
  917. cleanup:
  918. g_free(thunk.text);
  919. g_free(thunk.message);
  920. g_free(thunk.error_name);
  921. return FALSE;
  922. }
  923. /* a CURLOPT_READFUNCTION to read data from a buffer. */
  924. size_t
  925. s3_buffer_read_func(void *ptr, size_t size, size_t nmemb, void * stream)
  926. {
  927. CurlBuffer *data = stream;
  928. guint bytes_desired = (guint) size * nmemb;
  929. /* check the number of bytes remaining, just to be safe */
  930. if (bytes_desired > data->buffer_len - data->buffer_pos)
  931. bytes_desired = data->buffer_len - data->buffer_pos;
  932. memcpy((char *)ptr, data->buffer + data->buffer_pos, bytes_desired);
  933. data->buffer_pos += bytes_desired;
  934. return bytes_desired;
  935. }
  936. size_t
  937. s3_buffer_size_func(void *stream)
  938. {
  939. CurlBuffer *data = stream;
  940. return data->buffer_len;
  941. }
  942. GByteArray*
  943. s3_buffer_md5_func(void *stream)
  944. {
  945. CurlBuffer *data = stream;
  946. GByteArray req_body_gba = {(guint8 *)data->buffer, data->buffer_len};
  947. return s3_compute_md5_hash(&req_body_gba);
  948. }
  949. void
  950. s3_buffer_reset_func(void *stream)
  951. {
  952. CurlBuffer *data = stream;
  953. data->buffer_pos = 0;
  954. }
  955. /* a CURLOPT_WRITEFUNCTION to write data to a buffer. */
  956. size_t
  957. s3_buffer_write_func(void *ptr, size_t size, size_t nmemb, void *stream)
  958. {
  959. CurlBuffer * data = stream;
  960. guint new_bytes = (guint) size * nmemb;
  961. guint bytes_needed = data->buffer_pos + new_bytes;
  962. /* error out if the new size is greater than the maximum allowed */
  963. if (data->max_buffer_size && bytes_needed > data->max_buffer_size)
  964. return 0;
  965. /* reallocate if necessary. We use exponential sizing to make this
  966. * happen less often. */
  967. if (bytes_needed > data->buffer_len) {
  968. guint new_size = MAX(bytes_needed, data->buffer_len * 2);
  969. if (data->max_buffer_size) {
  970. new_size = MIN(new_size, data->max_buffer_size);
  971. }
  972. data->buffer = g_realloc(data->buffer, new_size);
  973. data->buffer_len = new_size;
  974. }
  975. if (!data->buffer)
  976. return 0; /* returning zero signals an error to libcurl */
  977. /* actually copy the data to the buffer */
  978. memcpy(data->buffer + data->buffer_pos, ptr, new_bytes);
  979. data->buffer_pos += new_bytes;
  980. /* signal success to curl */
  981. return new_bytes;
  982. }
  983. /* a CURLOPT_READFUNCTION that writes nothing. */
  984. size_t
  985. 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)
  986. {
  987. return 0;
  988. }
  989. size_t
  990. s3_empty_size_func(G_GNUC_UNUSED void *stream)
  991. {
  992. return 0;
  993. }
  994. GByteArray*
  995. s3_empty_md5_func(G_GNUC_UNUSED void *stream)
  996. {
  997. static const GByteArray empty = {(guint8 *) "", 0};
  998. return s3_compute_md5_hash(&empty);
  999. }
  1000. /* a CURLOPT_WRITEFUNCTION to write data that just counts data.
  1001. * s3_write_data should be NULL or a pointer to an gint64.
  1002. */
  1003. size_t
  1004. s3_counter_write_func(G_GNUC_UNUSED void *ptr, size_t size, size_t nmemb, void *stream)
  1005. {
  1006. gint64 *count = (gint64*) stream, inc = nmemb*size;
  1007. if (count) *count += inc;
  1008. return inc;
  1009. }
  1010. void
  1011. s3_counter_reset_func(void *stream)
  1012. {
  1013. gint64 *count = (gint64*) stream;
  1014. if (count) *count = 0;
  1015. }
  1016. #ifdef _WIN32
  1017. /* a CURLOPT_READFUNCTION to read data from a file. */
  1018. size_t
  1019. s3_file_read_func(void *ptr, size_t size, size_t nmemb, void * stream)
  1020. {
  1021. HANDLE *hFile = (HANDLE *) stream;
  1022. DWORD bytes_read;
  1023. ReadFile(hFile, ptr, (DWORD) size*nmemb, &bytes_read, NULL);
  1024. return bytes_read;
  1025. }
  1026. size_t
  1027. s3_file_size_func(void *stream)
  1028. {
  1029. HANDLE *hFile = (HANDLE *) stream;
  1030. DWORD size = GetFileSize(hFile, NULL);
  1031. if (INVALID_FILE_SIZE == size) {
  1032. return -1;
  1033. } else {
  1034. return size;
  1035. }
  1036. }
  1037. GByteArray*
  1038. s3_file_md5_func(void *stream)
  1039. {
  1040. #define S3_MD5_BUF_SIZE (10*1024)
  1041. HANDLE *hFile = (HANDLE *) stream;
  1042. guint8 buf[S3_MD5_BUF_SIZE];
  1043. DWORD bytes_read;
  1044. MD5_CTX md5_ctx;
  1045. GByteArray *ret = NULL;
  1046. g_assert(INVALID_SET_FILE_POINTER != SetFilePointer(hFile, 0, NULL, FILE_BEGIN));
  1047. ret = g_byte_array_sized_new(S3_MD5_HASH_BYTE_LEN);
  1048. g_byte_array_set_size(ret, S3_MD5_HASH_BYTE_LEN);
  1049. MD5_Init(&md5_ctx);
  1050. while (ReadFile(hFile, buf, S3_MD5_BUF_SIZE, &bytes_read, NULL)) {
  1051. MD5_Update(&md5_ctx, buf, bytes_read);
  1052. }
  1053. MD5_Final(ret->data, &md5_ctx);
  1054. g_assert(INVALID_SET_FILE_POINTER != SetFilePointer(hFile, 0, NULL, FILE_BEGIN));
  1055. return ret;
  1056. #undef S3_MD5_BUF_SIZE
  1057. }
  1058. GByteArray*
  1059. s3_file_reset_func(void *stream)
  1060. {
  1061. g_assert(INVALID_SET_FILE_POINTER != SetFilePointer(hFile, 0, NULL, FILE_BEGIN));
  1062. }
  1063. /* a CURLOPT_WRITEFUNCTION to write data to a file. */
  1064. size_t
  1065. s3_file_write_func(void *ptr, size_t size, size_t nmemb, void *stream)
  1066. {
  1067. HANDLE *hFile = (HANDLE *) stream;
  1068. DWORD bytes_written;
  1069. WriteFile(hFile, ptr, (DWORD) size*nmemb, &bytes_written, NULL);
  1070. return bytes_written;
  1071. }
  1072. #endif
  1073. static int
  1074. curl_debug_message(CURL *curl G_GNUC_UNUSED,
  1075. curl_infotype type,
  1076. char *s,
  1077. size_t len,
  1078. void *unused G_GNUC_UNUSED)
  1079. {
  1080. char *lineprefix;
  1081. char *message;
  1082. char **lines, **line;
  1083. switch (type) {
  1084. case CURLINFO_TEXT:
  1085. lineprefix="";
  1086. break;
  1087. case CURLINFO_HEADER_IN:
  1088. lineprefix="Hdr In: ";
  1089. break;
  1090. case CURLINFO_HEADER_OUT:
  1091. lineprefix="Hdr Out: ";
  1092. break;
  1093. /*
  1094. case CURLINFO_DATA_IN:
  1095. if (len > 1000) return 0;
  1096. lineprefix="Data In: ";
  1097. break;
  1098. case CURLINFO_DATA_OUT:
  1099. if (len > 1000) return 0;
  1100. lineprefix="Data Out: ";
  1101. break;
  1102. */
  1103. default:
  1104. /* ignore data in/out -- nobody wants to see that in the
  1105. * debug logs! */
  1106. return 0;
  1107. }
  1108. /* split the input into lines */
  1109. message = g_strndup(s, (gsize) len);
  1110. lines = g_strsplit(message, "\n", -1);
  1111. g_free(message);
  1112. for (line = lines; *line; line++) {
  1113. if (**line == '\0') continue; /* skip blank lines */
  1114. g_debug("%s%s", lineprefix, *line);
  1115. }
  1116. g_strfreev(lines);
  1117. return 0;
  1118. }
  1119. static s3_result_t
  1120. perform_request(S3Handle *hdl,
  1121. const char *verb,
  1122. const char *bucket,
  1123. const char *key,
  1124. const char *subresource,
  1125. const char *query,
  1126. s3_read_func read_func,
  1127. s3_reset_func read_reset_func,
  1128. s3_size_func size_func,
  1129. s3_md5_func md5_func,
  1130. gpointer read_data,
  1131. s3_write_func write_func,
  1132. s3_reset_func write_reset_func,
  1133. gpointer write_data,
  1134. s3_progress_func progress_func,
  1135. gpointer progress_data,
  1136. const result_handling_t *result_handling)
  1137. {
  1138. char *url = NULL;
  1139. s3_result_t result = S3_RESULT_FAIL; /* assume the worst.. */
  1140. CURLcode curl_code = CURLE_OK;
  1141. char curl_error_buffer[CURL_ERROR_SIZE] = "";
  1142. struct curl_slist *headers = NULL;
  1143. /* Set S3Internal Data */
  1144. S3InternalData int_writedata = {{NULL, 0, 0, MAX_ERROR_RESPONSE_LEN}, NULL, NULL, NULL, FALSE, FALSE, NULL, hdl};
  1145. gboolean should_retry;
  1146. guint retries = 0;
  1147. gulong backoff = EXPONENTIAL_BACKOFF_START_USEC;
  1148. /* corresponds to PUT, HEAD, GET, and POST */
  1149. int curlopt_upload = 0, curlopt_nobody = 0, curlopt_httpget = 0, curlopt_post = 0;
  1150. /* do we want to examine the headers */
  1151. const char *curlopt_customrequest = NULL;
  1152. /* for MD5 calculation */
  1153. GByteArray *md5_hash = NULL;
  1154. gchar *md5_hash_hex = NULL, *md5_hash_b64 = NULL;
  1155. size_t request_body_size = 0;
  1156. g_assert(hdl != NULL && hdl->curl != NULL);
  1157. s3_reset(hdl);
  1158. url = build_url(hdl, bucket, key, subresource, query);
  1159. if (!url) goto cleanup;
  1160. /* libcurl may behave strangely if these are not set correctly */
  1161. if (!strncmp(verb, "PUT", 4)) {
  1162. curlopt_upload = 1;
  1163. } else if (!strncmp(verb, "GET", 4)) {
  1164. curlopt_httpget = 1;
  1165. } else if (!strncmp(verb, "POST", 5)) {
  1166. curlopt_post = 1;
  1167. } else if (!strncmp(verb, "HEAD", 5)) {
  1168. curlopt_nobody = 1;
  1169. } else {
  1170. curlopt_customrequest = verb;
  1171. }
  1172. if (size_func) {
  1173. request_body_size = size_func(read_data);
  1174. }
  1175. if (md5_func) {
  1176. md5_hash = md5_func(read_data);
  1177. if (md5_hash) {
  1178. md5_hash_b64 = s3_base64_encode(md5_hash);
  1179. md5_hash_hex = s3_hex_encode(md5_hash);
  1180. g_byte_array_free(md5_hash, TRUE);
  1181. }
  1182. }
  1183. if (!read_func) {
  1184. /* Curl will use fread() otherwise */
  1185. read_func = s3_empty_read_func;
  1186. }
  1187. if (write_func) {
  1188. int_writedata.write_func = write_func;
  1189. int_writedata.reset_func = write_reset_func;
  1190. int_writedata.write_data = write_data;
  1191. } else {
  1192. /* Curl will use fwrite() otherwise */
  1193. int_writedata.write_func = s3_counter_write_func;
  1194. int_writedata.reset_func = s3_counter_reset_func;
  1195. int_writedata.write_data = NULL;
  1196. }
  1197. while (1) {
  1198. /* reset things */
  1199. if (headers) {
  1200. curl_slist_free_all(headers);
  1201. }
  1202. curl_error_buffer[0] = '\0';
  1203. if (read_reset_func) {
  1204. read_reset_func(read_data);
  1205. }
  1206. /* calls write_reset_func */
  1207. s3_internal_reset_func(&int_writedata);
  1208. /* set up the request */
  1209. headers = authenticate_request(hdl, verb, bucket, key, subresource,
  1210. md5_hash_b64);
  1211. if (hdl->use_ssl && hdl->ca_info) {
  1212. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_CAINFO, hdl->ca_info)))
  1213. goto curl_error;
  1214. }
  1215. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_VERBOSE, hdl->verbose)))
  1216. goto curl_error;
  1217. if (hdl->verbose) {
  1218. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_DEBUGFUNCTION,
  1219. curl_debug_message)))
  1220. goto curl_error;
  1221. }
  1222. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_ERRORBUFFER,
  1223. curl_error_buffer)))
  1224. goto curl_error;
  1225. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_NOPROGRESS, 1)))
  1226. goto curl_error;
  1227. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_FOLLOWLOCATION, 1)))
  1228. goto curl_error;
  1229. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_URL, url)))
  1230. goto curl_error;
  1231. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_HTTPHEADER,
  1232. headers)))
  1233. goto curl_error;
  1234. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_WRITEFUNCTION, s3_internal_write_func)))
  1235. goto curl_error;
  1236. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_WRITEDATA, &int_writedata)))
  1237. goto curl_error;
  1238. /* Note: we always have to set this apparently, for consistent "end of header" detection */
  1239. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_HEADERFUNCTION, s3_internal_header_func)))
  1240. goto curl_error;
  1241. /* Note: if set, CURLOPT_HEADERDATA seems to also be used for CURLOPT_WRITEDATA ? */
  1242. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_HEADERDATA, &int_writedata)))
  1243. goto curl_error;
  1244. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_PROGRESSFUNCTION, progress_func)))
  1245. goto curl_error;
  1246. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_PROGRESSDATA, progress_data)))
  1247. goto curl_error;
  1248. /* CURLOPT_INFILESIZE_LARGE added in 7.11.0 */
  1249. #if LIBCURL_VERSION_NUM >= 0x070b00
  1250. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_INFILESIZE_LARGE, (curl_off_t)request_body_size)))
  1251. goto curl_error;
  1252. #else
  1253. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_INFILESIZE, (long)request_body_size)))
  1254. goto curl_error;
  1255. #endif
  1256. /* CURLOPT_MAX_{RECV,SEND}_SPEED_LARGE added in 7.15.5 */
  1257. #if LIBCURL_VERSION_NUM >= 0x070f05
  1258. if (s3_curl_throttling_compat()) {
  1259. if (hdl->max_send_speed)
  1260. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_MAX_SEND_SPEED_LARGE, (curl_off_t)hdl->max_send_speed)))
  1261. goto curl_error;
  1262. if (hdl->max_recv_speed)
  1263. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_MAX_RECV_SPEED_LARGE, (curl_off_t)hdl->max_recv_speed)))
  1264. goto curl_error;
  1265. }
  1266. #endif
  1267. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_HTTPGET, curlopt_httpget)))
  1268. goto curl_error;
  1269. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_UPLOAD, curlopt_upload)))
  1270. goto curl_error;
  1271. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_POST, curlopt_post)))
  1272. goto curl_error;
  1273. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_NOBODY, curlopt_nobody)))
  1274. goto curl_error;
  1275. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_CUSTOMREQUEST,
  1276. curlopt_customrequest)))
  1277. goto curl_error;
  1278. if (curlopt_upload) {
  1279. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_READFUNCTION, read_func)))
  1280. goto curl_error;
  1281. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_READDATA, read_data)))
  1282. goto curl_error;
  1283. } else {
  1284. /* Clear request_body options. */
  1285. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_READFUNCTION,
  1286. NULL)))
  1287. goto curl_error;
  1288. if ((curl_code = curl_easy_setopt(hdl->curl, CURLOPT_READDATA,
  1289. NULL)))
  1290. goto curl_error;
  1291. }
  1292. /* Perform the request */
  1293. curl_code = curl_easy_perform(hdl->curl);
  1294. /* interpret the response into hdl->last* */
  1295. curl_error: /* (label for short-circuiting the curl_easy_perform call) */
  1296. should_retry = interpret_response(hdl, curl_code, curl_error_buffer,
  1297. int_writedata.resp_buf.buffer, int_writedata.resp_buf.buffer_pos, int_writedata.etag, md5_hash_hex);
  1298. /* and, unless we know we need to retry, see what we're to do now */
  1299. if (!should_retry) {
  1300. result = lookup_result(result_handling, hdl->last_response_code,
  1301. hdl->last_s3_error_code, hdl->last_curl_code);
  1302. /* break out of the while(1) unless we're retrying */
  1303. if (result != S3_RESULT_RETRY)
  1304. break;
  1305. }
  1306. if (retries >= EXPONENTIAL_BACKOFF_MAX_RETRIES) {
  1307. /* we're out of retries, so annotate hdl->last_message appropriately and bail
  1308. * out. */
  1309. char *m = g_strdup_printf("Too many retries; last message was '%s'", hdl->last_message);
  1310. if (hdl->last_message) g_free(hdl->last_message);
  1311. hdl->last_message = m;
  1312. result = S3_RESULT_FAIL;
  1313. break;
  1314. }
  1315. g_usleep(backoff);
  1316. retries++;
  1317. backoff *= EXPONENTIAL_BACKOFF_BASE;
  1318. }
  1319. if (result != S3_RESULT_OK) {
  1320. g_debug(_("%s %s failed with %d/%s"), verb, url,
  1321. hdl->last_response_code,
  1322. s3_error_name_from_code(hdl->last_s3_error_code));
  1323. }
  1324. cleanup:
  1325. g_free(url);
  1326. if (headers) curl_slist_free_all(headers);
  1327. g_free(md5_hash_b64);
  1328. g_free(md5_hash_hex);
  1329. /* we don't deallocate the response body -- we keep it for later */
  1330. hdl->last_response_body = int_writedata.resp_buf.buffer;
  1331. hdl->last_response_body_size = int_writedata.resp_buf.buffer_pos;
  1332. hdl->last_num_retries = retries;
  1333. return result;
  1334. }
  1335. static size_t
  1336. s3_internal_write_func(void *ptr, size_t size, size_t nmemb, void * stream)
  1337. {
  1338. S3InternalData *data = (S3InternalData *) stream;
  1339. size_t bytes_saved;
  1340. if (!data->headers_done)
  1341. return size*nmemb;
  1342. /* call write on internal buffer (if not full) */
  1343. if (data->int_write_done) {
  1344. bytes_saved = 0;
  1345. } else {
  1346. bytes_saved = s3_buffer_write_func(ptr, size, nmemb, &data->resp_buf);
  1347. if (!bytes_saved) {
  1348. data->int_write_done = TRUE;
  1349. }
  1350. }
  1351. /* call write on user buffer */
  1352. if (data->write_func) {
  1353. return data->write_func(ptr, size, nmemb, data->write_data);
  1354. } else {
  1355. return bytes_saved;
  1356. }
  1357. }
  1358. static void
  1359. s3_internal_reset_func(void * stream)
  1360. {
  1361. S3InternalData *data = (S3InternalData *) stream;
  1362. s3_buffer_reset_func(&data->resp_buf);
  1363. data->headers_done = FALSE;
  1364. data->int_write_done = FALSE;
  1365. data->etag = NULL;
  1366. if (data->reset_func) {
  1367. data->reset_func(data->write_data);
  1368. }
  1369. }
  1370. static size_t
  1371. s3_internal_header_func(void *ptr, size_t size, size_t nmemb, void * stream)
  1372. {
  1373. static const char *final_header = "\r\n";
  1374. time_t remote_time_in_sec,local_time;
  1375. char *header;
  1376. regmatch_t pmatch[2];
  1377. S3InternalData *data = (S3InternalData *) stream;
  1378. header = g_strndup((gchar *) ptr, (gsize) size*nmemb);
  1379. if (header[strlen(header)-1] == '\n')
  1380. header[strlen(header)-1] = '\0';
  1381. if (header[strlen(header)-1] == '\r')
  1382. header[strlen(header)-1] = '\0';
  1383. if (!s3_regexec_wrap(&etag_regex, header, 2, pmatch, 0))
  1384. data->etag = find_regex_substring(header, pmatch[1]);
  1385. if (!s3_regexec_wrap(&x_auth_token_regex, header, 2, pmatch, 0))
  1386. data->hdl->x_auth_token = find_regex_substring(header, pmatch[1]);
  1387. if (!s3_regexec_wrap(&x_storage_url_regex, header, 2, pmatch, 0))
  1388. data->hdl->x_storage_url = find_regex_substring(header, pmatch[1]);
  1389. if (strlen(header) == 0)
  1390. data->headers_done = TRUE;
  1391. if (g_str_equal(final_header, header))
  1392. data->headers_done = TRUE;
  1393. if (g_str_equal("\n", header))
  1394. data->headers_done = TRUE;
  1395. /* If date header is found */
  1396. if (!s3_regexec_wrap(&date_sync_regex, header, 2, pmatch, 0)){
  1397. char *date = find_regex_substring(header, pmatch[1]);
  1398. /* Remote time is always in GMT: RFC 2616 */
  1399. /* both curl_getdate and time operate in UTC, so no timezone math is necessary */
  1400. if ( (remote_time_in_sec = curl_getdate(date, NULL)) < 0 ){
  1401. g_debug("Error: Conversion of remote time to seconds failed.");
  1402. data->hdl->time_offset_with_s3 = 0;
  1403. }else{
  1404. local_time = time(NULL);
  1405. /* Offset time */
  1406. data->hdl->time_offset_with_s3

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