summary refs log tree commit diff
path: root/notemap.c
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--notemap.c52
1 files changed, 22 insertions, 30 deletions
diff --git a/notemap.c b/notemap.c
index 68e0484..9d65a9a 100644
--- a/notemap.c
+++ b/notemap.c
@@ -164,33 +164,24 @@ static char *format(const char *from, const char *uuid, const char *path) {
 		localtime(&status.st_mtime)
 	);
 
-#define HEADERS \
-	"From: <%s>\r\n" \
-	"Date: %s\r\n" \
-	"X-Universally-Unique-Identifier: %s\r\n" \
-	"X-Uniform-Type-Identifier: com.apple.mail-note\r\n" \
-	"X-Mailer: notemap\r\n" \
-	"MIME-Version: 1.0\r\n" \
-	"Content-Type: text/plain; charset=\"utf-8\"\r\n" \
-	"Content-Transfer-Encoding: quoted-printable\r\n" \
-	"Subject: =?utf-8?Q?"
-#define HEADERS_END "?=\r\n\r\n"
-
-	size_t max = sizeof(HEADERS)
-		+ strlen(from)
-		+ strlen(date)
-		+ strlen(uuid)
-		+ 3 * strlen(path)
-		+ sizeof(HEADERS_END)
-		+ 3 * status.st_size
-		+ 3 * status.st_size / 76;
-	char *buf = malloc(max);
-	if (!buf) err(EX_OSERR, "malloc");
-
-	FILE *msg = fmemopen(buf, max, "w");
-	if (!msg) err(EX_OSERR, "fmemopen");
-	fprintf(msg, HEADERS, from, date, uuid);
-
+	char *buf;
+	size_t buflen;
+	FILE *msg = open_memstream(&buf, &buflen);
+	if (!msg) err(EX_OSERR, "open_memstream");
+
+	fprintf(
+		msg,
+		"From: <%s>\r\n"
+		"Date: %s\r\n"
+		"X-Universally-Unique-Identifier: %s\r\n"
+		"X-Uniform-Type-Identifier: com.apple.mail-note\r\n"
+		"X-Mailer: notemap\r\n"
+		"MIME-Version: 1.0\r\n"
+		"Content-Type: text/plain; charset=\"utf-8\"\r\n"
+		"Content-Transfer-Encoding: quoted-printable\r\n"
+		"Subject: =?utf-8?Q?",
+		from, date, uuid
+	);
 	for (const char *ch = path; *ch; ++ch) {
 		if ((uint8_t)*ch & 0x80) {
 			fprintf(msg, "=%02hhX", (uint8_t)*ch);
@@ -200,7 +191,7 @@ static char *format(const char *from, const char *uuid, const char *path) {
 			fprintf(msg, "%c", *ch);
 		}
 	}
-	fprintf(msg, HEADERS_END);
+	fprintf(msg, "?=\r\n\r\n");
 
 	int ch;
 	int len = 0;
@@ -224,9 +215,10 @@ static char *format(const char *from, const char *uuid, const char *path) {
 	}
 	if (ferror(note)) err(EX_IOERR, "%s", path);
 	fclose(note);
-	fclose(msg);
 
-	buf[max - 1] = '\0';
+	error = fclose(msg);
+	if (error) err(EX_IOERR, "fclose");
+
 	return buf;
 }