11/*
22This file is part of libspnav, part of the spacenav project (spacenav.sf.net)
3- Copyright (C) 2007-2020 John Tsiombikas <nuclear@member.fsf.org>
3+ Copyright (C) 2007-2022 John Tsiombikas <nuclear@member.fsf.org>
44
55Redistribution and use in source and binary forms, with or without
66modification, are permitted provided that the following conditions are met:
@@ -27,6 +27,7 @@ OF SUCH DAMAGE.
2727#include <stdio.h>
2828#include <stdlib.h>
2929#include <string.h>
30+ #include <ctype.h>
3031#include <errno.h>
3132#include <unistd.h>
3233#include <sys/types.h>
@@ -70,11 +71,22 @@ static struct event_node *ev_queue, *ev_queue_tail;
7071/* AF_UNIX socket used for alternative communication with daemon */
7172static int sock = -1 ;
7273
74+ static int connect_afunix (int s , const char * path )
75+ {
76+ struct sockaddr_un addr = {0 };
77+
78+ addr .sun_family = AF_UNIX ;
79+ strncpy (addr .sun_path , path , sizeof addr .sun_path - 1 );
80+
81+ return connect (s , (struct sockaddr * )& addr , sizeof addr );
82+ }
7383
7484int spnav_open (void )
7585{
7686 int s ;
77- struct sockaddr_un addr ;
87+ char * path ;
88+ FILE * fp ;
89+ char buf [256 ], * ptr ;
7890
7991 if (IS_OPEN ) {
8092 return -1 ;
@@ -90,16 +102,38 @@ int spnav_open(void)
90102 return -1 ;
91103 }
92104
93- memset (& addr , 0 , sizeof addr );
94- addr .sun_family = AF_UNIX ;
95- strncpy (addr .sun_path , SPNAV_SOCK_PATH , sizeof (addr .sun_path ));
105+ /* heed SPNAV_SOCKET environment variable if it's defined */
106+ if ((path = getenv ("SPNAV_SOCKET" ))) {
107+ if (connect_afunix (s , path ) == 0 ) goto success ;
108+ }
109+
110+ /* hacky config file parser, to look for socket = <path> in /etc/spnavrc */
111+ if ((fp = fopen ("/etc/spnavrc" , "rb" ))) {
112+ path = 0 ;
113+ while (fgets (buf , sizeof buf , fp )) {
114+ ptr = buf ;
115+ while (* ptr && isspace (* ptr )) ptr ++ ;
116+ if (!* ptr || * ptr == '#' ) continue ; /* comment or empty line */
96117
118+ if (memcmp (ptr , "socket" , 6 ) == 0 && (ptr = strchr (ptr , '=' ))) {
119+ while (* ++ ptr && isspace (* ptr ));
120+ if (!* ptr ) continue ;
121+ path = ptr ;
122+ ptr += strlen (ptr ) - 1 ;
123+ while (ptr > path && isspace (* ptr )) * ptr -- = 0 ;
124+ break ;
125+ }
126+ }
127+ if (path && connect_afunix (s , path ) == 0 ) goto success ;
128+ }
97129
98- if (connect (s , (struct sockaddr * )& addr , sizeof addr ) == -1 ) {
130+ /* by default use SPNAV_SOCK_PATH (see top of this file) */
131+ if (connect_afunix (s , SPNAV_SOCK_PATH ) == -1 ) {
99132 close (s );
100133 return -1 ;
101134 }
102135
136+ success :
103137 sock = s ;
104138 return 0 ;
105139}
0 commit comments