chiark / gitweb /
sd-login: teach sd_pid_get_unit() proper handling of instantiated services
[elogind.git] / src / login / sd-login.c
index 8893b1de80cfa4449850a9a08b7e424c6d334d2e..eb1a4b910a46e87020ae3c1fde798a66209cf856 100644 (file)
@@ -123,7 +123,8 @@ _public_ int sd_pid_get_session(pid_t pid, char **session) {
 
 _public_ int sd_pid_get_unit(pid_t pid, char **unit) {
         int r;
 
 _public_ int sd_pid_get_unit(pid_t pid, char **unit) {
         int r;
-        char *cgroup, *p;
+        char *cgroup, *p, *at, *b;
+        size_t k;
 
         if (!unit)
                 return -EINVAL;
 
         if (!unit)
                 return -EINVAL;
@@ -138,13 +139,37 @@ _public_ int sd_pid_get_unit(pid_t pid, char **unit) {
         }
 
         p = cgroup + 8;
         }
 
         p = cgroup + 8;
-        p = strndup(p, strcspn(p, "/"));
+        k = strcspn(p, "/");
+
+        at = memchr(p, '@', k);
+        if (at && at[1] == '.') {
+                size_t j;
+
+                /* This is a templated service */
+                if (p[k] != '/') {
+                        free(cgroup);
+                        return -EIO;
+                }
+
+                j = strcspn(p+k+1, "/");
+
+                b = malloc(k + j + 1);
+
+                if (b) {
+                        memcpy(b, p, at - p + 1);
+                        memcpy(b + (at - p) + 1, p + k + 1, j);
+                        memcpy(b + (at - p) + 1 + j, at + 1, k - (at - p) - 1);
+                        b[k+j] = 0;
+                }
+        } else
+                  b = strndup(p, k);
+
         free(cgroup);
 
         free(cgroup);
 
-        if (!p)
+        if (!b)
                 return -ENOMEM;
 
                 return -ENOMEM;
 
-        *unit = p;
+        *unit = b;
         return 0;
 }
 
         return 0;
 }
 
@@ -415,6 +440,34 @@ _public_ int sd_session_get_seat(const char *session, char **seat) {
         return 0;
 }
 
         return 0;
 }
 
+_public_ int sd_session_get_service(const char *session, char **service) {
+        char *p, *s = NULL;
+        int r;
+
+        if (!session)
+                return -EINVAL;
+        if (!service)
+                return -EINVAL;
+
+        p = strappend("/run/systemd/sessions/", session);
+        if (!p)
+                return -ENOMEM;
+
+        r = parse_env_file(p, NEWLINE, "SERVICE", &s, NULL);
+        free(p);
+
+        if (r < 0) {
+                free(s);
+                return r;
+        }
+
+        if (isempty(s))
+                return -ENOENT;
+
+        *service = s;
+        return 0;
+}
+
 _public_ int sd_seat_get_active(const char *seat, char **session, uid_t *uid) {
         char *p, *s = NULL, *t = NULL;
         int r;
 _public_ int sd_seat_get_active(const char *seat, char **session, uid_t *uid) {
         char *p, *s = NULL, *t = NULL;
         int r;