Code

utils/os: Added sdb_get_current_user().
[sysdb.git] / src / utils / os.c
index 08cb188d172355126d16f80ed4ae096aad47ff06..e3f1fe2d42bb61d072940949a7ddee345836d4f6 100644 (file)
 #endif /* HAVE_CONFIG_H */
 
 #include "utils/os.h"
+#include "utils/error.h"
 
 #include <errno.h>
 
 #include <sys/types.h>
 #include <sys/stat.h>
 
+#include <dirent.h>
+
 #include <stdlib.h>
+#include <stdio.h>
 #include <string.h>
 #include <unistd.h>
 
 #include <libgen.h>
+#include <pwd.h>
 
 /*
  * public API
@@ -86,5 +91,80 @@ sdb_mkdir_all(const char *pathname, mode_t mode)
        return status;
 } /* sdb_mkdir_all */
 
+int
+sdb_remove_all(const char *pathname)
+{
+       struct stat st;
+
+       if ((! pathname) || (! *pathname)) {
+               errno = EINVAL;
+               return -1;
+       }
+
+       memset(&st, 0, sizeof(st));
+       if (stat(pathname, &st))
+               return -1;
+
+       if (S_ISDIR(st.st_mode)) {
+               DIR *d = opendir(pathname);
+
+               if (! d)
+                       return -1;
+
+               while (42) {
+                       struct dirent de;
+                       struct dirent *res = NULL;
+
+                       char filename[strlen(pathname) + sizeof(de.d_name) + 2];
+
+                       memset(&de, 0, sizeof(de));
+                       if (readdir_r(d, &de, &res)) {
+                               closedir(d);
+                               return -1;
+                       }
+
+                       if (! res)
+                               break;
+
+                       if ((de.d_name[0] == '.') && ((de.d_name[1] == '\0')
+                                               || ((de.d_name[1] == '.')&& (de.d_name[2] == '\0'))))
+                               continue;
+
+                       snprintf(filename, sizeof(filename),
+                                       "%s/%s", pathname, de.d_name);
+                       if (sdb_remove_all(filename)) {
+                               closedir(d);
+                               return -1;
+                       }
+               }
+               closedir(d);
+       }
+       return remove(pathname);
+} /* sdb_remove_all */
+
+char *
+sdb_get_current_user(void)
+{
+       struct passwd pw_entry;
+       struct passwd *result = NULL;
+
+       uid_t uid;
+
+       char buf[1024];
+       int status;
+
+       uid = geteuid();
+       memset(&pw_entry, 0, sizeof(pw_entry));
+       status = getpwuid_r(uid, &pw_entry, buf, sizeof(buf), &result);
+
+       if (status || (! result)) {
+               char errbuf[1024];
+               sdb_log(SDB_LOG_ERR, "Failed to determine current username: %s",
+                               sdb_strerror(errno, errbuf, sizeof(errbuf)));
+               return NULL;
+       }
+       return strdup(result->pw_name);
+} /* sdb_get_current_user */
+
 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */