PageRenderTime 93ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/amanda/tags/amanda261p2/device-src/s3.c

#
C | 1910 lines | 1346 code | 267 blank | 297 comment | 293 complexity | 7be6e4020a56b50be437c4756cd3c33b MD5 | raw file

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

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

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