aboutsummaryrefslogtreecommitdiffhomepage
path: root/fishd.c
blob: 8d4801a4ffafcab71a8ef84b7320b6f92c04b73f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
/** \file fishd.c

The universal variable server. fishd is automatically started by fish
if a fishd server isn't already running. fishd reads any saved
variables from ~/.fishd, and takes care of communication between fish
instances. When no clients are running, fishd will automatically shut
down and save.

\section fishd-commands Commands

Fishd works by sending and receiving commands. Each command is ended
with a newline. These are the commands supported by fishd:

<pre>set KEY:VALUE
set_export KEY:VALUE
</pre>

These commands update the value of a variable. The only difference
between the two is that <tt>set_export</tt>-variables should be
exported to children of the process using them. The variable value may
be escaped using C-style backslash escapes. In fact, this is required
for newline characters, which would otherwise be interpreted as end of
command.

<pre>erase KEY
</pre>

Erase the variable with the specified name.

<pre>barrier
barrier_reply
</pre>

A \c barrier command will result in a barrier_reply being added to
the end of the senders queue of unsent messages. These commands are
used to synchronize clients, since once the reply for a barrier
message returns, the sender can know that any updates available at the
time the original barrier request was sent have been received.

*/

#include "config.h"


#include <stdio.h>
#include <stdlib.h>
#include <wchar.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <pwd.h>
#include <fcntl.h>

#ifdef HAVE_GETOPT_H
#include <getopt.h>
#endif

#include <errno.h>
#include <locale.h>
#include <signal.h>

#include "fallback.h"
#include "util.h"

#include "common.h"
#include "wutil.h"
#include "env_universal_common.h"

/**
   Maximum length of socket filename
*/
#ifndef UNIX_PATH_MAX 
#define UNIX_PATH_MAX 100
#endif

/**
   Fallback if MSG_DONTWAIT isn't defined. That's actually prerry bad,
   and may lead to strange fishd behaviour, but at least it should
   work most of the time.
*/
#ifndef MSG_DONTWAIT
#define MSG_DONTWAIT 0
#endif

/**
   Small greeting to show that fishd is running
*/
#define GREETING "# Fish universal variable daemon\n"

/**
   Small not about not editing ~/.fishd manually. Inserted at the top of all .fishd files.
*/
#define SAVE_MSG "# This file is automatically generated by the fishd universal variable daemon.\n# Do NOT edit it directly, your changes will be overwritten.\n"

/**
   The name of the save file. The hostname is appended to this.
*/
#define FILE ".fishd."

/**
   Maximum length of hostname. Longer hostnames are truncated
*/
#define HOSTNAME_LEN 32

/**
   The string to append to the socket name to name the lockfile
*/
#define LOCKPOSTFIX ".lock"

/**
   The timeout in seconds on the lockfile for critical section
*/
#define LOCKTIMEOUT 1

/**
   Getopt short switches for fishd
*/
#define GETOPT_STRING "hv"

/**
   The list of connections to clients
*/
static connection_t *conn;

/**
   The socket to accept new clients on
*/
static int sock;

/**
   Set to one when fishd should save and exit
*/
static int quit=0;

/**
   Dynamically generated function, made from the documentation in doc_src.
*/
void print_help();

/**
   Constructs the fish socket filename
*/
static char *get_socket_filename()
{
	char *name;
	char *dir = getenv( "FISHD_SOCKET_DIR" );
	char *uname = getenv( "USER" );

	if( dir == NULL )
	{
		dir = "/tmp";
	}

	if( uname == NULL )
	{
		struct passwd *pw;
		pw = getpwuid( getuid() );
		uname = strdup( pw->pw_name );
	}

	name = malloc( strlen(dir)+ strlen(uname)+ strlen(SOCK_FILENAME) + 2 );
	if( name == NULL )
	{
		wperror( L"get_socket_filename" );
		exit( EXIT_FAILURE );
	}
	strcpy( name, dir );
	strcat( name, "/" );
	strcat( name, SOCK_FILENAME );
	strcat( name, uname );

	if( strlen( name ) >= UNIX_PATH_MAX )
	{
		debug( 1, L"Filename too long: '%s'", name );
		exit( EXIT_FAILURE );
	}
	return name;
}

/**
   Signal handler for the term signal. 
*/
static void handle_term( int signal )
{
	quit=1;
}


/**
   Acquire the lock for the socket
   Returns the name of the lock file if successful or 
   NULL if unable to obtain lock.
   The returned string must be free()d after unlink()ing the file to release 
   the lock
*/
static char *acquire_socket_lock( const char *sock_name )
{
	int len = strlen( sock_name );
	char *lockfile = malloc( len + strlen( LOCKPOSTFIX ) + 1 );
	
	if( lockfile == NULL ) 
	{
		wperror( L"acquire_socket_lock" );
		exit( EXIT_FAILURE );
	}
	strcpy( lockfile, sock_name );
	strcpy( lockfile + len, LOCKPOSTFIX );
	if ( !acquire_lock_file( lockfile, LOCKTIMEOUT, 1 ) )
	{
		free( lockfile );
		lockfile = NULL;
	}
	return lockfile;
}

