+ /* open the config file for writing now, so that it is locked */
+ f1 = uci_open_stream(ctx, p->path, NULL, SEEK_SET, true, true);
+
+ /* flush unsaved changes and reload from delta file */
+ UCI_TRAP_SAVE(ctx, done);
+ if (p->has_delta) {
+ if (!overwrite) {
+ name = uci_strdup(ctx, p->e.name);
+ path = uci_strdup(ctx, p->path);
+ /* dump our own changes to the delta file */
+ if (!uci_list_empty(&p->delta))
+ UCI_INTERNAL(uci_save, ctx, p);
+
+ /*
+ * other processes might have modified the config
+ * as well. dump and reload
+ */
+ uci_free_package(&p);
+ uci_cleanup(ctx);
+ UCI_INTERNAL(uci_import, ctx, f1, name, &p, true);
+
+ p->path = path;
+ p->has_delta = true;
+ *package = p;
+
+ /* freed together with the uci_package */
+ path = NULL;
+ }
+
+ /* flush delta */
+ if (!uci_load_delta(ctx, p, true))
+ goto done;
+ }
+
+ f2 = uci_open_stream(ctx, filename, p->path, SEEK_SET, true, true);
+ uci_export(ctx, f2, p, false);
+
+ fflush(f2);
+ fsync(fileno(f2));
+ uci_close_stream(f2);
+
+ do_rename = true;
+
+ UCI_TRAP_RESTORE(ctx);
+
+done:
+ free(name);
+ free(path);
+ uci_close_stream(f1);
+ if (do_rename && rename(filename, p->path)) {
+ unlink(filename);
+ UCI_THROW(ctx, UCI_ERR_IO);
+ }
+ free(filename);
+ sync();
+ if (ctx->err)
+ UCI_THROW(ctx, ctx->err);