0fe3bb0b8abb13e3b702bfec54c011cd64ceca7b
[debian/amanda] / device-src / s3-device.c
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
21 /* An S3 device uses Amazon's S3 service (http://www.amazon.com/s3) to store 
22  * data.  It stores data in keys named with a user-specified prefix, inside a
23  * user-specified bucket.  Data is stored in the form of numbered (large) 
24  * blocks. 
25  */
26
27 #include <string.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <unistd.h>
31 #include <dirent.h>
32 #include <regex.h>
33 #include <time.h>
34 #include "util.h"
35 #include "amanda.h"
36 #include "conffile.h"
37 #include "device.h"
38 #include "s3.h"
39 #include <curl/curl.h>
40 #ifdef HAVE_OPENSSL_HMAC_H
41 # include <openssl/hmac.h>
42 #else
43 # ifdef HAVE_CRYPTO_HMAC_H
44 #  include <crypto/hmac.h>
45 # else
46 #  ifdef HAVE_HMAC_H
47 #   include <hmac.h>
48 #  endif
49 # endif
50 #endif
51
52 /*
53  * Type checking and casting macros
54  */
55 #define TYPE_S3_DEVICE  (s3_device_get_type())
56 #define S3_DEVICE(obj)  G_TYPE_CHECK_INSTANCE_CAST((obj), s3_device_get_type(), S3Device)
57 #define S3_DEVICE_CONST(obj)    G_TYPE_CHECK_INSTANCE_CAST((obj), s3_device_get_type(), S3Device const)
58 #define S3_DEVICE_CLASS(klass)  G_TYPE_CHECK_CLASS_CAST((klass), s3_device_get_type(), S3DeviceClass)
59 #define IS_S3_DEVICE(obj)       G_TYPE_CHECK_INSTANCE_TYPE((obj), s3_device_get_type ())
60
61 #define S3_DEVICE_GET_CLASS(obj)        G_TYPE_INSTANCE_GET_CLASS((obj), s3_device_get_type(), S3DeviceClass)
62 static GType    s3_device_get_type      (void);
63
64 /*
65  * Main object structure
66  */
67 typedef struct _S3MetadataFile S3MetadataFile;
68
69 typedef struct _S3Device S3Device;
70 struct _S3Device {
71     Device __parent__;
72
73     /* The "easy" curl handle we use to access Amazon S3 */
74     S3Handle *s3;
75
76     /* S3 access information */
77     char *bucket;
78     char *prefix;
79
80     /* The S3 access information. */
81     char *secret_key;
82     char *access_key;
83     char *user_token;
84     gboolean is_devpay;
85
86     char *bucket_location;
87
88     /* a cache for unsuccessful reads (where we get the file but the caller
89      * doesn't have space for it or doesn't want it), where we expect the
90      * next call will request the same file.
91      */
92     char *cached_buf;
93     char *cached_key;
94     int cached_size;
95
96     /* Produce verbose output? */
97     gboolean verbose;
98
99     /* Use SSL? */
100     gboolean use_ssl;
101 };
102
103 /*
104  * Class definition
105  */
106 typedef struct _S3DeviceClass S3DeviceClass;
107 struct _S3DeviceClass {
108     DeviceClass __parent__;
109 };
110
111
112 /*
113  * Constants and static data
114  */
115
116 #define S3_DEVICE_NAME "s3"
117 #define DEVPAY_DEVICE_NAME "s3zmanda"
118
119 /* Maximum key length as specified in the S3 documentation
120  * (*excluding* null terminator) */
121 #define S3_MAX_KEY_LENGTH 1024
122
123 /* Note: for compatability, min can only be decreased and max increased */
124 #define S3_DEVICE_MIN_BLOCK_SIZE 1024
125 #define S3_DEVICE_MAX_BLOCK_SIZE (100*1024*1024)
126 #define S3_DEVICE_DEFAULT_BLOCK_SIZE (10*1024*1024)
127
128 /* This goes in lieu of file number for metadata. */
129 #define SPECIAL_INFIX "special-"
130
131 /* pointer to the class of our parent */
132 static DeviceClass *parent_class = NULL;
133
134 /*
135  * device-specific properties
136  */
137
138 /* Authentication information for Amazon S3. Both of these are strings. */
139 static DevicePropertyBase device_property_s3_access_key;
140 static DevicePropertyBase device_property_s3_secret_key;
141 #define PROPERTY_S3_SECRET_KEY (device_property_s3_secret_key.ID)
142 #define PROPERTY_S3_ACCESS_KEY (device_property_s3_access_key.ID)
143
144 /* Same, but for S3 with DevPay. */
145 static DevicePropertyBase device_property_s3_user_token;
146 #define PROPERTY_S3_USER_TOKEN (device_property_s3_user_token.ID)
147
148 /* Location constraint for new buckets created on Amazon S3. */
149 static DevicePropertyBase device_property_s3_bucket_location;
150 #define PROPERTY_S3_BUCKET_LOCATION (device_property_s3_bucket_location.ID)
151
152 /* Whether to use SSL with Amazon S3. */
153 static DevicePropertyBase device_property_s3_ssl;
154 #define PROPERTY_S3_SSL (device_property_s3_ssl.ID)
155
156
157 /*
158  * prototypes
159  */
160
161 void s3_device_register(void);
162
163 /* 
164  * utility functions */
165
166 /* Given file and block numbers, return an S3 key.
167  * 
168  * @param self: the S3Device object
169  * @param file: the file number
170  * @param block: the block within that file
171  * @returns: a newly allocated string containing an S3 key.
172  */
173 static char * 
174 file_and_block_to_key(S3Device *self, 
175                       int file, 
176                       guint64 block);
177
178 /* Given the name of a special file (such as 'tapestart'), generate
179  * the S3 key to use for that file.
180  *
181  * @param self: the S3Device object
182  * @param special_name: name of the special file
183  * @param file: a file number to include; omitted if -1
184  * @returns: a newly alocated string containing an S3 key.
185  */
186 static char * 
187 special_file_to_key(S3Device *self, 
188                     char *special_name, 
189                     int file);
190 /* Write an amanda header file to S3.
191  *
192  * @param self: the S3Device object
193  * @param label: the volume label
194  * @param timestamp: the volume timestamp
195  */
196 static gboolean 
197 write_amanda_header(S3Device *self, 
198                     char *label, 
199                     char * timestamp);
200
201 /* "Fast forward" this device to the end by looking up the largest file number
202  * present and setting the current file number one greater.
203  *
204  * @param self: the S3Device object
205  */
206 static gboolean 
207 seek_to_end(S3Device *self);
208
209 /* Find the number of the last file that contains any data (even just a header). 
210  *
211  * @param self: the S3Device object
212  * @returns: the last file, or -1 in event of an error
213  */
214 static int 
215 find_last_file(S3Device *self);
216
217 /* Delete all blocks in the given file, including the filestart block
218  *
219  * @param self: the S3Device object
220  * @param file: the file to delete
221  */
222 static gboolean 
223 delete_file(S3Device *self, 
224             int file);
225
226 /* Set up self->s3 as best as possible.
227  *
228  * The return value is TRUE iff self->s3 is useable.
229  *
230  * @param self: the S3Device object
231  * @returns: TRUE if the handle is set up
232  */
233 static gboolean 
234 setup_handle(S3Device * self);
235
236 /* 
237  * class mechanics */
238
239 static void
240 s3_device_init(S3Device * o);
241
242 static void
243 s3_device_class_init(S3DeviceClass * c);
244
245 static void
246 s3_device_finalize(GObject * o);
247
248 static Device*
249 s3_device_factory(char * device_name, char * device_type, char * device_node);
250
251 /*
252  * Property{Get,Set}Fns */
253
254 static gboolean s3_device_set_access_key_fn(Device *self,
255     DevicePropertyBase *base, GValue *val,
256     PropertySurety surety, PropertySource source);
257
258 static gboolean s3_device_set_secret_key_fn(Device *self,
259     DevicePropertyBase *base, GValue *val,
260     PropertySurety surety, PropertySource source);
261
262 static gboolean s3_device_set_user_token_fn(Device *self,
263     DevicePropertyBase *base, GValue *val,
264     PropertySurety surety, PropertySource source);
265
266 static gboolean s3_device_set_bucket_location_fn(Device *self,
267     DevicePropertyBase *base, GValue *val,
268     PropertySurety surety, PropertySource source);
269
270 static gboolean s3_device_set_verbose_fn(Device *self,
271     DevicePropertyBase *base, GValue *val,
272     PropertySurety surety, PropertySource source);
273
274 static gboolean s3_device_set_ssl_fn(Device *self,
275     DevicePropertyBase *base, GValue *val,
276     PropertySurety surety, PropertySource source);
277
278 /* 
279  * virtual functions */
280
281 static void
282 s3_device_open_device(Device *pself, char *device_name,
283                   char * device_type, char * device_node);
284
285 static DeviceStatusFlags s3_device_read_label(Device * self);
286
287 static gboolean 
288 s3_device_start(Device * self, 
289                 DeviceAccessMode mode, 
290                 char * label, 
291                 char * timestamp);
292
293 static gboolean
294 s3_device_finish(Device * self);
295
296 static gboolean 
297 s3_device_start_file(Device * self,
298                      dumpfile_t * jobInfo);
299
300 static gboolean 
301 s3_device_write_block(Device * self, 
302                       guint size, 
303                       gpointer data);
304
305 static gboolean 
306 s3_device_finish_file(Device * self);
307
308 static dumpfile_t* 
309 s3_device_seek_file(Device *pself, 
310                     guint file);
311
312 static gboolean 
313 s3_device_seek_block(Device *pself, 
314                      guint64 block);
315
316 static int
317 s3_device_read_block(Device * pself, 
318                      gpointer data, 
319                      int *size_req);
320
321 static gboolean 
322 s3_device_recycle_file(Device *pself, 
323                        guint file);
324
325 /*
326  * Private functions
327  */
328
329 static char *
330 file_and_block_to_key(S3Device *self, 
331                       int file, 
332                       guint64 block)
333 {
334     char *s3_key = g_strdup_printf("%sf%08x-b%016llx.data",
335                                    self->prefix, file, (long long unsigned int)block);
336     g_assert(strlen(s3_key) <= S3_MAX_KEY_LENGTH);
337     return s3_key;
338 }
339
340 static char *
341 special_file_to_key(S3Device *self, 
342                     char *special_name, 
343                     int file)
344 {
345     if (file == -1)
346         return g_strdup_printf("%s" SPECIAL_INFIX "%s", self->prefix, special_name);
347     else
348         return g_strdup_printf("%sf%08x-%s", self->prefix, file, special_name);
349 }
350
351 static gboolean
352 write_amanda_header(S3Device *self, 
353                     char *label, 
354                     char * timestamp)
355 {
356     CurlBuffer amanda_header = {NULL, 0, 0, 0};
357     char * key = NULL;
358     gboolean header_fits, result;
359     dumpfile_t * dumpinfo = NULL;
360     Device *d_self = DEVICE(self);
361
362     /* build the header */
363     dumpinfo = make_tapestart_header(DEVICE(self), label, timestamp);
364     amanda_header.buffer = device_build_amanda_header(DEVICE(self), dumpinfo, 
365         /* casting guint* to int* */
366         (int*) &amanda_header.buffer_len, &header_fits);
367     if (!header_fits) {
368         device_set_error(d_self,
369             stralloc(_("Amanda tapestart header won't fit in a single block!")),
370             DEVICE_STATUS_DEVICE_ERROR);
371         g_free(amanda_header.buffer);
372         return FALSE;
373     }
374
375     /* write out the header and flush the uploads. */
376     key = special_file_to_key(self, "tapestart", -1);
377     result = s3_upload(self->s3, self->bucket, key, S3_BUFFER_READ_FUNCS,
378                        &amanda_header, NULL, NULL);
379     g_free(amanda_header.buffer);
380     g_free(key);
381
382     if (!result) {
383         device_set_error(d_self,
384             vstrallocf(_("While writing amanda header: %s"), s3_strerror(self->s3)),
385             DEVICE_STATUS_DEVICE_ERROR | DEVICE_STATUS_VOLUME_ERROR);
386     }
387     return result;
388 }
389
390 static gboolean
391 seek_to_end(S3Device *self) {
392     int last_file;
393
394     Device *pself = DEVICE(self);
395
396     last_file = find_last_file(self);
397     if (last_file < 0)
398         return FALSE;
399
400     pself->file = last_file;
401
402     return TRUE;
403 }
404
405 /* Convert an object name into a file number, assuming the given prefix
406  * length. Returns -1 if the object name is invalid, or 0 if the object name
407  * is a "special" key. */
408 static int key_to_file(guint prefix_len, const char * key) {
409     int file;
410     int i;
411     
412     /* skip the prefix */
413     if (strlen(key) <= prefix_len)
414         return -1;
415
416     key += prefix_len;
417
418     if (strncmp(key, SPECIAL_INFIX, strlen(SPECIAL_INFIX)) == 0) {
419         return 0;
420     }
421     
422     /* check that key starts with 'f' */
423     if (key[0] != 'f')
424         return -1;
425     key++;
426     
427     /* check that key is of the form "%08x-" */
428     for (i = 0; i < 8; i++) {
429         if (!(key[i] >= '0' && key[i] <= '9') &&
430             !(key[i] >= 'a' && key[i] <= 'f') &&
431             !(key[i] >= 'A' && key[i] <= 'F')) break;
432     }
433     if (key[i] != '-') return -1;
434     if (i < 8) return -1;
435
436     /* convert the file number */
437     errno = 0;
438     file = strtoul(key, NULL, 16);
439     if (errno != 0) {
440         g_warning(_("unparseable file number '%s'"), key);
441         return -1;
442     }
443     
444     return file;
445 }
446
447 /* Find the number of the last file that contains any data (even just a header). 
448  * Returns -1 in event of an error
449  */
450 static int
451 find_last_file(S3Device *self) {
452     gboolean result;
453     GSList *keys;
454     unsigned int prefix_len = strlen(self->prefix);
455     int last_file = 0;
456     Device *d_self = DEVICE(self);
457
458     /* list all keys matching C{PREFIX*-*}, stripping the C{-*} */
459     result = s3_list_keys(self->s3, self->bucket, self->prefix, "-", &keys);
460     if (!result) {
461         device_set_error(d_self,
462             vstrallocf(_("While listing S3 keys: %s"), s3_strerror(self->s3)),
463             DEVICE_STATUS_DEVICE_ERROR | DEVICE_STATUS_VOLUME_ERROR);
464         return -1;
465     }
466
467     for (; keys; keys = g_slist_remove(keys, keys->data)) {
468         int file = key_to_file(prefix_len, keys->data);
469
470         /* and if it's the last, keep it */
471         if (file > last_file)
472             last_file = file;
473     }
474
475     return last_file;
476 }
477
478 /* Find the number of the file following the requested one, if any. 
479  * Returns 0 if there is no such file or -1 in event of an error
480  */
481 static int
482 find_next_file(S3Device *self, int last_file) {
483     gboolean result;
484     GSList *keys;
485     unsigned int prefix_len = strlen(self->prefix);
486     int next_file = 0;
487     Device *d_self = DEVICE(self);
488
489     /* list all keys matching C{PREFIX*-*}, stripping the C{-*} */
490     result = s3_list_keys(self->s3, self->bucket, self->prefix, "-", &keys);
491     if (!result) {
492         device_set_error(d_self,
493             vstrallocf(_("While listing S3 keys: %s"), s3_strerror(self->s3)),
494             DEVICE_STATUS_DEVICE_ERROR | DEVICE_STATUS_VOLUME_ERROR);
495         return -1;
496     }
497
498     for (; keys; keys = g_slist_remove(keys, keys->data)) {
499         int file;
500
501         file = key_to_file(prefix_len, (char*)keys->data);
502
503         if (file < 0) {
504             /* Set this in case we don't find a next file; this is not a
505              * hard error, so if we can find a next file we'll return that
506              * instead. */
507             next_file = -1;
508         }
509
510         if (file < next_file && file > last_file) {
511             next_file = file;
512         }
513     }
514
515     return last_file;
516 }
517
518 static gboolean
519 delete_file(S3Device *self,
520             int file)
521 {
522     gboolean result;
523     GSList *keys;
524     char *my_prefix = g_strdup_printf("%sf%08x-", self->prefix, file);
525     Device *d_self = DEVICE(self);
526     
527     result = s3_list_keys(self->s3, self->bucket, my_prefix, NULL, &keys);
528     if (!result) {
529         device_set_error(d_self,
530             vstrallocf(_("While listing S3 keys: %s"), s3_strerror(self->s3)),
531             DEVICE_STATUS_DEVICE_ERROR | DEVICE_STATUS_VOLUME_ERROR);
532         return FALSE;
533     }
534
535     /* this will likely be a *lot* of keys */
536     for (; keys; keys = g_slist_remove(keys, keys->data)) {
537         if (self->verbose) g_debug(_("Deleting %s"), (char*)keys->data);
538         if (!s3_delete(self->s3, self->bucket, keys->data)) {
539             device_set_error(d_self,
540                 vstrallocf(_("While deleting key '%s': %s"),
541                             (char*)keys->data, s3_strerror(self->s3)),
542                 DEVICE_STATUS_DEVICE_ERROR);
543             g_slist_free(keys);
544             return FALSE;
545         }
546     }
547
548     return TRUE;
549 }
550
551 /*
552  * Class mechanics
553  */
554
555 void 
556 s3_device_register(void)
557 {
558     static const char * device_prefix_list[] = { S3_DEVICE_NAME, DEVPAY_DEVICE_NAME, NULL };
559     g_assert(s3_init());
560
561     /* set up our properties */
562     device_property_fill_and_register(&device_property_s3_secret_key,
563                                       G_TYPE_STRING, "s3_secret_key",
564        "Secret access key to authenticate with Amazon S3");
565     device_property_fill_and_register(&device_property_s3_access_key,
566                                       G_TYPE_STRING, "s3_access_key",
567        "Access key ID to authenticate with Amazon S3");
568     device_property_fill_and_register(&device_property_s3_user_token,
569                                       G_TYPE_STRING, "s3_user_token",
570        "User token for authentication Amazon devpay requests");
571     device_property_fill_and_register(&device_property_s3_bucket_location,
572                                       G_TYPE_STRING, "s3_bucket_location",
573        "Location constraint for buckets on Amazon S3");
574     device_property_fill_and_register(&device_property_s3_ssl,
575                                       G_TYPE_BOOLEAN, "s3_ssl",
576        "Whether to use SSL with Amazon S3");
577
578
579     /* register the device itself */
580     register_device(s3_device_factory, device_prefix_list);
581 }
582
583 static GType
584 s3_device_get_type(void)
585 {
586     static GType type = 0;
587     
588     if G_UNLIKELY(type == 0) {
589         static const GTypeInfo info = {
590             sizeof (S3DeviceClass),
591             (GBaseInitFunc) NULL,
592             (GBaseFinalizeFunc) NULL,
593             (GClassInitFunc) s3_device_class_init,
594             (GClassFinalizeFunc) NULL,
595             NULL /* class_data */,
596             sizeof (S3Device),
597             0 /* n_preallocs */,
598             (GInstanceInitFunc) s3_device_init,
599             NULL
600         };
601         
602         type = g_type_register_static (TYPE_DEVICE, "S3Device", &info,
603                                        (GTypeFlags)0);
604     }
605
606     return type;
607 }
608
609 static void 
610 s3_device_init(S3Device * self)
611 {
612     Device * dself = DEVICE(self);
613     GValue response;
614
615     /* Register property values
616      * Note: Some aren't added until s3_device_open_device()
617      */
618     bzero(&response, sizeof(response));
619
620     g_value_init(&response, CONCURRENCY_PARADIGM_TYPE);
621     g_value_set_enum(&response, CONCURRENCY_PARADIGM_SHARED_READ);
622     device_set_simple_property(dself, PROPERTY_CONCURRENCY,
623             &response, PROPERTY_SURETY_GOOD, PROPERTY_SOURCE_DETECTED);
624     g_value_unset(&response);
625
626     g_value_init(&response, STREAMING_REQUIREMENT_TYPE);
627     g_value_set_enum(&response, STREAMING_REQUIREMENT_NONE);
628     device_set_simple_property(dself, PROPERTY_STREAMING,
629             &response, PROPERTY_SURETY_GOOD, PROPERTY_SOURCE_DETECTED);
630     g_value_unset(&response);
631
632     g_value_init(&response, G_TYPE_BOOLEAN);
633     g_value_set_boolean(&response, TRUE);
634     device_set_simple_property(dself, PROPERTY_APPENDABLE,
635             &response, PROPERTY_SURETY_GOOD, PROPERTY_SOURCE_DETECTED);
636     g_value_unset(&response);
637
638     g_value_init(&response, G_TYPE_BOOLEAN);
639     g_value_set_boolean(&response, TRUE);
640     device_set_simple_property(dself, PROPERTY_PARTIAL_DELETION,
641             &response, PROPERTY_SURETY_GOOD, PROPERTY_SOURCE_DETECTED);
642     g_value_unset(&response);
643
644     g_value_init(&response, G_TYPE_BOOLEAN);
645     g_value_set_boolean(&response, FALSE);
646     device_set_simple_property(dself, PROPERTY_COMPRESSION,
647             &response, PROPERTY_SURETY_GOOD, PROPERTY_SOURCE_DETECTED);
648     g_value_unset(&response);
649
650     g_value_init(&response, MEDIA_ACCESS_MODE_TYPE);
651     g_value_set_enum(&response, MEDIA_ACCESS_MODE_READ_WRITE);
652     device_set_simple_property(dself, PROPERTY_MEDIUM_ACCESS_TYPE,
653             &response, PROPERTY_SURETY_GOOD, PROPERTY_SOURCE_DETECTED);
654     g_value_unset(&response);
655
656 }
657
658 static void 
659 s3_device_class_init(S3DeviceClass * c G_GNUC_UNUSED)
660 {
661     GObjectClass *g_object_class = (GObjectClass*) c;
662     DeviceClass *device_class = (DeviceClass *)c;
663
664     parent_class = g_type_class_ref (TYPE_DEVICE);
665
666     device_class->open_device = s3_device_open_device;
667     device_class->read_label = s3_device_read_label;
668     device_class->start = s3_device_start;
669     device_class->finish = s3_device_finish;
670
671     device_class->start_file = s3_device_start_file;
672     device_class->write_block = s3_device_write_block;
673     device_class->finish_file = s3_device_finish_file;
674
675     device_class->seek_file = s3_device_seek_file;
676     device_class->seek_block = s3_device_seek_block;
677     device_class->read_block = s3_device_read_block;
678     device_class->recycle_file = s3_device_recycle_file;
679
680     g_object_class->finalize = s3_device_finalize;
681
682     device_class_register_property(device_class, PROPERTY_S3_ACCESS_KEY,
683             PROPERTY_ACCESS_GET_MASK | PROPERTY_ACCESS_SET_BEFORE_START,
684             device_simple_property_get_fn,
685             s3_device_set_access_key_fn);
686
687     device_class_register_property(device_class, PROPERTY_S3_SECRET_KEY,
688             PROPERTY_ACCESS_GET_MASK | PROPERTY_ACCESS_SET_BEFORE_START,
689             device_simple_property_get_fn,
690             s3_device_set_secret_key_fn);
691
692     device_class_register_property(device_class, PROPERTY_S3_USER_TOKEN,
693             PROPERTY_ACCESS_GET_MASK | PROPERTY_ACCESS_SET_BEFORE_START,
694             device_simple_property_get_fn,
695             s3_device_set_user_token_fn);
696
697     device_class_register_property(device_class, PROPERTY_S3_BUCKET_LOCATION,
698             PROPERTY_ACCESS_GET_MASK | PROPERTY_ACCESS_SET_BEFORE_START,
699             device_simple_property_get_fn,
700             s3_device_set_bucket_location_fn);
701
702     device_class_register_property(device_class, PROPERTY_VERBOSE,
703             PROPERTY_ACCESS_GET_MASK | PROPERTY_ACCESS_SET_BEFORE_START,
704             device_simple_property_get_fn,
705             s3_device_set_verbose_fn);
706
707     device_class_register_property(device_class, PROPERTY_S3_SSL,
708             PROPERTY_ACCESS_GET_MASK | PROPERTY_ACCESS_SET_BEFORE_START,
709             device_simple_property_get_fn,
710             s3_device_set_ssl_fn);
711
712     device_class_register_property(device_class, PROPERTY_COMPRESSION,
713             PROPERTY_ACCESS_GET_MASK,
714             device_simple_property_get_fn,
715             NULL);
716 }
717
718 static gboolean
719 s3_device_set_access_key_fn(Device *p_self, DevicePropertyBase *base,
720     GValue *val, PropertySurety surety, PropertySource source)
721 {
722     S3Device *self = S3_DEVICE(p_self);
723
724     amfree(self->access_key);
725     self->access_key = g_value_dup_string(val);
726     device_clear_volume_details(p_self);
727
728     return device_simple_property_set_fn(p_self, base, val, surety, source);
729 }
730
731 static gboolean
732 s3_device_set_secret_key_fn(Device *p_self, DevicePropertyBase *base,
733     GValue *val, PropertySurety surety, PropertySource source)
734 {
735     S3Device *self = S3_DEVICE(p_self);
736
737     amfree(self->secret_key);
738     self->secret_key = g_value_dup_string(val);
739     device_clear_volume_details(p_self);
740
741     return device_simple_property_set_fn(p_self, base, val, surety, source);
742 }
743
744 static gboolean
745 s3_device_set_user_token_fn(Device *p_self, DevicePropertyBase *base,
746     GValue *val, PropertySurety surety, PropertySource source)
747 {
748     S3Device *self = S3_DEVICE(p_self);
749
750     if (!self->is_devpay) {
751         device_set_error(p_self, stralloc(_(
752                    "Can't set a user token unless DevPay is in use")),
753             DEVICE_STATUS_DEVICE_ERROR);
754         return FALSE;
755     }
756
757     amfree(self->user_token);
758     self->user_token = g_value_dup_string(val);
759     device_clear_volume_details(p_self);
760
761     return device_simple_property_set_fn(p_self, base, val, surety, source);
762 }
763
764 static gboolean
765 s3_device_set_bucket_location_fn(Device *p_self, DevicePropertyBase *base,
766     GValue *val, PropertySurety surety, PropertySource source)
767 {
768     S3Device *self = S3_DEVICE(p_self);
769
770     if (self->use_ssl && !s3_curl_location_compat()) {
771         device_set_error(p_self, stralloc(_(
772                 "Location constraint given for Amazon S3 bucket, "
773                 "but libcurl is too old support wildcard certificates.")),
774             DEVICE_STATUS_DEVICE_ERROR);
775        return FALSE;
776     }
777
778     if (!s3_bucket_location_compat(self->bucket)) {
779         device_set_error(p_self, g_strdup_printf(_(
780                 "Location constraint given for Amazon S3 bucket, "
781                 "but the bucket name (%s) is not usable as a subdomain."),
782                 self->bucket),
783             DEVICE_STATUS_DEVICE_ERROR);
784        return FALSE;
785     }
786
787     amfree(self->bucket_location);
788     self->bucket_location = g_value_dup_string(val);
789     device_clear_volume_details(p_self);
790
791     return device_simple_property_set_fn(p_self, base, val, surety, source);
792 }
793
794 static gboolean
795 s3_device_set_verbose_fn(Device *p_self, DevicePropertyBase *base,
796     GValue *val, PropertySurety surety, PropertySource source)
797 {
798     S3Device *self = S3_DEVICE(p_self);
799
800     self->verbose = g_value_get_boolean(val);
801     /* Our S3 handle may not yet have been instantiated; if so, it will
802      * get the proper verbose setting when it is created */
803     if (self->s3)
804         s3_verbose(self->s3, self->verbose);
805
806     return device_simple_property_set_fn(p_self, base, val, surety, source);
807 }
808
809 static gboolean
810 s3_device_set_ssl_fn(Device *p_self, DevicePropertyBase *base,
811     GValue *val, PropertySurety surety, PropertySource source)
812 {
813     S3Device *self = S3_DEVICE(p_self);
814     gboolean new_val;
815
816     new_val = g_value_get_boolean(val);
817     /* Our S3 handle may not yet have been instantiated; if so, it will
818      * get the proper use_ssl setting when it is created */
819     if (self->s3 && !s3_use_ssl(self->s3, new_val)) {
820         device_set_error(p_self, g_strdup_printf(_(
821                 "Error setting S3 SSL/TLS use "
822                 "(tried to enable SSL/TLS for S3, but curl doesn't support it?)")),
823             DEVICE_STATUS_DEVICE_ERROR);
824         return FALSE;
825     }
826     self->use_ssl = new_val;
827
828     return device_simple_property_set_fn(p_self, base, val, surety, source);
829 }
830
831 static Device* 
832 s3_device_factory(char * device_name, char * device_type, char * device_node)
833 {
834     Device *rval;
835     S3Device * s3_rval;
836     g_assert(0 == strcmp(device_type, S3_DEVICE_NAME) ||
837              0 == strcmp(device_type, DEVPAY_DEVICE_NAME));
838     rval = DEVICE(g_object_new(TYPE_S3_DEVICE, NULL));
839     s3_rval = (S3Device*)rval;
840
841     device_open_device(rval, device_name, device_type, device_node);
842     return rval;
843 }
844
845 /*
846  * Virtual function overrides
847  */
848
849 static void
850 s3_device_open_device(Device *pself, char *device_name,
851                         char * device_type, char * device_node)
852 {
853     S3Device *self = S3_DEVICE(pself);
854     char * name_colon;
855     GValue tmp_value;
856
857     pself->min_block_size = S3_DEVICE_MIN_BLOCK_SIZE;
858     pself->max_block_size = S3_DEVICE_MAX_BLOCK_SIZE;
859     pself->block_size = S3_DEVICE_DEFAULT_BLOCK_SIZE;
860
861     /* Device name may be bucket/prefix, to support multiple volumes in a
862      * single bucket. */
863     name_colon = index(device_node, '/');
864     if (name_colon == NULL) {
865         self->bucket = g_strdup(device_node);
866         self->prefix = g_strdup("");
867     } else {
868         self->bucket = g_strndup(device_node, name_colon - device_node);
869         self->prefix = g_strdup(name_colon + 1);
870     }
871     
872     self->is_devpay = !strcmp(device_type, DEVPAY_DEVICE_NAME);
873
874     if (self->bucket == NULL || self->bucket[0] == '\0') {
875         device_set_error(pself,
876             vstrallocf(_("Empty bucket name in device %s"), device_name),
877             DEVICE_STATUS_DEVICE_ERROR);
878         amfree(self->bucket);
879         amfree(self->prefix);
880         return;
881     }
882
883     g_debug(_("S3 driver using bucket '%s', prefix '%s'"), self->bucket, self->prefix);
884
885     /* default values */
886     self->verbose = FALSE;
887
888     /* use SSL if available */
889     self->use_ssl = s3_curl_supports_ssl();
890     bzero(&tmp_value, sizeof(GValue));
891     g_value_init(&tmp_value, G_TYPE_BOOLEAN);
892     g_value_set_boolean(&tmp_value, self->use_ssl);
893     device_set_simple_property(pself, device_property_s3_ssl.ID,
894         &tmp_value, PROPERTY_SURETY_GOOD, PROPERTY_SOURCE_DEFAULT);
895
896     if (parent_class->open_device) {
897         parent_class->open_device(pself, device_name, device_type, device_node);
898     }
899 }
900
901 static void s3_device_finalize(GObject * obj_self) {
902     S3Device *self = S3_DEVICE (obj_self);
903
904     if(G_OBJECT_CLASS(parent_class)->finalize)
905         (* G_OBJECT_CLASS(parent_class)->finalize)(obj_self);
906
907     if(self->s3) s3_free(self->s3);
908     if(self->bucket) g_free(self->bucket);
909     if(self->prefix) g_free(self->prefix);
910     if(self->access_key) g_free(self->access_key);
911     if(self->secret_key) g_free(self->secret_key);
912     if(self->user_token) g_free(self->user_token);
913     if(self->bucket_location) g_free(self->bucket_location);
914 }
915
916 static gboolean setup_handle(S3Device * self) {
917     Device *d_self = DEVICE(self);
918     if (self->s3 == NULL) {
919         if (self->access_key == NULL)
920             return FALSE;
921         if (self->secret_key == NULL)
922             return FALSE;
923         if (self->is_devpay && self->user_token == NULL)
924             return FALSE;
925
926         self->s3 = s3_open(self->access_key, self->secret_key, self->user_token,
927             self->bucket_location);
928         if (self->s3 == NULL) {
929             device_set_error(d_self,
930                 stralloc(_("Internal error creating S3 handle")),
931                 DEVICE_STATUS_DEVICE_ERROR);
932             return FALSE;
933         }
934     }
935
936     s3_verbose(self->s3, self->verbose);
937
938     if (!s3_use_ssl(self->s3, self->use_ssl)) {
939         device_set_error(d_self, g_strdup_printf(_(
940                 "Error setting S3 SSL/TLS use "
941                 "(tried to enable SSL/TLS for S3, but curl doesn't support it?)")),
942             DEVICE_STATUS_DEVICE_ERROR);
943         return FALSE;
944     }
945
946     return TRUE;
947 }
948
949 static DeviceStatusFlags
950 s3_device_read_label(Device *pself) {
951     S3Device *self = S3_DEVICE(pself);
952     char *key;
953     CurlBuffer buf = {NULL, 0, 0, S3_DEVICE_MAX_BLOCK_SIZE};
954     dumpfile_t *amanda_header;
955
956     /* note that this may be called from s3_device_start, when
957      * self->access_mode is not ACCESS_NULL */
958
959     amfree(pself->volume_label);
960     amfree(pself->volume_time);
961     amfree(pself->volume_header);
962
963     if (device_in_error(self)) return pself->status;
964
965     if (!setup_handle(self)) {
966         device_set_error(pself, stralloc(_("Error setting up S3 interface")), DEVICE_STATUS_DEVICE_ERROR);
967         return pself->status;
968     }
969
970     key = special_file_to_key(self, "tapestart", -1);
971     if (!s3_read(self->s3, self->bucket, key, S3_BUFFER_WRITE_FUNCS, &buf, NULL, NULL)) {
972         guint response_code;
973         s3_error_code_t s3_error_code;
974         s3_error(self->s3, NULL, &response_code, &s3_error_code, NULL, NULL, NULL);
975
976         /* if it's an expected error (not found), just return FALSE */
977         if (response_code == 404 && 
978              (s3_error_code == S3_ERROR_NoSuchKey || s3_error_code == S3_ERROR_NoSuchBucket)) {
979             g_debug(_("Amanda header not found while reading tapestart header (this is expected for empty tapes)"));
980             device_set_error(pself,
981                 stralloc(_("Amanda header not found -- unlabeled volume?")),
982                   DEVICE_STATUS_DEVICE_ERROR
983                 | DEVICE_STATUS_VOLUME_ERROR
984                 | DEVICE_STATUS_VOLUME_UNLABELED);
985             return pself->status;
986         }
987
988         /* otherwise, log it and return */
989         device_set_error(pself,
990             vstrallocf(_("While trying to read tapestart header: %s"), s3_strerror(self->s3)),
991             DEVICE_STATUS_DEVICE_ERROR | DEVICE_STATUS_VOLUME_ERROR);
992         return pself->status;
993     }
994
995     g_assert(buf.buffer != NULL);
996     amanda_header = g_new(dumpfile_t, 1);
997     parse_file_header(buf.buffer, amanda_header, buf.buffer_pos);
998     pself->volume_header = amanda_header;
999
1000     g_free(buf.buffer);
1001
1002     if (amanda_header->type != F_TAPESTART) {
1003         device_set_error(pself, stralloc(_("Invalid amanda header")), DEVICE_STATUS_VOLUME_ERROR);
1004         return pself->status;
1005     }
1006
1007     pself->volume_label = g_strdup(amanda_header->name);
1008     pself->volume_time = g_strdup(amanda_header->datestamp);
1009     /* pself->volume_header is already set */
1010
1011     device_set_error(pself, NULL, DEVICE_STATUS_SUCCESS);
1012
1013     return pself->status;
1014 }
1015
1016 static gboolean 
1017 s3_device_start (Device * pself, DeviceAccessMode mode,
1018                  char * label, char * timestamp) {
1019     S3Device * self;
1020     int file, last_file;
1021
1022     self = S3_DEVICE(pself);
1023
1024     if (device_in_error(self)) return FALSE;
1025
1026     if (!setup_handle(self)) {
1027         device_set_error(pself,
1028             stralloc(_("Error setting up S3 interface")),
1029             DEVICE_STATUS_DEVICE_ERROR);
1030         return FALSE;
1031     }
1032
1033     pself->access_mode = mode;
1034     pself->in_file = FALSE;
1035
1036     /* try creating the bucket, in case it doesn't exist */
1037     if (mode != ACCESS_READ && !s3_make_bucket(self->s3, self->bucket)) {
1038         guint response_code;
1039         s3_error_code_t s3_error_code;
1040         s3_error(self->s3, NULL, &response_code, &s3_error_code, NULL, NULL, NULL);
1041
1042         /* if it isn't an expected error (bucket already exists),
1043          * return FALSE */
1044         if (response_code != 409 ||
1045             s3_error_code != S3_ERROR_BucketAlreadyExists) {
1046             device_set_error(pself,
1047                 vstrallocf(_("While creating new S3 bucket: %s"), s3_strerror(self->s3)),
1048                 DEVICE_STATUS_DEVICE_ERROR);
1049             return FALSE;
1050         }
1051     }
1052
1053     /* take care of any dirty work for this mode */
1054     switch (mode) {
1055         case ACCESS_READ:
1056             if (pself->volume_label == NULL && s3_device_read_label(pself) != DEVICE_STATUS_SUCCESS) {
1057                 /* s3_device_read_label already set our error message */
1058                 return FALSE;
1059             }
1060             break;
1061
1062         case ACCESS_WRITE:
1063             /* delete all files */
1064             last_file = find_last_file(self);
1065             if (last_file < 0) return FALSE;
1066             for (file = 0; file <= last_file; file++) {
1067                 if (!delete_file(self, file))
1068                     /* delete_file already set our error message */
1069                     return FALSE;
1070             }
1071
1072             /* write a new amanda header */
1073             if (!write_amanda_header(self, label, timestamp)) {
1074                 return FALSE;
1075             }
1076
1077             pself->volume_label = newstralloc(pself->volume_label, label);
1078             pself->volume_time = newstralloc(pself->volume_time, timestamp);
1079
1080             /* unset the VOLUME_UNLABELED flag, if it was set */
1081             device_set_error(pself, NULL, DEVICE_STATUS_SUCCESS);
1082             break;
1083
1084         case ACCESS_APPEND:
1085             if (pself->volume_label == NULL && s3_device_read_label(pself) != DEVICE_STATUS_SUCCESS) {
1086                 /* s3_device_read_label already set our error message */
1087                 return FALSE;
1088             }
1089             return seek_to_end(self);
1090             break;
1091
1092         case ACCESS_NULL:
1093             g_assert_not_reached();
1094     }
1095
1096     return TRUE;
1097 }
1098
1099 static gboolean
1100 s3_device_finish (Device * pself) {
1101     if (device_in_error(pself)) return FALSE;
1102
1103     /* we're not in a file anymore */
1104     pself->access_mode = ACCESS_NULL;
1105
1106     return TRUE;
1107 }
1108
1109 /* functions for writing */
1110
1111
1112 static gboolean
1113 s3_device_start_file (Device *pself, dumpfile_t *jobInfo) {
1114     S3Device *self = S3_DEVICE(pself);
1115     CurlBuffer amanda_header = {NULL, 0, 0, 0};
1116     gboolean header_fits, result;
1117     char *key;
1118
1119     if (device_in_error(self)) return FALSE;
1120
1121     /* Set the blocksize to zero, since there's no header to skip (it's stored
1122      * in a distinct file, rather than block zero) */
1123     jobInfo->blocksize = 0;
1124
1125     /* Build the amanda header. */
1126     amanda_header.buffer = device_build_amanda_header(pself, jobInfo,
1127         (int *) &amanda_header.buffer_len, &header_fits);
1128     if (!header_fits) {
1129         device_set_error(pself,
1130             stralloc(_("Amanda file header won't fit in a single block!")),
1131             DEVICE_STATUS_DEVICE_ERROR);
1132         return FALSE;
1133     }
1134
1135     /* set the file and block numbers correctly */
1136     pself->file = (pself->file > 0)? pself->file+1 : 1;
1137     pself->block = 0;
1138     pself->in_file = TRUE;
1139
1140     /* write it out as a special block (not the 0th) */
1141     key = special_file_to_key(self, "filestart", pself->file);
1142     result = s3_upload(self->s3, self->bucket, key, S3_BUFFER_READ_FUNCS,
1143                        &amanda_header, NULL, NULL);
1144     g_free(amanda_header.buffer);
1145     g_free(key);
1146     if (!result) {
1147         device_set_error(pself,
1148             vstrallocf(_("While writing filestart header: %s"), s3_strerror(self->s3)),
1149             DEVICE_STATUS_DEVICE_ERROR | DEVICE_STATUS_VOLUME_ERROR);
1150         return FALSE;
1151     }
1152
1153     return TRUE;
1154 }
1155
1156 static gboolean
1157 s3_device_write_block (Device * pself, guint size, gpointer data) {
1158     gboolean result;
1159     char *filename;
1160     S3Device * self = S3_DEVICE(pself);
1161     CurlBuffer to_write = {data, size, 0, 0};
1162
1163     g_assert (self != NULL);
1164     g_assert (data != NULL);
1165     if (device_in_error(self)) return FALSE;
1166     
1167     filename = file_and_block_to_key(self, pself->file, pself->block);
1168
1169     result = s3_upload(self->s3, self->bucket, filename, S3_BUFFER_READ_FUNCS,
1170         &to_write, NULL, NULL);
1171     g_free(filename);
1172     if (!result) {
1173         device_set_error(pself,
1174             vstrallocf(_("While writing data block to S3: %s"), s3_strerror(self->s3)),
1175             DEVICE_STATUS_DEVICE_ERROR | DEVICE_STATUS_VOLUME_ERROR);
1176         return FALSE;
1177     }
1178
1179     pself->block++;
1180
1181     return TRUE;
1182 }
1183
1184 static gboolean
1185 s3_device_finish_file (Device * pself) {
1186     if (device_in_error(pself)) return FALSE;
1187
1188     /* we're not in a file anymore */
1189     pself->in_file = FALSE;
1190
1191     return TRUE;
1192 }
1193
1194 static gboolean
1195 s3_device_recycle_file(Device *pself, guint file) {
1196     S3Device *self = S3_DEVICE(pself);
1197     if (device_in_error(self)) return FALSE;
1198
1199     return delete_file(self, file);
1200     /* delete_file already set our error message if necessary */
1201 }
1202
1203 /* functions for reading */
1204
1205 static dumpfile_t*
1206 s3_device_seek_file(Device *pself, guint file) {
1207     S3Device *self = S3_DEVICE(pself);
1208     gboolean result;
1209     char *key;
1210     CurlBuffer buf = {NULL, 0, 0, S3_DEVICE_MAX_BLOCK_SIZE};
1211     dumpfile_t *amanda_header;
1212     const char *errmsg = NULL;
1213
1214     if (device_in_error(self)) return NULL;
1215
1216     pself->file = file;
1217     pself->is_eof = FALSE;
1218     pself->in_file = FALSE;
1219     pself->block = 0;
1220
1221     /* read it in */
1222     key = special_file_to_key(self, "filestart", pself->file);
1223     result = s3_read(self->s3, self->bucket, key, S3_BUFFER_WRITE_FUNCS,
1224         &buf, NULL, NULL);
1225     g_free(key);
1226  
1227     if (!result) {
1228         guint response_code;
1229         s3_error_code_t s3_error_code;
1230         s3_error(self->s3, &errmsg, &response_code, &s3_error_code, NULL, NULL, NULL);
1231
1232         /* if it's an expected error (not found), check what to do. */
1233         if (response_code == 404 && s3_error_code == S3_ERROR_NoSuchKey) {
1234             int next_file;
1235             next_file = find_next_file(self, pself->file);
1236             if (next_file > 0) {
1237                 /* Note short-circut of dispatcher. */
1238                 return s3_device_seek_file(pself, next_file);
1239             } else if (next_file == 0) {
1240                 /* No next file. Check if we are one past the end. */
1241                 key = special_file_to_key(self, "filestart", pself->file - 1);
1242                 result = s3_read(self->s3, self->bucket, key,
1243                     S3_BUFFER_WRITE_FUNCS, &buf, NULL, NULL);
1244                 g_free(key);
1245                 if (result) {
1246                     /* pself->file, etc. are already correct */
1247                     return make_tapeend_header();
1248                 } else {
1249                     device_set_error(pself,
1250                         stralloc(_("Attempt to read past tape-end file")),
1251                         DEVICE_STATUS_SUCCESS);
1252                     return NULL;
1253                 }
1254             }
1255         } else {
1256             /* An unexpected error occured finding out if we are the last file. */
1257             device_set_error(pself,
1258                 stralloc(errmsg),
1259                 DEVICE_STATUS_DEVICE_ERROR);
1260             return NULL;
1261         }
1262     }
1263    
1264     /* and make a dumpfile_t out of it */
1265     g_assert(buf.buffer != NULL);
1266     amanda_header = g_new(dumpfile_t, 1);
1267     fh_init(amanda_header);
1268     parse_file_header(buf.buffer, amanda_header, buf.buffer_pos);
1269     g_free(buf.buffer);
1270
1271     switch (amanda_header->type) {
1272         case F_DUMPFILE:
1273         case F_CONT_DUMPFILE:
1274         case F_SPLIT_DUMPFILE:
1275             break;
1276
1277         default:
1278             device_set_error(pself,
1279                 stralloc(_("Invalid amanda header while reading file header")),
1280                 DEVICE_STATUS_VOLUME_ERROR);
1281             g_free(amanda_header);
1282             return NULL;
1283     }
1284
1285     pself->in_file = TRUE;
1286     return amanda_header;
1287 }
1288
1289 static gboolean
1290 s3_device_seek_block(Device *pself, guint64 block) {
1291     if (device_in_error(pself)) return FALSE;
1292
1293     pself->block = block;
1294     return TRUE;
1295 }
1296
1297 typedef struct s3_read_block_data {
1298     gpointer data;
1299     int size_req;
1300     int size_written;
1301
1302     CurlBuffer curl;
1303 } s3_read_block_data;
1304
1305 /* wrapper around s3_buffer_write_func to write as much data as possible to
1306  * the user's buffer, and switch to a dynamically allocated buffer if that
1307  * isn't large enough */
1308 static size_t
1309 s3_read_block_write_func(void *ptr, size_t size, size_t nmemb, void *stream)
1310 {
1311     s3_read_block_data *dat = stream;
1312     guint new_bytes, bytes_needed;
1313
1314     /* if data is NULL, call through to s3_buffer_write_func */
1315     if (!dat->data) {
1316         return s3_buffer_write_func(ptr, size, nmemb, (void *)(&dat->curl));
1317     }
1318
1319     new_bytes = (guint) size * nmemb;
1320     bytes_needed = dat->size_written + new_bytes;
1321
1322     if (bytes_needed > (guint)dat->size_written) {
1323         /* this read will overflow the user's buffer, so malloc ourselves
1324          * a new buffer and keep reading */
1325         dat->curl.buffer = g_malloc(bytes_needed);
1326         dat->curl.buffer_len = bytes_needed;
1327         dat->curl.buffer_pos = dat->size_written;
1328         memcpy(dat->curl.buffer, dat->data, dat->size_written);
1329         dat->data = NULL; /* signal that the user's buffer is too small */
1330         return s3_buffer_write_func(ptr, size, nmemb, (void *)(&dat->curl));
1331     }
1332
1333     memcpy(dat->data + dat->size_written, ptr, bytes_needed);
1334     return new_bytes;
1335 }
1336
1337 static int
1338 s3_device_read_block (Device * pself, gpointer data, int *size_req) {
1339     S3Device * self = S3_DEVICE(pself);
1340     char *key;
1341     s3_read_block_data dat = {NULL, 0, 0, { NULL, 0, 0, S3_DEVICE_MAX_BLOCK_SIZE} };
1342     gboolean result;
1343
1344     g_assert (self != NULL);
1345     if (device_in_error(self)) return -1;
1346
1347     /* get the file*/
1348     key = file_and_block_to_key(self, pself->file, pself->block);
1349     g_assert(key != NULL);
1350     if (self->cached_key && (0 == strcmp(key, self->cached_key))) {
1351         if (*size_req >= self->cached_size) {
1352             /* use the cached copy and clear the cache */
1353             memcpy(data, self->cached_buf, self->cached_size);
1354             *size_req = self->cached_size;
1355
1356             g_free(key);
1357             g_free(self->cached_key);
1358             self->cached_key = NULL;
1359             g_free(self->cached_buf);
1360             self->cached_buf = NULL;
1361
1362             pself->block++;
1363             return *size_req;
1364         } else {
1365             *size_req = self->cached_size;
1366             g_free(key);
1367             return 0;
1368         }
1369     }
1370
1371     /* clear the cache, as it's useless to us */
1372     if (self->cached_key) {
1373         g_free(self->cached_key);
1374         self->cached_key = NULL;
1375
1376         g_free(self->cached_buf);
1377         self->cached_buf = NULL;
1378     }
1379
1380     /* set up dat for the write_func callback */
1381     if (!data || *size_req <= 0) {
1382         dat.data = NULL;
1383         dat.size_req = 0;
1384     } else {
1385         dat.data = data;
1386         dat.size_req = *size_req;
1387     }
1388
1389     result = s3_read(self->s3, self->bucket, key, s3_read_block_write_func,
1390         s3_buffer_reset_func, &dat, NULL, NULL);
1391     if (!result) {
1392         guint response_code;
1393         s3_error_code_t s3_error_code;
1394         s3_error(self->s3, NULL, &response_code, &s3_error_code, NULL, NULL, NULL);
1395
1396         g_free(key);
1397         key = NULL;
1398
1399         /* if it's an expected error (not found), just return -1 */
1400         if (response_code == 404 && s3_error_code == S3_ERROR_NoSuchKey) {
1401             pself->is_eof = TRUE;
1402             pself->in_file = FALSE;
1403             device_set_error(pself,
1404                 stralloc(_("EOF")),
1405                 DEVICE_STATUS_SUCCESS);
1406             return -1;
1407         }
1408
1409         /* otherwise, log it and return FALSE */
1410         device_set_error(pself,
1411             vstrallocf(_("While reading data block from S3: %s"), s3_strerror(self->s3)),
1412             DEVICE_STATUS_VOLUME_ERROR);
1413         return -1;
1414     }
1415
1416     if (dat.data == NULL) {
1417         /* data was larger than the available space, so cache it and return
1418          * the actual size */
1419         self->cached_buf = dat.curl.buffer;
1420         self->cached_size = dat.curl.buffer_pos;
1421         self->cached_key = key;
1422         key = NULL;
1423
1424         *size_req = dat.curl.buffer_pos;
1425         return 0;
1426     }
1427
1428     /* ok, the read went directly to the user's buffer, so we need only
1429      * set and return the size */
1430     pself->block++;
1431     g_free(key);
1432     *size_req = dat.size_req;
1433     return dat.size_req;
1434 }