aboutsummaryrefslogtreecommitdiffstats
path: root/lib/kvstorage/libkvstorageclient.c
blob: 10e9be8a469309db55ee521dc93017eb5acfa5d0 (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
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
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
/* Copyright (c) 2010, Vsevolod Stakhov
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *       * Redistributions of source code must retain the above copyright
 *         notice, this list of conditions and the following disclaimer.
 *       * Redistributions in binary form must reproduce the above copyright
 *         notice, this list of conditions and the following disclaimer in the
 *         documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AUTHOR BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */


#include "config.h"
#include "mem_pool.h"
#include "util.h"
#include "libkvstorageclient.h"

#define MAX_KV_LINE 1024

#ifdef CRLF
#undef CRLF
#undef CR
#undef LF
#endif

#define CRLF "\r\n"
#define CR '\r'
#define LF '\n'

struct kvstorage_buf {
	guint pos;
	guint len;
	guint8 data[1];
};

struct rspamd_kvstorage_connection {
	gboolean asynced;
	gint sock;
	struct timeval tv;
	enum {
		KV_STATE_NONE = 0,
		KV_STATE_CONNECTED,
		KV_STATE_SET,
		KV_STATE_GET,
		KV_STATE_WRITE_DATA,
		KV_STATE_READ_DATA,
		KV_STATE_READ_ELT,
		KV_STATE_READ_REPLY
	} state;
	struct event ev;
	kvstorage_connect_cb conn_cb;
	kvstorage_read_cb read_cb;
	kvstorage_write_cb write_cb;
	memory_pool_t *pool;
};

struct rspamd_kvstorage_async_data {
	struct rspamd_kvstorage_connection *c;
	struct kvstorage_buf *buf;
	gchar *key;
	guint keylen;
	gpointer data;
	guint datalen;
	guint expire;
	gpointer ud;
};

/*
 * Buffer functions
 */

/*
 * Create new kvstorage_buf
 */
static struct kvstorage_buf *
rspamd_kvstorage_buf_create (guint size, memory_pool_t *pool)
{
	struct kvstorage_buf					*new;

	new = memory_pool_alloc (pool, sizeof (struct kvstorage_buf) + size);
	new->len = size;
	new->pos = 0;

	return new;
}

/*
 * Read a single line synced or asynced
 */
static gint
rspamd_kvstorage_buf_readline (struct kvstorage_buf *buf, struct rspamd_kvstorage_connection *conn)
{
	gint									r;
	guint8								   *p;

	r = read (conn->sock, buf->data, buf->len);
	if (r == -1) {
		return errno;
	}
	/* Try to parse what we have */
	p = buf->data;
	while (p - buf->data < r) {
		if (*p == '\r' || *p == '\n') {

			buf->pos = p - buf->data;
			return 0;
		}
		p ++;
	}

	if (r == (gint)buf->len) {
		/* Buffer is overflowed */
		return EOVERFLOW;
	}
	/* Line end not found */
	return EAGAIN;
}

/*
 * Read the whole buffer, return remaining characters or -1
 */
static gint
rspamd_kvstorage_buf_readall (struct kvstorage_buf *buf, struct rspamd_kvstorage_connection *conn)
{
	gint									r;

	if (buf->len - buf->pos == 0) {
		return 0;
	}
	r = read (conn->sock, buf->data + buf->pos, buf->len - buf->pos);
	if (r == -1) {
		return -1;
	}

	buf->pos += r;

	/* Line end not found */
	return buf->len - buf->pos;
}

/*
 * Write the whole buffer, return remaining characters or -1
 */
static gint
rspamd_kvstorage_buf_writeall (struct kvstorage_buf *buf, struct rspamd_kvstorage_connection *conn)
{
	gint									r;

	if (buf->len - buf->pos == 0) {
		return 0;
	}
	r = write (conn->sock, buf->data + buf->pos, buf->len - buf->pos);
	if (r == -1) {
		return -1;
	}

	buf->pos += r;

	/* Line end not found */
	return buf->len - buf->pos;
}

/*
 * Drain line from the begin of buffer, moving it from the beginning of buf
 */
static void
rspamd_kvstorage_buf_drainline (struct kvstorage_buf *buf)
{
	guint8								   *p;

	p = buf->data + buf->pos;
	/* Skip \r and \n characters */
	while (p - buf->data < (gint)buf->len && (*p == '\r' || *p == '\n')) {
		p ++;
	}
	if (p - buf->data == (gint)buf->len) {
		/* Do not move anything */
		buf->pos = 0;
		return;
	}
	memcpy (buf->data, p, buf->len - (p - buf->data));
	buf->pos = buf->len - (p - buf->data);
}

/* Common utility functions */

/*
 * Parse reply line that contains an error
 */
static enum rspamd_kvstorage_error
rspamd_kvstorage_parse_reply_error (struct kvstorage_buf *buf)
{
	guint8								   *p;
	guint                                   l = 0;

	/* Get one word */
	p = buf->data;
	while (p - buf->data < (gint)buf->pos) {
		if (g_ascii_isspace (*p)) {
			while (p - buf->data < (gint)buf->pos && g_ascii_isspace (*p)) {
				p ++;
			}
			break;
		}
		p ++;
		l ++;
	}

	/* Get common errors */
	if (g_ascii_strncasecmp (buf->data, "ERROR", MIN (l, sizeof("ERORR") - 1)) == 0) {
		return KVSTORAGE_ERROR_INTERNAL_ERROR;
	}
	else if (g_ascii_strncasecmp (buf->data, "SERVER_ERROR", MIN (l, sizeof("SERVER_ERORR") - 1)) == 0) {
		return KVSTORAGE_ERROR_SERVER_ERROR;
	}
	else if (g_ascii_strncasecmp (buf->data, "CLIENT_ERROR", MIN (l, sizeof("CLIENT_ERORR") - 1)) == 0) {
		return KVSTORAGE_ERROR_CLIENT_ERROR;
	}
	else if (g_ascii_strncasecmp (buf->data, "NOT_STORED", MIN (l, sizeof("NOT_STORED") - 1)) == 0) {
		return KVSTORAGE_ERROR_NOT_STORED;
	}
	else if (g_ascii_strncasecmp (buf->data, "NOT_FOUND", MIN (l, sizeof("NOT_FOUND") - 1)) == 0) {
		return KVSTORAGE_ERROR_NOT_FOUND;
	}
	else if (g_ascii_strncasecmp (buf->data, "EXISTS", MIN (l, sizeof("EXISTS") - 1)) == 0) {
		return KVSTORAGE_ERROR_EXISTS;
	}
	else if (g_ascii_strncasecmp (buf->data, "STORED", MIN (l, sizeof("STORED") - 1)) == 0) {
		return KVSTORAGE_ERROR_OK;
	}
	else if (g_ascii_strncasecmp (buf->data, "DELETED", MIN (l, sizeof("DELETED") - 1)) == 0) {
		return KVSTORAGE_ERROR_OK;
	}

	return KVSTORAGE_ERROR_INTERNAL_ERROR;
}

/*
 * Parse reply line, store element length
 */
static enum rspamd_kvstorage_error
rspamd_kvstorage_parse_get_line (struct kvstorage_buf *buf, guint *len, guint *flags)
{
	guint8								   *p, *c, *end;
	gboolean                                error = TRUE;
	gchar                                  *err_str;

	p = buf->data;
	end = buf->data + buf->pos;
	while (p < end) {
		if (g_ascii_isspace (*p)) {
			error = FALSE;
			while (p - buf->data < (gint)buf->pos && g_ascii_isspace (*p)) {
				p ++;
			}
			break;
		}
		p ++;
	}
	/* Here we got a word or error flag */
	if (error) {
		/* Something wrong here */
		return KVSTORAGE_ERROR_SERVER_ERROR;
	}
	if (g_ascii_strncasecmp (buf->data, "VALUE", sizeof ("VALUE") - 1) != 0) {
		return rspamd_kvstorage_parse_reply_error (buf);
	}
	/* Here we got key, flags and size items */
	/* Skip key */
	error = TRUE;
	while (p < end) {
		if (g_ascii_isspace (*p)) {
			error = FALSE;
			/* Skip spaces after key */
			while (p < end && g_ascii_isspace (*p)) {
				p ++;
			}
			break;
		}
		p ++;
	}
	if (error) {
		/* Something wrong here */
		return KVSTORAGE_ERROR_SERVER_ERROR;
	}
	/* Read flags */
	c = p;
	error = TRUE;
	while (p < end) {
		if (g_ascii_isspace (*p)) {
			error = FALSE;
			/* Skip spaces after flags */
			while (p - buf->data < (gint)buf->pos && g_ascii_isspace (*p)) {
				p ++;
			}
			break;
		}
		else if (!g_ascii_isdigit (*p)) {
			break;
		}
		p ++;
	}
	if (error) {
		/* Something wrong here */
		return KVSTORAGE_ERROR_SERVER_ERROR;
	}
	*flags = strtoul (c, &err_str, 10);
	if (!g_ascii_isspace (*err_str)) {
		return KVSTORAGE_ERROR_SERVER_ERROR;
	}
	/* Read len */
	c = p;
	while (p < end) {
		if (!g_ascii_isdigit (*p)) {
			break;
		}
		p ++;
	}
	if (error) {
		/* Something wrong here */
		return KVSTORAGE_ERROR_SERVER_ERROR;
	}
	*len = strtoul (c, &err_str, 10);
	if (!g_ascii_isspace (*err_str)) {
		return KVSTORAGE_ERROR_SERVER_ERROR;
	}

	return KVSTORAGE_ERROR_OK;
}

/* Callbacks for async API */
static void
rspamd_kvstorage_connect_cb (int fd, short what, gpointer ud)
{
	struct rspamd_kvstorage_async_data		*d = ud;
	kvstorage_connect_cb                     cb;

	cb = (kvstorage_connect_cb)d->c->conn_cb;

	if (what == EV_TIMEOUT) {
		cb (KVSTORAGE_ERROR_TIMEOUT, d->c, d->ud);
	}
	else {
		d->c->state = KV_STATE_CONNECTED;
		cb (KVSTORAGE_ERROR_OK, d->c, d->ud);
	}
}

static void
rspamd_kvstorage_read_cb (int fd, short what, gpointer ud)
{
	struct rspamd_kvstorage_async_data		*d = ud;
	kvstorage_read_cb                        cb;
	guint									 buflen, flags;
	gint									 r;
	struct kvstorage_buf 					*databuf;

	cb = (kvstorage_read_cb)d->c->read_cb;

	if (what == EV_TIMEOUT) {
		cb (KVSTORAGE_ERROR_TIMEOUT, d->key, d->keylen, NULL, 0, d->c, d->ud);
		return;
	}
	if (d->c->state == KV_STATE_GET) {
		/* Create, fill and write buffer */
		buflen = d->keylen + sizeof ("get " CRLF);
		d->buf = rspamd_kvstorage_buf_create (buflen, d->c->pool);

		r = rspamd_snprintf (d->buf->data, d->buf->len, "get %*s" CRLF,
				d->keylen, d->key);
		d->buf->len = r;
		r = rspamd_kvstorage_buf_writeall (d->buf, d->c);
		if (r > 0) {
			/* Write more data at next call of this function */
			d->c->state = KV_STATE_WRITE_DATA;
			/* Event magic */
			event_del (&d->c->ev);
			event_set (&d->c->ev, d->c->sock, EV_WRITE, rspamd_kvstorage_read_cb, d);
			if (d->c->tv.tv_sec != 0 || d->c->tv.tv_usec != 0) {
				event_add (&d->c->ev, &d->c->tv);
			}
			else {
				event_add (&d->c->ev, NULL);
			}
		}
		else if (r == 0) {
			/* We have written everything */
			d->buf = rspamd_kvstorage_buf_create (MAX_KV_LINE, d->c->pool);
			d->c->state = KV_STATE_READ_ELT;
			event_del (&d->c->ev);
			event_set (&d->c->ev, d->c->sock, EV_READ, rspamd_kvstorage_read_cb, d);
			if (d->c->tv.tv_sec != 0 || d->c->tv.tv_usec != 0) {
				event_add (&d->c->ev, &d->c->tv);
			}
			else {
				event_add (&d->c->ev, NULL);
			}
		}
		else {
			/* Error occured during writing */
			cb (KVSTORAGE_ERROR_INTERNAL_ERROR, d->key, d->keylen, NULL, 0, d->c, d->ud);
		}
	}
	else if (d->c->state == KV_STATE_WRITE_DATA) {
		r = rspamd_kvstorage_buf_writeall (d->buf, d->c);
		if (r > 0) {
			/* Write more data at next call of this function */
			d->c->state = KV_STATE_WRITE_DATA;
			/* Event magic */
			event_del (&d->c->ev);
			event_set (&d->c->ev, d->c->sock, EV_WRITE, rspamd_kvstorage_read_cb, d);
			if (d->c->tv.tv_sec != 0 || d->c->tv.tv_usec != 0) {
				event_add (&d->c->ev, &d->c->tv);
			}
			else {
				event_add (&d->c->ev, NULL);
			}
		}
		else if (r == 0) {
			/* We have written everything */
			d->c->state = KV_STATE_READ_ELT;
			d->buf = rspamd_kvstorage_buf_create (MAX_KV_LINE, d->c->pool);
			event_del (&d->c->ev);
			event_set (&d->c->ev, d->c->sock, EV_READ, rspamd_kvstorage_read_cb, d);
			if (d->c->tv.tv_sec != 0 || d->c->tv.tv_usec != 0) {
				event_add (&d->c->ev, &d->c->tv);
			}
			else {
				event_add (&d->c->ev, NULL);
			}
		}
		else {
			/* Error occured during writing */
			cb (KVSTORAGE_ERROR_INTERNAL_ERROR, d->key, d->keylen, NULL, 0, d->c, d->ud);
		}
	}
	else if (d->c->state == KV_STATE_READ_ELT) {
		/* Read element info */
		r = rspamd_kvstorage_buf_readline (d->buf, d->c);
		if (r == EAGAIN) {
			/* Read more data */
			event_del (&d->c->ev);
			event_set (&d->c->ev, d->c->sock, EV_READ, rspamd_kvstorage_read_cb, d);
			if (d->c->tv.tv_sec != 0 || d->c->tv.tv_usec != 0) {
				event_add (&d->c->ev, &d->c->tv);
			}
			else {
				event_add (&d->c->ev, NULL);
			}
		}
		else if (r == 0) {
			/* Got all data about elt */
			if ((r = rspamd_kvstorage_parse_get_line (d->buf, &d->datalen, &flags)) != KVSTORAGE_ERROR_OK) {
				cb (KVSTORAGE_ERROR_INTERNAL_ERROR, d->key, d->keylen, NULL, 0, d->c, d->ud);
				return;
			}
			rspamd_kvstorage_buf_drainline (d->buf);

			/* Now allocate and read the data */
			databuf = rspamd_kvstorage_buf_create (d->datalen, d->c->pool);
			memcpy (databuf->data, d->buf->data, d->buf->pos);
			d->buf = databuf;
			d->c->state = KV_STATE_READ_DATA;
			event_del (&d->c->ev);
			event_set (&d->c->ev, d->c->sock, EV_READ, rspamd_kvstorage_read_cb, d);
			if (d->c->tv.tv_sec != 0 || d->c->tv.tv_usec != 0) {
				event_add (&d->c->ev, &d->c->tv);
			}
			else {
				event_add (&d->c->ev, NULL);
			}
		}
		else {
			/* Error occured during reading reply line */
			cb (KVSTORAGE_ERROR_INTERNAL_ERROR, d->key, d->keylen, NULL, 0, d->c, d->ud);
		}
	}
	else if (d->c->state == KV_STATE_READ_DATA) {
		/* Read data to the buffer */
		r = rspamd_kvstorage_buf_readall (d->buf, d->c);
		if (r == 0) {
			/* All data read, read the last line */
			d->c->state = KV_STATE_READ_REPLY;
			/* Save databuf */
			d->data = d->buf->data;
			event_del (&d->c->ev);
			event_set (&d->c->ev, d->c->sock, EV_READ, rspamd_kvstorage_read_cb, d);
			if (d->c->tv.tv_sec != 0 || d->c->tv.tv_usec != 0) {
				event_add (&d->c->ev, &d->c->tv);
			}
			else {
				event_add (&d->c->ev, NULL);
			}
		}
		else if (r > 0) {
			/* Read more data into buffer */
			event_del (&d->c->ev);
			event_set (&d->c->ev, d->c->sock, EV_READ, rspamd_kvstorage_read_cb, d);
			if (d->c->tv.tv_sec != 0 || d->c->tv.tv_usec != 0) {
				event_add (&d->c->ev, &d->c->tv);
			}
			else {
				event_add (&d->c->ev, NULL);
			}
		}
		else {
			/* Error occured */
			cb (KVSTORAGE_ERROR_INTERNAL_ERROR, d->key, d->keylen, NULL, 0, d->c, d->ud);
		}
	}
	else if (d->c->state == KV_STATE_READ_REPLY) {
		/* Got something from server, try to read line */
		r = rspamd_kvstorage_buf_readline (d->buf, d->c);
		if (r == EAGAIN) {
			/* Read more data */
			event_del (&d->c->ev);
			event_set (&d->c->ev, d->c->sock, EV_READ, rspamd_kvstorage_read_cb, d);
			if (d->c->tv.tv_sec != 0 || d->c->tv.tv_usec != 0) {
				event_add (&d->c->ev, &d->c->tv);
			}
			else {
				event_add (&d->c->ev, NULL);
			}
		}
		else if (r == 0) {
			d->c->state = KV_STATE_CONNECTED;
			cb (rspamd_kvstorage_parse_reply_error (d->buf), d->key, d->keylen, d->data, d->datalen, d->c, d->ud);
		}
		else {
			/* Error occured during reading reply line */
			cb (KVSTORAGE_ERROR_INTERNAL_ERROR, d->key, d->keylen, NULL, 0, d->c, d->ud);
		}
	}
}

static void
rspamd_kvstorage_write_cb (int fd, short what, gpointer ud)
{
	struct rspamd_kvstorage_async_data		*d = ud;
	kvstorage_write_cb                       cb;
	guint									 buflen;
	gint									 r;

	cb = (kvstorage_write_cb)d->c->write_cb;

	if (what == EV_TIMEOUT) {
		cb (KVSTORAGE_ERROR_TIMEOUT, d->key, d->keylen, d->c, d->ud);
		return;
	}
	if (d->c->state == KV_STATE_SET) {
		/* Create, fill and write buffer */
		buflen = d->datalen + d->keylen + sizeof ("set  4294967296 4294967296 4294967296" CRLF);
		d->buf = rspamd_kvstorage_buf_create (buflen, d->c->pool);

		r = rspamd_snprintf (d->buf->data, d->buf->len, "set %*s %ud %ud %ud" CRLF "%*s",
				d->keylen, d->key, 0, d->expire, d->datalen, d->datalen, d->data);
		d->buf->len = r;
		r = rspamd_kvstorage_buf_writeall (d->buf, d->c);
		if (r > 0) {
			/* Write more data at next call of this function */
			d->c->state = KV_STATE_WRITE_DATA;
			/* Event magic */
			event_del (&d->c->ev);
			event_set (&d->c->ev, d->c->sock, EV_WRITE, rspamd_kvstorage_write_cb, d);
			if (d->c->tv.tv_sec != 0 || d->c->tv.tv_usec != 0) {
				event_add (&d->c->ev, &d->c->tv);
			}
			else {
				event_add (&d->c->ev, NULL);
			}
		}
		else if (r == 0) {
			/* We have written everything */
			d->buf = rspamd_kvstorage_buf_create (MAX_KV_LINE, d->c->pool);
			d->c->state = KV_STATE_READ_REPLY;
			event_del (&d->c->ev);
			event_set (&d->c->ev, d->c->sock, EV_READ, rspamd_kvstorage_write_cb, d);
			if (d->c->tv.tv_sec != 0 || d->c->tv.tv_usec != 0) {
				event_add (&d->c->ev, &d->c->tv);
			}
			else {
				event_add (&d->c->ev, NULL);
			}
		}
		else {
			/* Error occured during writing */
			cb (KVSTORAGE_ERROR_INTERNAL_ERROR, d->key, d->keylen, d->c, d->ud);
		}
	}
	else if (d->c->state == KV_STATE_WRITE_DATA) {
		r = rspamd_kvstorage_buf_writeall (d->buf, d->c);
		if (r > 0) {
			/* Write more data at next call of this function */
			d->c->state = KV_STATE_WRITE_DATA;
			/* Event magic */
			event_del (&d->c->ev);
			event_set (&d->c->ev, d->c->sock, EV_WRITE, rspamd_kvstorage_write_cb, d);
			if (d->c->tv.tv_sec != 0 || d->c->tv.tv_usec != 0) {
				event_add (&d->c->ev, &d->c->tv);
			}
			else {
				event_add (&d->c->ev, NULL);
			}
		}
		else if (r == 0) {
			/* We have written everything */
			d->c->state = KV_STATE_READ_REPLY;
			d->buf = rspamd_kvstorage_buf_create (MAX_KV_LINE, d->c->pool);
			event_del (&d->c->ev);
			event_set (&d->c->ev, d->c->sock, EV_READ, rspamd_kvstorage_write_cb, d);
			if (d->c->tv.tv_sec != 0 || d->c->tv.tv_usec != 0) {
				event_add (&d->c->ev, &d->c->tv);
			}
			else {
				event_add (&d->c->ev, NULL);
			}
		}
		else {
			/* Error occured during writing */
			cb (KVSTORAGE_ERROR_INTERNAL_ERROR, d->key, d->keylen, d->c, d->ud);
		}
	}
	else if (d->c->state == KV_STATE_READ_REPLY) {
		/* Got something from server, try to read line */
		r = rspamd_kvstorage_buf_readline (d->buf, d->c);
		if (r == EAGAIN) {
			/* Read more data */
			event_del (&d->c->ev);
			event_set (&d->c->ev, d->c->sock, EV_READ, rspamd_kvstorage_write_cb, d);
			if (d->c->tv.tv_sec != 0 || d->c->tv.tv_usec != 0) {
				event_add (&d->c->ev, &d->c->tv);
			}
			else {
				event_add (&d->c->ev, NULL);
			}
		}
		else if (r == 0) {
			d->c->state = KV_STATE_CONNECTED;
			cb (rspamd_kvstorage_parse_reply_error (d->buf), d->key, d->keylen, d->c, d->ud);
		}
		else {
			/* Error occured during reading reply line */
			cb (KVSTORAGE_ERROR_INTERNAL_ERROR, d->key, d->keylen, d->c, d->ud);
		}
	}
}

static void
rspamd_kvstorage_delete_cb (int fd, short what, gpointer ud)
{
	struct rspamd_kvstorage_async_data		*d = ud;
	kvstorage_write_cb                       cb;
	guint									 buflen;
	gint									 r;

	cb = (kvstorage_write_cb)d->c->write_cb;

	if (what == EV_TIMEOUT) {
		cb (KVSTORAGE_ERROR_TIMEOUT, d->key, d->keylen, d->c, d->ud);
		return;
	}
	if (d->c->state == KV_STATE_SET) {
		/* Create, fill and write buffer */
		buflen = MAX (MAX_KV_LINE, d->keylen + sizeof ("delete " CRLF));
		d->buf = rspamd_kvstorage_buf_create (buflen, d->c->pool);

		r = rspamd_snprintf (d->buf->data, d->buf->len, "delete %*s" CRLF,
				d->keylen, d->key);
		d->buf->len = r;
		r = rspamd_kvstorage_buf_writeall (d->buf, d->c);
		if (r > 0) {
			/* Write more data at next call of this function */
			d->c->state = KV_STATE_WRITE_DATA;
			/* Event magic */
			event_del (&d->c->ev);
			event_set (&d->c->ev, d->c->sock, EV_WRITE, rspamd_kvstorage_delete_cb, d);
			if (d->c->tv.tv_sec != 0 || d->c->tv.tv_usec != 0) {
				event_add (&d->c->ev, &d->c->tv);
			}
			else {
				event_add (&d->c->ev, NULL);
			}
		}
		else if (r == 0) {
			/* We have written everything */
			d->buf = rspamd_kvstorage_buf_create (MAX_KV_LINE, d->c->pool);
			d->c->state = KV_STATE_READ_REPLY;
			event_del (&d->c->ev);
			event_set (&d->c->ev, d->c->sock, EV_READ, rspamd_kvstorage_delete_cb, d);
			if (d->c->tv.tv_sec != 0 || d->c->tv.tv_usec != 0) {
				event_add (&d->c->ev, &d->c->tv);
			}
			else {
				event_add (&d->c->ev, NULL);
			}
		}
		else {
			/* Error occured during writing */
			cb (KVSTORAGE_ERROR_INTERNAL_ERROR, d->key, d->keylen, d->c, d->ud);
		}
	}
	else if (d->c->state == KV_STATE_WRITE_DATA) {
		r = rspamd_kvstorage_buf_writeall (d->buf, d->c);
		if (r > 0) {
			/* Write more data at next call of this function */
			d->c->state = KV_STATE_WRITE_DATA;
			/* Event magic */
			event_del (&d->c->ev);
			event_set (&d->c->ev, d->c->sock, EV_WRITE, rspamd_kvstorage_delete_cb, d);
			if (d->c->tv.tv_sec != 0 || d->c->tv.tv_usec != 0) {
				event_add (&d->c->ev, &d->c->tv);
			}
			else {
				event_add (&d->c->ev, NULL);
			}
		}
		else if (r == 0) {
			/* We have written everything */
			d->c->state = KV_STATE_READ_REPLY;
			d->buf = rspamd_kvstorage_buf_create (MAX_KV_LINE, d->c->pool);
			event_del (&d->c->ev);
			event_set (&d->c->ev, d->c->sock, EV_READ, rspamd_kvstorage_delete_cb, d);
			if (d->c->tv.tv_sec != 0 || d->c->tv.tv_usec != 0) {
				event_add (&d->c->ev, &d->c->tv);
			}
			else {
				event_add (&d->c->ev, NULL);
			}
		}
		else {
			/* Error occured during writing */
			cb (KVSTORAGE_ERROR_INTERNAL_ERROR, d->key, d->keylen, d->c, d->ud);
		}
	}
	else if (d->c->state == KV_STATE_READ_REPLY) {
		/* Got something from server, try to read line */
		r = rspamd_kvstorage_buf_readline (d->buf, d->c);
		if (r == EAGAIN) {
			/* Read more data */
			event_del (&d->c->ev);
			event_set (&d->c->ev, d->c->sock, EV_READ, rspamd_kvstorage_delete_cb, d);
			if (d->c->tv.tv_sec != 0 || d->c->tv.tv_usec != 0) {
				event_add (&d->c->ev, &d->c->tv);
			}
			else {
				event_add (&d->c->ev, NULL);
			}
		}
		else if (r == 0) {
			d->c->state = KV_STATE_CONNECTED;
			cb (rspamd_kvstorage_parse_reply_error (d->buf), d->key, d->keylen, d->c, d->ud);
		}
		else {
			/* Error occured during reading reply line */
			cb (KVSTORAGE_ERROR_INTERNAL_ERROR, d->key, d->keylen, d->c, d->ud);
		}
	}
}

/**
 *  Create async connection with rspamd
 *  @param host hostname, ip or unix socket for a server
 *  @param port port number in host byte order
 *  @param tv timeout for operations
 *  @param cb callback
 *  @param ud user data for callback
 *  @param conn target connection
 */
enum rspamd_kvstorage_error
rspamd_kvstorage_connect_async (const gchar *host,
		guint16 port, struct timeval *tv, kvstorage_connect_cb cb, gpointer ud,
		struct rspamd_kvstorage_connection **conn)
{
	struct rspamd_kvstorage_connection		*new;
	struct rspamd_kvstorage_async_data      *data;
	gint									 sock;

	/* Here we do NOT try to resolve hostname */
	if ((sock = make_universal_stream_socket (host, port, TRUE, FALSE, TRUE)) == -1) {
		return KVSTORAGE_ERROR_SERVER_ERROR;
	}

	/* Allocate new connection structure */
	new = g_malloc (sizeof (struct rspamd_kvstorage_connection));

	/* Set fields */
	new->sock = sock;
	new->state = KV_STATE_NONE;
	new->asynced = TRUE;
	if (tv != NULL) {
		memcpy (&new->tv, tv, sizeof (struct timeval));
	}
	else {
		memset (&new->tv, 0, sizeof (struct timeval));
	}

	new->conn_cb = cb;
	new->pool = memory_pool_new (memory_pool_get_size ());
	data = memory_pool_alloc (new->pool, sizeof (struct rspamd_kvstorage_async_data));
	data->ud = ud;
	data->c = new;

	/* Set event */
	event_set (&new->ev, new->sock, EV_WRITE, rspamd_kvstorage_connect_cb, data);
	if (tv != NULL) {
		event_add (&new->ev, &new->tv);
	}
	else {
		event_add (&new->ev, NULL);
	}

	*conn = new;
	return KVSTORAGE_ERROR_OK;
}

/**
 * Read key asynced
 * @param conn connection structure
 * @param key key to read
 * @param cb callback
 * @param ud user data for callback
 */
enum rspamd_kvstorage_error
rspamd_kvstorage_get_async (struct rspamd_kvstorage_connection *conn,
		const gpointer key, guint keylen, kvstorage_read_cb cb, gpointer ud)
{
	struct rspamd_kvstorage_async_data		*d;

	if (conn == NULL || conn->state != KV_STATE_CONNECTED) {
		return KVSTORAGE_ERROR_INTERNAL_ERROR;
	}
	else {
		conn->read_cb = cb;
		d = memory_pool_alloc (conn->pool, sizeof (struct rspamd_kvstorage_async_data));
		d->ud = ud;
		d->c = conn;
		d->ud = ud;
		d->key = memory_pool_strdup (conn->pool, key);
		d->keylen = keylen;
		conn->state = KV_STATE_GET;

		/* Set event */
		event_set (&conn->ev, conn->sock, EV_WRITE, rspamd_kvstorage_read_cb, d);
		if (conn->tv.tv_sec != 0) {
			event_add (&conn->ev, &conn->tv);
		}
		else {
			event_add (&conn->ev, NULL);
		}
	}
	return KVSTORAGE_ERROR_OK;
}

/**
 * Write key asynced
 * @param conn connection structure
 * @param key key to set
 * @param value data to write
 * @param cb callback
 * @param ud user data for callback
 */
enum rspamd_kvstorage_error
rspamd_kvstorage_set_async (struct rspamd_kvstorage_connection *conn,
		const gpointer key, guint keylen, const gpointer value, gsize len, guint expire, kvstorage_write_cb cb,
		gpointer ud)
{
	struct rspamd_kvstorage_async_data		*d;

	if (conn == NULL || conn->state != KV_STATE_CONNECTED) {
		return KVSTORAGE_ERROR_INTERNAL_ERROR;
	}
	else {
		conn->write_cb = cb;
		d = memory_pool_alloc (conn->pool, sizeof (struct rspamd_kvstorage_async_data));
		d->ud = ud;
		d->c = conn;
		d->ud = ud;
		d->key = memory_pool_strdup (conn->pool, key);
		d->keylen = keylen;
		d->data = value;
		d->datalen = len;
		conn->state = KV_STATE_SET;

		/* Set event */
		event_set (&conn->ev, conn->sock, EV_WRITE, rspamd_kvstorage_write_cb, d);
		if (conn->tv.tv_sec != 0) {
			event_add (&conn->ev, &conn->tv);
		}
		else {
			event_add (&conn->ev, NULL);
		}
	}
	return KVSTORAGE_ERROR_OK;
}

/**
 * Delete key asynced
 * @param conn connection structure
 * @param key key to delete
 * @param cb callback
 * @param ud user data for callback
 */
enum rspamd_kvstorage_error
rspamd_kvstorage_delete_async (struct rspamd_kvstorage_connection *conn,
		const gpointer key, guint keylen, kvstorage_write_cb cb, gpointer ud)
{
	struct rspamd_kvstorage_async_data		*d;

	if (conn == NULL || conn->state != KV_STATE_CONNECTED) {
		return KVSTORAGE_ERROR_INTERNAL_ERROR;
	}
	else {
		conn->write_cb = cb;
		d = memory_pool_alloc (conn->pool, sizeof (struct rspamd_kvstorage_async_data));
		d->ud = ud;
		d->c = conn;
		d->ud = ud;
		d->key = memory_pool_strdup (conn->pool, key);
		d->keylen = keylen;
		conn->state = KV_STATE_SET;

		/* Set event */
		event_set (&conn->ev, conn->sock, EV_WRITE, rspamd_kvstorage_delete_cb, d);
		if (conn->tv.tv_sec != 0) {
			event_add (&conn->ev, &conn->tv);
		}
		else {
			event_add (&conn->ev, NULL);
		}
	}
	return KVSTORAGE_ERROR_OK;
}

/**
 * Close connection
 * @param conn connection structure
 */
enum rspamd_kvstorage_error
rspamd_kvstorage_close_async (struct rspamd_kvstorage_connection *conn)
{
	close (conn->sock);
	memory_pool_delete (conn->pool);
	event_del (&conn->ev);
	g_free (conn);

	return KVSTORAGE_ERROR_OK;
}

/* Synced API */
/**
 *  Create sync connection with rspamd
 *  @param host hostname, ip or unix socket for a server
 *  @param port port number in host byte order
 *  @param tv timeout for operations
 *  @param conn target connection
 */
enum rspamd_kvstorage_error
rspamd_kvstorage_connect_sync (const gchar *host,
		guint16 port, struct timeval *tv,
		struct rspamd_kvstorage_connection **conn)
{
	struct rspamd_kvstorage_connection		*new;
	gint									 sock;

	if ((sock = make_universal_stream_socket (host, port, FALSE, FALSE, TRUE)) == -1) {
		return KVSTORAGE_ERROR_INTERNAL_ERROR;
	}

	/* Allocate new connection structure */
	new = g_malloc (sizeof (struct rspamd_kvstorage_connection));

	/* Set fields */
	new->sock = sock;
	new->state = KV_STATE_CONNECTED;
	new->asynced = FALSE;
	if (tv != NULL) {
		memcpy (&new->tv, tv, sizeof (struct timeval));
	}
	else {
		memset (&new->tv, 0, sizeof (struct timeval));
	}
	new->pool = memory_pool_new (memory_pool_get_size ());

	*conn = new;
	return KVSTORAGE_ERROR_OK;
}

/**
 * Read key synced
 * @param conn connection structure
 * @param key key to read
 * @param value value readed
 */
enum rspamd_kvstorage_error
rspamd_kvstorage_get_sync (struct rspamd_kvstorage_connection *conn,
		const gpointer key, guint keylen, gpointer **value, guint *len)
{
	struct kvstorage_buf 				   *buf, *databuf;
	gint                                    r;
	guint									flags;

	if (conn == NULL || conn->state != KV_STATE_CONNECTED) {
		return KVSTORAGE_ERROR_INTERNAL_ERROR;
	}

	buf = rspamd_kvstorage_buf_create (MAX_KV_LINE, conn->pool);

	r = rspamd_snprintf (buf->data, buf->len, "get %*s" CRLF, keylen, key);
	buf->len = r;
	while ((r = rspamd_kvstorage_buf_writeall (buf, conn)) > 0) {
		poll_sync_socket (conn->sock, tv_to_msec (&conn->tv), POLL_OUT);
	}

	if (r == -1) {
		return KVSTORAGE_ERROR_INTERNAL_ERROR;
	}
	/* Now read reply and try to parse line */
	buf->len = MAX_KV_LINE;
	buf->pos = 0;
	while ((r = rspamd_kvstorage_buf_readline (buf, conn)) == EAGAIN) {
		poll_sync_socket (conn->sock, tv_to_msec (&conn->tv), POLL_IN);
	}
	/* A line was read */
	if (r == 0) {
		if ((r = rspamd_kvstorage_parse_get_line (buf, len, &flags)) != KVSTORAGE_ERROR_OK) {
			return r;
		}
		rspamd_kvstorage_buf_drainline (buf);
		/* Now allocate and read the data */
		databuf = rspamd_kvstorage_buf_create (*len, conn->pool);
		memcpy (databuf->data, buf->data, buf->pos);
		while ((r = rspamd_kvstorage_buf_readall (databuf, conn)) > 0) {
			poll_sync_socket (conn->sock, tv_to_msec (&conn->tv), POLL_IN);
		}
		if (r == -1) {
			return KVSTORAGE_ERROR_INTERNAL_ERROR;
		}
		/* Now we have data inside buffer, read the last line */
		buf->pos = 0;
		while ((r = rspamd_kvstorage_buf_readline (buf, conn)) == EAGAIN) {
			poll_sync_socket (conn->sock, tv_to_msec (&conn->tv), POLL_IN);
		}
		*value = (gpointer)buf->data;
	}


	return KVSTORAGE_ERROR_OK;
}

/**
 * Write key synced
 * @param conn connection structure
 * @param key key to set
 * @param value data to write
 */
enum rspamd_kvstorage_error
rspamd_kvstorage_set_sync (struct rspamd_kvstorage_connection *conn,
		const gpointer key, guint keylen, const gpointer value, gsize len, guint expire)
{
	struct kvstorage_buf 				   *buf;
	gint                                    r, buflen;

	if (conn == NULL || conn->state != KV_STATE_CONNECTED) {
		return KVSTORAGE_ERROR_INTERNAL_ERROR;
	}

	/* Create buf */
	buflen = len + keylen + sizeof ("set  4294967296 4294967296 4294967296" CRLF);
	buf = rspamd_kvstorage_buf_create (buflen, conn->pool);

	r = rspamd_snprintf (buf->data, buf->len, "set %*s %ud %ud %ud" CRLF "%*s",
			keylen, key, 0, expire, len, len, value);
	buf->len = r;
	while ((r = rspamd_kvstorage_buf_writeall (buf, conn)) > 0) {
		poll_sync_socket (conn->sock, tv_to_msec (&conn->tv), POLL_OUT);
	}
	if (r == -1) {
		return KVSTORAGE_ERROR_INTERNAL_ERROR;
	}
	/* Now we can read reply */
	buf->pos = 0;
	buf->len = buflen;
	while ((r = rspamd_kvstorage_buf_readline (buf, conn)) == EAGAIN) {
		poll_sync_socket (conn->sock, tv_to_msec (&conn->tv), POLL_IN);
	}

	return rspamd_kvstorage_parse_reply_error (buf);
}

/**
 * Delete key synced
 * @param conn connection structure
 * @param key key to delete
 */
enum rspamd_kvstorage_error
rspamd_kvstorage_delete_sync (struct rspamd_kvstorage_connection *conn,
		const gpointer key, guint keylen)
{
	struct kvstorage_buf 				   *buf;
	gint                                    r, buflen;

	if (conn == NULL || conn->state != KV_STATE_CONNECTED) {
		return KVSTORAGE_ERROR_INTERNAL_ERROR;
	}

	/* Create buf */
	buflen = MAX (keylen + sizeof ("delete " CRLF), MAX_KV_LINE);
	buf = rspamd_kvstorage_buf_create (buflen, conn->pool);

	r = rspamd_snprintf (buf->data, buf->len, "delete %*s" CRLF,
			keylen, key);
	buf->len = r;
	while ((r = rspamd_kvstorage_buf_writeall (buf, conn)) > 0) {
		poll_sync_socket (conn->sock, tv_to_msec (&conn->tv), POLL_OUT);
	}
	if (r == -1) {
		return KVSTORAGE_ERROR_INTERNAL_ERROR;
	}
	/* Now we can read reply */
	buf->len = buflen;
	buf->pos = 0;
	while ((r = rspamd_kvstorage_buf_readline (buf, conn)) == EAGAIN) {
		poll_sync_socket (conn->sock, tv_to_msec (&conn->tv), POLL_IN);
	}

	return rspamd_kvstorage_parse_reply_error (buf);
}

/**
 * Close connection
 * @param conn connection structure
 */
enum rspamd_kvstorage_error
rspamd_kvstorage_close_sync (struct rspamd_kvstorage_connection *conn)
{
	close (conn->sock);
	memory_pool_delete (conn->pool);
	g_free (conn);

	return KVSTORAGE_ERROR_OK;
}

const gchar*
rspamd_kvstorage_strerror (enum rspamd_kvstorage_error err)
{
	switch (err) {
	case KVSTORAGE_ERROR_OK:
		return "operation completed";
	case KVSTORAGE_ERROR_TIMEOUT:
		return "operation timeout";
	case KVSTORAGE_ERROR_NOT_FOUND:
		return "key not found";
	case KVSTORAGE_ERROR_NOT_STORED:
		return "key not stored";
	case KVSTORAGE_ERROR_EXISTS:
		return "key exists";
	case KVSTORAGE_ERROR_SERVER_ERROR:
		return "server error";
	case KVSTORAGE_ERROR_CLIENT_ERROR:
		return "client error";
	case KVSTORAGE_ERROR_INTERNAL_ERROR:
		return "library error";
	}

	/* Not reached */
	return "unknown error";
}