File: request_common.c

package info (click to toggle)
c-icap 1:0.5.3-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 3,600 kB
  • sloc: ansic: 27,220; sh: 4,415; makefile: 242; perl: 95; awk: 10
file content (1590 lines) | stat: -rw-r--r-- 49,754 bytes parent folder | download | duplicates (2)
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
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
/*
 *  Copyright (C) 2004-2008 Christos Tsantilas
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This program 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
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 *  MA  02110-1301  USA.
 */

#include "common.h"
#include "c-icap.h"
#include <errno.h>
#include <ctype.h>
#include <time.h>
#include <assert.h>
#include "debug.h"
#include "request.h"
#include "simple_api.h"
#include "util.h"
#include "body.h"

const char *CI_DEFAULT_USER_AGENT = "C-ICAP-Client-Library/" VERSION;
char *CI_USER_AGENT = NULL;

static void * _os_malloc(int size)
{
    return malloc(size);
}

static void _os_free(void *ptr)
{
    free(ptr);
}

void *(*__intl_malloc)(int) = _os_malloc;
void (*__intl_free)(void *) = _os_free;


/* struct buf functions*/
void ci_buf_init(struct ci_buf *buf)
{
    buf->buf = NULL;
    buf->size = 0;
    buf->used = 0;
}

void ci_buf_reset(struct ci_buf *buf)
{
    buf->used = 0;
}
int ci_buf_mem_alloc(struct ci_buf *buf, int size)
{
    if (!(buf->buf = __intl_malloc(size * sizeof(char))))
        return 0;
    buf->size = size;
    buf->used = 0;
    return size;
}

void ci_buf_mem_free(struct ci_buf *buf)
{
    __intl_free(buf->buf);
    buf->buf = NULL;
    buf->size = 0;
    buf->used = 0;
}


int ci_buf_write(struct ci_buf *buf, char *data, int len)
{
    if (len > (buf->size - buf->used))
        return -1;
    memcpy(buf->buf + buf->used, data, len);
    buf->used += len;
    return len;
}

int ci_buf_reset_size(struct ci_buf *buf, int req_size)
{
    if (buf->size > req_size)
        return req_size;
    if (buf->buf)
        __intl_free(buf->buf);
    return ci_buf_mem_alloc(buf, req_size);
}

void ci_request_t_pack(ci_request_t * req, int is_request)
{
    ci_encaps_entity_t **elist, *e;
    char buf[256];

    req->packed = 1;

    if (is_request && req->preview >= 0) {
        sprintf(buf, "Preview: %d", req->preview);
        ci_headers_add(req->request_header, buf);
    }

    elist = req->entities;

    if (elist[0] != NULL)
        elist[0]->start = 0;

    if (elist[1] != NULL) {
        elist[1]->start = sizeofencaps(elist[0]);
    }

    if (elist[2] != NULL) {
        elist[2]->start = sizeofencaps(elist[1]) + elist[1]->start;
    }


    if (elist[0] == NULL) {
        sprintf(buf, "Encapsulated: null-body=0");
    } else if (elist[2] != NULL) {
        sprintf(buf, "Encapsulated: %s=%d, %s=%d, %s=%d",
                ci_encaps_entity_string(elist[0]->type), elist[0]->start,
                ci_encaps_entity_string(elist[1]->type), elist[1]->start,
                ci_encaps_entity_string(elist[2]->type), elist[2]->start);
    } else if (elist[1] != NULL) {
        sprintf(buf, "Encapsulated: %s=%d, %s=%d",
                ci_encaps_entity_string(elist[0]->type), elist[0]->start,
                ci_encaps_entity_string(elist[1]->type), elist[1]->start);
    } else {                   /*Only req->entities[0] exists */
        sprintf(buf, "Encapsulated: %s=%d",
                ci_encaps_entity_string(elist[0]->type), elist[0]->start);
    }
    if (is_request)
        ci_headers_add(req->request_header, buf);
    else
        ci_headers_add(req->response_header, buf);

    while ((e = *elist++) != NULL) {
        if (e->type == ICAP_REQ_HDR || e->type == ICAP_RES_HDR)
            ci_headers_pack((ci_headers_list_t *) e->entity);
    }
    /*e_list is not usable now !!!!!!! */
    if (is_request)
        ci_headers_pack(req->request_header);
    else
        ci_headers_pack(req->response_header);
}

void ci_request_pack(ci_request_t *req)
{
    ci_request_t_pack(req, 1);
}

void ci_response_pack(ci_request_t *req)
{
    ci_request_t_pack(req, 0);
}

static int block_write_nonblock(ci_connection_t *conn, char **block, int *block_size, uint64_t *counter)
{
    if (!block || !(*block) || !(block_size))
        return CI_ERROR;

    if (!*block_size)
        return CI_OK;

    int ret = ci_connection_write_nonblock(conn, *block, *block_size);
    if (ret < 0)
        return CI_ERROR;

    *counter += ret;
    *block_size -= ret;
    *block += ret;
    return *block_size > 0 ? CI_NEEDS_MORE : CI_OK;
}

/*
Valid forms of encapsulated entities

   REQMOD  request  encapsulated_list: [reqhdr] reqbody
   REQMOD  response encapsulated_list: {[reqhdr] reqbody} |
                                       {[reshdr] resbody}
   RESPMOD request  encapsulated_list: [reqhdr] [reshdr] resbody
   RESPMOD response encapsulated_list: [reshdr] resbody
   OPTIONS request  encapsulated_list: [optbody]
   OPTIONS response encapsulated_list: optbody

TODO:
   The following function must chech request and if the encapsulated entity is valid
   must put it to the right position in req->entities .........
*/

//alloc_an_entity
ci_encaps_entity_t *ci_request_alloc_entity(ci_request_t * req, int type, int val)
{
    ci_encaps_entity_t *e = NULL;

    if (type > ICAP_OPT_BODY || type < 0) {    //
        return NULL;
    }

    if (req->trash_entities[type]) {
        e = req->trash_entities[type];
        req->trash_entities[type] = NULL;
        e->type = type;
        e->start = val;
        if (e->type == ICAP_REQ_HDR
                || e->type == ICAP_RES_HDR) {
            if (e->entity)
                ci_headers_reset((ci_headers_list_t *)e->entity);
        }
        ci_debug_printf(8, "Get entity from trash....\n");
        return e;
    }

    //Else there is no available entity to trash_entities so make a new....
    ci_debug_printf(8, "Allocate a new entity of type %d\n", type);
    return mk_encaps_entity(type, val);
}


