305f583
From ed83954ce404d0e58a04dfe7bfd379203f7830b5 Mon Sep 17 00:00:00 2001
305f583
From: Kalev Lember <kalev@smartlink.ee>
305f583
Date: Thu, 23 Jun 2011 21:58:56 +0300
305f583
Subject: [PATCH 1/3] Support systemd socket activation
305f583
305f583
Add systemd socket-based activation support to pcscd as an alternative
305f583
to the existing autostart code which used forking from the user space
305f583
library. Systemd socket activation makes it possible to start pcscd on
305f583
demand by systemd when a request is sent on the IPC socket.
305f583
305f583
The implementation uses the $LISTEN_FDS/$LISTEN_PID env var parsing code
305f583
from systemd's sd-daemon.[ch] copy library.
305f583
---
305f583
 PCSC/src/Makefile.am        |    6 +
305f583
 PCSC/src/pcscdaemon.c       |   56 ++++--
305f583
 PCSC/src/sd-daemon.c        |  520 +++++++++++++++++++++++++++++++++++++++++++
305f583
 PCSC/src/sd-daemon.h        |  277 +++++++++++++++++++++++
305f583
 PCSC/src/winscard_msg.h     |    1 +
305f583
 PCSC/src/winscard_msg_srv.c |   25 ++
305f583
 6 files changed, 870 insertions(+), 15 deletions(-)
305f583
 create mode 100644 PCSC/src/sd-daemon.c
305f583
 create mode 100644 PCSC/src/sd-daemon.h
305f583
305f583
diff --git a/PCSC/src/Makefile.am b/PCSC/src/Makefile.am
305f583
index 2bd2f11..1b70466 100644
305f583
--- a/PCSC/src/Makefile.am
305f583
+++ b/PCSC/src/Makefile.am
305f583
@@ -67,6 +67,8 @@ pcscd_SOURCES = \
305f583
 	prothandler.h \
305f583
 	readerfactory.c \
305f583
 	readerfactory.h \
305f583
+	sd-daemon.c \
305f583
+	sd-daemon.h \
305f583
 	simclist.c \
305f583
 	simclist.h \
305f583
 	strlcat.c \
305f583
@@ -95,6 +97,10 @@ fix-rights: install-sbinPROGRAMS
305f583
 	chgrp pcscd $(DESTDIR)$(sbindir)/pcscd
305f583
 	chmod g+s $(DESTDIR)$(sbindir)/pcscd
305f583
 
305f583
+update-systemd:
305f583
+	curl http://cgit.freedesktop.org/systemd/plain/src/sd-daemon.c > sd-daemon.c
305f583
+	curl http://cgit.freedesktop.org/systemd/plain/src/sd-daemon.h > sd-daemon.h
305f583
+
305f583
 testpcsc_SOURCES = testpcsc.c
305f583
 testpcsc_LDADD = libpcsclite.la
305f583
 
305f583
diff --git a/PCSC/src/pcscdaemon.c b/PCSC/src/pcscdaemon.c
305f583
index 6abc328..609f981 100644
305f583
--- a/PCSC/src/pcscdaemon.c
305f583
+++ b/PCSC/src/pcscdaemon.c
305f583
@@ -37,6 +37,7 @@
305f583
 #include "pcsclite.h"
305f583
 #include "pcscd.h"
305f583
 #include "debuglog.h"
305f583
+#include "sd-daemon.h"
305f583
 #include "winscard_msg.h"
305f583
 #include "winscard_svc.h"
305f583
 #include "sys_generic.h"
305f583
@@ -54,6 +55,7 @@
305f583
 char AraKiri = FALSE;
305f583
 static char Init = TRUE;
305f583
 char AutoExit = FALSE;
305f583
+char SocketActivated = FALSE;
305f583
 static int ExitValue = EXIT_FAILURE;
305f583
 int HPForceReaderPolling = 0;
305f583
 static int pipefd[] = {-1, -1};
305f583
@@ -316,6 +318,20 @@ int main(int argc, char **argv)
305f583
 	}
305f583
 
305f583
 	/*
305f583
+	 * Check if systemd passed us any file descriptors
305f583
+	 */
305f583
+	rv = sd_listen_fds(0);
305f583
+	if (rv > 1)
305f583
+	{
305f583
+		Log1(PCSC_LOG_CRITICAL, "Too many file descriptors received");
305f583
+		return EXIT_FAILURE;
305f583
+	}
305f583
+	else if (rv == 1)
305f583
+		SocketActivated = TRUE;
305f583
+	else
305f583
+		SocketActivated = FALSE;
305f583
+
305f583
+	/*
305f583
 	 * test the presence of /var/run/pcscd/pcscd.comm
305f583
 	 */
305f583
 
305f583
@@ -366,16 +382,19 @@ int main(int argc, char **argv)
305f583
 				return EXIT_FAILURE;
305f583
 			}
305f583
 
