File: unixsock_server.c

package info (click to toggle)
openser 1.1.0-9etch1
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 9,828 kB
  • ctags: 11,809
  • sloc: ansic: 120,528; sh: 5,249; yacc: 1,716; makefile: 1,261; php: 656; perl: 205; sql: 190
file content (1027 lines) | stat: -rw-r--r-- 21,021 bytes parent folder | download
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
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
/*
 * $Id: unixsock_server.c,v 1.2 2006/01/09 18:51:57 miconda Exp $
 *
 * UNIX Domain Socket Server
 *
 * Copyright (C) 2001-2004 FhG Fokus
 *
 * This file is part of openser, a free SIP server.
 *
 * openser is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version
 *
 * openser is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License 
 * along with this program; if not, write to the Free Software 
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * History:
 *              created by janakj
 *  2004-03-03  added tcp init code (andrei)
 *  2004-04-29  added chmod(sock_perm) & chown(sock_user,sock_group)  (andrei)
 */

#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <signal.h>
#include <stdarg.h>
#include <time.h>
#include <fcntl.h>
#include "config.h"
#include "ut.h"
#include "globals.h"
#include "trim.h"
#include "pt.h"
#include "sr_module.h"
#include "mem/mem.h"
#include "fifo_server.h" /* CMD_SEPARATOR */
#include "unixsock_server.h"
#include "tsend.h"


/* AF_LOCAL is not defined on solaris */
#if !defined(AF_LOCAL)
#define AF_LOCAL AF_UNIX
#endif
#if !defined(PF_LOCAL)
#define PF_LOCAL PF_UNIX
#endif


/* solaris doesn't have SUN_LEN */
#ifndef SUN_LEN
#define SUN_LEN(sa)	 ( strlen((sa)->sun_path) + \
					 (size_t)(((struct sockaddr_un*)0)->sun_path) )
#endif


#define UNIXSOCK_BUF_SIZE BUF_SIZE

char* unixsock_name = 0;
int unixsock_children = 1;
int unixsock_tx_timeout = 2000; /* Timeout for sending replies in milliseconds */


static int rx_sock, tx_sock;
static struct unixsock_cmd* cmd_list = 0;
static char reply_buf[UNIXSOCK_BUF_SIZE];
static str reply_pos;
static struct sockaddr_un reply_addr;
static unsigned int reply_addr_len;

static time_t up_since;
static char up_since_ctime[MAX_CTIME_LEN];


#define PRINT_CMD "print"     /* Diagnostic command */
#define VERSION_CMD "version" /* Print the version of the server */
#define UPTIME_CMD "uptime"   /* Print server's uptime */
#define WHICH_CMD "which"     /* Print available FIFO commands */
#define PS_CMD "ps"           /* Print server's process table */
#define ARG_CMD "arg"         /* Print server's command line arguments */
#define PWD_CMD "pwd"         /* Get the current working directory */
#define KILL_CMD "kill"       /* Kill the server */


/* 
 * Diagnostic and hello-world command 
 */
static int print_cmd(str* msg)
{
	str line;
	int ret;

	ret = 0;

	if (unixsock_read_line(&line, msg) < 0) {
		unixsock_reply_asciiz("500 Error while reading text\n");
		ret = -1;
		goto end;
	}

	if (unixsock_reply_printf("200 OK\n%.*s\n", line.len, ZSW(line.s)) < 0) {
		unixsock_reply_reset();
		unixsock_reply_asciiz("500 Error while sending reply\n");
		ret = -1;
	}

 end:
	if (unixsock_reply_send() < 0) ret = -1;
	return ret;
}


/*
 * Print the version of the server
 */
static int version_cmd(str* msg)
{
	int ret;

	ret = 0;
	if (unixsock_reply_asciiz("200 OK\n" SERVER_HDR CRLF) < 0) ret = -1;
	if (unixsock_reply_send() < 0) ret = -1;
	return ret;
}


