From 22c69d415dd6adf0a7b315240be6d4f46a7ad2fa Mon Sep 17 00:00:00 2001 From: Michael Andrews Date: Sun, 9 Nov 2014 15:56:26 -0500 Subject: [PATCH] Automatically check for sockets without screen name. --- bspc.c | 51 +++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 41 insertions(+), 10 deletions(-) diff --git a/bspc.c b/bspc.c index 5174c62..04ed970 100644 --- a/bspc.c +++ b/bspc.c @@ -22,6 +22,7 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +#include #include #ifdef __OpenBSD__ #include @@ -33,6 +34,8 @@ #include "helpers.h" #include "common.h" +extern char *strdup(const char*); + int main(int argc, char *argv[]) { int fd; @@ -43,11 +46,45 @@ int main(int argc, char *argv[]) err("No arguments given.\n"); sock_address.sun_family = AF_UNIX; - char *sp = getenv(SOCKET_ENV_VAR); - if (sp != NULL) + char *sp, *dp, *tdp; + int con, it; + unsigned int dplen; + + if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) + err("Failed to create the socket.\n"); + + sp = getenv(SOCKET_ENV_VAR); + if (sp != NULL) { snprintf(sock_address.sun_path, sizeof(sock_address.sun_path), "%s", sp); - else - snprintf(sock_address.sun_path, sizeof(sock_address.sun_path), SOCKET_PATH_TPL, getenv("DISPLAY")); + con = connect(fd, (struct sockaddr *) &sock_address, sizeof(sock_address)); + } else { + con = -1; + } + + dp = getenv("DISPLAY"); + if (con == -1 && dp != NULL) { + snprintf(sock_address.sun_path, sizeof(sock_address.sun_path), SOCKET_PATH_TPL, dp); + con = connect(fd, (struct sockaddr *) &sock_address, sizeof(sock_address)); + } + + if (con == -1 && dp != NULL) { + tdp = strdup(dp); + dplen = strlen(dp); + for (it = dplen - 1; (it > 1) && (tdp[it] != ':'); it--) { + if (tdp[it] == '.') { + tdp[it] = '\0'; + break; + } + } + if (strlen(tdp) != dplen) { + snprintf(sock_address.sun_path, sizeof(sock_address.sun_path), SOCKET_PATH_TPL, tdp); + con = connect(fd, (struct sockaddr *) &sock_address, sizeof(sock_address)); + } + free(tdp); + } + + if (con == -1) + err("Failed to connect to the socket.\n"); argc--, argv++; int msg_len = 0; @@ -57,12 +94,6 @@ int main(int argc, char *argv[]) msg_len += n; } - if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) - err("Failed to create the socket.\n"); - - if (connect(fd, (struct sockaddr *) &sock_address, sizeof(sock_address)) == -1) - err("Failed to connect to the socket.\n"); - if (send(fd, msg, msg_len, 0) == -1) err("Failed to send the data.\n");