305f583
-			Log1(PCSC_LOG_CRITICAL,
305f583
-				"file " PCSCLITE_CSOCK_NAME " already exists.");
305f583
-			Log1(PCSC_LOG_CRITICAL,
305f583
-				"Maybe another pcscd is running?");
305f583
-			Log1(PCSC_LOG_CRITICAL,
305f583
-				"I can't read process pid from " PCSCLITE_RUN_PID);
305f583
-			Log1(PCSC_LOG_CRITICAL, "Remove " PCSCLITE_CSOCK_NAME);
305f583
-			Log1(PCSC_LOG_CRITICAL,
305f583
-				"if pcscd is not running to clear this message.");
305f583
-			return EXIT_FAILURE;
305f583
+			if (!SocketActivated)
305f583
+			{
305f583
+				Log1(PCSC_LOG_CRITICAL,
305f583
+					"file " PCSCLITE_CSOCK_NAME " already exists.");
305f583
+				Log1(PCSC_LOG_CRITICAL,
305f583
+					"Maybe another pcscd is running?");
305f583
+				Log1(PCSC_LOG_CRITICAL,
305f583
+					"I can't read process pid from " PCSCLITE_RUN_PID);
305f583
+				Log1(PCSC_LOG_CRITICAL, "Remove " PCSCLITE_CSOCK_NAME);
305f583
+				Log1(PCSC_LOG_CRITICAL,
305f583
+					"if pcscd is not running to clear this message.");
305f583
+				return EXIT_FAILURE;
305f583
+			}
305f583
 		}
305f583
 	}
305f583
 	else
305f583
@@ -568,7 +587,11 @@ int main(int argc, char **argv)
305f583
 	/*
305f583
 	 * Initialize the comm structure
305f583
 	 */
305f583
-	rv = InitializeSocket();
305f583
+	if (SocketActivated)
305f583
+		rv = ListenExistingSocket(SD_LISTEN_FDS_START + 0);
305f583
+	else
305f583
+		rv = InitializeSocket();
305f583
+
305f583
 	if (rv)