static int uptime_cmd(str* msg)
{
	time_t now;
	int ret;

	time(&now);
	ret = 0;
	
	if (unixsock_reply_printf("200 OK\nNow: %sUp Since: %sUp time: %.0f [sec]\n",
				  ctime(&now), up_since_ctime, difftime(now, up_since)) < 0) {
		unixsock_reply_reset();
		unixsock_reply_asciiz("500 Error while printing reply\n");
		ret = -1;
	}
	
	if (unixsock_reply_send() < 0) {
		ret = -1;
	}
	
	return ret;
}


static int which_cmd(str* msg)
{
	struct unixsock_cmd* c;
	int ret;

	ret = 0;
	unixsock_reply_asciiz("200 OK\n");

	for(c = cmd_list; c; c = c->next) {
		if (unixsock_reply_printf("%s\n", c->name) < 0) {
			unixsock_reply_reset();
			unixsock_reply_asciiz("500 Error while creating reply\n");
			ret = -1;
			break;
		}
	}
	
	if (unixsock_reply_send() < 0) {
		ret = -1;
	}
	return ret;
}


static int ps_cmd(str* msg)
{
	int p, ret;

	ret = 0;
	unixsock_reply_asciiz("200 OK\n");
	for (p = 0; p < process_count(); p++) {
		if (unixsock_reply_printf("%d\t%d\t%s\n", p, pt[p].pid, pt[p].desc) < 0) {
			unixsock_reply_reset();
			unixsock_reply_asciiz("500 Error while printing reply\n");
			ret = -1;
			break;
		}
	}
	
	if (unixsock_reply_send() < 0) {
		ret = -1;
	}
	return ret;
}


static int pwd_cmd(str* msg)
{
	char *cwd_buf;
	int max_len, ret;

	max_len = pathmax();
	cwd_buf = pkg_malloc(max_len);
	ret = 0;
	if (!cwd_buf) {
		LOG(L_ERR, "pwd_cmd: No memory left\n");
		unixsock_reply_asciiz("500 No Memory Left\n");
		ret = -1;
	}

	if (getcwd(cwd_buf, max_len)) {
		if (unixsock_reply_printf("200 OK\n%s\n", cwd_buf) < 0) {
			unixsock_reply_reset();
			unixsock_reply_asciiz("500 Error while sending reply\n");
			ret = -1;
		}
	} else {
		unixsock_reply_asciiz("500 getcwd Failed\n");
		ret = -1;
	}

	pkg_free(cwd_buf);
	if (unixsock_reply_send() < 0) {
		ret = -1;
	}
	return ret;
}


static int arg_cmd(str* msg)
{
	int p, ret;

	ret = 0;
	unixsock_reply_asciiz("200 OK\n");
	for (p = 0; p < my_argc; p++) {
		if (unixsock_reply_printf("%s\n", my_argv[p]) < 0) {
			unixsock_reply_reset();
			unixsock_reply_asciiz("500 Could not create reply\n");
			ret = -1;
			break;
		}
	}
			
	if (unixsock_reply_send() < 0) {
		ret = -1;
	}
	return ret;
}


static int kill_cmd(str* msg)
{
	unixsock_reply_asciiz("200 Killing now\n");
	unixsock_reply_send();
	kill(0, SIGTERM);
	return 0;
}


static int register_core_commands(void)
{
	if (unixsock_register_cmd(PRINT_CMD, print_cmd) < 0) {
		return -1;
	}

	if (unixsock_register_cmd(VERSION_CMD, version_cmd) < 0) {
		return -1;
	}

	if (unixsock_register_cmd(UPTIME_CMD, uptime_cmd) < 0) {
		return -1;
	}

	if (unixsock_register_cmd(WHICH_CMD, which_cmd) < 0) {
		return -1;
	}

	if (unixsock_register_cmd(PS_CMD, ps_cmd) < 0) {
		return -1;
	}

	if (unixsock_register_cmd(PWD_CMD, pwd_cmd) < 0) {
		return -1;
	}

	if (unixsock_register_cmd(ARG_CMD, arg_cmd) < 0) {
		return -1;
	}

	if (unixsock_register_cmd(KILL_CMD, kill_cmd) < 0) {
		return -1;
	}
	return 0;
}


