+ UCI_ASSERT(ctx, uci_validate_package(name));
+ filename = uci_malloc(ctx, strlen(name) + strlen(ctx->confdir) + 2);
+ sprintf(filename, "%s/%s", ctx->confdir, name);
+
+ return filename;
+}
+
+static void uci_file_commit(struct uci_context *ctx, struct uci_package **package, bool overwrite)
+{
+ struct uci_package *p = *package;
+ FILE *f1, *f2 = NULL;
+ char *name = NULL;
+ char *path = NULL;
+ char *filename = NULL;
+ struct stat statbuf;
+ bool do_rename = false;
+
+ if (!p->path) {
+ if (overwrite)
+ p->path = uci_config_path(ctx, p->e.name);
+ else
+ UCI_THROW(ctx, UCI_ERR_INVAL);
+ }
+
+ if ((asprintf(&filename, "%s/.%s.uci-XXXXXX", ctx->confdir, p->e.name) < 0) || !filename)
+ UCI_THROW(ctx, UCI_ERR_MEM);
+
+ if (!mktemp(filename))
+ *filename = 0;
+
+ if (!*filename) {
+ free(filename);
+ UCI_THROW(ctx, UCI_ERR_IO);
+ }
+
+ if ((stat(filename, &statbuf) == 0) && ((statbuf.st_mode & S_IFMT) != S_IFREG))
+ UCI_THROW(ctx, UCI_ERR_IO);
+
+ /* 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);