305f583
 	{
305f583
 		Log1(PCSC_LOG_CRITICAL, "Error initializing pcscd.");
305f583
@@ -652,10 +675,13 @@ static void clean_temp_files(void)
305f583
 {
305f583
 	int rv;
305f583
 
305f583
-	rv = remove(PCSCLITE_CSOCK_NAME);
305f583
-	if (rv != 0)
305f583
-		Log2(PCSC_LOG_ERROR, "Cannot remove " PCSCLITE_CSOCK_NAME ": %s",
305f583
-			strerror(errno));
305f583
+	if (!SocketActivated)
305f583
+	{
305f583
+		rv = remove(PCSCLITE_CSOCK_NAME);
305f583
+		if (rv != 0)
305f583
+			Log2(PCSC_LOG_ERROR, "Cannot remove " PCSCLITE_CSOCK_NAME ": %s",
305f583
+				strerror(errno));
305f583
+	}
305f583
 
305f583
 	rv = remove(PCSCLITE_RUN_PID);
305f583
 	if (rv != 0)
305f583
diff --git a/PCSC/src/sd-daemon.c b/PCSC/src/sd-daemon.c
305f583
new file mode 100644
305f583
index 0000000..a2ec74c
305f583
--- /dev/null
305f583
+++ b/PCSC/src/sd-daemon.c
305f583
@@ -0,0 +1,520 @@
305f583
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
305f583
+
305f583
+/***
305f583
+  Copyright 2010 Lennart Poettering
305f583
+
305f583
+  Permission is hereby granted, free of charge, to any person
305f583
+  obtaining a copy of this software and associated documentation files
305f583
+  (the "Software"), to deal in the Software without restriction,
305f583
+  including without limitation the rights to use, copy, modify, merge,
305f583
+  publish, distribute, sublicense, and/or sell copies of the Software,
305f583
+  and to permit persons to whom the Software is furnished to do so,
305f583
+  subject to the following conditions:
305f583
+
305f583
+  The above copyright notice and this permission notice shall be
305f583
+  included in all copies or substantial portions of the Software.
305f583
+
305f583
+  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
305f583
+  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
305f583
+  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
305f583
+  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
305f583
+  BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
305f583
+  ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
305f583
+  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
305f583
+  SOFTWARE.
305f583
+***/
305f583
+
305f583
+#ifndef _GNU_SOURCE
305f583
+#define _GNU_SOURCE
305f583
+#endif
305f583
+
305f583
+#include <sys/types.h>
305f583
+#include <sys/stat.h>
305f583
+#include <sys/socket.h>
305f583
+#include <sys/un.h>
305f583
+#include <sys/fcntl.h>
305f583
+#include <netinet/in.h>
305f583
+#include <stdlib.h>
305f583
+#include <errno.h>
305f583
+#include <unistd.h>
305f583
+#include <string.h>
305f583
+#include <stdarg.h>
305f583
+#include <stdio.h>
305f583
+#include <stddef.h>
305f583
+#include <limits.h>
305f583
+
305f583
+#if defined(__linux__)
305f583
+#include <mqueue.h>
305f583
+#endif
305f583
+
305f583
+#include "sd-daemon.h"
305f583
+
305f583
+#if (__GNUC__ >= 4) && !defined(SD_EXPORT_SYMBOLS)
305f583
+#define _sd_hidden_ __attribute__ ((visibility("hidden")))
305f583
+#else
305f583
+#define _sd_hidden_
305f583
+#endif
305f583
+
305f583
+_sd_hidden_ int sd_listen_fds(int unset_environment) {
305f583
+
305f583
+#if defined(DISABLE_SYSTEMD) || !defined(__linux__)
305f583
+        return 0;
305f583
+#else
305f583
+        int r, fd;
305f583
+        const char *e;
305f583
+        char *p = NULL;
305f583
+        unsigned long l;
305f583
+
305f583
+        if (!(e = getenv("LISTEN_PID"))) {
305f583
+                r = 0;
305f583
+                goto finish;
305f583
+        }
305f583
+
305f583
+        errno = 0;
305f583
+        l = strtoul(e, &p, 10);
305f583
+
305f583
+        if (errno != 0) {
305f583
+                r = -errno;
305f583
+                goto finish;
305f583
+        }
305f583
+
305f583
+        if (!p || *p || l <= 0) {
305f583
+                r = -EINVAL;
305f583
+                goto finish;
305f583
+        }
305f583
+
305f583
+        /* Is this for us? */
305f583
+        if (getpid() != (pid_t) l) {
305f583
+                r = 0;
305f583
+                goto finish;
305f583
+        }
305f583
+
305f583
+        if (!(e = getenv("LISTEN_FDS"))) {
305f583
+                r = 0;
305f583
+                goto finish;
305f583
+        }
305f583
+
305f583
+        errno = 0;
305f583
+        l = strtoul(e, &p, 10);
305f583
+
305f583
+        if (errno != 0) {
305f583
+                r = -errno;
305f583
+                goto finish;
305f583
+        }
305f583
+
305f583
+        if (!p || *p) {
305f583
+                r = -EINVAL;
305f583
+                goto finish;
305f583
+        }
305f583
+
305f583
+        for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + (int) l; fd ++) {
305f583
+                int flags;
305f583
+
305f583
+                if ((flags = fcntl(fd, F_GETFD)) < 0) {
305f583
+                        r = -errno;
305f583
+                        goto finish;
305f583
+                }
305f583
+
305f583
+                if (flags & FD_CLOEXEC)
305f583
+                        continue;
305f583
+
305f583
+                if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) < 0) {
305f583
+                        r = -errno;
305f583
+                        goto finish;
305f583
+                }
305f583
+        }
305f583
+
305f583
+        r = (int) l;
305f583
+
305f583
+finish:
305f583
+        if (unset_environment) {
305f583
+                unsetenv("LISTEN_PID");
305f583
+                unsetenv("LISTEN_FDS");
305f583
+        }
305f583
+
305f583
+        return r;
305f583
+#endif
305f583
+}
305f583
+
305f583
+_sd_hidden_ int sd_is_fifo(int fd, const char *path) {
305f583
+        struct stat st_fd;
305f583
+
305f583
+        if (fd < 0)
305f583
+                return -EINVAL;
305f583
+
305f583
+        memset(&st_fd, 0, sizeof(st_fd));
305f583
+        if (fstat(fd, &st_fd) < 0)
305f583
+                return -errno;
305f583
+
305f583
+        if (!S_ISFIFO(st_fd.st_mode))
305f583
+                return 0;
305f583
+
305f583
+        if (path) {
305f583
+                struct stat st_path;
305f583
+
305f583
+                memset(&st_path, 0, sizeof(st_path));
305f583
+                if (stat(path, &st_path) < 0) {
305f583
+
305f583
+                        if (errno == ENOENT || errno == ENOTDIR)
305f583
+                                return 0;
305f583
+
305f583
+                        return -errno;
305f583
+                }
305f583
+
305f583
+                return
305f583
+                        st_path.st_dev == st_fd.st_dev &&
305f583
+                        st_path.st_ino == st_fd.st_ino;
305f583
+        }
305f583
+
305f583
+        return 1;
305f583
+}
305f583
+
305f583
+_sd_hidden_ int sd_is_special(int fd, const char *path) {
305f583
+        struct stat st_fd;
305f583
+
305f583
+        if (fd < 0)
305f583
+                return -EINVAL;
305f583
+
305f583
+        if (fstat(fd, &st_fd) < 0)
305f583
+                return -errno;
305f583
+
305f583
+        if (!S_ISREG(st_fd.st_mode) && !S_ISCHR(st_fd.st_mode))
305f583
+                return 0;
305f583
+
305f583
+        if (path) {
305f583
+                struct stat st_path;
305f583
+
305f583
+                if (stat(path, &st_path) < 0) {
305f583
+
305f583
+                        if (errno == ENOENT || errno == ENOTDIR)
305f583
+                                return 0;
305f583
+
305f583
+                        return -errno;
305f583
+                }
305f583
+
305f583
+                if (S_ISREG(st_fd.st_mode) && S_ISREG(st_path.st_mode))
305f583
+                        return
305f583
+                                st_path.st_dev == st_fd.st_dev &&
305f583
+                                st_path.st_ino == st_fd.st_ino;
305f583
+                else if (S_ISCHR(st_fd.st_mode) && S_ISCHR(st_path.st_mode))
305f583
+                        return st_path.st_rdev == st_fd.st_rdev;
305f583
+                else
305f583
+                        return 0;
305f583
+        }
305f583
+
305f583
+        return 1;
305f583
+}
305f583
+
305f583
+static int sd_is_socket_internal(int fd, int type, int listening) {
305f583
+        struct stat st_fd;
305f583
+
305f583
+        if (fd < 0 || type < 0)
305f583
+                return -EINVAL;
305f583
+
305f583
+        if (fstat(fd, &st_fd) < 0)
305f583
+                return -errno;
305f583
+
305f583
+        if (!S_ISSOCK(st_fd.st_mode))
305f583
+                return 0;
305f583
+
305f583
+        if (type != 0) {
305f583
+                int other_type = 0;
305f583
+                socklen_t l = sizeof(other_type);
305f583
+
305f583
+                if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &other_type, &l) < 0)
305f583
+                        return -errno;
305f583
+
305f583
+                if (l != sizeof(other_type))
305f583
+                        return -EINVAL;
305f583
+
305f583
+                if (other_type != type)
305f583
+                        return 0;
305f583
+        }
305f583
+
305f583
+        if (listening >= 0) {
305f583
+                int accepting = 0;
305f583
+                socklen_t l = sizeof(accepting);
305f583
+
305f583
+                if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, &accepting, &l) < 0)
305f583
+                        return -errno;
305f583
+
305f583
+                if (l != sizeof(accepting))
305f583
+                        return -EINVAL;
305f583
+
305f583
+                if (!accepting != !listening)
305f583
+                        return 0;
305f583
+        }
305f583
+
305f583
+        return 1;
305f583
+}
305f583
+
305f583
+union sockaddr_union {
305f583
+        struct sockaddr sa;
305f583
+        struct sockaddr_in in4;
305f583
+        struct sockaddr_in6 in6;
305f583
+        struct sockaddr_un un;
305f583
+        struct sockaddr_storage storage;
305f583
+};
305f583
+
305f583
+_sd_hidden_ int sd_is_socket(int fd, int family, int type, int listening) {
305f583
+        int r;
305f583
+
305f583
+        if (family < 0)
305f583
+                return -EINVAL;
305f583
+
305f583
+        if ((r = sd_is_socket_internal(fd, type, listening)) <= 0)
305f583
+                return r;
305f583
+
305f583
+        if (family > 0) {
305f583
+                union sockaddr_union sockaddr;
305f583
+                socklen_t l;
305f583
+
305f583
+                memset(&sockaddr, 0, sizeof(sockaddr));
305f583
+                l = sizeof(sockaddr);
305f583
+
305f583
+                if (getsockname(fd, &sockaddr.sa, &l) < 0)
305f583
+                        return -errno;
305f583
+
305f583
+                if (l < sizeof(sa_family_t))
305f583
+                        return -EINVAL;
305f583
+
305f583
+                return sockaddr.sa.sa_family == family;
305f583
+        }
305f583
+
305f583
+        return 1;
305f583
+}
305f583
+
305f583
+_sd_hidden_ int sd_is_socket_inet(int fd, int family, int type, int listening, uint16_t port) {
305f583
+        union sockaddr_union sockaddr;
305f583
+        socklen_t l;
305f583
+        int r;
305f583
+
305f583
+        if (family != 0 && family != AF_INET && family != AF_INET6)
305f583
+                return -EINVAL;
305f583
+
305f583
+        if ((r = sd_is_socket_internal(fd, type, listening)) <= 0)
305f583
+                return r;
305f583
+
305f583
+        memset(&sockaddr, 0, sizeof(sockaddr));
305f583
+        l = sizeof(sockaddr);
305f583
+
305f583
+        if (getsockname(fd, &sockaddr.sa, &l) < 0)
305f583
+                return -errno;
305f583
+
305f583
+        if (l < sizeof(sa_family_t))
305f583
+                return -EINVAL;
305f583
+
305f583
+        if (sockaddr.sa.sa_family != AF_INET &&
305f583
+            sockaddr.sa.sa_family != AF_INET6)
305f583
+                return 0;
305f583
+
305f583
+        if (family > 0)
305f583
+                if (sockaddr.sa.sa_family != family)
305f583
+                        return 0;
305f583
+
305f583
+        if (port > 0) {
305f583
+                if (sockaddr.sa.sa_family == AF_INET) {
305f583
+                        if (l < sizeof(struct sockaddr_in))
305f583
+                                return -EINVAL;
305f583
+
305f583
+                        return htons(port) == sockaddr.in4.sin_port;
305f583
+                } else {
305f583
+                        if (l < sizeof(struct sockaddr_in6))
305f583
+                                return -EINVAL;
305f583
+
305f583
+                        return htons(port) == sockaddr.in6.sin6_port;
305f583
+                }
305f583
+        }
305f583
+
305f583
+        return 1;
305f583
+}
305f583
+
305f583
+_sd_hidden_ int sd_is_socket_unix(int fd, int type, int listening, const char *path, size_t length) {
305f583
+        union sockaddr_union sockaddr;
305f583
+        socklen_t l;
305f583
+        int r;
305f583
+
305f583
+        if ((r = sd_is_socket_internal(fd, type, listening)) <= 0)
305f583
+                return r;
305f583
+
305f583
+        memset(&sockaddr, 0, sizeof(sockaddr));
305f583
+        l = sizeof(sockaddr);
305f583
+
305f583
+        if (getsockname(fd, &sockaddr.sa, &l) < 0)
305f583
+                return -errno;
305f583
+
305f583
+        if (l < sizeof(sa_family_t))
305f583
+                return -EINVAL;
305f583
+
305f583
+        if (sockaddr.sa.sa_family != AF_UNIX)
305f583
+                return 0;
305f583
+
305f583
+        if (path) {
305f583
+                if (length <= 0)
305f583
+                        length = strlen(path);
305f583
+
305f583
+                if (length <= 0)
305f583
+                        /* Unnamed socket */
305f583
+                        return l == offsetof(struct sockaddr_un, sun_path);
305f583
+
305f583
+                if (path[0])
305f583
+                        /* Normal path socket */
305f583
+                        return
305f583
+                                (l >= offsetof(struct sockaddr_un, sun_path) + length + 1) &&
305f583
+                                memcmp(path, sockaddr.un.sun_path, length+1) == 0;
305f583
+                else
305f583
+                        /* Abstract namespace socket */
305f583
+                        return
305f583
+                                (l == offsetof(struct sockaddr_un, sun_path) + length) &&
305f583
+                                memcmp(path, sockaddr.un.sun_path, length) == 0;
305f583
+        }
305f583
+
305f583
+        return 1;
305f583
+}
305f583
+
305f583
+_sd_hidden_ int sd_is_mq(int fd, const char *path) {
305f583
+#if !defined(__linux__)
305f583
+        return 0;
305f583
+#else
305f583
+        struct mq_attr attr;
305f583
+
305f583
+        if (fd < 0)
305f583
+                return -EINVAL;
305f583
+
305f583
+        if (mq_getattr(fd, &attr) < 0)
305f583
+                return -errno;
305f583
+
305f583
+        if (path) {
305f583
+                char fpath[PATH_MAX];
305f583
+                struct stat a, b;
305f583
+
305f583
+                if (path[0] != '/')
305f583
+                        return -EINVAL;
305f583
+
305f583
+                if (fstat(fd, &a) < 0)
305f583
+                        return -errno;
305f583
+
305f583
+                strncpy(stpcpy(fpath, "/dev/mqueue"), path, sizeof(fpath) - 12);
305f583
+                fpath[sizeof(fpath)-1] = 0;
305f583
+
305f583
+                if (stat(fpath, &b) < 0)
305f583
+                        return -errno;
305f583
+
305f583
+                if (a.st_dev != b.st_dev ||
305f583
+                    a.st_ino != b.st_ino)
305f583
+                        return 0;
305f583
+        }
305f583
+
305f583
+        return 1;
305f583
+#endif
305f583
+}
305f583
+
305f583
+_sd_hidden_ int sd_notify(int unset_environment, const char *state) {
305f583
+#if defined(DISABLE_SYSTEMD) || !defined(__linux__) || !defined(SOCK_CLOEXEC)
305f583
+        return 0;
305f583
+#else
305f583
+        int fd = -1, r;
305f583
+        struct msghdr msghdr;
305f583
+        struct iovec iovec;
305f583
+        union sockaddr_union sockaddr;
305f583
+        const char *e;
305f583
+
305f583
+        if (!state) {
305f583
+                r = -EINVAL;
305f583
+                goto finish;
305f583
+        }
305f583
+
305f583
+        if (!(e = getenv("NOTIFY_SOCKET")))
305f583
+                return 0;
305f583
+
305f583
+        /* Must be an abstract socket, or an absolute path */
305f583
+        if ((e[0] != '@' && e[0] != '/') || e[1] == 0) {
305f583
+                r = -EINVAL;
305f583
+                goto finish;
305f583
+        }
305f583
+
305f583
+        if ((fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0)) < 0) {
305f583
+                r = -errno;
305f583
+                goto finish;
305f583
+        }
305f583
+
305f583
+        memset(&sockaddr, 0, sizeof(sockaddr));
305f583
+        sockaddr.sa.sa_family = AF_UNIX;
305f583
+        strncpy(sockaddr.un.sun_path, e, sizeof(sockaddr.un.sun_path));
305f583
+
305f583
+        if (sockaddr.un.sun_path[0] == '@')
305f583
+                sockaddr.un.sun_path[0] = 0;
305f583
+
305f583
+        memset(&iovec, 0, sizeof(iovec));
305f583
+        iovec.iov_base = (char*) state;
305f583
+        iovec.iov_len = strlen(state);
305f583
+
305f583
+        memset(&msghdr, 0, sizeof(msghdr));
305f583
+        msghdr.msg_name = &sockaddr;
305f583
+        msghdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + strlen(e);
305f583
+
305f583
+        if (msghdr.msg_namelen > sizeof(struct sockaddr_un))
305f583
+                msghdr.msg_namelen = sizeof(struct sockaddr_un);
305f583
+
305f583
+        msghdr.msg_iov = &iovec;
305f583
+        msghdr.msg_iovlen = 1;
305f583
+
305f583
+        if (sendmsg(fd, &msghdr, MSG_NOSIGNAL) < 0) {
305f583
+                r = -errno;
305f583
+                goto finish;
305f583
+        }
305f583
+
305f583
+        r = 1;
305f583
+
305f583
+finish:
305f583
+        if (unset_environment)
305f583
+                unsetenv("NOTIFY_SOCKET");
305f583
+
305f583
+        if (fd >= 0)
305f583
+                close(fd);
305f583
+
305f583
+        return r;
305f583
+#endif
305f583
+}
305f583
+
305f583
+_sd_hidden_ int sd_notifyf(int unset_environment, const char *format, ...) {
305f583
+#if defined(DISABLE_SYSTEMD) || !defined(__linux__)
305f583
+        return 0;
305f583
+#else
305f583
+        va_list ap;
305f583
+        char *p = NULL;
305f583
+        int r;
305f583
+
305f583
+        va_start(ap, format);
305f583
+        r = vasprintf(&p, format, ap);
305f583
+        va_end(ap);
305f583
+
305f583
+        if (r < 0 || !p)
305f583
+                return -ENOMEM;
305f583
+
305f583
+        r = sd_notify(unset_environment, p);
305f583
+        free(p);
305f583
+
305f583
+        return r;
305f583
+#endif
305f583
+}
305f583
+
305f583
+_sd_hidden_ int sd_booted(void) {
305f583
+#if defined(DISABLE_SYSTEMD) || !defined(__linux__)
305f583
+        return 0;
305f583
+#else
305f583
+
305f583
+        struct stat a, b;
305f583
+
305f583
+        /* We simply test whether the systemd cgroup hierarchy is
305f583
+         * mounted */
305f583
+
305f583
+        if (lstat("/sys/fs/cgroup", &a) < 0)
305f583
+                return 0;
305f583
+
305f583
+        if (lstat("/sys/fs/cgroup/systemd", &b) < 0)
305f583
+                return 0;
305f583
+
305f583
+        return a.st_dev != b.st_dev;
305f583
+#endif
305f583
+}
305f583
diff --git a/PCSC/src/sd-daemon.h b/PCSC/src/sd-daemon.h
305f583
new file mode 100644
305f583
index 0000000..46dc7fd
305f583
--- /dev/null
305f583
+++ b/PCSC/src/sd-daemon.h
305f583
@@ -0,0 +1,277 @@
305f583
+/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
305f583
+
305f583
+#ifndef foosddaemonhfoo
305f583
+#define foosddaemonhfoo
305f583
+
305f583
+/***
305f583
+  Copyright 2010 Lennart Poettering
305f583
+
305f583
+  Permission is hereby granted, free of charge, to any person
305f583
+  obtaining a copy of this software and associated documentation files
305f583
+  (the "Software"), to deal in the Software without restriction,
305f583
+  including without limitation the rights to use, copy, modify, merge,
305f583
+  publish, distribute, sublicense, and/or sell copies of the Software,
305f583
+  and to permit persons to whom the Software is furnished to do so,
305f583
+  subject to the following conditions:
305f583
+
305f583
+  The above copyright notice and this permission notice shall be
305f583
+  included in all copies or substantial portions of the Software.
305f583
+
305f583
+  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
305f583
+  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
305f583
+  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
305f583
+  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
305f583
+  BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
305f583
+  ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
305f583
+  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
305f583
+  SOFTWARE.
305f583
+***/
305f583
+
305f583
+#include <sys/types.h>
305f583
+#include <inttypes.h>
305f583
+
305f583
+#ifdef __cplusplus
305f583
+extern "C" {
305f583
+#endif
305f583
+
305f583
+/*
305f583
+  Reference implementation of a few systemd related interfaces for
305f583
+  writing daemons. These interfaces are trivial to implement. To
305f583
+  simplify porting we provide this reference implementation.
305f583
+  Applications are welcome to reimplement the algorithms described
305f583
+  here if they do not want to include these two source files.
305f583
+
305f583
+  The following functionality is provided:
305f583
+
305f583
+  - Support for logging with log levels on stderr
305f583
+  - File descriptor passing for socket-based activation
305f583
+  - Daemon startup and status notification
305f583
+  - Detection of systemd boots
305f583
+
305f583
+  You may compile this with -DDISABLE_SYSTEMD to disable systemd
305f583
+  support. This makes all those calls NOPs that are directly related to
305f583
+  systemd (i.e. only sd_is_xxx() will stay useful).
305f583
+
305f583
+  Since this is drop-in code we don't want any of our symbols to be
305f583
+  exported in any case. Hence we declare hidden visibility for all of
305f583
+  them.
305f583
+
305f583
+  You may find an up-to-date version of these source files online:
305f583
+
305f583
+  http://cgit.freedesktop.org/systemd/plain/src/sd-daemon.h
305f583
+  http://cgit.freedesktop.org/systemd/plain/src/sd-daemon.c
305f583
+
305f583
+  This should compile on non-Linux systems, too, but with the
305f583
+  exception of the sd_is_xxx() calls all functions will become NOPs.
305f583
+
305f583
+  See sd-daemon(7) for more information.
305f583
+*/
305f583
+
305f583
+#ifndef _sd_printf_attr_
305f583
+#if __GNUC__ >= 4
305f583
+#define _sd_printf_attr_(a,b) __attribute__ ((format (printf, a, b)))
305f583
+#else
305f583
+#define _sd_printf_attr_(a,b)
305f583
+#endif
305f583
+#endif
305f583
+
305f583
+/*
305f583
+  Log levels for usage on stderr:
305f583
+
305f583
+          fprintf(stderr, SD_NOTICE "Hello World!\n");
305f583
+
305f583
+  This is similar to printk() usage in the kernel.
305f583
+*/
305f583
+#define SD_EMERG   "<0>"  /* system is unusable */
305f583
+#define SD_ALERT   "<1>"  /* action must be taken immediately */
305f583
+#define SD_CRIT    "<2>"  /* critical conditions */
305f583
+#define SD_ERR     "<3>"  /* error conditions */
305f583
+#define SD_WARNING "<4>"  /* warning conditions */
305f583
+#define SD_NOTICE  "<5>"  /* normal but significant condition */
305f583
+#define SD_INFO    "<6>"  /* informational */
305f583
+#define SD_DEBUG   "<7>"  /* debug-level messages */
305f583
+
305f583
+/* The first passed file descriptor is fd 3 */
305f583
+#define SD_LISTEN_FDS_START 3
305f583
+
305f583
+/*
305f583
+  Returns how many file descriptors have been passed, or a negative
305f583
+  errno code on failure. Optionally, removes the $LISTEN_FDS and
305f583
+  $LISTEN_PID file descriptors from the environment (recommended, but
305f583
+  problematic in threaded environments). If r is the return value of
305f583
+  this function you'll find the file descriptors passed as fds
305f583
+  SD_LISTEN_FDS_START to SD_LISTEN_FDS_START+r-1. Returns a negative
305f583
+  errno style error code on failure. This function call ensures that
305f583
+  the FD_CLOEXEC flag is set for the passed file descriptors, to make
305f583
+  sure they are not passed on to child processes. If FD_CLOEXEC shall
305f583
+  not be set, the caller needs to unset it after this call for all file
305f583
+  descriptors that are used.
305f583
+
305f583
+  See sd_listen_fds(3) for more information.
305f583
+*/
305f583
+int sd_listen_fds(int unset_environment);
305f583
+
305f583
+/*
305f583
+  Helper call for identifying a passed file descriptor. Returns 1 if
305f583
+  the file descriptor is a FIFO in the file system stored under the
305f583
+  specified path, 0 otherwise. If path is NULL a path name check will
305f583
+  not be done and the call only verifies if the file descriptor
305f583
+  refers to a FIFO. Returns a negative errno style error code on
305f583
+  failure.
305f583
+
305f583
+  See sd_is_fifo(3) for more information.
305f583
+*/
305f583
+int sd_is_fifo(int fd, const char *path);
305f583
+
305f583
+/*
305f583
+  Helper call for identifying a passed file descriptor. Returns 1 if
305f583
+  the file descriptor is a special character device on the file
305f583
+  system stored under the specified path, 0 otherwise.
305f583
+  If path is NULL a path name check will not be done and the call
305f583
+  only verifies if the file descriptor refers to a special character.
305f583
+  Returns a negative errno style error code on failure.
305f583
+
305f583
+  See sd_is_special(3) for more information.
305f583
+*/
305f583
+int sd_is_special(int fd, const char *path);
305f583
+
305f583
+/*
305f583
+  Helper call for identifying a passed file descriptor. Returns 1 if
305f583
+  the file descriptor is a socket of the specified family (AF_INET,
305f583
+  ...) and type (SOCK_DGRAM, SOCK_STREAM, ...), 0 otherwise. If
305f583
+  family is 0 a socket family check will not be done. If type is 0 a
305f583
+  socket type check will not be done and the call only verifies if
305f583
+  the file descriptor refers to a socket. If listening is > 0 it is
305f583
+  verified that the socket is in listening mode. (i.e. listen() has
305f583
+  been called) If listening is == 0 it is verified that the socket is
305f583
+  not in listening mode. If listening is < 0 no listening mode check
305f583
+  is done. Returns a negative errno style error code on failure.
305f583
+
305f583
+  See sd_is_socket(3) for more information.
305f583
+*/
305f583
+int sd_is_socket(int fd, int family, int type, int listening);
305f583
+
305f583
+/*
305f583
+  Helper call for identifying a passed file descriptor. Returns 1 if
305f583
+  the file descriptor is an Internet socket, of the specified family
305f583
+  (either AF_INET or AF_INET6) and the specified type (SOCK_DGRAM,
305f583
+  SOCK_STREAM, ...), 0 otherwise. If version is 0 a protocol version
305f583
+  check is not done. If type is 0 a socket type check will not be
305f583
+  done. If port is 0 a socket port check will not be done. The
305f583
+  listening flag is used the same way as in sd_is_socket(). Returns a
305f583
+  negative errno style error code on failure.
305f583
+
305f583
+  See sd_is_socket_inet(3) for more information.
305f583
+*/
305f583
+int sd_is_socket_inet(int fd, int family, int type, int listening, uint16_t port);
305f583
+
305f583
+/*
305f583
+  Helper call for identifying a passed file descriptor. Returns 1 if
305f583
+  the file descriptor is an AF_UNIX socket of the specified type
305f583
+  (SOCK_DGRAM, SOCK_STREAM, ...) and path, 0 otherwise. If type is 0
305f583
+  a socket type check will not be done. If path is NULL a socket path
305f583
+  check will not be done. For normal AF_UNIX sockets set length to
305f583
+  0. For abstract namespace sockets set length to the length of the
305f583
+  socket name (including the initial 0 byte), and pass the full
305f583
+  socket path in path (including the initial 0 byte). The listening
305f583
+  flag is used the same way as in sd_is_socket(). Returns a negative
305f583
+  errno style error code on failure.
305f583
+
305f583
+  See sd_is_socket_unix(3) for more information.
305f583
+*/
305f583
+int sd_is_socket_unix(int fd, int type, int listening, const char *path, size_t length);
305f583
+
305f583
+/*
305f583
+  Helper call for identifying a passed file descriptor. Returns 1 if
305f583
+  the file descriptor is a POSIX Message Queue of the specified name,
305f583
+  0 otherwise. If path is NULL a message queue name check is not
305f583
+  done. Returns a negative errno style error code on failure.
305f583
+*/
305f583
+int sd_is_mq(int fd, const char *path);
305f583
+
305f583
+/*
305f583
+  Informs systemd about changed daemon state. This takes a number of
305f583
+  newline separated environment-style variable assignments in a
305f583
+  string. The following variables are known:
305f583
+
305f583
+     READY=1      Tells systemd that daemon startup is finished (only
305f583
+                  relevant for services of Type=notify). The passed
305f583
+                  argument is a boolean "1" or "0". Since there is
305f583
+                  little value in signaling non-readiness the only
305f583
+                  value daemons should send is "READY=1".
305f583
+
305f583
+     STATUS=...   Passes a single-line status string back to systemd
305f583
+                  that describes the daemon state. This is free-from
305f583
+                  and can be used for various purposes: general state
305f583
+                  feedback, fsck-like programs could pass completion
305f583
+                  percentages and failing programs could pass a human
305f583
+                  readable error message. Example: "STATUS=Completed
305f583
+                  66% of file system check..."
305f583
+
305f583
+     ERRNO=...    If a daemon fails, the errno-style error code,
305f583
+                  formatted as string. Example: "ERRNO=2" for ENOENT.
305f583
+
305f583
+     BUSERROR=... If a daemon fails, the D-Bus error-style error
305f583
+                  code. Example: "BUSERROR=org.freedesktop.DBus.Error.TimedOut"
305f583
+
305f583
+     MAINPID=...  The main pid of a daemon, in case systemd did not
305f583
+                  fork off the process itself. Example: "MAINPID=4711"
305f583
+
305f583
+  Daemons can choose to send additional variables. However, it is
305f583
+  recommended to prefix variable names not listed above with X_.
305f583
+
305f583
+  Returns a negative errno-style error code on failure. Returns > 0
305f583
+  if systemd could be notified, 0 if it couldn't possibly because
305f583
+  systemd is not running.
305f583
+
305f583
+  Example: When a daemon finished starting up, it could issue this
305f583
+  call to notify systemd about it:
305f583
+
305f583
+     sd_notify(0, "READY=1");
305f583
+
305f583
+  See sd_notifyf() for more complete examples.
305f583
+
305f583
+  See sd_notify(3) for more information.
305f583
+*/
305f583
+int sd_notify(int unset_environment, const char *state);
305f583
+
305f583
+/*
305f583
+  Similar to sd_notify() but takes a format string.
305f583
+
305f583
+  Example 1: A daemon could send the following after initialization:
305f583
+
305f583
+     sd_notifyf(0, "READY=1\n"
305f583
+                   "STATUS=Processing requests...\n"
305f583
+                   "MAINPID=%lu",
305f583
+                   (unsigned long) getpid());
305f583
+
305f583
+  Example 2: A daemon could send the following shortly before
305f583
+  exiting, on failure:
305f583
+
305f583
+     sd_notifyf(0, "STATUS=Failed to start up: %s\n"
305f583
+                   "ERRNO=%i",
305f583
+                   strerror(errno),
305f583
+                   errno);
305f583
+
305f583
+  See sd_notifyf(3) for more information.
305f583
+*/
305f583
+int sd_notifyf(int unset_environment, const char *format, ...) _sd_printf_attr_(2,3);
305f583
+
305f583
+/*
305f583
+  Returns > 0 if the system was booted with systemd. Returns < 0 on
305f583
+  error. Returns 0 if the system was not booted with systemd. Note
305f583
+  that all of the functions above handle non-systemd boots just
305f583
+  fine. You should NOT protect them with a call to this function. Also
305f583
+  note that this function checks whether the system, not the user
305f583
+  session is controlled by systemd. However the functions above work
305f583
+  for both user and system services.
305f583
+
305f583
+  See sd_booted(3) for more information.
305f583
+*/
305f583
+int sd_booted(void);
305f583
+
305f583
+#ifdef __cplusplus
305f583
+}
305f583
+#endif
305f583
+
305f583
+#endif
305f583
diff --git a/PCSC/src/winscard_msg.h b/PCSC/src/winscard_msg.h
305f583
index b2b6f90..b8c490c 100644
305f583
--- a/PCSC/src/winscard_msg.h
305f583
+++ b/PCSC/src/winscard_msg.h
305f583
@@ -252,6 +252,7 @@
305f583
 