/*
 * Create and bind local socket
 */
int init_unixsock_socket(void)
{
	struct sockaddr_un addr;
	int len, flags;

	if (unixsock_name == 0) {
		DBG("init_unixsock_socket: No unix domain socket"
		    " will be opened\n");
		return 1;
	}

	len = strlen(unixsock_name);
	if (len == 0) {
		DBG("init_unixsock_socket: Unix domain socket server disabled\n");
		return 1;
	} else if (len > 107) {
		LOG(L_ERR, "ERROR: init_unixsock_socket: Socket name too long\n");
		return -1;
	}

	DBG("init_unixsock_socket: Initializing Unix domain socket server @ %s\n", 
	    unixsock_name);

	if (unlink(unixsock_name) == -1) {
		if (errno != ENOENT) {
			LOG(L_ERR, "ERROR: init_unixsock_socket: Error while unlinking "
			    "old socket (%s): %s\n", unixsock_name, strerror(errno));
			return -1;
		}
	}

	rx_sock = socket(PF_LOCAL, SOCK_DGRAM, 0);
	if (rx_sock == -1) {
		LOG(L_ERR, "ERROR: init_unixsock_socket: Cannot create RX "
				"socket: %s\n", strerror(errno));
		return -1;
	}

	memset(&addr, 0, sizeof(addr));
	addr.sun_family = PF_LOCAL;
	memcpy(addr.sun_path, unixsock_name, len);

	if (bind(rx_sock, (struct sockaddr*)&addr, SUN_LEN(&addr)) == -1) {
		LOG(L_ERR, "ERROR: init_unixsock_socket: bind: %s\n", strerror(errno));
		goto err_rx;
	}
	/* try to change the permissions */
	if (sock_mode){ /* sock_mode==0 doesn't make sense, nobody can read/write*/
		if (chmod(unixsock_name, sock_mode)<0){
			LOG(L_ERR, "ERROR: init_unixsock_socket: failed to change the"
					" permissions for %s to %04o: %s[%d]\n",
					unixsock_name, sock_mode, strerror(errno), errno);
			goto err_rx;
		}
	}
	/* try to change the ownership */
	if ((sock_uid!=-1) || (sock_gid!=-1)){
		if (chown(unixsock_name, sock_uid, sock_gid)<0){
			LOG(L_ERR, "ERROR: init_unixsock_socket: failed to change the"
					" owner/group for %s  to %d.%d; %s[%d]\n",
					unixsock_name, sock_uid, sock_gid, strerror(errno), errno);
			goto err_rx;
		}
	}

	tx_sock = socket(PF_LOCAL, SOCK_DGRAM, 0);
	if (tx_sock == -1) {
		LOG(L_ERR, "ERROR: init_unixsock_socket: Cannot create TX socket:"
				" %s\n", strerror(errno));
		goto err_rx;
	}

	     /* Turn non-blocking mode on */
	flags = fcntl(tx_sock, F_GETFL);
	if (flags == -1){
		LOG(L_ERR, "ERROR: init_unixsock_socket: fcntl failed: %s\n",
		    strerror(errno));
		goto err_both;
	}
		
	if (fcntl(tx_sock, F_SETFL, flags | O_NONBLOCK) == -1) {
		LOG(L_ERR, "ERROR: init_unixsock_socket: fcntl: "
				"set non-blocking failed: %s\n", strerror(errno));
		goto err_both;
	}
	
	return 1;
 err_both:
	close(tx_sock);
 err_rx:
	close(rx_sock);
	return -1;
}


static struct unixsock_cmd* lookup_cmd(str* cmd)
{
	struct unixsock_cmd* c;