int ci_request_release_entity(ci_request_t * req, int pos)
{
    int type = 0;
    if (!req->entities[pos])
        return 0;

    type = req->entities[pos]->type;
    if (type > ICAP_OPT_BODY || type < 0) {    //?????????
        destroy_encaps_entity(req->entities[pos]);
        req->entities[pos] = NULL;
        return 0;
    }

    if (req->trash_entities[type] != NULL) {
        ci_debug_printf(3,
                        "ERROR!!!!! There is an entity of type %d to trash..... ",
                        type);
        destroy_encaps_entity(req->trash_entities[type]);
    }
    req->trash_entities[type] = req->entities[pos];
    req->entities[pos] = NULL;
    return 1;
}


ci_request_t *ci_request_alloc(ci_connection_t * connection)
{
    ci_request_t *req;
    int i;
    req = (ci_request_t *) __intl_malloc(sizeof(ci_request_t));
    if (!req)
        return NULL;

    req->connection = connection;
    req->packed = 0;
    req->user[0] = '\0';

    req->access_type = 0;

    req->service[0] = '\0';
    req->req_server[0] = '\0';
    req->current_service_mod = NULL;
    req->service_data = NULL;
    req->args[0] = '\0';
    req->type = -1;
    req->preview = -1;
    ci_buf_init(&(req->preview_data));

    req->keepalive = 1;        /*Keep alive connection is the default behaviour for icap protocol. */
    req->allow204 = 0;
    req->allow206 = 0;
    req->hasbody = 0;
    req->responce_hasbody = 0;
    req->eof_received = 0;
    req->eof_sent = 0;

    req->request_header = ci_headers_create();
    req->response_header = ci_headers_create();
    req->xheaders = ci_headers_create();
    req->status = SEND_NOTHING;
    req->return_code = -1;

    req->pstrblock_read = NULL;
    req->pstrblock_read_len = 0;
    req->current_chunk_len = 0;
    req->chunk_bytes_read = 0;
    req->write_to_module_pending = 0;

    req->pstrblock_responce = NULL;
    req->remain_send_block_bytes = 0;
    req->data_locked = 1;
    req->i206_use_original_body = -1;

    req->echo_body = NULL;

    req->preview_data_type = -1;
    req->auth_required = 0;


    req->log_str = NULL;
    req->attributes = NULL;
    memset(&(req->xclient_ip), 0, sizeof(ci_ip_t));

    req->bytes_in = 0;
    req->bytes_out = 0;
    req->request_bytes_in = 0;
    req->http_bytes_in = 0;
    req->http_bytes_out = 0;
    req->body_bytes_in = 0;
    req->body_bytes_out = 0;

    for (i = 0; i < 5; i++)    //
        req->entities[i] = NULL;
    for (i = 0; i < 7; i++)    //
        req->trash_entities[i] = NULL;

    return req;

}

/*reset_request simply reset request to use it with tunneled requests
  The req->access_type must not be reset!!!!!

  Also buffers where the pstrblock_read points must not free or reset.
*/
void ci_request_reset(ci_request_t * req)
{
    int i;
    req->packed = 0;
    req->user[0] = '\0';
    req->service[0] = '\0';
    req->current_service_mod = NULL;
    req->service_data = NULL;
    req->args[0] = '\0';
    req->type = -1;
    req->preview = -1;
    ci_buf_reset(&(req->preview_data));

    req->keepalive = 1;        /*Keep alive connection is the default behaviour for icap protocol. */
    req->allow204 = 0;
    req->allow206 = 0;
    req->hasbody = 0;
    req->responce_hasbody = 0;
    ci_headers_reset(req->request_header);
    ci_headers_reset(req->response_header);
    ci_headers_reset(req->xheaders);
    req->eof_received = 0;
    req->eof_sent = 0;

    req->status = SEND_NOTHING;
    req->return_code = -1;

    req->pstrblock_read = NULL;
    req->pstrblock_read_len = 0;
    req->current_chunk_len = 0;
    req->chunk_bytes_read = 0;
    req->pstrblock_responce = NULL;
    req->remain_send_block_bytes = 0;
    req->write_to_module_pending = 0;
    req->data_locked = 1;
    req->i206_use_original_body = -1;

    if (req->echo_body) {
        ci_ring_buf_destroy(req->echo_body);
        req->echo_body = NULL;
    }

    req->preview_data_type = -1;
    req->auth_required = 0;

    if (req->log_str)
        __intl_free(req->log_str);
    req->log_str = NULL;

    if (req->attributes)
        ci_array_destroy(req->attributes);
    req->attributes = NULL;
    memset(&(req->xclient_ip), 0, sizeof(ci_ip_t));

    req->bytes_in = 0;
    req->bytes_out = 0;
    req->request_bytes_in = 0;
    req->http_bytes_in = 0;
    req->http_bytes_out = 0;
    req->body_bytes_in = 0;
    req->body_bytes_out = 0;

    for (i = 0; req->entities[i] != NULL; i++) {
        ci_request_release_entity(req, i);
    }

    /*Reset the encapsulated response or request headers*/
    if (req->trash_entities[ICAP_REQ_HDR] &&
            req->trash_entities[ICAP_REQ_HDR]->entity)
        ci_headers_reset((ci_headers_list_t *)req->trash_entities[ICAP_REQ_HDR]->entity);
    if (req->trash_entities[ICAP_RES_HDR] &&
            req->trash_entities[ICAP_RES_HDR]->entity)
        ci_headers_reset((ci_headers_list_t *)req->trash_entities[ICAP_RES_HDR]->entity);
}

void ci_request_destroy(ci_request_t * req)
{
    int i;
    if (req->connection)
        __intl_free(req->connection);

    ci_buf_mem_free(&(req->preview_data));
    ci_headers_destroy(req->request_header);
    ci_headers_destroy(req->response_header);
    ci_headers_destroy(req->xheaders);
    for (i = 0; req->entities[i] != NULL; i++)
        destroy_encaps_entity(req->entities[i]);

    for (i = 0; i < 7; i++) {
        if (req->trash_entities[i])
            destroy_encaps_entity(req->trash_entities[i]);
    }

    if (req->echo_body) {
        ci_ring_buf_destroy(req->echo_body);
        req->echo_body = NULL;
    }

    if (req->log_str)
        __intl_free(req->log_str);

    if (req->attributes)
        ci_array_destroy(req->attributes);

    __intl_free(req);
}