305f583
 #ifdef PCSCD
305f583
 	int32_t InitializeSocket(void);
305f583
+	int32_t ListenExistingSocket(int fd);
305f583
 	int32_t ProcessEventsServer(/*@out@*/ uint32_t *);
305f583
 #else
305f583
 	char *getSocketName(void);
305f583
diff --git a/PCSC/src/winscard_msg_srv.c b/PCSC/src/winscard_msg_srv.c
305f583
index 19ea363..4bb5bdc 100644
305f583
--- a/PCSC/src/winscard_msg_srv.c
305f583
+++ b/PCSC/src/winscard_msg_srv.c
305f583
@@ -39,6 +39,7 @@
305f583
 
305f583
 #include "misc.h"
305f583
 #include "pcscd.h"
305f583
+#include "sd-daemon.h"
305f583
 #include "winscard.h"
305f583
 #include "debuglog.h"
305f583
 #include "winscard_msg.h"
305f583
@@ -138,6 +139,30 @@ INTERNAL int32_t InitializeSocket(void)
305f583
 }
305f583
 
305f583
 /**
305f583
+ * @brief Acquires a socket passed in from systemd.
305f583
+ *
305f583
+ * This is called by the server to start listening on an existing socket for
305f583
+ * local IPC with the clients.
305f583
+ *
305f583
+ * @param fd The file descriptor to start listening on.
305f583
+ *
305f583
+ * @return Error code.
305f583
+ * @retval 0 Success
305f583
+ * @retval -1 Passed FD is not an UNIX socket.
305f583
+ */
305f583
+INTERNAL int32_t ListenExistingSocket(int fd)
305f583
+{
305f583
+	if (!sd_is_socket(fd, AF_UNIX, SOCK_STREAM, -1))
305f583
+	{
305f583
+		Log1(PCSC_LOG_CRITICAL, "Passed FD is not an UNIX socket");
305f583
+		return -1;
305f583
+	}
305f583
+
305f583
+	commonSocket = fd;
305f583
+	return 0;
305f583
+}
305f583
+
305f583
+/**
305f583
  * @brief Looks for messages sent by clients.
305f583
  *
305f583
  * This is called by the Server's function \c SVCServiceRunLoop().
305f583
-- 
305f583
1.7.5.4
305f583