1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
diff --git a/apps/scrobbler.c b/apps/scrobbler.c
index 891e635..c0948e5 100644
--- a/apps/scrobbler.c
+++ b/apps/scrobbler.c
@@ -108,14 +108,15 @@ static void write_cache(void)
     int i;
     int fd;
 
-    char scrobbler_file[MAX_PATH];
-    get_scrobbler_filename(scrobbler_file, MAX_PATH);
+    size_t buflen = MAX(MAX_PATH, SCROBBLER_CACHE_LEN);
+    char buf[buflen];
+    get_scrobbler_filename(buf, buflen);
 
     /* If the file doesn't exist, create it.
     Check at each write since file may be deleted at any time */
-    if(!file_exists(scrobbler_file))
+    if(!file_exists(buf))
     {
-        fd = open(scrobbler_file, O_RDWR | O_CREAT, 0666);
+        fd = open(buf, O_RDWR | O_CREAT, 0666);
         if(fd >= 0)
         {
             fdprintf(fd, "#AUDIOSCROBBLER/" SCROBBLER_VERSION "\n"
@@ -135,15 +136,19 @@ static void write_cache(void)
     }
 
     /* write the cache entries */
-    fd = open(scrobbler_file, O_WRONLY | O_APPEND);
+    fd = open(buf, O_WRONLY | O_APPEND);
     if(fd >= 0)
     {
         logf("SCROBBLER: writing %d entries", cache_pos); 
         char* scrobbler_buf = core_get_data(scrobbler_cache);
+        /* copy data to temporary storage in case data moves during I/O */
         for ( i=0; i < cache_pos; i++ )
         {
             logf("SCROBBLER: write %d", i);
-            fdprintf(fd, "%s", scrobbler_buf+(SCROBBLER_CACHE_LEN*i));
+            ssize_t len = strlcpy(buf, scrobbler_buf+(SCROBBLER_CACHE_LEN*i),
+                                        sizeof(buflen));
+            if (write(fd, buf, len) != len)
+                break;
         }
         close(fd);
     }