/**
   Connects to the fish socket and starts listening for connections
*/
static int get_socket()
{
	int s, len, doexit = 0;
	int exitcode = EXIT_FAILURE;
	struct sockaddr_un local;
	char *sock_name = get_socket_filename();

	/*
	   Start critical section protected by lock
	*/
	char *lockfile = acquire_socket_lock( sock_name );
	if( lockfile == NULL )
	{
		debug( 0, L"Unable to obtain lock on socket, exiting" );
		exit( EXIT_FAILURE );
	}
	debug( 4, L"Acquired lockfile: %s", lockfile );
	
	local.sun_family = AF_UNIX;
	strcpy( local.sun_path, sock_name );
	len = sizeof(local);
	
	debug(1, L"Connect to socket at %s", sock_name);
	
	if( ( s = socket( AF_UNIX, SOCK_STREAM, 0 ) ) == -1 )
	{
		wperror( L"socket" );
		doexit = 1;
		goto unlock;
	}

	/*
	   First check whether the socket has been opened by another fishd;
	   if so, exit with success status
	*/
	if( connect( s, (struct sockaddr *)&local, len ) == 0 )
	{
		debug( 1, L"Socket already exists, exiting" );
		doexit = 1;
		exitcode = 0;
		goto unlock;
	}
	
	unlink( local.sun_path );
	if( bind( s, (struct sockaddr *)&local, len ) == -1 )
	{
		wperror( L"bind" );
		doexit = 1;
		goto unlock;
	}

	if( fcntl( s, F_SETFL, O_NONBLOCK ) != 0 )
	{
		wperror( L"fcntl" );
		close( s );
		doexit = 1;
	} else if( listen( s, 64 ) == -1 )
	{
		wperror( L"listen" );
		doexit = 1;
	}

unlock:
	(void)unlink( lockfile );
	debug( 4, L"Released lockfile: %s", lockfile );
	/*
	   End critical section protected by lock
	*/
	
	free( lockfile );
	
	free( sock_name );

	if( doexit )
	{
		exit( exitcode );
	}

	return s;
}

/**
   Event handler. Broadcasts updates to all clients.
*/
static void broadcast( int type, const wchar_t *key, const wchar_t *val )
{
	connection_t *c;
	message_t *msg;

	if( !conn )
		return;
	
	msg = create_message( type, key, val );
	
	/*
	  Don't merge these loops, or try_send_all can free the message
	  prematurely
	*/
	
	for( c = conn; c; c=c->next )
	{
		msg->count++;
		q_put( &c->unsent, msg );
	}	
	
	for( c = conn; c; c=c->next )
	{
		try_send_all( c );
	}	
}

/**
   Make program into a creature of the night.
*/
static void daemonize()
{
	/*
	  Fork, and let parent exit
	*/
	switch( fork() )
	{
		case -1:
			debug( 0, L"Could not put fishd in background. Quitting" );
			wperror( L"fork" );
			exit(1);
			
		case 0:
		{
			/*
			  Make fishd ignore the HUP signal.
			*/
			struct sigaction act;
			sigemptyset( & act.sa_mask );
			act.sa_flags=0;
			act.sa_handler=SIG_IGN;
			sigaction( SIGHUP, &act, 0);

			/*
			  Make fishd save and exit on the TERM signal.
			*/
			sigfillset( & act.sa_mask );
			act.sa_flags=0;
			act.sa_handler=&handle_term;
			sigaction( SIGTERM, &act, 0);
			break;
		}
		
		default:
		{			
			debug( 0, L"Parent process exiting (This is normal)" );
			exit(0);
		}		
	}
	
	/*
	  Put ourself in out own processing group
	*/
	setsid();
	
	/*
	  Close stdin and stdout. We only use stderr, anyway.
	*/
	close( 0 );
	close( 1 );

}

/**
   Load or save all variables
*/
void load_or_save( int save)
{
	struct passwd *pw;
	char *name;
	char *dir = getenv( "HOME" );
	char hostname[HOSTNAME_LEN];
	connection_t c;
	
	if( !dir )
	{
		pw = getpwuid( getuid() );
		dir = pw->pw_dir;
	}
	
	gethostname( hostname, HOSTNAME_LEN );
	
	name = malloc( strlen(dir)+ strlen(FILE)+ strlen(hostname) + 2 );
	strcpy( name, dir );
	strcat( name, "/" );
	strcat( name, FILE );
	strcat( name, hostname );
	
	debug( 4, L"Open file for %s: '%s'", 
		   save?"saving":"loading", 
		   name );
	
	c.fd = open( name, save?(O_CREAT | O_TRUNC | O_WRONLY):O_RDONLY, 0600);
	free( name );
	
	if( c.fd == -1 )
	{
		debug( 1, L"Could not open load/save file. No previous saves?" );
		wperror( L"open" );
		return;		
	}
	debug( 4, L"File open on fd %d", c.fd );

	sb_init( &c.input );
	memset (&c.wstate, '\0', sizeof (mbstate_t));
	q_init( &c.unsent );

	if( save )
	{
		
		write( c.fd, SAVE_MSG, strlen(SAVE_MSG) );
		enqueue_all( &c );
	}
	else
		read_message( &c );

	q_destroy( &c.unsent );
	sb_destroy( &c.input );
	close( c.fd );
}

