Code

Fix compilation with GCC when _GNU_SOURCE isn't defined.
[sysdb.git] / src / utils / os.c
index 4afc466683138aed81667a446638698bbe96da91..8ab52c75bc023c2bc5b68ca61d2cc0f13ce0f916 100644 (file)
 #include <errno.h>
 
 #include <sys/types.h>
+#include <sys/select.h>
 #include <sys/socket.h>
 #include <sys/stat.h>
+#include <sys/time.h>
+#include <sys/types.h>
 
 #include <dirent.h>
 
 #include <libgen.h>
 #include <netdb.h>
 #include <pwd.h>
+#include <time.h>
 
 /*
  * public API
  */
 
+char *
+sdb_get_homedir(void)
+{
+       char *username = sdb_get_current_user();
+
+       struct passwd pw_entry;
+       struct passwd *result = NULL;
+
+       char buf[4096];
+
+       int status;
+
+       if (username) {
+               memset(&pw_entry, 0, sizeof(pw_entry));
+               status = getpwnam_r(username, &pw_entry, buf, sizeof(buf), &result);
+       }
+       else
+               status = -1;
+
+       if (status || (! result)) {
+               char errbuf[1024];
+               sdb_log(SDB_LOG_WARNING, "os: Failed to determine home directory "
+                               "for user %s: %s", username,
+                               sdb_strerror(errno, errbuf, sizeof(errbuf)));
+               free(username);
+               return NULL;
+       }
+       free(username);
+       return strdup(result->pw_dir);
+} /* sdb_get_homedir */
+
+char *
+sdb_realpath(const char *path)
+{
+       if (! path)
+               return NULL;
+
+       if ((strlen(path) >= 2) && (path[0] == '~') && (path[1] == '/')) {
+               char *homedir = sdb_get_homedir();
+               char tmp[(homedir ? strlen(homedir) : 0) + strlen(path)];
+               char *ret;
+
+               if (! homedir)
+                       return NULL;
+
+               snprintf(tmp, sizeof(tmp), "%s/%s", homedir, path + 2);
+               ret = realpath(tmp, NULL);
+               free(homedir);
+               return ret;
+       }
+
+       return realpath(path, NULL);
+} /* sdb_realpath */
+
 int
 sdb_mkdir_all(const char *pathname, mode_t mode)
 {
@@ -152,7 +210,7 @@ sdb_get_current_user(void)
 
        uid_t uid;
 
-       char buf[1024];
+       char buf[4096];
        int status;
 
        uid = geteuid();
@@ -265,7 +323,7 @@ sdb_resolve(int network, const char *address, struct addrinfo **res)
 
        if (address) {
                host = address;
-               port = strchr(host, ':');
+               port = strrchr(host, ':');
                if (port) {
                        *port = '\0';
                        ++port;