	for(c = cmd_list; c; c = c->next) {
		if ((cmd->len == c->name.len) &&
		    (strncasecmp(c->name.s, cmd->s, cmd->len) == 0)) {
			return c;
		}
	}
	return 0;
}


static int parse_cmd(str* res, str* buffer)
{
	char* cmd_end;

	if (!res || !buffer) {
		LOG(L_ERR, "parse_cmd: Invalid parameter value\n");
		return -1;
	}

	if (buffer->len < 3) {
		LOG(L_ERR, "parse_cmd: Message too short\n");
		return -1;
	}

	if (buffer->s[0] != CMD_SEPARATOR) {
		LOG(L_ERR, "parse_cmd: Command must start with %c\n", 
		    CMD_SEPARATOR);
		return -1;
	}
	
	cmd_end = q_memchr(buffer->s + 1, CMD_SEPARATOR, buffer->len - 1);
	if (!cmd_end) {
		LOG(L_ERR, "parse_cmd: Closing '%c' missing\n", CMD_SEPARATOR);
		return -1;
	}

	res->s = buffer->s + 1;
	res->len = cmd_end - res->s;
	return 0;
} 


static void skip_line(str* buffer)
{
	if (!buffer) return;

	     /* Find \n */
	while (buffer->len && (buffer->s[0] != '\n')) {
		buffer->s++;
		buffer->len--;
	}

	if (buffer->len) {
		buffer->s++;
		buffer->len--;
	}

	     /* Skip CR following LF */
	while (buffer->len && (buffer->s[0] == '\r')) {
		buffer->s++;
		buffer->len--;
	}
}


static void unix_server_loop(void)
{
	int ret;
	str cmd, buffer;
	static char buf[UNIXSOCK_BUF_SIZE];
	struct unixsock_cmd* c;

	
	while(1) {
		reply_addr_len = sizeof(reply_addr);
		ret = recvfrom(rx_sock, buf, UNIXSOCK_BUF_SIZE, 0, 
			       (struct sockaddr*)&reply_addr, &reply_addr_len);
		if (ret == -1) {
			LOG(L_ERR, "unix_server_loop: recvfrom: (%d) %s\n", 
			    errno, strerror(errno));
			if ((errno == EINTR) || 
			    (errno == EAGAIN) || 
			    (errno == EWOULDBLOCK) || 
			    (errno == ECONNREFUSED)) {
				DBG("unix_server_loop: Got %d (%s), going on\n",
				    errno, strerror(errno));
				continue;
			}
			LOG(L_CRIT, "BUG: unix_server_loop: unexpected recvfrom error\n");
			continue;
		}

		buffer.s = buf;
		buffer.len = ret;
		unixsock_reply_reset();

		if (parse_cmd(&cmd, &buffer) < 0) {
			unixsock_reply_asciiz("400 First line malformed\n");
			unixsock_reply_send();
			continue;
		}

		buffer.s = cmd.s + cmd.len + 1;
		buffer.len -= cmd.len + 1 + 1;
		skip_line(&buffer); /* Skip the reply filename */

		c = lookup_cmd(&cmd);
		if (c == 0) {
			LOG(L_ERR, "unix_server_loop: Could not find "
			    "command '%.*s'\n", cmd.len, ZSW(cmd.s));
			unixsock_reply_printf("500 Command %.*s not found\n", cmd.len, ZSW(cmd.s));
			unixsock_reply_send();
			continue;
		}

		ret = c->f(&buffer);
		if (ret < 0) {
			LOG(L_ERR, "unix_server_loop: Command '%.*s' failed with "
			    "return value %d\n", cmd.len, ZSW(cmd.s), ret);
			     /* Note that we do not send reply here, the 
			      * function is supposed to do so, it knows the 
			      * reason of the failure better than us
			      */
		}
	}
}


static int get_uptime(void)
{
	char* t;

	time(&up_since);
	t = ctime(&up_since);
	if (strlen(t) + 1 >= MAX_CTIME_LEN) {
		LOG(L_ERR, "get_uptime: Too long date %d\n", (int)strlen(t));
		return -1;
	}
	memcpy(up_since_ctime, t, strlen(t) + 1);
	return 0;
}


