+ 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);
+
+ 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);
+}
+
+
+/*
+ * This function returns the filename by returning the string
+ * after the last '/' character. By checking for a non-'\0'
+ * character afterwards, directories are ignored (glob marks
+ * those with a trailing '/'
+ */
+static inline char *get_filename(char *path)
+{
+ char *p;
+
+ p = strrchr(path, '/');
+ p++;
+ if (!*p)
+ return NULL;
+ return p;
+}
+
+static char **uci_list_config_files(struct uci_context *ctx)
+{
+ char **configs;
+ glob_t globbuf;
+ int size, i;
+ char *buf;
+ char *dir;
+
+ dir = uci_malloc(ctx, strlen(ctx->confdir) + 1 + sizeof("/*"));
+ sprintf(dir, "%s/*", ctx->confdir);
+ if (glob(dir, GLOB_MARK, NULL, &globbuf) != 0) {
+ free(dir);
+ UCI_THROW(ctx, UCI_ERR_NOTFOUND);
+ }
+
+ size = sizeof(char *) * (globbuf.gl_pathc + 1);
+ for(i = 0; i < globbuf.gl_pathc; i++) {
+ char *p;
+
+ p = get_filename(globbuf.gl_pathv[i]);
+ if (!p)
+ continue;
+
+ size += strlen(p) + 1;
+ }
+
+ configs = uci_malloc(ctx, size);
+ buf = (char *) &configs[globbuf.gl_pathc + 1];
+ for(i = 0; i < globbuf.gl_pathc; i++) {
+ char *p;
+
+ p = get_filename(globbuf.gl_pathv[i]);
+ if (!p)
+ continue;
+
+ if (!uci_validate_package(p))
+ continue;
+
+ configs[i] = buf;
+ strcpy(buf, p);
+ buf += strlen(buf) + 1;
+ }
+ free(dir);
+ globfree(&globbuf);
+ return configs;
+}
+
+static struct uci_package *uci_file_load(struct uci_context *ctx, const char *name)
+{
+ struct uci_package *package = NULL;
+ char *filename;
+ bool confdir;
+ FILE *file = NULL;