+static int mutt_update_list_file (char *filename, char *section,
+ const char *key, char *line) {
+ FILE *ifp;
+ FILE *ofp;
+ char buf[HUGE_STRING];
+ char tmpf[_POSIX_PATH_MAX], lnk[_POSIX_PATH_MAX];
+ char *c;
+ int ext = 0, done = 0, r = 0, l = 0;
+
+ /* if file not exist, create it */
+ if ((ifp = safe_fopen (filename, "a")))
+ m_fclose(&ifp);
+ if (!(ifp = safe_fopen (filename, "r"))) {
+ mutt_error (_("Unable to open %s for reading"), filename);
+ return -1;
+ }
+ if (mx_lock_file (filename, fileno (ifp), 0, 0, 1)) {
+ m_fclose(&ifp);
+ mutt_error (_("Unable to lock %s"), filename);
+ return -1;
+ }
+
+ /* use m_tempfile() to get a tempfile in the same
+ * directory as filename is so that we can follow symlinks
+ * via rename(2); as dirname(2) may modify its argument,
+ * temporarily use buf as copy of it
+ */
+ m_strcpy(buf, sizeof(buf), filename);
+ ofp = m_tempfile(tmpf, sizeof(tmpf), dirname(buf), filename);
+ if (!ofp) {
+ m_fclose(&ifp);
+ mutt_error (_("Unable to open %s for writing"), tmpf);
+ return -1;
+ }
+
+ if (section) {
+ while (r != EOF && !done && fgets (buf, sizeof (buf), ifp)) {
+ r = fputs (buf, ofp);
+ c = buf;
+ while (*c && *c != '\n') c++;
+ c[0] = 0; /* strip EOL */
+ if (!strncmp (buf, "#: ", 3) && !m_strcasecmp(buf+3, section))
+ done++;
+ }
+ if (r != EOF && !done) {
+ snprintf (buf, sizeof(buf), "#: %s\n", section);
+ r = fputs (buf, ofp);
+ }
+ done = 0;
+ }
+
+ while (r != EOF && fgets (buf, sizeof (buf), ifp)) {
+ if (ext) {
+ c = buf;
+ while (*c && (*c != '\r') && (*c != '\n')) c++;
+ c--;
+ if (*c != '\\') ext = 0;
+ } else if ((section && !strncmp (buf, "#: ", 3))) {
+ if (!done && line) {
+ fputs (line, ofp);
+ fputc ('\n', ofp);
+ }
+ r = fputs (buf, ofp);
+ done++;
+ break;
+ } else if (key && !strncmp (buf, key, strlen(key)) &&
+ (!*key || buf[strlen(key)] == ' ')) {
+ c = buf;
+ ext = 0;
+ while (*c && (*c != '\r') && (*c != '\n')) c++;
+ c--;
+ if (*c == '\\') ext = 1;
+ if (!done && line) {
+ r = fputs (line, ofp);
+ if (*key)
+ r = fputc ('\n', ofp);
+ done++;
+ }
+ } else {
+ r = fputs (buf, ofp);
+ }
+ }
+
+ while (r != EOF && fgets (buf, sizeof (buf), ifp))
+ r = fputs (buf, ofp);
+
+ /* If there wasn't a line to replace, put it on the end of the file */
+ if (r != EOF && !done && line) {
+ fputs (line, ofp);
+ r = fputc ('\n', ofp);
+ }
+ mx_unlock_file (filename, fileno (ifp), 0);
+ m_fclose(&ofp);
+ m_fclose(&ifp);
+ if (r == EOF) {
+ unlink (tmpf);
+ mutt_error (_("Can't write %s"), tmpf);
+ return -1;
+ }
+ lnk[0] = '\0';
+ if ((l = readlink (filename, lnk, sizeof(lnk)-1)) > 0)
+ lnk[l] = '\0';
+ if (rename (tmpf, l > 0 ? lnk : filename) < 0) {
+ unlink (tmpf);
+ mutt_error (_("Can't rename %s to %s"), tmpf, l > 0 ? lnk : filename);
+ return -1;
+ }
+ return 0;
+}
+