/*
 * Spawn listeners
 */
int init_unixsock_children(void)
{
	int i;
	pid_t pid;
#ifdef USE_TCP
	int sockfd[2];
#endif

	if (!unixsock_name || *unixsock_name == '\0') {
		return 1;
	}

	if (get_uptime() < 0) {
		return -1;
	}
	
        if (register_core_commands() < 0) {
		close(rx_sock);
		close(tx_sock);
		return -1;
	}

	for(i = 0; i < unixsock_children; i++) {
		process_no++;
#ifdef USE_TCP
		if(!tcp_disable){
 			if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockfd)<0){
				LOG(L_ERR, "ERROR: init_unixsock_server: socketpair"
						" failed: %s\n", strerror(errno));
				return -1;
			}
		}
#endif
		pid = fork();
		if (pid < 0) {
			LOG(L_ERR, "init_unixsock_server: Unable to fork: %s\n",
			    strerror(errno));
			close(rx_sock);
			close(tx_sock);
			return -1;
		} else if (pid == 0) { /* child */
#ifdef USE_TCP
			if (!tcp_disable){
				close(sockfd[0]);
				unix_tcp_sock=sockfd[1];
			}
#endif
			/* record pid twice to avoid the child using it, before
  	        * parent gets a chance to set it*/
  	        pt[process_no].pid=getpid();
			if (init_child(PROC_UNIXSOCK) < 0) {
				LOG(L_ERR, "init_unixsock_server: Error in "
				    "init_child\n");
				close(rx_sock);
				close(tx_sock);
				return -1;
			}

			unix_server_loop(); /* Never returns */
		}

		     /* Parent */
		pt[process_no].pid = pid;
		strncpy(pt[process_no].desc, "unix domain socket server", 
			MAX_PT_DESC);
#ifdef USE_TCP
		if (!tcp_disable){
			close(sockfd[1]);
			pt[process_no].unix_sock=sockfd[0];
			pt[process_no].idx=-1; /* this is not a "tcp"
									  process*/
		}
#endif

	}

	DBG("init_unixsock_server: Unix domain socket server successfully initialized @ %s\n",
	    unixsock_name);
	return 1;
}


/*
 * Clean up
 */
void close_unixsock_server(void)
{
	struct unixsock_cmd* c;
	close(rx_sock);
	close(tx_sock);

	while(cmd_list) {
		c = cmd_list;
		cmd_list = cmd_list->next;
		pkg_free(c);
	}
}


/*
 * Register a new command
 */
int unixsock_register_cmd(char* command, unixsock_f* f)
{
	str cmd;
	struct unixsock_cmd* new_cmd;

	cmd.s = command;
	cmd.len = strlen(command);

	if (lookup_cmd(&cmd)) {
		LOG(L_ERR, "unixsock_register_cmd: Function already exists\n");
		return -1;
	}

	new_cmd = pkg_malloc(sizeof(struct unixsock_cmd));
	if (new_cmd == 0) {
		LOG(L_ERR, "register_unixsock_cmd: Out of mem\n");
		return -1;
	}

	new_cmd->name = cmd;
	new_cmd->f = f;

	new_cmd->next = cmd_list;
	cmd_list = new_cmd;
	
	DBG("unixsock_register_cmd: New command (%.*s) registered\n", 
	    cmd.len, ZSW(cmd.s));
	return 1;
}


int unixsock_add_to_reply(const char* buf, size_t len)
{
	if (reply_pos.len < len) {
		LOG(L_ERR, "unixsock_add_to_reply: Buffer too small\n");
		return -1;
	}

	memcpy(reply_pos.s, buf, len);
	reply_pos.s += len;
	reply_pos.len -= len;
	return 0;
}


/*
 * Send a reply
 */