char *ci_request_set_log_str(ci_request_t *req, char *logstr)
{
    int size;
    if (req->log_str)
        __intl_free(req->log_str);

    size = strlen(logstr) + 1;
    req->log_str = __intl_malloc(size*sizeof(char));
    if (!req->log_str)
        return NULL;
    strcpy(req->log_str, logstr);
    return req->log_str;
}

int  ci_request_set_str_attribute(ci_request_t *req, const char *name, const char *value)
{
    if (req->attributes == NULL) {
        req->attributes = ci_array_new(4096);
        if (!req->attributes) {
            ci_debug_printf(1, "Error allocating request attributes array!\n");
            return 0;
        }
    }

    if (!ci_str_array_add(req->attributes, name, value)) {
        ci_debug_printf(1, "Not enough space to add attribute %s:%s for service %s\n", name, value, req->service);
        return 0;
    }
    return 1;
}

int ci_request_206_origin_body(ci_request_t *req, uint64_t offset)
{
    if (!req)
        return 0;

    if (!req->allow206) {
        ci_debug_printf(1, "Request does not support allow206 responses! Can not set use-original-body extension\n");
        return 0;
    }

#if 0
    if (req->body_bytes_in < offset) {
        ci_debug_printf(1, "Can not set use-original-body extension to offset longer than the known body size");
        return 0;
    }
#endif
    req->i206_use_original_body = offset;
    return 1;
}

int process_encapsulated(ci_request_t * req, const char *buf)
{
    const char *start;
    const char *pos;
    char *end;
    int type = 0, num = 0, val = 0;
    int hasbody = 1;           /*Assume that we have a resbody or reqbody or optbody */
    start = buf + 13; /*strlen("Encapsulated:")*/
    pos = start;
    end = (char *)start;
    for (; isspace(*pos) && *pos != '\0'; ++pos);
    while (*pos != '\0') {
        type = get_encaps_type(pos, &val, &end);
        if (type < 0) /*parse error - return "400 bad request"*/
            return EC_400;
        if (num > 5)          /*In practice there is an error here .... */
            break;
        if (type == ICAP_NULL_BODY)
            hasbody = 0;     /*We have not a body */
        req->entities[num++] = ci_request_alloc_entity(req, type, val);

        assert(start != end);
        pos = end;            /* points after the value of entity.... */
        for (; (isspace(*pos) || *pos == ',') && *pos != '\0'; ++pos);
    }
    req->hasbody = hasbody;
    return EC_100;
}


enum chunk_status { READ_CHUNK_DEF = 1, READ_CHUNK_DATA };


/*
  maybe the wdata must moved to the ci_request_t and write_to_module_pending must replace wdata_len
*/
int parse_chunk_data(ci_request_t * req, char **wdata)
{
    char *end;
    const char *eofChunk;
    int chunkLen, remains, tmp;
    int read_status = 0;

    *wdata = NULL;
    if (req->write_to_module_pending) {
        /*We must not here if the chunk buffer did not flashed */
        return CI_ERROR;
    }

    while (1) {
        if (req->current_chunk_len == req->chunk_bytes_read)
            read_status = READ_CHUNK_DEF;
        else
            read_status = READ_CHUNK_DATA;

        if (read_status == READ_CHUNK_DEF) {
            if ((eofChunk = strnstr(req->pstrblock_read, "\r\n", req->pstrblock_read_len)) == NULL) {
                /*Check for wrong protocol data, or possible parse error*/
                if (req->pstrblock_read_len >= BUFSIZE)
                    return CI_ERROR; /* To big chunk definition?*/
                return CI_NEEDS_MORE;
            }
            eofChunk += 2;
            chunkLen = eofChunk - req->pstrblock_read;
            // Count parse data
            req->request_bytes_in += (eofChunk - req->pstrblock_read);

            errno = 0;
            tmp = strtol(req->pstrblock_read, &end, 16);
            /*here must check for erron */
            if (tmp == 0 && req->pstrblock_read == end) {    /*Oh .... an error ... */
                ci_debug_printf(5, "Parse error:count=%d,start=%c\n",
                                tmp, req->pstrblock_read[0]);
                return CI_ERROR;
            }
            req->current_chunk_len = tmp;
            req->chunk_bytes_read = 0;

            while (*end == ' ' || *end == '\t') ++end; /*ignore spaces*/
            if (req->current_chunk_len == 0) {
                remains = req->pstrblock_read_len - chunkLen;
                if (remains < 2) /*missing the \r\n of the 0[; ...]\r\n\r\n of the eof chunk*/
                    return CI_NEEDS_MORE;

                if (*eofChunk != '\r' && *(eofChunk + 1) != '\n')
                    return CI_ERROR; /* Not an \r\n\r\n eof chunk definition. Parse Error*/

                eofChunk += 2;
                chunkLen += 2;
                req->request_bytes_in += 2; /*count 2 extra chars on parsed data*/

                if (*end == ';') {
                    end++;
                    while (*end == ' ' || *end == '\t') ++end; /*ignore spaces*/
                    remains = req->pstrblock_read_len - (end - req->pstrblock_read);
                    if (remains >= 18 && strncmp(end, "use-original-body=", 18) == 0) {
                        req->i206_use_original_body = strtol(end + 18, &end, 10);
                    } else if (remains >= 4 && strncmp(end, "ieof", 4) != 0)
                        return CI_ERROR;
                    // ignore any char after ';'
                    while (*end != '\r') ++end;
                    req->eof_received = 1;
                }

            } else {
                read_status = READ_CHUNK_DATA;
                /*include the \r\n end of chunk data */
                req->current_chunk_len += 2;
            }

            /*The end pointing after the number and extensions. Should point to \r\n*/
            if (*end != '\r' || *(end + 1) != '\n') {
                /*Extra chars in chunk definition!*/
                return CI_ERROR;
            }

            req->pstrblock_read_len -= chunkLen;
            req->pstrblock_read += chunkLen;
        }
        if (req->current_chunk_len == 0) /*zero chunk received, stop for now*/
            return CI_EOF;

        /*if we have data for service leaving this function now */
        if (req->write_to_module_pending)
            return CI_OK;
        if (read_status == READ_CHUNK_DATA) {
            if (req->pstrblock_read_len <= 0) {
                return CI_NEEDS_MORE;
            }
            *wdata = req->pstrblock_read;
            remains = req->current_chunk_len - req->chunk_bytes_read;
            if (remains <= req->pstrblock_read_len) {        /*we have all the chunks data */
                if (remains > 2) {
                    req->write_to_module_pending = remains - 2;
                    req->http_bytes_in += req->write_to_module_pending;
                    req->body_bytes_in += req->write_to_module_pending;
                } else      /*we are in all or part of the \r\n end of chunk data */
                    req->write_to_module_pending = 0;
                req->chunk_bytes_read += remains;
                req->pstrblock_read += remains;
                req->pstrblock_read_len -= remains;
                req->request_bytes_in += remains; //append parsed data
            } else {
                tmp = remains - req->pstrblock_read_len;
                if (tmp < 2) {
                    req->write_to_module_pending =
                        req->pstrblock_read_len - tmp;
                } else {
                    req->write_to_module_pending = req->pstrblock_read_len;
                }
                req->http_bytes_in += req->write_to_module_pending;
                req->body_bytes_in += req->write_to_module_pending;
                req->request_bytes_in += req->pstrblock_read_len; //append parsed data

                req->chunk_bytes_read += req->pstrblock_read_len;
                req->pstrblock_read += req->pstrblock_read_len;
                req->pstrblock_read_len -= req->pstrblock_read_len;
            }
        }
        if (req->pstrblock_read_len == 0)
            return CI_NEEDS_MORE;
    }

    return CI_OK;
}

