+bool modify_config_file(struct meshlink_handle *mesh, const char *name, const char *key, const char *value, int trim) {
+ assert(mesh && name && key);
+
+ char filename[PATH_MAX];
+ char tmpname[PATH_MAX];
+ bool error = false;
+
+ if(snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name) >= PATH_MAX) {
+ logger(mesh, MESHLINK_ERROR, "Filename too long: %s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
+ return false;
+ }
+
+ if(snprintf(tmpname, sizeof(tmpname), "%s.tmp", filename) >= PATH_MAX) {
+ logger(mesh, MESHLINK_ERROR, "Filename too long: %s.tmp", filename);
+ return false;
+ }
+
+ 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;
+ int found = 0;
+
+ if(value) {
+ fprintf(fw, "%s = %s\n", key, value);
+ found++;
+ }
+
+ 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;
+ }
+
+ // We found the key and the value. We already added it at the top, so ignore this one.
+ if(value && sep[1] == '=' && sep[2] == ' ' && !strcmp(sep + 3, value)) {
+ continue;
+ }
+
+ // We found the key but with a different value, delete it if wanted.
+ found++;
+
+ if((!value || trim) && found > trim) {
+ continue;
+ }
+
+ *sep = ' ';
+
+copy:
+ fprintf(fw, "%s\n", buf);