ssize_t unixsock_reply_send(void)
{
	return tsend_dgram(tx_sock, 
			   reply_buf, reply_pos.s - reply_buf,
			   (struct sockaddr*)&reply_addr, reply_addr_len, 
			   unixsock_tx_timeout);
}


/*
 * Send a reply
 */
ssize_t unixsock_reply_sendto(struct sockaddr_un* to)
{
	if (!to) {
		LOG(L_ERR, "unixsock_reply_sendto: Invalid parameter value\n");
		return -1;
	}

	return tsend_dgram(tx_sock, 
			   reply_buf, reply_pos.s - reply_buf, 
			   (struct sockaddr*)to, SUN_LEN(to), 
			   unixsock_tx_timeout);
}


/*
 * Read a line, the result will be stored in line
 * parameter, the data is not copied, it's just
 * a pointer to an existing buffer
 */
int unixsock_read_line(str* line, str* source)
{
	if (!line || !source) {
		LOG(L_ERR, "unixsock_read_line: Invalid parameter value\n");
		return -1;
	}

	*line = *source;
	skip_line(source);
	line->len = source->s - line->s;
	trim_trailing(line);
	if (line->len) {
		return 0;
	} else {
		return 1;
	}
}


/*
 * Read body until the closing .CRLF, no CRLF recovery
 * is done so no additional buffer is necessary, body will
 * point to an existing buffer
 */
int unixsock_read_body(str* body, str* source)
{
	int i, state, last_dot;

	enum states {
		ST_BEGIN,
		ST_CRLF,
		ST_DATA,
		ST_NEWLINE
	};

	if (!body || !source) {
		LOG(L_ERR, "unixsock_read_body: Invalid parameter value\n");
		return -1;
	}

	if (source->len < 2) {
		LOG(L_ERR, "unixsock_read_body: Not enough input data "
		    "(malformed message ?)\n");
		return -1;
	}

	state = ST_BEGIN;
	body->s = source->s;
	last_dot = 0;
	for(i = 0; i < source->len; i++) {
		switch(state) {
		case ST_BEGIN:
			if (source->s[i] == '.') {
				last_dot = i;
				state = ST_CRLF;
			} else if (source->s[i] == '\n') {
				state = ST_NEWLINE;
			} else {
				state = ST_DATA;
			}
			break;
			
		case ST_CRLF:
			if (source->s[i] == '\n') {
				body->len = last_dot;
				source->s += i + 1;
				source->len -= i + 1;
				return 0;
			} else if (source->s[i] != '\r') {
				state = ST_DATA;
			}
			break;

		case ST_DATA:
			if (source->s[i] == '\n') {
				state = ST_NEWLINE;
			}
			break;

		case ST_NEWLINE:
			if (source->s[i] == '.') {
				last_dot = i;
				state = ST_CRLF;
			}
			break;
		}
	}

	LOG(L_ERR, "unixsock_read_body: Could not find the end of the body\n");
	return -1;
}


/*
 * Read a set of lines, the functions performs CRLF recovery,
 * therefore lineset must point to an additional buffer
 * to which the data will be copied. Initial lineset->len contains
 * the size of the buffer
 */