int net_data_read(ci_request_t * req)
{
    int bytes;

    if (req->pstrblock_read != req->rbuf) {
        /*... put the current data to the begining of buf .... */
        if (req->pstrblock_read_len)
            memmove(req->rbuf, req->pstrblock_read, req->pstrblock_read_len);
        req->pstrblock_read = req->rbuf;
    }

    bytes = BUFSIZE - req->pstrblock_read_len;
    if (bytes <= 0) {
        ci_debug_printf(5,
                        "Not enough space to read data! Is this a bug (%d %d)?????\n",
                        req->pstrblock_read_len, BUFSIZE);
        return CI_ERROR;
    }

    if ((bytes = ci_connection_read_nonblock(req->connection, req->rbuf + req->pstrblock_read_len, bytes)) < 0) {    /*... read some data... */
        ci_debug_printf(5, "Error reading data (read return=%d, errno=%d) \n", bytes, errno);
        return CI_ERROR;
    }
    req->pstrblock_read_len += bytes;  /* ... (size of data is readed plus old)... */
    req->bytes_in += bytes;
    return CI_OK;
}




/*************************************************************************/
/* ICAP client functions                                                 */


ci_request_t *ci_client_request(ci_connection_t * conn, const char *server,
                                const char *service)
{
    ci_request_t *req;
    req = ci_request_alloc(conn);
    if (!req) {
        ci_debug_printf(1, "Error allocation ci_request_t object(ci_client_request())\n");
        return NULL;
    }
    strncpy(req->req_server, server, CI_MAXHOSTNAMELEN);
    req->req_server[CI_MAXHOSTNAMELEN] = '\0';
    strncpy(req->service, service, MAX_SERVICE_NAME);
    req->service[MAX_SERVICE_NAME] = '\0';
    return req;
}


void ci_client_request_reuse(ci_request_t * req)
{
    int i;

    req->packed = 0;
    req->args[0] = '\0';
    req->type = -1;
    ci_buf_reset(&(req->preview_data));

    req->hasbody = 0;
    req->responce_hasbody = 0;
    ci_headers_reset(req->request_header);
    ci_headers_reset(req->response_header);
    ci_headers_reset(req->xheaders);
    req->eof_received = 0;
    req->eof_sent = 0;
    req->status = 0;

    req->pstrblock_read = NULL;
    req->pstrblock_read_len = 0;
    req->current_chunk_len = 0;
    req->chunk_bytes_read = 0;
    req->pstrblock_responce = NULL;
    req->remain_send_block_bytes = 0;
    req->write_to_module_pending = 0;
    req->data_locked = 1;

    req->allow204 = 0;
    req->allow206 = 0;
    req->i206_use_original_body = -1;

    req->bytes_in = 0;
    req->bytes_out = 0;
    req->http_bytes_in = 0;
    req->http_bytes_out = 0;
    req->body_bytes_in = 0;
    req->body_bytes_out = 0;

    for (i = 0; req->entities[i] != NULL; i++) {
        ci_request_release_entity(req, i);
    }

}



static int client_create_request(ci_request_t * req, char *servername, char *service,
                                 int reqtype)
{
    char buf[256];

    if (reqtype != ICAP_OPTIONS && reqtype != ICAP_REQMOD
            && reqtype != ICAP_RESPMOD)
        return CI_ERROR;

    req->type = reqtype;
    snprintf(buf, 255, "%s icap://%s/%s ICAP/1.0",
             ci_method_string(reqtype), servername, service);
    buf[255] = '\0';
    ci_headers_add(req->request_header, buf);
    snprintf(buf, 255, "Host: %s", servername);
    buf[255] = '\0';
    ci_headers_add(req->request_header, buf);

    const char* useragent = NULL;
    if (CI_USER_AGENT) {
        if (CI_USER_AGENT[0])
            useragent = CI_USER_AGENT;
    } else {
        useragent = CI_DEFAULT_USER_AGENT;
    }

    if (useragent) {
        snprintf(buf, 255, "User-Agent: %s", useragent);
        ci_headers_add(req->request_header, buf);
    }

    if (ci_allow204(req) && ci_allow206(req))
        ci_headers_add(req->request_header, "Allow: 204, 206");
    else if (ci_allow204(req))
        ci_headers_add(req->request_header, "Allow: 204");
    if (ci_allow206(req))
        ci_headers_add(req->request_header, "Allow: 206");

    if (!ci_headers_is_empty(req->xheaders)) {
        ci_headers_addheaders(req->request_header, req->xheaders);
    }

    return CI_OK;
}

static int get_request_options(ci_request_t * req, ci_headers_list_t * h)
{
    const char *pstr;

    if ((pstr = ci_headers_value(h, "Preview")) != NULL) {
        req->preview = strtol(pstr, NULL, 10);
    } else
        req->preview = -1;


    req->allow204 = 0;
    if ((pstr = ci_headers_value(h, "Allow")) != NULL) {
        if (strtol(pstr, NULL, 10) == 204)
            req->allow204 = 1;
    }

    if ((pstr = ci_headers_value(h, "Connection")) != NULL
            && strncmp(pstr, "close", 5) == 0) {
        req->keepalive = 0;
    }

    /*Moreover we are interested for the followings */
    if ((pstr = ci_headers_value(h, "Transfer-Preview")) != NULL) {
        /*Not implemented yet */
    }

    if ((pstr = ci_headers_value(h, "Transfer-Ignore")) != NULL) {
        /*Not implemented yet */
    }

    if ((pstr = ci_headers_value(h, "Transfer-Complete")) != NULL) {
        /*Not implemented yet */
    }

    /*
       The headers Max-Connections and  Options-TTL are not needed in this client
       but if this functions moves to a general client api must be implemented
     */

    return CI_OK;
}

