- 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);
+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++;