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

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

#
C | 2068 lines | 1449 code | 300 blank | 319 comment | 318 complexity | e53d0b75c0a4e84f37c55265d812cac3 MD5 | raw file

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

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

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