/**
   Load variables from disk
*/
static void load()
{
	load_or_save(0);
}

/**
   Save variables to disk
*/
static void save()
{
	load_or_save(1);
}

/**
   Do all sorts of boring initialization.
*/
static void init()
{

	sock = get_socket();
	daemonize();	
	env_universal_common_init( &broadcast );
	
	load();	
}

/**
   Main function for fishd
*/
int main( int argc, char ** argv )
{
	int child_socket;
	struct sockaddr_un remote;
	socklen_t t;
	int max_fd;
	int update_count=0;
	
	fd_set read_fd, write_fd;
	
	program_name=L"fishd";
	wsetlocale( LC_ALL, L"" );	

	/*
	  Parse options
	*/
	while( 1 )
	{
#ifdef HAVE_GETOPT_LONG
		static struct option
			long_options[] =
			{
				{
					"help", no_argument, 0, 'h' 
				}
				,
				{
					"version", no_argument, 0, 'v' 
				}
				,
				{ 
					0, 0, 0, 0 
				}
			}
		;
		
		int opt_index = 0;
		
		int opt = getopt_long( argc,
							   argv, 
							   GETOPT_STRING,
							   long_options, 
							   &opt_index );
		
#else	
		int opt = getopt( argc,
						  argv, 
						  GETOPT_STRING );
#endif
		if( opt == -1 )
			break;
		
		switch( opt )
		{
			case 0:
				break;				

			case 'h':
				print_help();
				exit(0);				
								
			case 'v':
				debug( 0, L"%ls, version %s\n", program_name, PACKAGE_VERSION );
				exit( 0 );				
				
			case '?':
				return 1;
				
		}		
	}
	
	init();
	while(1) 
	{
		connection_t *c;
		int res;

		t=sizeof( remote );		
		
		FD_ZERO( &read_fd );
		FD_ZERO( &write_fd );
		FD_SET( sock, &read_fd );
		max_fd = sock+1;
		for( c=conn; c; c=c->next )
		{
			FD_SET( c->fd, &read_fd );
			max_fd = maxi( max_fd, c->fd+1);
			
			if( ! q_empty( &c->unsent ) )
			{
				FD_SET( c->fd, &write_fd );
			}
		}

		while( 1 )
		{
			res=select( max_fd, &read_fd, &write_fd, 0, 0 );

			if( quit )
			{
				save();
				exit(0);
			}
			
			if( res != -1 )
				break;
			
			if( errno != EINTR )
			{
				wperror( L"select" );
				exit(1);
			}
		}
				
		if( FD_ISSET( sock, &read_fd ) )
		{
			if( (child_socket = 
				 accept( sock, 
						 (struct sockaddr *)&remote, 
						 &t) ) == -1) {
				wperror( L"accept" );
				exit(1);
			}
			else
			{
				debug( 4, L"Connected with new child on fd %d", child_socket );

				if( fcntl( child_socket, F_SETFL, O_NONBLOCK ) != 0 )
				{
					wperror( L"fcntl" );
					close( child_socket );		
				}
				else
				{
					connection_t *new = malloc( sizeof(connection_t));
					new->fd = child_socket;
					new->next = conn;
					q_init( &new->unsent );
					new->killme=0;				
					sb_init( &new->input );
					memset (&new->wstate, '\0', sizeof (mbstate_t));					
					send( new->fd, GREETING, strlen(GREETING), MSG_DONTWAIT );
					enqueue_all( new );				
					conn=new;
				}
			}
		}
		
		for( c=conn; c; c=c->next )
		{
			if( FD_ISSET( c->fd, &write_fd ) )
			{
				try_send_all( c );
			}
		}
		
		for( c=conn; c; c=c->next )
		{
			if( FD_ISSET( c->fd, &read_fd ) )
			{
				read_message( c );

				/*
				  Occasionally we save during normal use, so that we
				  won't lose everything on a system crash
				*/
				update_count++;
				if( update_count >= 64 )
				{
					save();
					update_count = 0;
				}
			}
		}
		
		connection_t *prev=0;
		c=conn;
		
		while( c )
		{
			if( c->killme )
			{
				debug( 4, L"Close connection %d", c->fd );

				close(c->fd );
				sb_destroy( &c->input );

				while( !q_empty( &c->unsent ) )
				{
					message_t *msg = (message_t *)q_get( &c->unsent );
					msg->count--;
					if( !msg->count )
						free( msg );
				}
				
				q_destroy( &c->unsent );				
				if( prev )
				{
					prev->next=c->next;
				}
				else
				{
					conn=c->next;
				}
				
				free(c);
				
				c=(prev?prev->next:conn);
				
			}
			else
			{
				prev=c;
				c=c->next;
			}
		}
		if( !conn )
		{
			debug( 0, L"No more clients. Quitting" );
			save();			
			env_universal_common_destroy();
			exit(0);
			c=c->next;
		}		
	}
}