static ci_headers_list_t* get_headers_from_entities(ci_encaps_entity_t** entities, int type)
{
    ci_encaps_entity_t* e;
    while ((e = *entities++) != NULL) {
        if (e->type == type)
            return (ci_headers_list_t*)(e->entity);
    }
    return NULL;
}


static int client_send_request_headers(ci_request_t * req, int has_eof)
{
    int ret;

    if (req->status == CLIENT_SEND_HEADERS_WRITE_NOTHING) {
        ci_request_pack(req);
        req->status = CLIENT_SEND_HEADERS_WRITE_ICAP_HEADERS;
        req->pstrblock_responce = req->request_header->buf;
        req->remain_send_block_bytes = req->request_header->bufused;
    }

    if (!req->remain_send_block_bytes)
        return CI_OK;

    ret = block_write_nonblock(req->connection, &req->pstrblock_responce, &req->remain_send_block_bytes, &req->bytes_out);
    if (ret != CI_OK)
        return ret;

    if (req->status == CLIENT_SEND_HEADERS_WRITE_ICAP_HEADERS) {
        req->status = CLIENT_SEND_HEADERS_WRITE_REQ_HEADERS;
        ci_headers_list_t *headers = get_headers_from_entities(req->entities, ICAP_REQ_HDR);
        if (headers) {
            req->pstrblock_responce = headers->buf;
            req->remain_send_block_bytes = headers->bufused;
            return CI_NEEDS_MORE;
        }
    }

    if (req->status == CLIENT_SEND_HEADERS_WRITE_REQ_HEADERS) {
        req->status = CLIENT_SEND_HEADERS_WRITE_RES_HEADERS;
        ci_headers_list_t *headers = get_headers_from_entities(req->entities, ICAP_RES_HDR);
        if (headers) {
            req->pstrblock_responce = headers->buf;
            req->remain_send_block_bytes = headers->bufused;
            return CI_NEEDS_MORE;
        }
    }

    if (req->status == CLIENT_SEND_HEADERS_WRITE_RES_HEADERS) {

        if (req->preview > 0 && req->preview_data.used > 0) {
            int bytes = sprintf(req->wbuf, "%x\r\n", req->preview);
            req->status = CLIENT_SEND_HEADERS_WRITE_PREVIEW_INFO;
            req->pstrblock_responce = req->wbuf;
            req->remain_send_block_bytes = bytes;
            return CI_NEEDS_MORE;
        } else if (req->preview == 0) {
            int bytes = sprintf(req->wbuf, "0\r\n\r\n");
            req->status = CLIENT_SEND_HEADERS_WRITE_EOF_INFO;
            req->pstrblock_responce = req->wbuf;
            req->remain_send_block_bytes = bytes;
            return CI_NEEDS_MORE;
        } else {
            req->status = CLIENT_PROCESS_DATA;
            assert(req->remain_send_block_bytes == 0);
        }
    }

    if (req->status == CLIENT_SEND_HEADERS_WRITE_PREVIEW_INFO) {
        req->status = CLIENT_SEND_HEADERS_WRITE_PREVIEW;
        req->pstrblock_responce = req->preview_data.buf;
        req->remain_send_block_bytes = req->preview_data.used;
        return CI_NEEDS_MORE;
    }

    if (req->status == CLIENT_SEND_HEADERS_WRITE_PREVIEW) {
        req->status = CLIENT_SEND_HEADERS_WRITE_EOF_INFO;
        int bytes = sprintf(req->wbuf, "\r\n0%s\r\n\r\n", has_eof ? "; ieof" : "");
        req->pstrblock_responce = req->wbuf;
        req->remain_send_block_bytes = bytes;
        return CI_NEEDS_MORE;
    }

    if (req->status == CLIENT_SEND_HEADERS_WRITE_EOF_INFO) {
        if (has_eof)
            req->eof_sent = 1;

        req->status = CLIENT_PROCESS_DATA;
    }

    return CI_OK;
}


/*this function check if there is enough space in buffer buf ....*/
static int check_realloc(char **buf, int *size, int used, int mustadded)
{
    char *newbuf;
    int len;
    while (*size - used < mustadded) {
        len = *size + HEADSBUFSIZE;
        newbuf = realloc(*buf, len);
        if (!newbuf) {
            return EC_500;
        }
        *buf = newbuf;
        *size = *size + HEADSBUFSIZE;
    }
    return CI_OK;
}


static int client_parse_icap_header(ci_request_t * req, ci_headers_list_t * h)
{
    int readed = 0, eoh = 0;
    char *buf;
    const char *end;
    if (req->pstrblock_read_len < 4)   /*we need 4 bytes for the end of headers "\r\n\r\n" string */
        return CI_NEEDS_MORE;
    if ((end = strnstr(req->pstrblock_read, "\r\n\r\n", req->pstrblock_read_len)) != NULL) {
        readed = end - req->pstrblock_read + 4;
        eoh = 1;
    } else
        readed = req->pstrblock_read_len - 3;

    if (check_realloc(&(h->buf), &(h->bufsize), h->bufused, readed) != CI_OK)
        return CI_ERROR;

    buf = h->buf + h->bufused;
    memcpy(buf, req->pstrblock_read, readed);
    h->bufused += readed;
    req->pstrblock_read += readed;
    req->pstrblock_read_len -= readed;

    if (!eoh)
        return CI_NEEDS_MORE;

    h->bufused -= 2;           /*We keep the first \r\n  of the eohead sequence and the other dropped
                                   So stupid but for the time never mind.... */

    /* Zero-terminate buffer to avoid valgrind errors */
    h->buf[h->bufused] = '\0';
    return CI_OK;
}

static int client_parse_encaps_header(ci_request_t * req, ci_headers_list_t * h, int size)
{
    int remains, readed = 0;
    char *buf_end = NULL;

//     readed = h->bufused;
    remains = size - h->bufused;
    if (remains < 0)           /*is it possible ????? */
        return CI_ERROR;
    if (remains == 0)
        return CI_OK;

    if (req->pstrblock_read_len > 0) {
        readed =
            (remains >
             req->pstrblock_read_len ? req->pstrblock_read_len : remains);
        memcpy(h->buf + h->bufused, req->pstrblock_read, readed);
        h->bufused += readed;
        req->pstrblock_read = (req->pstrblock_read) + readed;
        req->pstrblock_read_len = (req->pstrblock_read_len) - readed;

    }

    if (h->bufused < size)
        return CI_NEEDS_MORE;

    buf_end = h->buf + h->bufused;
    if (strncmp(buf_end - 4, "\r\n\r\n", 4) == 0) {
        h->bufused -= 2;      /*eat the last 2 bytes of "\r\n\r\n" */
        return CI_OK;
    } else {
        ci_debug_printf(1, "Error parsing encapsulated headers,"
                        "no \\r\\n\\r\\n at the end of headers:%s!\n",
                        buf_end);
    }

    return CI_ERROR;

}

