return r;
}
-char* pakfire_key_dump(struct pakfire_key* key) {
+char* pakfire_key_dump(struct pakfire_key* key, size_t* length) {
char* buffer = NULL;
FILE* f = NULL;
- int fd = -EBADF;
int r;
- // Allocate a buffer in memory
- fd = memfd_create("pakfire-key-dump", MFD_CLOEXEC);
- if (fd < 0) {
- ERROR(key->ctx, "Could not allocate a temporary file: %m\n");
- r = -errno;
- goto ERROR;
- }
-
- // Re-open as FILE handle
- f = fdopen(fd, "r+");
+ // Create a file handle to write to the buffer
+ f = open_memstream(&buffer, length);
if (!f) {
- ERROR(key->ctx, "Could not open file handle for temporary file: %m\n");
+ ERROR(key->ctx, "Could not open a new memstream: %m\n");
r = -errno;
goto ERROR;
}
goto ERROR;
}
- // Determine the length of the buffer
- size_t length = ftell(f);
-
- // Go back to the beginning of the file
- r = pakfire_rewind(f);
- if (r < 0) {
- ERROR(key->ctx, "Could not rewind buffer: %m\n");
- r = -errno;
- goto ERROR;
- }
-
- // Allocate a buffer
- buffer = calloc(1, length + 1);
- if (!buffer) {
- ERROR(key->ctx, "Could not allocate buffer of %zu byte(s)\n", length + 1);
- r = -errno;
- goto ERROR;
- }
-
- // Read everything into the buffer
- size_t bytes_read = fread(buffer, 1, length, f);
- if (bytes_read < length) {
- ERROR(key->ctx, "Could not read back the buffer: %m\n");
- r = -errno;
- goto ERROR;
- }
-
- // Success!
- r = 0;
-
ERROR:
if (f)
fclose(f);
- if (fd >= 0)
- close(fd);
// Free the buffer on error
if (r && buffer) {
int pakfire_key_export(struct pakfire_key* key, FILE* f, const pakfire_key_export_mode_t mode);
int pakfire_key_import(struct pakfire_key** key, struct pakfire_ctx* ctx, FILE* f);
-char* pakfire_key_dump(struct pakfire_key* key);
+char* pakfire_key_dump(struct pakfire_key* key, size_t* length);
// Sign
int pakfire_key_sign(struct pakfire_key* key,
}
static PyObject* Key_str(KeyObject* self) {
- char* string = pakfire_key_dump(self->key);
+ PyObject* ret = NULL;
+ char* string = NULL;
+ size_t length = 0;
- PyObject* object = PyUnicode_FromString(string);
+ // Dump the key
+ string = pakfire_key_dump(self->key, &length);
+ if (!string) {
+ PyErr_SetFromErrno(PyExc_OSError);
+ return NULL;
+ }
+
+ // Parse the string
+ ret = PyUnicode_FromStringAndSize(string, length);
free(string);
- return object;
+ return ret;
}
static PyObject* Key_get_id(KeyObject* self) {