- if(!fp) {
- logger(DEBUG_ALWAYS, LOG_ERR, "Cannot open config file %s: %s", fname, strerror(errno));
- } else {
- fprintf(fp, "\n# The following line was automatically added by tinc\n%s = %s\n", key, value);
- fclose(fp);
+ char filename[PATH_MAX];
+ char tmpname[PATH_MAX];
+ bool error = false;
+
+ snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
+ snprintf(tmpname, sizeof tmpname, "%s.tmp", filename);
+
+ FILE *fr = fopen(filename, "r");
+
+ if(!fr) {
+ logger(mesh, MESHLINK_ERROR, "Cannot open config file %s: %s", filename, strerror(errno));
+ return false;
+ }
+
+ FILE *fw = fopen(tmpname, "w");
+
+ if(!fw) {
+ logger(mesh, MESHLINK_ERROR, "Cannot open temporary file %s: %s", tmpname, strerror(errno));
+ fclose(fr);
+ return false;
+ }
+
+ char buf[4096];
+ char *sep;
+ bool found = false;
+
+ while(readline(fr, buf, sizeof buf)) {
+ if(!*buf || *buf == '#')
+ goto copy;
+
+ sep = strchr(buf, ' ');
+ if(!sep)
+ goto copy;
+
+ *sep = 0;
+ if(strcmp(buf, key)) {
+ *sep = ' ';
+ goto copy;
+ }
+
+ if(!value) {
+ found = true;
+ continue;
+ }
+
+ // We found the key and the value. Keep one copy around.
+ if(sep[1] == '=' && sep[2] == ' ' && !strcmp(sep + 3, value)) {
+ if(found)
+ continue;
+ found = true;
+ }
+
+ // We found the key but with a different value, delete it if wanted.
+ if(!found && replace)
+ continue;
+
+ *sep = ' ';
+
+copy:
+ fprintf(fw, "%s\n", buf);