int ci_client_get_server_options_nonblocking(ci_request_t * req)
{
    int ret, i;

    if (req->status == CLIENT_INIT) {
        if (CI_OK != client_create_request(req, req->req_server,
                                           req->service, ICAP_OPTIONS)) {
            return CI_ERROR;
        }
        req->status = CLIENT_SEND_HEADERS;
    }

    if (req->status >= CLIENT_SEND_HEADERS && req->status < CLIENT_SEND_HEADERS_FINISHED) {
        ret = client_send_request_headers(req, 0);
        if (ret == CI_NEEDS_MORE)
            return NEEDS_TO_WRITE_TO_ICAP;
        else if (ret == CI_ERROR)
            return CI_ERROR;

        req->status = CLIENT_SEND_HEADERS_FINISHED;
    }

    if (req->status == CLIENT_SEND_HEADERS_FINISHED) {
        // Reset encaps entities to receive new entities from server
        for (i = 0; req->entities[i] != NULL; i++)
            ci_request_release_entity(req, i);

        req->status = CLIENT_PROCESS_DATA;
        return NEEDS_TO_READ_FROM_ICAP;
    }

    if (req->status >= CLIENT_PROCESS_DATA) {
        if (net_data_read(req) == CI_ERROR)
            return CI_ERROR;

        ret = client_parse_icap_header(req, req->response_header);

        if (ret == CI_NEEDS_MORE)
            return NEEDS_TO_READ_FROM_ICAP;
        else if (ret == CI_ERROR)
            return CI_ERROR;
        ci_headers_unpack(req->response_header);
        get_request_options(req, req->response_header);
    }
    return 0;
}

int ci_client_get_server_options(ci_request_t * req, int timeout)
{
    int status;
    int wait;
    do {
        status = ci_client_get_server_options_nonblocking(req);
        if (status == CI_ERROR)
            return CI_ERROR;

        wait = 0;
        if (status & NEEDS_TO_READ_FROM_ICAP)
            wait |= ci_wait_for_read;

        if (status & NEEDS_TO_WRITE_TO_ICAP)
            wait |= ci_wait_for_write;

        if (wait) {
            int ret;
            do {
                ret = ci_connection_wait(req->connection, timeout, wait);
                if (ret <= 0)
                    return CI_ERROR;
            } while (ret & ci_wait_should_retry);
        }
    } while (status);

    return CI_OK;
}


ci_connection_t *ci_client_connect_to(char *servername, int port, int proto)
{
    return ci_connect_to(servername, port, proto, -1);
}


static int client_prepere_body_chunk(ci_request_t * req, void *data,
                                     int (*readdata) (void *data, char *, int))
{
    int chunksize, def_bytes;
    char *wbuf = NULL;
    char tmpbuf[EXTRA_CHUNK_SIZE];


    wbuf = req->wbuf + EXTRA_CHUNK_SIZE;       /*Let size of EXTRA_CHUNK_SIZE space in the beggining of chunk */
    chunksize = (*readdata) (data, wbuf, MAX_CHUNK_SIZE);
    if (chunksize == CI_EOF || chunksize == 0) {
        req->remain_send_block_bytes = 0;
        return chunksize == CI_EOF ? CI_EOF : CI_NEEDS_MORE;
    } else if (chunksize < 0)
        return chunksize;

    wbuf += chunksize;         /*Put the "\r\n" sequence at the end of chunk */
    *(wbuf++) = '\r';
    *wbuf = '\n';

    def_bytes = snprintf(tmpbuf, EXTRA_CHUNK_SIZE, "%x\r\n", chunksize);
    wbuf = req->wbuf + EXTRA_CHUNK_SIZE - def_bytes;   /*Copy the chunk define in the beggining of chunk ..... */
    memcpy(wbuf, tmpbuf, def_bytes);

    req->pstrblock_responce = wbuf;
    req->remain_send_block_bytes = def_bytes + chunksize + 2;

    return CI_OK;
}


static int client_parse_incoming_data(ci_request_t * req, void *data_dest,
                                      int (*dest_write) (void *, char *, int))
{
    int ret, v1, v2, status, bytes, size;
    char *buf;
    const char *val;
    ci_headers_list_t *resp_heads;

    if (req->status == CLIENT_PROCESS_DATA_GET_NOTHING) {
        /*And reading the new ..... */
        ret = client_parse_icap_header(req, req->response_header);
        if (ret != CI_OK)
            return ret;
        if (3 != sscanf(req->response_header->buf, "ICAP/%d.%d %3d", &v1, &v2, &status))
            return CI_ERROR;
        req->return_code = status;
        ci_debug_printf(3, "Response was with status:%d \n", status);
        ci_headers_unpack(req->response_header);

        if (ci_allow204(req) && status == 204) {
            req->status = CLIENT_PROCESS_DATA_GET_EOF;
            return 204;
        }

        if ((val = ci_headers_search(req->response_header, "Encapsulated")) == NULL) {
            ci_debug_printf(1, "No encapsulated entities!\n");
            return CI_ERROR;
        }
        process_encapsulated(req, val);

        if (!req->entities[0])
            return CI_ERROR;

        if (!req->entities[1]) {      /*Then we have only body */
            req->status = CLIENT_PROCESS_DATA_GET_BODY;
            if (req->pstrblock_read_len == 0)
                return CI_NEEDS_MORE;
        } else {
            req->status = CLIENT_PROCESS_DATA_GET_HEADERS;
            size = req->entities[1]->start - req->entities[0]->start;
            resp_heads = req->entities[0]->entity;
            if (!ci_headers_setsize(resp_heads, size))
                return CI_ERROR;
        }

//        return CI_NEEDS_MORE;
    }

    /*read encups headers */

    /*Non option responce has one or two entities:
       "req-headers req-body|null-body" or [resp-headers] resp-body||null-body
       So here client_parse_encaps_header will be called for one headers block
     */

    if (req->status == CLIENT_PROCESS_DATA_GET_HEADERS) {
        size = req->entities[1]->start - req->entities[0]->start;
        resp_heads = req->entities[0]->entity;
        if ((ret =
                    client_parse_encaps_header(req, resp_heads, size)) != CI_OK)
            return ret;


        ci_headers_unpack(resp_heads);
        ci_debug_printf(5, "OK reading headers, going to read body\n");

        /*reseting body chunks related variables */
        req->current_chunk_len = 0;
        req->chunk_bytes_read = 0;
        req->write_to_module_pending = 0;

        if (req->entities[1]->type == ICAP_NULL_BODY) {
            req->status = CLIENT_PROCESS_DATA_GET_EOF;
            return CI_OK;
        } else {
            req->status = CLIENT_PROCESS_DATA_GET_BODY;
            if (req->pstrblock_read_len == 0)
                return CI_NEEDS_MORE;
        }
    }

    if (req->status == CLIENT_PROCESS_DATA_GET_BODY) {
        do {
            if ((ret = parse_chunk_data(req, &buf)) == CI_ERROR) {
                ci_debug_printf(1,
                                "Error parsing chunks, current chunk len: %d, read: %d, readlen: %d, str: %.*s\n",
                                req->current_chunk_len,
                                req->chunk_bytes_read,
                                req->pstrblock_read_len,
                                (req->pstrblock_read_len < 64 ? req->pstrblock_read_len : 64),
                                req->pstrblock_read);
                return CI_ERROR;
            }

            while (req->write_to_module_pending > 0) {
                bytes =
                    (*dest_write) (data_dest, buf,
                                   req->write_to_module_pending);
                if (bytes < 0) {
                    ci_debug_printf(1, "Error writing to output file!\n");
                    return CI_ERROR;
                }
                req->write_to_module_pending -= bytes;
            }

            if (ret == CI_EOF) {
                req->status = CLIENT_PROCESS_DATA_GET_EOF;
                return CI_OK;
            }
        } while (ret != CI_NEEDS_MORE);

        return CI_NEEDS_MORE;
    }

    return CI_OK;
}