int unixsock_read_lineset(str* lineset, str* source)
{
	int i, state, len;

	enum states {
		ST_BEGIN,
		ST_CRLF,
		ST_DATA,
		ST_NEWLINE
	};

	if (!lineset || !source) {
		LOG(L_ERR, "unixsock_read_lineset: Invalid parameter value\n");
		return -1;
	}

	if (!lineset->s || !lineset->len) {
		LOG(L_ERR, "unixsock_read_lineset: Buffer too small\n");
		return -1;
	}

	if (source->len < 2) {
		LOG(L_ERR, "unixsock_read_lineset: Not enough input "
		    "data (malformed message ?)\n");
		return -1;
	}                 

	state = ST_BEGIN;
	len = 0;
	for(i = 0; i < source->len; i++) {
		if (source->s[i] == '\r') {
			     /* Filter out CR */
			continue;
		}

		switch(state) {
		case ST_BEGIN:
			if (source->s[i] == '.') {
				state = ST_CRLF;
			} else if (source->s[i] == '\n') {
				if (len + 2 > lineset->len) goto buf_err;
				lineset->s[len++] = '\r';
				lineset->s[len++] = '\n';
				state = ST_NEWLINE;
			} else {
				if (len + 1 > lineset->len) goto buf_err;
				lineset->s[len++] = source->s[i];
			}
			break;
			
		case ST_CRLF:
			if (source->s[i] == '\n') {
				lineset->len = len;
				source->s += i + 1;
				source->len -= i + 1;
				return 0;
			} else {
				if (len + 2 > lineset->len) goto buf_err;
				lineset->s[len++] = '.';
				lineset->s[len++] = source->s[i];
				state = ST_DATA;
			}
			break;

		case ST_DATA:
			if (source->s[i] == '\n') {
				if (len + 2 > lineset->len) goto buf_err;
				lineset->s[len++] = '\r';
				lineset->s[len++] = '\n';
				state = ST_NEWLINE;
			} else {
				if (len + 1 > lineset->len) goto buf_err;
				lineset->s[len++] = source->s[i];
			}
			break;

		case ST_NEWLINE:
			if (source->s[i] == '.') {
				state = ST_CRLF;
			} else {
				if (len + 1 > lineset->len) goto buf_err;
				lineset->s[len++] = source->s[i];
				state = ST_DATA;
			}
			break;
		}
	}

	LOG(L_ERR, "unixsock_read_body: Could not find the end of the body\n");
	return -1;

 buf_err:
	LOG(L_ERR, "unixsock_read_lineset: Buffer too small\n");
	return -1;
}


/*
 * Reset the reply buffer -- start to write
 * at the beginning
 */
void unixsock_reply_reset(void)
{
	reply_pos.s = reply_buf;
	reply_pos.len = UNIXSOCK_BUF_SIZE;
}


/*
 * Add ASCIIZ to the reply buffer
 */
int unixsock_reply_asciiz(char* str)
{
	int len;
	
	if (!str) {
		LOG(L_ERR, "unixsock_reply_asciiz: Invalid parameter value\n");
		return -1;
	}

	len = strlen(str);

	if (reply_pos.len < len) {
		LOG(L_ERR, "unixsock_reply_asciiz: Buffer too small\n");
		return -1;
	}

	memcpy(reply_pos.s, str, len);
	reply_pos.s += len;
	reply_pos.len -= len;
	return 0;
}


/*
 * Add a string represented by str structure
 * to the reply buffer
 */
int unixsock_reply_str(str* s)
{
	if (!s) {
		LOG(L_ERR, "unixsock_reply_str: Invalid parameter value\n");
		return -1;
	}

	if (reply_pos.len < s->len) {
		LOG(L_ERR, "unixsock_reply_str: Buffer too small\n");
		return -1;
	}
	
	memcpy(reply_pos.s, s->s, s->len);
	reply_pos.s += s->len;
	reply_pos.len -= s->len;
	return 0;
}


/*
 * Printf-like reply function
 */
int unixsock_reply_printf(char* fmt, ...)
{
	va_list ap;
	int ret;

	if (!fmt) {
		LOG(L_ERR, "unixsock_reply_printf: Invalid parameter value\n");
		return -1;
	}

	va_start(ap, fmt);
	ret = vsnprintf(reply_pos.s, reply_pos.len, fmt, ap);
	if ((ret < 0) || (ret >= reply_pos.len)) {
		LOG(L_ERR, "unixsock_reply_printf: Buffer too small\n");
		va_end(ap);
		return -1;
	}

	va_end(ap);
	reply_pos.s += ret;
	reply_pos.len -= ret;
	return 0;
}


/*
 * Return the address of the sender
 */
struct sockaddr_un* unixsock_sender_addr(void)
{
	return &reply_addr;
}