static const char *eof_str = "0\r\n\r\n";

static int ci_client_send_and_get_data(ci_request_t * req,
                                       void *data_source, int (*source_read) (void *, char *,
                                               int),
                                       void *data_dest, int (*dest_write) (void *, char *,
                                               int),
                                       int io_action_in
                                      )
{
    int read_status, bytes;
    int needs_user_data = 0;
    if (!data_source)
        req->eof_sent = 1;

    if (io_action_in & ci_wait_for_write) {
        if (req->remain_send_block_bytes == 0) {
            if (!req->eof_sent && data_source) {
                switch (client_prepere_body_chunk(req, data_source, source_read)) {
                case CI_ERROR:
                    return CI_ERROR;
                case CI_NEEDS_MORE:
                    needs_user_data = 1;
                    break;
                case CI_EOF:
                    req->eof_sent = 1;
                    req->pstrblock_responce = (char *) eof_str;
                    req->remain_send_block_bytes = 5;
                    break;
                }
            }
        }
        if (req->remain_send_block_bytes > 0) {
            bytes = ci_connection_write_nonblock(req->connection,
                                                 req->pstrblock_responce,
                                                 req->remain_send_block_bytes);
            if (bytes < 0)
                return CI_ERROR;
            req->bytes_out += bytes;
            req->pstrblock_responce += bytes;
            req->remain_send_block_bytes -= bytes;
        }
    }

    if (io_action_in & ci_wait_for_read) {
        if (net_data_read(req) == CI_ERROR)
            return CI_ERROR;

        read_status = client_parse_incoming_data(req, data_dest, dest_write);
        if (read_status == CI_ERROR)
            return CI_ERROR;

        if (read_status == 204) {
            req->return_code = 204;
            return 0;
        }
    }

    int client_action = 0;

    if (needs_user_data)
        client_action |= NEEDS_TO_READ_USER_DATA;

    if (req->write_to_module_pending > 0)
        client_action |= NEEDS_TO_WRITE_USER_DATA;

    if (!req->eof_sent || req->remain_send_block_bytes)
        client_action |= NEEDS_TO_WRITE_TO_ICAP;

    if (req->status != CLIENT_PROCESS_DATA_GET_EOF)
        client_action |= NEEDS_TO_READ_FROM_ICAP;

    return client_action;
}

static int client_build_headers(ci_request_t *req, int has_reqhdr, int has_reshdr, int has_body)
{
    int i = 0;

    for (i = 0; i < 4; i++) {
        if (req->entities[i]) {
            ci_request_release_entity(req, i);
        }
    }
    i = 0;

    if (has_reqhdr)
        req->entities[i++] = ci_request_alloc_entity(req, ICAP_REQ_HDR, 0);
    if (has_reshdr)
        req->entities[i++] = ci_request_alloc_entity(req, ICAP_RES_HDR, 0);
    if (has_body)
        req->entities[i] = ci_request_alloc_entity(req, req->type == ICAP_RESPMOD ? ICAP_RES_BODY : ICAP_REQ_BODY, 0);
    else
        req->entities[i] = ci_request_alloc_entity(req, ICAP_NULL_BODY, 0);
    return 1;
}


static int ci_client_handle_previewed_response(ci_request_t * req, int *preview_status)
{
    int v1, v2, ret;
    const char *val;

    if (net_data_read(req) == CI_ERROR)
        return CI_ERROR;

    ret = client_parse_icap_header(req, req->response_header);
    if (ret != CI_OK)
        return ret;

    if (3 != sscanf(req->response_header->buf, "ICAP/%d.%d %3d", &v1, &v2, preview_status))
        return CI_ERROR;

    ci_debug_printf(3, "Preview response was with status: %d \n",
                    *preview_status);
    if (*preview_status == 204) {
        ci_headers_unpack(req->response_header);
    } else if ((req->eof_sent && *preview_status == 200) || *preview_status == 206) {
        ci_headers_unpack(req->response_header);
        if ((val = ci_headers_search(req->response_header, "Encapsulated")) == NULL) {
            ci_debug_printf(1, "No encapsulated entities!\n");
            return CI_ERROR;
        }
        process_encapsulated(req, val);
        if (!req->entities[1])   /*Then we have only body */
            req->status = CLIENT_PROCESS_DATA_GET_BODY;
        else
            req->status = CLIENT_PROCESS_DATA_GET_HEADERS;
    } else {
        if (*preview_status == 100)
            req->status = CLIENT_PROCESS_DATA;
        ci_headers_reset(req->response_header);
    }
    return CI_OK;
}

static int prepare_headers(ci_request_t * req,
                           ci_headers_list_t * req_headers,
                           ci_headers_list_t * resp_headers,
                           void *data_source, int (*source_read) (void *, char *, int))
{
    int i, ret, remains, pre_eof = 0;
    char *buf;

    if (CI_OK !=
            client_create_request(req, req->req_server, req->service,
                                  req->type)) {
        ci_debug_printf(1, "Error making respmod request ....\n");
        return CI_ERROR;
    }

    if (!data_source)
        req->preview = -1;

    if (req->preview > 0) {    /*The preview data will be send with headers.... */
        ci_buf_mem_alloc(&(req->preview_data), req->preview); /*Alloc mem for preview data */
        buf = req->preview_data.buf;
        remains = req->preview;
        while (remains && !pre_eof) { /*Getting the preview data */
            ret = (*source_read) (data_source, buf, remains);
            if (ret == CI_EOF || ret == 0)
                pre_eof = 1;
            else if (ret < 0)
                return ret;
            else
                remains -= ret;
        }
        req->preview -= remains;
        req->preview_data.used = req->preview;
    }
    if (pre_eof)
        req->eof_sent = 1;

    /*Bulid client request structure*/
    if (!client_build_headers(req, (req_headers != NULL), (resp_headers != NULL), (data_source != NULL)))
        return CI_ERROR;

    /*Add the user supplied headers */
    if (req_headers) {
        ci_debug_printf(5, "Going to add %d request headers\n", req_headers->used);
        for (i = 0; i < req_headers->used; i++) {
            ci_debug_printf(8, "Add request header: %s\n", req_headers->headers[i]);
            ci_http_request_add_header(req, req_headers->headers[i]);
        }
    }
    if (resp_headers) {
        ci_debug_printf(5, "Going to add %d response headers\n", resp_headers->used);
        for (i = 0; i < resp_headers->used; i++) {
            ci_debug_printf(8, "Add resp header: %s\n", resp_headers->headers[i]);
            ci_http_response_add_header(req, resp_headers->headers[i]);
        }
    }

    req->status = CLIENT_SEND_HEADERS;
    return CI_OK;
}

int ci_client_icapfilter_nonblocking(ci_request_t * req, int io_action,
                                     ci_headers_list_t * req_headers,
                                     ci_headers_list_t * resp_headers,
                                     void *data_source,
                                     int (*source_read) (void *, char *, int),
                                     void *data_dest,
                                     int (*dest_write) (void *, char *, int))
{
    int ret, preview_status, i;

    if (req->status == CLIENT_INIT) {
        ret = prepare_headers(req, req_headers, resp_headers,
                              data_source, source_read);
        if (ret == CI_NEEDS_MORE)
            return NEEDS_TO_READ_USER_DATA;
        if (ret != CI_OK)
            return ret;
        req->status = CLIENT_SEND_HEADERS;
    }

    if (req->status >= CLIENT_SEND_HEADERS && req->status < CLIENT_SEND_HEADERS_FINISHED) {
        ret = client_send_request_headers(req, req->eof_sent);
        if (ret == CI_NEEDS_MORE)
            return NEEDS_TO_WRITE_TO_ICAP;
        else if (ret == CI_ERROR)
            return CI_ERROR;

        req->status = CLIENT_SEND_HEADERS_FINISHED;
    }

    if (req->status == CLIENT_SEND_HEADERS_FINISHED) {
        // Reset encaps entities to receive new entities from server
        for (i = 0; req->entities[i] != NULL; i++)
            ci_request_release_entity(req, i);

        if (req->preview >= 0) {   /*we must wait for ICAP responce here..... */
            req->status = CLIENT_READ_PREVIEW_RESPONSE;
            return NEEDS_TO_READ_FROM_ICAP;
        } else
            req->status = CLIENT_PROCESS_DATA;
    }

    if (req->preview >= 0 && req->status == CLIENT_READ_PREVIEW_RESPONSE) {
        preview_status = 100;
        ret = ci_client_handle_previewed_response(req, &preview_status);
        if (ret == CI_NEEDS_MORE)
            return NEEDS_TO_READ_FROM_ICAP;
        else if (ret == CI_ERROR)
            return CI_ERROR;

        req->return_code = preview_status;
        if (preview_status == 204 || preview_status == 206)
            return 0;

        if (preview_status == 100)
            return NEEDS_TO_WRITE_TO_ICAP;
    }

    if (req->status >= CLIENT_PROCESS_DATA) {
        ret = ci_client_send_and_get_data(req, data_source, source_read,
                                          data_dest, dest_write, io_action);
        return ret;
    }

    return 0;
}

int ci_client_icapfilter(ci_request_t * req, int timeout,
                         ci_headers_list_t * req_headers,
                         ci_headers_list_t * resp_headers,
                         void *data_source, int (*source_read) (void *, char *, int),
                         void *data_dest, int (*dest_write) (void *, char *, int))
{
    int io_action = 0;

    for (;;) {
        int ret = ci_client_icapfilter_nonblocking(req, io_action, req_headers, resp_headers,
                  data_source, source_read, data_dest, dest_write);
        if (ret < 0)
            return CI_ERROR;

        if (ret == 0)
            return req->return_code;

        int wait = 0;
        if (ret & NEEDS_TO_READ_FROM_ICAP)
            wait |= ci_wait_for_read;

        if (ret & NEEDS_TO_WRITE_TO_ICAP)
            wait |= ci_wait_for_write;

        if (wait != 0) {
            do {
                io_action = ci_connection_wait(req->connection, timeout, wait);
                if (io_action <= 0)
                    return CI_ERROR;
            } while (io_action & ci_wait_should_retry);
        } /*Else probably NEEDS_TO_READ_USER_DATA|NEEDS_TO_WRITE_USER_DATA*/
    }

    return CI_ERROR; /*not reached*/
}

/**
 * Return 1 if the HTTP headers (if any) are read completely
 * otherwise return 0;
 */
int ci_client_http_headers_completed(ci_request_t * req)
{
    return (req->status >= CLIENT_PROCESS_DATA_HEADERS_FINISHED);
}

void ci_client_set_user_agent(const char *agent)
{
    if (!agent)
        return  ;

    if (CI_USER_AGENT)
        free(CI_USER_AGENT);

    CI_USER_AGENT = strdup(agent);
}


void ci_client_library_init()
{
    ci_cfg_lib_init();
}

void ci_client_library_release()
{
    if (CI_USER_AGENT) {
        free(CI_USER_AGENT);
        CI_USER_AGENT = NULL;
    }
}